| 1 |
package benchmark |
| 2 |
|
| 3 |
import ( |
| 4 |
stdjson "encoding/json" |
| 5 |
"fmt" |
| 6 |
"strings" |
| 7 |
) |
| 8 |
|
| 9 |
// The payloads of the APIs of large language models ( see llm_api_test.go ): one session of a coding agent, |
| 10 |
// rendered in the format of each API. The session is a system prompt, the definitions of five tools, a request |
| 11 |
// of a user and five tool calls with their results, a search, a source file of 15 KB, an edit, the output of the |
| 12 |
// tests and a directory; then the answer of the model: its reasoning, a text and a tool call. |
| 13 |
|
| 14 |
// llmToolCall is a call of a tool, and its result. |
| 15 |
type llmToolCall struct { |
| 16 |
id, name string |
| 17 |
arguments string |
| 18 |
result string |
| 19 |
} |
| 20 |
|
| 21 |
type llmSession struct { |
| 22 |
system string |
| 23 |
tools []llmTool |
| 24 |
request string |
| 25 |
calls []llmToolCall |
| 26 |
remark string // a text of the model before a call |
| 27 |
followUp string // a text of the user after the calls |
| 28 |
reasoning string |
| 29 |
summary string |
| 30 |
signature string |
| 31 |
answer string |
| 32 |
final llmToolCall |
| 33 |
} |
| 34 |
|
| 35 |
type llmTool struct { |
| 36 |
name, description string |
| 37 |
parameters JSONSchema |
| 38 |
} |
| 39 |
|
| 40 |
func float(v float64) *float64 { return &v } |
| 41 |
|
| 42 |
func llmTools() []llmTool { |
| 43 |
str := func(description string) JSONSchema { return JSONSchema{Type: "string", Description: description} } |
| 44 |
integer := func(description string) JSONSchema { return JSONSchema{Type: "integer", Description: description} } |
| 45 |
boolean := func(description string) JSONSchema { return JSONSchema{Type: "boolean", Description: description} } |
| 46 |
params := func(required []string, properties map[string]JSONSchema) JSONSchema { |
| 47 |
return JSONSchema{Type: "object", Properties: properties, Required: required, AdditionalProperties: false} |
| 48 |
} |
| 49 |
timeout := integer("The timeout in milliseconds, up to 10 minutes") |
| 50 |
timeout.Minimum, timeout.Maximum = float(1), float(600000) |
| 51 |
replaceAll := boolean("Replace every occurrence instead of the first one") |
| 52 |
replaceAll.Default = false |
| 53 |
return []llmTool{ |
| 54 |
{"read_file", "Reads a file of the repository. Lines are numbered from 1; a long file can be read by parts with offset and limit.", |
| 55 |
params([]string{"path"}, map[string]JSONSchema{ |
| 56 |
"path": str("The path of the file, relative to the root of the repository"), |
| 57 |
"offset": integer("The line to start reading from, from 1"), |
| 58 |
"limit": integer("The number of lines to read"), |
| 59 |
})}, |
| 60 |
{"edit_file", "Replaces a text of a file by another one. The text to replace must be unique in the file unless replace_all is set, and must match the file exactly, indentation included.", |
| 61 |
params([]string{"path", "old_string", "new_string"}, map[string]JSONSchema{ |
| 62 |
"path": str("The path of the file to edit"), |
| 63 |
"old_string": str("The text to replace, which must be unique in the file"), |
| 64 |
"new_string": str("The text to replace it with"), |
| 65 |
"replace_all": replaceAll, |
| 66 |
})}, |
| 67 |
{"search", "Searches the files of the repository for a regular expression, and returns the matching lines with their paths and line numbers.", |
| 68 |
params([]string{"pattern"}, map[string]JSONSchema{ |
| 69 |
"pattern": str("A regular expression to search for"), |
| 70 |
"path": str("The directory to search in"), |
| 71 |
"glob": str("A glob of the files to search in, e.g. \"*.go\" or \"**/*.ts\""), |
| 72 |
"case_insensitive": boolean("Match regardless of case"), |
| 73 |
})}, |
| 74 |
{"run_command", "Runs a shell command at the root of the repository and returns its output.", |
| 75 |
params([]string{"command"}, map[string]JSONSchema{ |
| 76 |
"command": str("The command to run"), |
| 77 |
"description": str("What the command does, in a few words"), |
| 78 |
"timeout": timeout, |
| 79 |
})}, |
| 80 |
{"list_files", "Lists the files of a directory.", |
| 81 |
params([]string{"path"}, map[string]JSONSchema{ |
| 82 |
"path": str("The directory to list, relative to the root of the repository"), |
| 83 |
})}, |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
// callID returns an identifier of a tool call, as the OpenAI APIs make them. |
| 88 |
func callID(r *payloadRand) string { |
| 89 |
return "call_" + r.token(alphanumeric, 24) |
| 90 |
} |
| 91 |
|
| 92 |
func newLLMSession() *llmSession { |
| 93 |
r := newPayloadRand(3) |
| 94 |
args := func(o object) string { return string(encodePayload(o)) } |
| 95 |
source := goSource(r, 15000) |
| 96 |
var numbered strings.Builder |
| 97 |
for i, line := range strings.SplitAfter(source, "\n") { |
| 98 |
fmt.Fprintf(&numbered, "%6d\t%s", 160+i, line) |
| 99 |
} |
| 100 |
var matches strings.Builder |
| 101 |
for i, line := range strings.Split(goSource(r, 500), "\n")[:8] { |
| 102 |
fmt.Fprintf(&matches, "internal/decoder/%s.go:%d:%s\n", r.pick(nouns), 40+i*37, line) |
| 103 |
} |
| 104 |
var tests strings.Builder |
| 105 |
for tests.Len() < 2000 { |
| 106 |
name := "TestDecode" + strings.ToUpper(identifier(r)[:1]) + identifier(r)[1:] |
| 107 |
fmt.Fprintf(&tests, "=== RUN %s\n--- PASS: %s (0.%02ds)\n", name, name, r.intn(100)) |
| 108 |
} |
| 109 |
tests.WriteString("PASS\nok \tgithub.com/example/json-codec/internal/decoder\t0.412s\n") |
| 110 |
var files strings.Builder |
| 111 |
for i := 0; i < 24; i++ { |
| 112 |
fmt.Fprintf(&files, "%s_%s_test.go\n", r.pick(nouns), r.pick(nouns)) |
| 113 |
} |
| 114 |
oldCode := goSource(r, 150) |
| 115 |
newCode := goSource(r, 430) |
| 116 |
s := &llmSession{ |
| 117 |
system: markdown(r, 1400), |
| 118 |
tools: llmTools(), |
| 119 |
request: prose(r, 260), |
| 120 |
calls: []llmToolCall{ |
| 121 |
{callID(r), "search", args(object{{"pattern", `func \(d \*structDecoder\) Decode`}, {"path", "internal/decoder"}, {"glob", "*.go"}}), matches.String()}, |
| 122 |
{callID(r), "read_file", args(object{{"path", "internal/decoder/struct.go"}, {"offset", 160}, {"limit", 120}}), numbered.String()}, |
| 123 |
{callID(r), "edit_file", args(object{{"path", "internal/decoder/struct.go"}, {"old_string", oldCode}, {"new_string", newCode}}), "The file internal/decoder/struct.go has been updated."}, |
| 124 |
{callID(r), "run_command", args(object{{"command", "go test ./internal/decoder/... -run TestDecodeStructKeys -count=1"}, {"description", "Run the tests of the decoder"}}), tests.String()}, |
| 125 |
{callID(r), "list_files", args(object{{"path", "benchmarks"}}), files.String()}, |
| 126 |
}, |
| 127 |
remark: prose(r, 220), |
| 128 |
followUp: prose(r, 76), |
| 129 |
reasoning: prose(r, 700), |
| 130 |
summary: "**" + sentence(r) + "**\n\n" + prose(r, 120), |
| 131 |
signature: r.token(base64URL, 702), |
| 132 |
answer: markdown(r, 950), |
| 133 |
final: llmToolCall{id: callID(r), name: "run_command", arguments: args(object{ |
| 134 |
{"command", "cd benchmarks && go test -run '^$' -bench 'Benchmark_Decode_(Short|Long)Keys' -benchtime 300ms -count 3 ."}, |
| 135 |
{"description", "Benchmark the decoding of long keys"}, |
| 136 |
})}, |
| 137 |
} |
| 138 |
return s |
| 139 |
} |
| 140 |
|
| 141 |
var llmSessionPayload = newLLMSession() |
| 142 |
|
| 143 |
const ( |
| 144 |
openAIModel = "gpt-5.1-codex" |
| 145 |
openAIModelVersion = "gpt-5.1-codex-2025-11-13" |
| 146 |
anthropicModel = "claude-sonnet-4-5" |
| 147 |
anthropicVersion = "claude-sonnet-4-5-20250929" |
| 148 |
llmCreated = 1790000000 |
| 149 |
promptCacheKey = "session-7f3c2a9e41d84b06" |
| 150 |
) |
| 151 |
|
| 152 |
// ---------------------------------------------------------------- OpenAI Chat Completions |
| 153 |
|
| 154 |
func openAIChatRequestPayload() []byte { |
| 155 |
s := llmSessionPayload |
| 156 |
messages := []ChatCompletionMessage{{Role: "system", Content: s.system}, {Role: "user", Content: s.request}} |
| 157 |
for i, c := range s.calls { |
| 158 |
m := ChatCompletionMessage{Role: "assistant", ToolCalls: []ChatToolCall{{ID: c.id, Type: "function", Function: ChatFunctionCall{Name: c.name, Arguments: c.arguments}}}} |
| 159 |
if i == 2 { |
| 160 |
m.Content = s.remark |
| 161 |
} |
| 162 |
messages = append(messages, m, ChatCompletionMessage{Role: "tool", Content: c.result, ToolCallID: c.id}) |
| 163 |
} |
| 164 |
messages = append(messages, ChatCompletionMessage{Role: "user", Content: s.followUp}) |
| 165 |
var tools []ChatTool |
| 166 |
for _, t := range s.tools { |
| 167 |
tools = append(tools, ChatTool{Type: "function", Function: &ChatFunctionDefinition{Name: t.name, Description: t.description, Strict: true, Parameters: t.parameters}}) |
| 168 |
} |
| 169 |
return encodePayload(ChatCompletionRequest{ |
| 170 |
Model: openAIModel, |
| 171 |
Messages: messages, |
| 172 |
MaxCompletionTokens: 16384, |
| 173 |
Stream: true, |
| 174 |
StreamOptions: &ChatStreamOptions{IncludeUsage: true}, |
| 175 |
Tools: tools, |
| 176 |
ToolChoice: "auto", |
| 177 |
ParallelToolCalls: false, |
| 178 |
ReasoningEffort: "medium", |
| 179 |
PromptCacheKey: promptCacheKey, |
| 180 |
}) |
| 181 |
} |
| 182 |
|
| 183 |
func openAIChatUsage() object { |
| 184 |
return object{ |
| 185 |
{"prompt_tokens", 21874}, |
| 186 |
{"completion_tokens", 1243}, |
| 187 |
{"total_tokens", 23117}, |
| 188 |
{"prompt_tokens_details", object{{"cached_tokens", 19200}, {"audio_tokens", 0}}}, |
| 189 |
{"completion_tokens_details", object{{"reasoning_tokens", 384}, {"audio_tokens", 0}, {"accepted_prediction_tokens", 0}, {"rejected_prediction_tokens", 0}}}, |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
const openAIChatID = "chatcmpl-SXRVxfCQGgXkH1zxFUbEctT2NLLzP" |
| 194 |
|
| 195 |
func openAIChatResponsePayload() []byte { |
| 196 |
s := llmSessionPayload |
| 197 |
return encodePayload(object{ |
| 198 |
{"id", openAIChatID}, |
| 199 |
{"object", "chat.completion"}, |
| 200 |
{"created", llmCreated}, |
| 201 |
{"model", openAIModelVersion}, |
| 202 |
{"choices", []any{object{ |
| 203 |
{"index", 0}, |
| 204 |
{"message", object{ |
| 205 |
{"role", "assistant"}, |
| 206 |
{"content", s.answer}, |
| 207 |
{"refusal", nil}, |
| 208 |
{"annotations", []any{}}, |
| 209 |
{"tool_calls", []any{object{ |
| 210 |
{"id", s.final.id}, |
| 211 |
{"type", "function"}, |
| 212 |
{"function", object{{"name", s.final.name}, {"arguments", s.final.arguments}}}, |
| 213 |
}}}, |
| 214 |
}}, |
| 215 |
{"logprobs", nil}, |
| 216 |
{"finish_reason", "tool_calls"}, |
| 217 |
}}}, |
| 218 |
{"usage", openAIChatUsage()}, |
| 219 |
{"service_tier", "default"}, |
| 220 |
{"system_fingerprint", nil}, |
| 221 |
}) |
| 222 |
} |
| 223 |
|
| 224 |
func openAIChatStreamPayload() [][]byte { |
| 225 |
s := llmSessionPayload |
| 226 |
r := newPayloadRand(4) |
| 227 |
chunk := func(choices []any, usage any, obfuscate bool) object { |
| 228 |
o := object{ |
| 229 |
{"id", openAIChatID}, |
| 230 |
{"object", "chat.completion.chunk"}, |
| 231 |
{"created", llmCreated}, |
| 232 |
{"model", openAIModelVersion}, |
| 233 |
{"service_tier", "default"}, |
| 234 |
{"system_fingerprint", nil}, |
| 235 |
{"choices", choices}, |
| 236 |
{"usage", usage}, |
| 237 |
} |
| 238 |
if obfuscate { |
| 239 |
o = append(o, field{"obfuscation", r.token(alphanumeric, r.between(1, 9))}) |
| 240 |
} |
| 241 |
return o |
| 242 |
} |
| 243 |
delta := func(delta object, finish any) []any { |
| 244 |
return []any{object{{"index", 0}, {"delta", delta}, {"logprobs", nil}, {"finish_reason", finish}}} |
| 245 |
} |
| 246 |
events := []object{chunk(delta(object{{"role", "assistant"}, {"content", ""}, {"refusal", nil}}, nil), nil, true)} |
| 247 |
for _, piece := range chunks(r, s.answer) { |
| 248 |
events = append(events, chunk(delta(object{{"content", piece}}, nil), nil, true)) |
| 249 |
} |
| 250 |
events = append(events, chunk(delta(object{{"tool_calls", []any{object{ |
| 251 |
{"index", 0}, {"id", s.final.id}, {"type", "function"}, {"function", object{{"name", s.final.name}, {"arguments", ""}}}, |
| 252 |
}}}}, nil), nil, false)) |
| 253 |
for _, piece := range chunks(r, s.final.arguments) { |
| 254 |
events = append(events, chunk(delta(object{{"tool_calls", []any{object{{"index", 0}, {"function", object{{"arguments", piece}}}}}}}, nil), nil, true)) |
| 255 |
} |
| 256 |
events = append(events, |
| 257 |
chunk(delta(object{}, "tool_calls"), nil, false), |
| 258 |
chunk([]any{}, openAIChatUsage(), true), |
| 259 |
) |
| 260 |
return jsonLines(events) |
| 261 |
} |
| 262 |
|
| 263 |
// ---------------------------------------------------------------- OpenAI Responses |
| 264 |
|
| 265 |
func responseTools(s *llmSession) []ResponseTool { |
| 266 |
var tools []ResponseTool |
| 267 |
for _, t := range s.tools { |
| 268 |
tools = append(tools, ResponseTool{Type: "function", Name: t.name, Description: t.description, Parameters: t.parameters, Strict: true}) |
| 269 |
} |
| 270 |
return tools |
| 271 |
} |
| 272 |
|
| 273 |
func openAIResponsesRequestPayload() []byte { |
| 274 |
s := llmSessionPayload |
| 275 |
r := newPayloadRand(5) |
| 276 |
input := []ResponseInputItem{{Type: "message", Role: "user", Content: []ResponseContent{{Type: "input_text", Text: s.request}}}} |
| 277 |
for i, c := range s.calls { |
| 278 |
if i == 2 { |
| 279 |
input = append(input, ResponseInputItem{Type: "message", ID: "msg_" + r.token(hexDigits, 48), Status: "completed", Role: "assistant", |
| 280 |
Content: []ResponseContent{{Type: "output_text", Text: s.remark, Annotations: []ResponseAnnotation{}, Logprobs: []ResponseLogprob{}}}}) |
| 281 |
} |
| 282 |
input = append(input, |
| 283 |
ResponseInputItem{Type: "function_call", ID: "fc_" + r.token(hexDigits, 48), Status: "completed", CallID: c.id, Name: c.name, Arguments: c.arguments}, |
| 284 |
ResponseInputItem{Type: "function_call_output", CallID: c.id, Output: c.result}, |
| 285 |
) |
| 286 |
} |
| 287 |
input = append(input, ResponseInputItem{Type: "message", Role: "user", Content: []ResponseContent{{Type: "input_text", Text: s.followUp}}}) |
| 288 |
return encodePayload(ResponsesRequest{ |
| 289 |
Model: openAIModel, |
| 290 |
Instructions: s.system, |
| 291 |
Input: input, |
| 292 |
Tools: responseTools(s), |
| 293 |
ToolChoice: "auto", |
| 294 |
Reasoning: &ResponseReasoning{Effort: "medium", Summary: "auto"}, |
| 295 |
Store: false, |
| 296 |
Stream: true, |
| 297 |
Include: []string{"reasoning.encrypted_content"}, |
| 298 |
PromptCacheKey: promptCacheKey, |
| 299 |
MaxOutputTokens: 16384, |
| 300 |
Text: &ResponseTextOptions{Verbosity: "medium"}, |
| 301 |
}) |
| 302 |
} |
| 303 |
|
| 304 |
// openAIResponse is a response of the Responses API, whose output and usage are the ones given. |
| 305 |
func openAIResponse(s *llmSession, status string, output []any, usage any) object { |
| 306 |
return object{ |
| 307 |
{"id", "resp_b9dba03eeb9caf3cc6086ed95e6b0cdca2f790d4c8520b8d"}, |
| 308 |
{"object", "response"}, |
| 309 |
{"created_at", llmCreated}, |
| 310 |
{"status", status}, |
| 311 |
{"background", false}, |
| 312 |
{"billing", object{{"payer", "developer"}}}, |
| 313 |
{"error", nil}, |
| 314 |
{"incomplete_details", nil}, |
| 315 |
{"instructions", s.system}, |
| 316 |
{"max_output_tokens", 16384}, |
| 317 |
{"max_tool_calls", nil}, |
| 318 |
{"model", openAIModelVersion}, |
| 319 |
{"output", output}, |
| 320 |
{"parallel_tool_calls", false}, |
| 321 |
{"previous_response_id", nil}, |
| 322 |
{"prompt_cache_key", promptCacheKey}, |
| 323 |
{"prompt_cache_retention", nil}, |
| 324 |
{"reasoning", object{{"effort", "medium"}, {"summary", "detailed"}}}, |
| 325 |
{"safety_identifier", nil}, |
| 326 |
{"service_tier", "default"}, |
| 327 |
{"store", false}, |
| 328 |
{"temperature", 1.0}, |
| 329 |
{"text", object{{"format", object{{"type", "text"}}}, {"verbosity", "medium"}}}, |
| 330 |
{"tool_choice", "auto"}, |
| 331 |
{"tools", responseTools(s)}, |
| 332 |
{"top_logprobs", 0}, |
| 333 |
{"top_p", 0.98}, |
| 334 |
{"truncation", "disabled"}, |
| 335 |
{"usage", usage}, |
| 336 |
{"user", nil}, |
| 337 |
{"metadata", object{}}, |
| 338 |
} |
| 339 |
} |
| 340 |
|
| 341 |
const ( |
| 342 |
responseReasoningID = "rs_94e8f5e183d2b2e0552c89667a822be1598b7cc5f8a7870c" |
| 343 |
responseMessageID = "msg_3c1f0e8d9b2a47c6a5d4e3f2b1a09876c5d4e3f2a1b0c9d8" |
| 344 |
responseCallID = "fc_7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6d5e4f" |
| 345 |
) |
| 346 |
|
| 347 |
// openAIResponseOutput returns the items of the output: the reasoning, the message and the function call, with |
| 348 |
// their texts as far as they are written. |
| 349 |
func openAIResponseOutput(s *llmSession, encrypted, summary, answer, arguments string, done bool) (reasoning, message, call object) { |
| 350 |
status := "in_progress" |
| 351 |
if done { |
| 352 |
status = "completed" |
| 353 |
} |
| 354 |
summaries := []any{} |
| 355 |
if summary != "" { |
| 356 |
summaries = append(summaries, object{{"type", "summary_text"}, {"text", summary}}) |
| 357 |
} |
| 358 |
content := []any{} |
| 359 |
if answer != "" { |
| 360 |
content = append(content, object{{"type", "output_text"}, {"annotations", []any{}}, {"logprobs", []any{}}, {"text", answer}}) |
| 361 |
} |
| 362 |
reasoning = object{{"id", responseReasoningID}, {"type", "reasoning"}, {"encrypted_content", encrypted}, {"summary", summaries}} |
| 363 |
message = object{{"id", responseMessageID}, {"type", "message"}, {"status", status}, {"content", content}, {"role", "assistant"}} |
| 364 |
call = object{{"id", responseCallID}, {"type", "function_call"}, {"status", status}, {"arguments", arguments}, {"call_id", s.final.id}, {"name", s.final.name}} |
| 365 |
return reasoning, message, call |
| 366 |
} |
| 367 |
|
| 368 |
func openAIResponsesUsage() object { |
| 369 |
return object{ |
| 370 |
{"input_tokens", 21874}, |
| 371 |
{"input_tokens_details", object{{"cached_tokens", 19200}}}, |
| 372 |
{"output_tokens", 1243}, |
| 373 |
{"output_tokens_details", object{{"reasoning_tokens", 384}}}, |
| 374 |
{"total_tokens", 23117}, |
| 375 |
} |
| 376 |
} |
| 377 |
|
| 378 |
func encryptedReasoning(s *llmSession) string { |
| 379 |
return "gAAAAA" + s.signature + s.signature[:700] |
| 380 |
} |
| 381 |
|
| 382 |
func openAIResponsesResponsePayload() []byte { |
| 383 |
s := llmSessionPayload |
| 384 |
reasoning, message, call := openAIResponseOutput(s, encryptedReasoning(s), s.summary, s.answer, s.final.arguments, true) |
| 385 |
return encodePayload(openAIResponse(s, "completed", []any{reasoning, message, call}, openAIResponsesUsage())) |
| 386 |
} |
| 387 |
|
| 388 |
func openAIResponsesStreamPayload() [][]byte { |
| 389 |
s := llmSessionPayload |
| 390 |
r := newPayloadRand(6) |
| 391 |
var events []object |
| 392 |
event := func(typ string, fields ...field) { |
| 393 |
events = append(events, append(object{{"type", typ}, {"sequence_number", len(events)}}, fields...)) |
| 394 |
} |
| 395 |
obfuscation := func() field { return field{"obfuscation", r.token(alphanumeric, r.between(1, 9))} } |
| 396 |
encrypted := encryptedReasoning(s) |
| 397 |
event("response.created", field{"response", openAIResponse(s, "in_progress", []any{}, nil)}) |
| 398 |
event("response.in_progress", field{"response", openAIResponse(s, "in_progress", []any{}, nil)}) |
| 399 |
|
| 400 |
reasoning, _, _ := openAIResponseOutput(s, encrypted, "", "", "", false) |
| 401 |
event("response.output_item.added", field{"output_index", 0}, field{"item", reasoning}) |
| 402 |
summaryPart := func(text string) object { return object{{"type", "summary_text"}, {"text", text}} } |
| 403 |
event("response.reasoning_summary_part.added", field{"item_id", responseReasoningID}, field{"output_index", 0}, field{"summary_index", 0}, field{"part", summaryPart("")}) |
| 404 |
for _, piece := range chunks(r, s.summary) { |
| 405 |
event("response.reasoning_summary_text.delta", field{"item_id", responseReasoningID}, field{"output_index", 0}, field{"summary_index", 0}, field{"delta", piece}, obfuscation()) |
| 406 |
} |
| 407 |
event("response.reasoning_summary_text.done", field{"item_id", responseReasoningID}, field{"output_index", 0}, field{"summary_index", 0}, field{"text", s.summary}) |
| 408 |
event("response.reasoning_summary_part.done", field{"item_id", responseReasoningID}, field{"output_index", 0}, field{"summary_index", 0}, field{"part", summaryPart(s.summary)}) |
| 409 |
reasoning, _, _ = openAIResponseOutput(s, encrypted, s.summary, "", "", true) |
| 410 |
event("response.output_item.done", field{"output_index", 0}, field{"item", reasoning}) |
| 411 |
|
| 412 |
_, message, _ := openAIResponseOutput(s, encrypted, "", "", "", false) |
| 413 |
event("response.output_item.added", field{"output_index", 1}, field{"item", message}) |
| 414 |
textPart := func(text string) object { |
| 415 |
return object{{"type", "output_text"}, {"annotations", []any{}}, {"logprobs", []any{}}, {"text", text}} |
| 416 |
} |
| 417 |
event("response.content_part.added", field{"item_id", responseMessageID}, field{"output_index", 1}, field{"content_index", 0}, field{"part", textPart("")}) |
| 418 |
for _, piece := range chunks(r, s.answer) { |
| 419 |
event("response.output_text.delta", field{"item_id", responseMessageID}, field{"output_index", 1}, field{"content_index", 0}, field{"delta", piece}, field{"logprobs", []any{}}, obfuscation()) |
| 420 |
} |
| 421 |
event("response.output_text.done", field{"item_id", responseMessageID}, field{"output_index", 1}, field{"content_index", 0}, field{"text", s.answer}, field{"logprobs", []any{}}) |
| 422 |
event("response.content_part.done", field{"item_id", responseMessageID}, field{"output_index", 1}, field{"content_index", 0}, field{"part", textPart(s.answer)}) |
| 423 |
_, message, _ = openAIResponseOutput(s, encrypted, "", s.answer, "", true) |
| 424 |
event("response.output_item.done", field{"output_index", 1}, field{"item", message}) |
| 425 |
|
| 426 |
_, _, call := openAIResponseOutput(s, encrypted, "", "", "", false) |
| 427 |
event("response.output_item.added", field{"output_index", 2}, field{"item", call}) |
| 428 |
for _, piece := range chunks(r, s.final.arguments) { |
| 429 |
event("response.function_call_arguments.delta", field{"item_id", responseCallID}, field{"output_index", 2}, field{"delta", piece}, obfuscation()) |
| 430 |
} |
| 431 |
event("response.function_call_arguments.done", field{"item_id", responseCallID}, field{"output_index", 2}, field{"arguments", s.final.arguments}) |
| 432 |
_, _, call = openAIResponseOutput(s, encrypted, "", "", s.final.arguments, true) |
| 433 |
event("response.output_item.done", field{"output_index", 2}, field{"item", call}) |
| 434 |
|
| 435 |
reasoning, message, call = openAIResponseOutput(s, encrypted, s.summary, s.answer, s.final.arguments, true) |
| 436 |
event("response.completed", field{"response", openAIResponse(s, "completed", []any{reasoning, message, call}, openAIResponsesUsage())}) |
| 437 |
return jsonLines(events) |
| 438 |
} |
| 439 |
|
| 440 |
// ---------------------------------------------------------------- Anthropic Messages |
| 441 |
|
| 442 |
func anthropicToolID(r *payloadRand) string { |
| 443 |
return "toolu_01" + r.token(alphanumeric, 22) |
| 444 |
} |
| 445 |
|
| 446 |
func anthropicRequestPayload() []byte { |
| 447 |
s := llmSessionPayload |
| 448 |
r := newPayloadRand(7) |
| 449 |
ephemeral := &AnthropicCacheCtrl{Type: "ephemeral"} |
| 450 |
messages := []AnthropicMessage{{Role: "user", Content: []AnthropicBlock{{Type: "text", Text: s.request}}}} |
| 451 |
for i, c := range s.calls { |
| 452 |
id := anthropicToolID(r) |
| 453 |
var assistant []AnthropicBlock |
| 454 |
if i == 2 { |
| 455 |
assistant = append(assistant, AnthropicBlock{Type: "text", Text: s.remark}) |
| 456 |
} |
| 457 |
assistant = append(assistant, AnthropicBlock{Type: "tool_use", ID: id, Name: c.name, Input: stdjson.RawMessage(c.arguments)}) |
| 458 |
user := []AnthropicBlock{{Type: "tool_result", ToolUseID: id, Content: c.result}} |
| 459 |
if i == len(s.calls)-1 { |
| 460 |
user = append(user, AnthropicBlock{Type: "text", Text: s.followUp, CacheControl: ephemeral}) |
| 461 |
} |
| 462 |
messages = append(messages, AnthropicMessage{Role: "assistant", Content: assistant}, AnthropicMessage{Role: "user", Content: user}) |
| 463 |
} |
| 464 |
var tools []AnthropicTool |
| 465 |
for _, t := range s.tools { |
| 466 |
tools = append(tools, AnthropicTool{Name: t.name, Description: t.description, InputSchema: t.parameters}) |
| 467 |
} |
| 468 |
return encodePayload(MessagesRequest{ |
| 469 |
Model: anthropicModel, |
| 470 |
MaxTokens: 32000, |
| 471 |
System: []AnthropicBlock{{Type: "text", Text: s.system, CacheControl: ephemeral}}, |
| 472 |
Messages: messages, |
| 473 |
Tools: tools, |
| 474 |
Thinking: &AnthropicThinking{Type: "enabled", BudgetTokens: 10000}, |
| 475 |
Stream: true, |
| 476 |
Metadata: &AnthropicMetadata{UserID: "user_" + r.token(hexDigits, 32)}, |
| 477 |
}) |
| 478 |
} |
| 479 |
|
| 480 |
const anthropicMessageID = "msg_010ZX2h3zvgCT7KHTPEQrjBx" |
| 481 |
|
| 482 |
var anthropicFinalToolID = anthropicToolID(newPayloadRand(8)) |
| 483 |
|
| 484 |
func anthropicUsage(outputTokens int) object { |
| 485 |
return object{ |
| 486 |
{"input_tokens", 312}, |
| 487 |
{"cache_creation_input_tokens", 2362}, |
| 488 |
{"cache_read_input_tokens", 19200}, |
| 489 |
{"cache_creation", object{{"ephemeral_5m_input_tokens", 2362}, {"ephemeral_1h_input_tokens", 0}}}, |
| 490 |
{"output_tokens", outputTokens}, |
| 491 |
{"service_tier", "standard"}, |
| 492 |
} |
| 493 |
} |
| 494 |
|
| 495 |
func anthropicResponsePayload() []byte { |
| 496 |
s := llmSessionPayload |
| 497 |
return encodePayload(object{ |
| 498 |
{"id", anthropicMessageID}, |
| 499 |
{"type", "message"}, |
| 500 |
{"role", "assistant"}, |
| 501 |
{"model", anthropicVersion}, |
| 502 |
{"content", []any{ |
| 503 |
object{{"type", "thinking"}, {"thinking", s.reasoning}, {"signature", s.signature}}, |
| 504 |
object{{"type", "text"}, {"text", s.answer}}, |
| 505 |
object{{"type", "tool_use"}, {"id", anthropicFinalToolID}, {"name", s.final.name}, {"input", stdjson.RawMessage(s.final.arguments)}}, |
| 506 |
}}, |
| 507 |
{"stop_reason", "tool_use"}, |
| 508 |
{"stop_sequence", nil}, |
| 509 |
{"usage", anthropicUsage(1243)}, |
| 510 |
}) |
| 511 |
} |
| 512 |
|
| 513 |
func anthropicStreamPayload() [][]byte { |
| 514 |
s := llmSessionPayload |
| 515 |
r := newPayloadRand(9) |
| 516 |
events := []object{{ |
| 517 |
{"type", "message_start"}, |
| 518 |
{"message", object{ |
| 519 |
{"id", anthropicMessageID}, |
| 520 |
{"type", "message"}, |
| 521 |
{"role", "assistant"}, |
| 522 |
{"model", anthropicVersion}, |
| 523 |
{"content", []any{}}, |
| 524 |
{"stop_reason", nil}, |
| 525 |
{"stop_sequence", nil}, |
| 526 |
{"usage", anthropicUsage(1)}, |
| 527 |
}}, |
| 528 |
}} |
| 529 |
block := func(index int, start object, deltaType, key, text string, extra ...object) { |
| 530 |
events = append(events, object{{"type", "content_block_start"}, {"index", index}, {"content_block", start}}) |
| 531 |
if index == 0 { |
| 532 |
events = append(events, object{{"type", "ping"}}) |
| 533 |
} |
| 534 |
for _, piece := range chunks(r, text) { |
| 535 |
events = append(events, object{{"type", "content_block_delta"}, {"index", index}, {"delta", object{{"type", deltaType}, {key, piece}}}}) |
| 536 |
} |
| 537 |
for _, delta := range extra { |
| 538 |
events = append(events, object{{"type", "content_block_delta"}, {"index", index}, {"delta", delta}}) |
| 539 |
} |
| 540 |
events = append(events, object{{"type", "content_block_stop"}, {"index", index}}) |
| 541 |
} |
| 542 |
block(0, object{{"type", "thinking"}, {"thinking", ""}, {"signature", ""}}, "thinking_delta", "thinking", s.reasoning, |
| 543 |
object{{"type", "signature_delta"}, {"signature", s.signature}}) |
| 544 |
block(1, object{{"type", "text"}, {"text", ""}}, "text_delta", "text", s.answer) |
| 545 |
block(2, object{{"type", "tool_use"}, {"id", anthropicFinalToolID}, {"name", s.final.name}, {"input", object{}}}, "input_json_delta", "partial_json", s.final.arguments) |
| 546 |
events = append(events, |
| 547 |
object{ |
| 548 |
{"type", "message_delta"}, |
| 549 |
{"delta", object{{"stop_reason", "tool_use"}, {"stop_sequence", nil}}}, |
| 550 |
{"usage", object{{"input_tokens", 312}, {"cache_creation_input_tokens", 2362}, {"cache_read_input_tokens", 19200}, {"output_tokens", 1243}}}, |
| 551 |
}, |
| 552 |
object{{"type", "message_stop"}}, |
| 553 |
) |
| 554 |
return jsonLines(events) |
| 555 |
} |