forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoManagedChatGPTMemoryOpenAIStrategy.swift
More file actions
66 lines (58 loc) · 2.29 KB
/
AutoManagedChatGPTMemoryOpenAIStrategy.swift
File metadata and controls
66 lines (58 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import Foundation
import Logger
import TokenEncoder
extension AutoManagedChatGPTMemory {
struct OpenAIStrategy: AutoManagedChatGPTMemoryStrategy {
static let encoder: TokenEncoder = TiktokenCl100kBaseTokenEncoder()
func countToken(_ message: ChatMessage) async -> Int {
await Self.encoder.countToken(message)
}
func countToken<F>(_ function: F) async -> Int where F : ChatGPTFunction {
async let nameTokenCount = Self.encoder.countToken(text: function.name)
async let descriptionTokenCount = Self.encoder.countToken(text: function.description)
async let schemaTokenCount = {
guard let data = try? JSONEncoder().encode(function.argumentSchema),
let string = String(data: data, encoding: .utf8)
else { return 0 }
return await Self.encoder.countToken(text: string)
}()
return await (nameTokenCount + descriptionTokenCount + schemaTokenCount)
}
func reformat(_ prompt: ChatGPTPrompt) async -> ChatGPTPrompt {
prompt
}
}
}
extension TokenEncoder {
/// https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
func countToken(_ message: ChatMessage) async -> Int {
var total = 3
var encodingContent = [String]()
if let content = message.content {
encodingContent.append(content)
}
if let name = message.name {
encodingContent.append(name)
total += 1
}
if let functionCall = message.functionCall {
encodingContent.append(functionCall.name)
encodingContent.append(functionCall.arguments)
}
total += await withTaskGroup(of: Int.self, body: { group in
for content in encodingContent {
group.addTask {
await encode(text: content).count
}
}
return await group.reduce(0, +)
})
return total
}
func countToken(_ message: inout ChatMessage) async -> Int {
if let count = message.tokensCount { return count }
let count = await countToken(message)
message.tokensCount = count
return count
}
}