forked from coaidev/coai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer.go
343 lines (274 loc) · 7.36 KB
/
buffer.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package utils
import (
"chat/globals"
"fmt"
"strings"
"time"
)
type Charge interface {
GetType() string
GetModels() []string
GetInput() float32
GetOutput() float32
SupportAnonymous() bool
IsBilling() bool
IsBillingType(t string) bool
GetLimit() float32
}
type Buffer struct {
Model string `json:"model"`
Quota float32 `json:"quota"`
Data string `json:"data"`
Latest string `json:"latest"`
Cursor int `json:"cursor"`
Times int `json:"times"`
InputTokens int `json:"input_tokens"`
Images Images `json:"images"`
ToolCalls *globals.ToolCalls `json:"tool_calls"`
ToolCallsCursor int `json:"tool_calls_cursor"`
FunctionCall *globals.FunctionCall `json:"function_call"`
StartTime *time.Time `json:"-"`
Prompts string `json:"prompts"`
TokenName string `json:"-"`
Charge Charge `json:"-"`
VisionRecall bool `json:"-"`
}
func initInputToken(model string, history []globals.Message) int {
if globals.IsVisionModel(model) {
for _, message := range history {
if message.Role == globals.User {
content, _ := ExtractImages(message.Content, true)
message.Content = content
}
}
history = Each(history, func(message globals.Message) globals.Message {
if message.Role == globals.User {
raw, _ := ExtractImages(message.Content, true)
return globals.Message{
Role: message.Role,
Content: raw,
Name: message.Name,
FunctionCall: message.FunctionCall,
ToolCalls: message.ToolCalls,
ToolCallId: message.ToolCallId,
}
}
return message
})
}
return NumTokensFromMessages(history, model, false)
}
func NewBuffer(model string, history []globals.Message, charge Charge) *Buffer {
token := initInputToken(model, history)
return &Buffer{
Model: model,
Quota: CountInputQuota(charge, token),
InputTokens: token,
Charge: charge,
FunctionCall: nil,
ToolCalls: nil,
ToolCallsCursor: 0,
StartTime: ToPtr(time.Now()),
}
}
func (b *Buffer) GetCursor() int {
return b.Cursor
}
func (b *Buffer) GetQuota() float32 {
return b.Quota + CountOutputToken(b.Charge, b.CountOutputToken(true))
}
func (b *Buffer) GetRecordQuota() float32 {
// end of the buffer, the output token is counted using the times
return b.Quota + CountOutputToken(b.Charge, b.CountOutputToken(false))
}
func (b *Buffer) Write(data string) string {
b.Data += data
b.Cursor += len(data)
b.Times++
b.Latest = data
return data
}
func (b *Buffer) WriteChunk(data *globals.Chunk) string {
if data == nil {
return ""
}
b.Write(data.Content)
b.AddToolCalls(data.ToolCall)
b.SetFunctionCall(data.FunctionCall)
return data.Content
}
func (b *Buffer) GetChunk() string {
return b.Latest
}
func (b *Buffer) InitVisionRecall() {
// set the vision recall flag to true to prevent the buffer from adding more images of retrying the channel
b.VisionRecall = true
}
func (b *Buffer) AddImage(image *Image) {
if image == nil || b.VisionRecall {
return
}
b.Images = append(b.Images, *image)
tokens := image.CountTokens(b.Model)
b.InputTokens += tokens
if b.Charge.IsBillingType(globals.TokenBilling) {
b.Quota += float32(tokens) / 1000 * b.Charge.GetInput()
}
}
func (b *Buffer) GetImages() Images {
return b.Images
}
func (b *Buffer) SetToolCalls(toolCalls *globals.ToolCalls) {
b.ToolCalls = toolCalls
}
func hitTool(tool globals.ToolCall, tools globals.ToolCalls) (int, *globals.ToolCall) {
for i, t := range tools {
if t.Id == tool.Id {
return i, &t
}
}
if len(tool.Type) == 0 && len(tool.Id) == 0 {
length := len(tools)
if length > 0 {
// if the tool is empty, return the last tool as the hit
return length - 1, &tools[length-1]
}
}
return 0, nil
}
func appendTool(tool globals.ToolCall, chunk globals.ToolCall) string {
from := ToString(tool.Function.Arguments)
to := ToString(chunk.Function.Arguments)
return from + to
}
func mixTools(source *globals.ToolCalls, target *globals.ToolCalls) *globals.ToolCalls {
if source == nil {
return target
}
tools := make(globals.ToolCalls, 0)
arr := Collect[globals.ToolCall](*source, *target)
for _, tool := range arr {
idx, hit := hitTool(tool, tools)
if hit != nil {
tools[idx].Function.Arguments = appendTool(tools[idx], tool)
} else {
tools = append(tools, tool)
}
}
return &tools
}
func (b *Buffer) AddToolCalls(toolCalls *globals.ToolCalls) {
if toolCalls == nil {
return
}
b.ToolCalls = mixTools(b.ToolCalls, toolCalls)
}
func (b *Buffer) SetFunctionCall(functionCall *globals.FunctionCall) {
if functionCall == nil {
return
}
b.FunctionCall = functionCall
}
func (b *Buffer) GetToolCalls() *globals.ToolCalls {
calls := b.ToolCalls
b.ToolCalls = nil
return calls
}
func (b *Buffer) GetFunctionCall() *globals.FunctionCall {
return b.FunctionCall
}
func (b *Buffer) IsFunctionCalling() bool {
return b.FunctionCall != nil || b.ToolCalls != nil
}
func (b *Buffer) IsEmpty() bool {
return b.Cursor == 0 && !b.IsFunctionCalling()
}
func (b *Buffer) GetModel() string {
return b.Model
}
func (b *Buffer) GetCharge() Charge {
return b.Charge
}
func (b *Buffer) ToChargeInfo() string {
switch b.Charge.GetType() {
case globals.TokenBilling:
return fmt.Sprintf(
"input tokens: %0.4f quota / 1k tokens\n"+
"output tokens: %0.4f quota / 1k tokens\n",
b.Charge.GetInput(), b.Charge.GetOutput(),
)
case globals.TimesBilling:
return fmt.Sprintf("%f quota per request\n", b.Charge.GetLimit())
case globals.NonBilling:
return "no cost"
}
return ""
}
func (b *Buffer) SetPrompts(prompts interface{}) {
b.Prompts = ToString(prompts)
}
func (b *Buffer) Read() string {
return b.Data
}
func (b *Buffer) ReadBytes() []byte {
return []byte(b.Data)
}
func (b *Buffer) ReadWithDefault(_default string) string {
if b.IsEmpty() || (len(strings.TrimSpace(b.Data)) == 0 && !b.IsFunctionCalling()) {
return _default
}
return b.Data
}
func (b *Buffer) ReadTimes() int {
return b.Times
}
func (b *Buffer) SetInputTokens(tokens int) {
b.InputTokens = tokens
}
func (b *Buffer) CountInputToken() int {
return b.InputTokens
}
func (b *Buffer) CountOutputToken(running bool) int {
if running {
// performance optimization:
// if the buffer is still running, the output token counted using the times instead
return b.Times
}
return NumTokensFromResponse(b.Read(), b.Model)
}
func (b *Buffer) CountToken() int {
return b.CountInputToken() + b.CountOutputToken(true)
}
func (b *Buffer) GetDuration() float32 {
if b.StartTime == nil {
return 0
}
return float32(time.Since(*b.StartTime).Seconds())
}
func (b *Buffer) GetStartTime() *time.Time {
return b.StartTime
}
func (b *Buffer) GetPrompts() string {
return b.Prompts
}
func (b *Buffer) GetTokenName() string {
if len(b.TokenName) == 0 {
return globals.WebTokenType
}
return b.TokenName
}
func (b *Buffer) SetTokenName(tokenName string) {
b.TokenName = tokenName
}
func (b *Buffer) GetRecordPrompts() string {
if !globals.AcceptPromptStore {
return ""
}
return b.GetPrompts()
}
func (b *Buffer) GetRecordResponsePrompts() string {
if !globals.AcceptPromptStore {
return ""
}
return b.Read()
}