Debian Codegraph @

benchmarks/llm_api_test.go

raw
1 package benchmark
2
3 import (
4 "bytes"
5 stdjson "encoding/json"
6 "reflect"
7 "testing"
8
9 "github.com/bytedance/sonic"
10 gojson "github.com/goccy/go-json"
11 )
12
13 // The benchmarks of the requests and the responses of the APIs of large language models, which coding agents
14 // exchange at every step: the OpenAI Chat Completions API ( /v1/chat/completions ), the OpenAI Responses API
15 // ( /v1/responses ) and the Anthropic Messages API ( /v1/messages ).
16 //
17 // The payloads are one session of a coding agent in the format of each API, generated after the references of
18 // the APIs ( see llm_payload_test.go ): a system prompt, tool definitions by JSON Schema, and turns of tool calls
19 // whose results are source files, then an answer with text and a tool call. Each API has:
20 //
21 // - a request, whose encoding is measured ( Encode ): the conversation so far, sent at every step.
22 // - a response, whose decoding is measured ( Decode ).
23 // - a stream of the events of the same response, as server-sent events deliver them one JSON document at a
24 // time: the decoding of every event is measured ( Decode ...Stream ). Most events carry a few bytes of
25 // text, so a stream measures the cost of a call more than the one of a byte.
26 //
27 // The types are the ones Go programs decode these APIs into: the ones of github.com/sashabaranov/go-openai for
28 // the Chat Completions API, and types of the same kind for the others, with json.RawMessage for the input of
29 // a tool as in the Anthropic SDK.
30
31 // JSONSchema is a JSON Schema of the parameters of a tool, as jsonschema.Definition of go-openai.
32 type JSONSchema struct {
33 Type string `json:"type,omitempty"`
34 Description string `json:"description,omitempty"`
35 Enum []string `json:"enum,omitempty"`
36 Properties map[string]JSONSchema `json:"properties,omitempty"`
37 Required []string `json:"required,omitempty"`
38 Items *JSONSchema `json:"items,omitempty"`
39 AdditionalProperties any `json:"additionalProperties,omitempty"`
40 Default any `json:"default,omitempty"`
41 Minimum *float64 `json:"minimum,omitempty"`
42 Maximum *float64 `json:"maximum,omitempty"`
43 }
44
45 // ---------------------------------------------------------------- OpenAI Chat Completions
46
47 type ChatCompletionRequest struct {
48 Model string `json:"model"`
49 Messages []ChatCompletionMessage `json:"messages"`
50 MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
51 Temperature float32 `json:"temperature,omitempty"`
52 Stream bool `json:"stream,omitempty"`
53 StreamOptions *ChatStreamOptions `json:"stream_options,omitempty"`
54 Tools []ChatTool `json:"tools,omitempty"`
55 ToolChoice any `json:"tool_choice,omitempty"`
56 ParallelToolCalls any `json:"parallel_tool_calls,omitempty"`
57 ReasoningEffort string `json:"reasoning_effort,omitempty"`
58 PromptCacheKey string `json:"prompt_cache_key,omitempty"`
59 }
60
61 type ChatStreamOptions struct {
62 IncludeUsage bool `json:"include_usage,omitempty"`
63 }
64
65 type ChatTool struct {
66 Type string `json:"type"`
67 Function *ChatFunctionDefinition `json:"function,omitempty"`
68 }
69
70 type ChatFunctionDefinition struct {
71 Name string `json:"name"`
72 Description string `json:"description,omitempty"`
73 Strict bool `json:"strict,omitempty"`
74 Parameters JSONSchema `json:"parameters"`
75 }
76
77 type ChatCompletionMessage struct {
78 Role string `json:"role"`
79 Content string `json:"content,omitempty"`
80 Refusal string `json:"refusal,omitempty"`
81 Name string `json:"name,omitempty"`
82 ToolCalls []ChatToolCall `json:"tool_calls,omitempty"`
83 ToolCallID string `json:"tool_call_id,omitempty"`
84 }
85
86 type ChatToolCall struct {
87 Index *int `json:"index,omitempty"`
88 ID string `json:"id,omitempty"`
89 Type string `json:"type"`
90 Function ChatFunctionCall `json:"function"`
91 }
92
93 type ChatFunctionCall struct {
94 Name string `json:"name,omitempty"`
95 Arguments string `json:"arguments,omitempty"`
96 }
97
98 type ChatCompletionResponse struct {
99 ID string `json:"id"`
100 Object string `json:"object"`
101 Created int64 `json:"created"`
102 Model string `json:"model"`
103 Choices []ChatCompletionChoice `json:"choices"`
104 Usage ChatUsage `json:"usage"`
105 SystemFingerprint string `json:"system_fingerprint"`
106 ServiceTier string `json:"service_tier,omitempty"`
107 }
108
109 type ChatCompletionChoice struct {
110 Index int `json:"index"`
111 Message ChatCompletionMessage `json:"message"`
112 FinishReason string `json:"finish_reason"`
113 LogProbs *ChatLogProbs `json:"logprobs,omitempty"`
114 }
115
116 type ChatLogProbs struct {
117 Content []ChatLogProb `json:"content"`
118 }
119
120 type ChatLogProb struct {
121 Token string `json:"token"`
122 LogProb float64 `json:"logprob"`
123 Bytes []byte `json:"bytes,omitempty"`
124 }
125
126 type ChatUsage struct {
127 PromptTokens int `json:"prompt_tokens"`
128 CompletionTokens int `json:"completion_tokens"`
129 TotalTokens int `json:"total_tokens"`
130 PromptTokensDetails *ChatPromptTokensDetails `json:"prompt_tokens_details"`
131 CompletionTokensDetails *ChatCompletionTokensDetails `json:"completion_tokens_details"`
132 }
133
134 type ChatPromptTokensDetails struct {
135 AudioTokens int `json:"audio_tokens"`
136 CachedTokens int `json:"cached_tokens"`
137 }
138
139 type ChatCompletionTokensDetails struct {
140 AudioTokens int `json:"audio_tokens"`
141 ReasoningTokens int `json:"reasoning_tokens"`
142 AcceptedPredictionTokens int `json:"accepted_prediction_tokens"`
143 RejectedPredictionTokens int `json:"rejected_prediction_tokens"`
144 }
145
146 type ChatCompletionStreamResponse struct {
147 ID string `json:"id"`
148 Object string `json:"object"`
149 Created int64 `json:"created"`
150 Model string `json:"model"`
151 Choices []ChatCompletionStreamChoice `json:"choices"`
152 SystemFingerprint string `json:"system_fingerprint"`
153 ServiceTier string `json:"service_tier,omitempty"`
154 Usage *ChatUsage `json:"usage,omitempty"`
155 }
156
157 type ChatCompletionStreamChoice struct {
158 Index int `json:"index"`
159 Delta ChatCompletionStreamChoiceDelta `json:"delta"`
160 LogProbs *ChatLogProbs `json:"logprobs,omitempty"`
161 FinishReason string `json:"finish_reason"`
162 }
163
164 type ChatCompletionStreamChoiceDelta struct {
165 Content string `json:"content,omitempty"`
166 Role string `json:"role,omitempty"`
167 ToolCalls []ChatToolCall `json:"tool_calls,omitempty"`
168 Refusal string `json:"refusal,omitempty"`
169 }
170
171 // ---------------------------------------------------------------- OpenAI Responses
172
173 type ResponsesRequest struct {
174 Model string `json:"model"`
175 Instructions string `json:"instructions,omitempty"`
176 Input []ResponseInputItem `json:"input"`
177 Tools []ResponseTool `json:"tools,omitempty"`
178 ToolChoice string `json:"tool_choice,omitempty"`
179 ParallelToolCalls bool `json:"parallel_tool_calls,omitempty"`
180 Reasoning *ResponseReasoning `json:"reasoning,omitempty"`
181 Store bool `json:"store"`
182 Stream bool `json:"stream,omitempty"`
183 Include []string `json:"include,omitempty"`
184 PromptCacheKey string `json:"prompt_cache_key,omitempty"`
185 MaxOutputTokens int `json:"max_output_tokens,omitempty"`
186 Text *ResponseTextOptions `json:"text,omitempty"`
187 }
188
189 type ResponseInputItem struct {
190 Type string `json:"type"`
191 ID string `json:"id,omitempty"`
192 Status string `json:"status,omitempty"`
193 Role string `json:"role,omitempty"`
194 Content []ResponseContent `json:"content,omitempty"`
195 CallID string `json:"call_id,omitempty"`
196 Name string `json:"name,omitempty"`
197 Arguments string `json:"arguments,omitempty"`
198 Output string `json:"output,omitempty"`
199 }
200
201 type ResponseContent struct {
202 Type string `json:"type"`
203 Text string `json:"text"`
204 Annotations []ResponseAnnotation `json:"annotations,omitempty"`
205 Logprobs []ResponseLogprob `json:"logprobs,omitempty"`
206 }
207
208 type ResponseAnnotation struct {
209 Type string `json:"type"`
210 URL string `json:"url,omitempty"`
211 Title string `json:"title,omitempty"`
212 StartIndex int `json:"start_index,omitempty"`
213 EndIndex int `json:"end_index,omitempty"`
214 }
215
216 type ResponseLogprob struct {
217 Token string `json:"token"`
218 Logprob float64 `json:"logprob"`
219 }
220
221 type ResponseTool struct {
222 Type string `json:"type"`
223 Name string `json:"name"`
224 Description string `json:"description,omitempty"`
225 Parameters JSONSchema `json:"parameters"`
226 Strict bool `json:"strict"`
227 }
228
229 type ResponseReasoning struct {
230 Effort string `json:"effort,omitempty"`
231 Summary string `json:"summary,omitempty"`
232 }
233
234 type ResponseTextOptions struct {
235 Format *ResponseTextFormat `json:"format,omitempty"`
236 Verbosity string `json:"verbosity,omitempty"`
237 }
238
239 type ResponseTextFormat struct {
240 Type string `json:"type"`
241 }
242
243 type Response struct {
244 ID string `json:"id"`
245 Object string `json:"object"`
246 CreatedAt int64 `json:"created_at"`
247 Status string `json:"status"`
248 Background bool `json:"background"`
249 Error *ResponseError `json:"error"`
250 IncompleteDetails *ResponseIncomplete `json:"incomplete_details"`
251 Instructions string `json:"instructions"`
252 MaxOutputTokens *int `json:"max_output_tokens"`
253 MaxToolCalls *int `json:"max_tool_calls"`
254 Model string `json:"model"`
255 Output []ResponseOutputItem `json:"output"`
256 ParallelToolCalls bool `json:"parallel_tool_calls"`
257 PreviousResponseID *string `json:"previous_response_id"`
258 PromptCacheKey string `json:"prompt_cache_key"`
259 Reasoning ResponseReasoning `json:"reasoning"`
260 SafetyIdentifier *string `json:"safety_identifier"`
261 ServiceTier string `json:"service_tier"`
262 Store bool `json:"store"`
263 Temperature float64 `json:"temperature"`
264 Text ResponseTextOptions `json:"text"`
265 ToolChoice any `json:"tool_choice"`
266 Tools []ResponseTool `json:"tools"`
267 TopLogprobs int `json:"top_logprobs"`
268 TopP float64 `json:"top_p"`
269 Truncation string `json:"truncation"`
270 Usage *ResponseUsage `json:"usage"`
271 User *string `json:"user"`
272 Metadata map[string]string `json:"metadata"`
273 }
274
275 type ResponseError struct {
276 Code string `json:"code"`
277 Message string `json:"message"`
278 }
279
280 type ResponseIncomplete struct {
281 Reason string `json:"reason"`
282 }
283
284 type ResponseOutputItem struct {
285 ID string `json:"id"`
286 Type string `json:"type"`
287 Status string `json:"status,omitempty"`
288 Role string `json:"role,omitempty"`
289 Content []ResponseContent `json:"content,omitempty"`
290 Summary []ResponseSummary `json:"summary,omitempty"`
291 EncryptedContent *string `json:"encrypted_content,omitempty"`
292 CallID string `json:"call_id,omitempty"`
293 Name string `json:"name,omitempty"`
294 Arguments string `json:"arguments,omitempty"`
295 }
296
297 type ResponseSummary struct {
298 Type string `json:"type"`
299 Text string `json:"text"`
300 }
301
302 type ResponseUsage struct {
303 InputTokens int `json:"input_tokens"`
304 InputTokensDetails struct {
305 CachedTokens int `json:"cached_tokens"`
306 } `json:"input_tokens_details"`
307 OutputTokens int `json:"output_tokens"`
308 OutputTokensDetails struct {
309 ReasoningTokens int `json:"reasoning_tokens"`
310 } `json:"output_tokens_details"`
311 TotalTokens int `json:"total_tokens"`
312 }
313
314 type ResponseStreamEvent struct {
315 Type string `json:"type"`
316 SequenceNumber int `json:"sequence_number"`
317 Response *Response `json:"response,omitempty"`
318 OutputIndex int `json:"output_index"`
319 ItemID string `json:"item_id,omitempty"`
320 ContentIndex int `json:"content_index"`
321 SummaryIndex int `json:"summary_index"`
322 Item *ResponseOutputItem `json:"item,omitempty"`
323 Part *ResponseContent `json:"part,omitempty"`
324 Delta string `json:"delta,omitempty"`
325 Text string `json:"text,omitempty"`
326 Arguments string `json:"arguments,omitempty"`
327 Logprobs []ResponseLogprob `json:"logprobs,omitempty"`
328 Obfuscation string `json:"obfuscation,omitempty"`
329 }
330
331 // ---------------------------------------------------------------- Anthropic Messages
332
333 type MessagesRequest struct {
334 Model string `json:"model"`
335 MaxTokens int `json:"max_tokens"`
336 System []AnthropicBlock `json:"system,omitempty"`
337 Messages []AnthropicMessage `json:"messages"`
338 Tools []AnthropicTool `json:"tools,omitempty"`
339 ToolChoice *AnthropicChoice `json:"tool_choice,omitempty"`
340 Thinking *AnthropicThinking `json:"thinking,omitempty"`
341 Stream bool `json:"stream,omitempty"`
342 Metadata *AnthropicMetadata `json:"metadata,omitempty"`
343 }
344
345 type AnthropicMessage struct {
346 Role string `json:"role"`
347 Content []AnthropicBlock `json:"content"`
348 }
349
350 // AnthropicBlock is a block of content of any type: text, tool_use, tool_result, thinking.
351 type AnthropicBlock struct {
352 Type string `json:"type"`
353 Text string `json:"text,omitempty"`
354 ID string `json:"id,omitempty"`
355 Name string `json:"name,omitempty"`
356 Input stdjson.RawMessage `json:"input,omitempty"`
357 ToolUseID string `json:"tool_use_id,omitempty"`
358 Content string `json:"content,omitempty"`
359 IsError bool `json:"is_error,omitempty"`
360 Thinking string `json:"thinking,omitempty"`
361 Signature string `json:"signature,omitempty"`
362 CacheControl *AnthropicCacheCtrl `json:"cache_control,omitempty"`
363 }
364
365 type AnthropicCacheCtrl struct {
366 Type string `json:"type"`
367 }
368
369 type AnthropicTool struct {
370 Name string `json:"name"`
371 Description string `json:"description,omitempty"`
372 InputSchema JSONSchema `json:"input_schema"`
373 CacheControl *AnthropicCacheCtrl `json:"cache_control,omitempty"`
374 }
375
376 type AnthropicChoice struct {
377 Type string `json:"type"`
378 }
379
380 type AnthropicThinking struct {
381 Type string `json:"type"`
382 BudgetTokens int `json:"budget_tokens,omitempty"`
383 }
384
385 type AnthropicMetadata struct {
386 UserID string `json:"user_id,omitempty"`
387 }
388
389 type MessagesResponse struct {
390 ID string `json:"id"`
391 Type string `json:"type"`
392 Role string `json:"role"`
393 Model string `json:"model"`
394 Content []AnthropicBlock `json:"content"`
395 StopReason string `json:"stop_reason"`
396 StopSequence *string `json:"stop_sequence"`
397 Usage AnthropicUsage `json:"usage"`
398 }
399
400 type AnthropicUsage struct {
401 InputTokens int `json:"input_tokens"`
402 CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
403 CacheReadInputTokens int `json:"cache_read_input_tokens"`
404 CacheCreation *AnthropicCacheCreation `json:"cache_creation,omitempty"`
405 OutputTokens int `json:"output_tokens"`
406 ServiceTier string `json:"service_tier,omitempty"`
407 }
408
409 type AnthropicCacheCreation struct {
410 Ephemeral5mInputTokens int `json:"ephemeral_5m_input_tokens"`
411 Ephemeral1hInputTokens int `json:"ephemeral_1h_input_tokens"`
412 }
413
414 type MessageStreamEvent struct {
415 Type string `json:"type"`
416 Message *MessagesResponse `json:"message,omitempty"`
417 Index int `json:"index"`
418 ContentBlock *AnthropicBlock `json:"content_block,omitempty"`
419 Delta *MessageDelta `json:"delta,omitempty"`
420 Usage *AnthropicUsage `json:"usage,omitempty"`
421 }
422
423 type MessageDelta struct {
424 Type string `json:"type,omitempty"`
425 Text string `json:"text,omitempty"`
426 PartialJSON string `json:"partial_json,omitempty"`
427 Thinking string `json:"thinking,omitempty"`
428 Signature string `json:"signature,omitempty"`
429 StopReason string `json:"stop_reason,omitempty"`
430 StopSequence *string `json:"stop_sequence,omitempty"`
431 }
432
433 // ---------------------------------------------------------------- payloads
434
435 var (
436 openAIChatRequestJSON = openAIChatRequestPayload()
437 openAIChatResponseJSON = openAIChatResponsePayload()
438 openAIChatStream = openAIChatStreamPayload()
439 openAIResponsesRequestJSON = openAIResponsesRequestPayload()
440 openAIResponsesResponseJSON = openAIResponsesResponsePayload()
441 openAIResponsesStream = openAIResponsesStreamPayload()
442 anthropicRequestJSON = anthropicRequestPayload()
443 anthropicResponseJSON = anthropicResponsePayload()
444 anthropicStream = anthropicStreamPayload()
445
446 openAIChatRequest = mustDecode[ChatCompletionRequest](openAIChatRequestJSON)
447 openAIResponsesRequest = mustDecode[ResponsesRequest](openAIResponsesRequestJSON)
448 anthropicRequest = mustDecode[MessagesRequest](anthropicRequestJSON)
449 )
450
451 func mustDecode[T any](data []byte) *T {
452 var v T
453 if err := stdjson.Unmarshal(data, &v); err != nil {
454 panic(err)
455 }
456 return &v
457 }
458
459 func init() {
460 for _, v := range []any{
461 ChatCompletionRequest{}, ChatCompletionResponse{}, ChatCompletionStreamResponse{},
462 ResponsesRequest{}, Response{}, ResponseStreamEvent{},
463 MessagesRequest{}, MessagesResponse{}, MessageStreamEvent{},
464 } {
465 sonicTypes = append(sonicTypes, reflect.TypeOf(v))
466 }
467 }
468
469 func TestLLMPayloads(t *testing.T) {
470 // go-json decodes the responses and the events as encoding/json does, and encodes the requests to the same
471 // bytes.
472 checkDecode[ChatCompletionResponse](t, openAIChatResponseJSON)
473 checkDecode[Response](t, openAIResponsesResponseJSON)
474 checkDecode[MessagesResponse](t, anthropicResponseJSON)
475 for _, line := range openAIChatStream {
476 checkDecode[ChatCompletionStreamResponse](t, line)
477 }
478 for _, line := range openAIResponsesStream {
479 checkDecode[ResponseStreamEvent](t, line)
480 }
481 for _, line := range anthropicStream {
482 checkDecode[MessageStreamEvent](t, line)
483 }
484 for _, v := range []any{openAIChatRequest, openAIResponsesRequest, anthropicRequest} {
485 want, err := stdjson.Marshal(v)
486 if err != nil {
487 t.Fatal(err)
488 }
489 got, err := gojson.Marshal(v)
490 if err != nil {
491 t.Fatal(err)
492 }
493 if !bytes.Equal(got, want) {
494 t.Fatalf("%T encodes differently", v)
495 }
496 }
497 }
498
499 func checkDecode[T any](t *testing.T, data []byte) {
500 t.Helper()
501 var want, got T
502 if err := stdjson.Unmarshal(data, &want); err != nil {
503 t.Fatal(err)
504 }
505 if err := gojson.Unmarshal(data, &got); err != nil {
506 t.Fatalf("%s: %v", data, err)
507 }
508 if !reflect.DeepEqual(got, want) {
509 t.Fatalf("%s decodes differently:\n got %+v\nwant %+v", data, got, want)
510 }
511 }
512
513 // benchDecodeStream decodes every event of a stream into a new value, as a client does with the data of the
514 // server-sent events.
515 func benchDecodeStream[T any](b *testing.B, events [][]byte, unmarshal func([]byte, any) error) {
516 n := 0
517 for _, e := range events {
518 n += len(e)
519 }
520 b.SetBytes(int64(n))
521 b.ReportAllocs()
522 b.ResetTimer()
523 for i := 0; i < b.N; i++ {
524 for _, e := range events {
525 var v T
526 if err := unmarshal(e, &v); err != nil {
527 b.Fatal(err)
528 }
529 }
530 }
531 }
532
533 func benchDecodeStreamOf[T any](b *testing.B, events [][]byte) {
534 n := 0
535 for _, e := range events {
536 n += len(e)
537 }
538 b.SetBytes(int64(n))
539 b.ReportAllocs()
540 b.ResetTimer()
541 for i := 0; i < b.N; i++ {
542 for _, e := range events {
543 var v T
544 if err := gojson.UnmarshalOf(e, &v); err != nil {
545 b.Fatal(err)
546 }
547 }
548 }
549 }
550
551 func benchEncode(b *testing.B, v any, marshal func(any) ([]byte, error)) {
552 data, err := marshal(v)
553 if err != nil {
554 b.Fatal(err)
555 }
556 b.SetBytes(int64(len(data)))
557 b.ReportAllocs()
558 b.ResetTimer()
559 for i := 0; i < b.N; i++ {
560 if _, err := marshal(v); err != nil {
561 b.Fatal(err)
562 }
563 }
564 }
565
566 func marshalLikeSonic(v any) ([]byte, error) { return gojson.MarshalWithOption(v, likeSonicOptions...) }
567
568 // ---------------------------------------------------------------- OpenAI Chat Completions benchmarks
569
570 func Benchmark_Decode_OpenAIChatCompletion_Unmarshal_EncodingJson(b *testing.B) {
571 benchDecode[ChatCompletionResponse](b, openAIChatResponseJSON, stdjson.Unmarshal)
572 }
573
574 func Benchmark_Decode_OpenAIChatCompletion_Unmarshal_GoJson(b *testing.B) {
575 benchDecode[ChatCompletionResponse](b, openAIChatResponseJSON, gojson.Unmarshal)
576 }
577
578 func Benchmark_Decode_OpenAIChatCompletion_Unmarshal_GoJsonUnmarshalOf(b *testing.B) {
579 benchDecodeOf[ChatCompletionResponse](b, openAIChatResponseJSON)
580 }
581
582 func Benchmark_Decode_OpenAIChatCompletion_Unmarshal_Sonic(b *testing.B) {
583 pretouchSonic()
584 benchDecode[ChatCompletionResponse](b, openAIChatResponseJSON, sonic.ConfigDefault.Unmarshal)
585 }
586
587 func Benchmark_Decode_OpenAIChatCompletion_Unmarshal_SonicStd(b *testing.B) {
588 pretouchSonic()
589 benchDecode[ChatCompletionResponse](b, openAIChatResponseJSON, sonic.ConfigStd.Unmarshal)
590 }
591
592 func Benchmark_Decode_OpenAIChatCompletionStream_Unmarshal_EncodingJson(b *testing.B) {
593 benchDecodeStream[ChatCompletionStreamResponse](b, openAIChatStream, stdjson.Unmarshal)
594 }
595
596 func Benchmark_Decode_OpenAIChatCompletionStream_Unmarshal_GoJson(b *testing.B) {
597 benchDecodeStream[ChatCompletionStreamResponse](b, openAIChatStream, gojson.Unmarshal)
598 }
599
600 func Benchmark_Decode_OpenAIChatCompletionStream_Unmarshal_GoJsonUnmarshalOf(b *testing.B) {
601 benchDecodeStreamOf[ChatCompletionStreamResponse](b, openAIChatStream)
602 }
603
604 func Benchmark_Decode_OpenAIChatCompletionStream_Unmarshal_Sonic(b *testing.B) {
605 pretouchSonic()
606 benchDecodeStream[ChatCompletionStreamResponse](b, openAIChatStream, sonic.ConfigDefault.Unmarshal)
607 }
608
609 func Benchmark_Decode_OpenAIChatCompletionStream_Unmarshal_SonicStd(b *testing.B) {
610 pretouchSonic()
611 benchDecodeStream[ChatCompletionStreamResponse](b, openAIChatStream, sonic.ConfigStd.Unmarshal)
612 }
613
614 func Benchmark_Encode_OpenAIChatCompletionRequest_EncodingJson(b *testing.B) {
615 benchEncode(b, openAIChatRequest, stdjson.Marshal)
616 }
617
618 func Benchmark_Encode_OpenAIChatCompletionRequest_GoJson(b *testing.B) {
619 benchEncode(b, openAIChatRequest, gojson.Marshal)
620 }
621
622 func Benchmark_Encode_OpenAIChatCompletionRequest_GoJsonLikeSonic(b *testing.B) {
623 benchEncode(b, openAIChatRequest, marshalLikeSonic)
624 }
625
626 func Benchmark_Encode_OpenAIChatCompletionRequest_Sonic(b *testing.B) {
627 pretouchSonic()
628 benchEncode(b, openAIChatRequest, sonic.ConfigDefault.Marshal)
629 }
630
631 func Benchmark_Encode_OpenAIChatCompletionRequest_SonicStd(b *testing.B) {
632 pretouchSonic()
633 benchEncode(b, openAIChatRequest, sonic.ConfigStd.Marshal)
634 }
635
636 // ---------------------------------------------------------------- OpenAI Responses benchmarks
637
638 func Benchmark_Decode_OpenAIResponse_Unmarshal_EncodingJson(b *testing.B) {
639 benchDecode[Response](b, openAIResponsesResponseJSON, stdjson.Unmarshal)
640 }
641
642 func Benchmark_Decode_OpenAIResponse_Unmarshal_GoJson(b *testing.B) {
643 benchDecode[Response](b, openAIResponsesResponseJSON, gojson.Unmarshal)
644 }
645
646 func Benchmark_Decode_OpenAIResponse_Unmarshal_GoJsonUnmarshalOf(b *testing.B) {
647 benchDecodeOf[Response](b, openAIResponsesResponseJSON)
648 }
649
650 func Benchmark_Decode_OpenAIResponse_Unmarshal_Sonic(b *testing.B) {
651 pretouchSonic()
652 benchDecode[Response](b, openAIResponsesResponseJSON, sonic.ConfigDefault.Unmarshal)
653 }
654
655 func Benchmark_Decode_OpenAIResponse_Unmarshal_SonicStd(b *testing.B) {
656 pretouchSonic()
657 benchDecode[Response](b, openAIResponsesResponseJSON, sonic.ConfigStd.Unmarshal)
658 }
659
660 func Benchmark_Decode_OpenAIResponseStream_Unmarshal_EncodingJson(b *testing.B) {
661 benchDecodeStream[ResponseStreamEvent](b, openAIResponsesStream, stdjson.Unmarshal)
662 }
663
664 func Benchmark_Decode_OpenAIResponseStream_Unmarshal_GoJson(b *testing.B) {
665 benchDecodeStream[ResponseStreamEvent](b, openAIResponsesStream, gojson.Unmarshal)
666 }
667
668 func Benchmark_Decode_OpenAIResponseStream_Unmarshal_GoJsonUnmarshalOf(b *testing.B) {
669 benchDecodeStreamOf[ResponseStreamEvent](b, openAIResponsesStream)
670 }
671
672 func Benchmark_Decode_OpenAIResponseStream_Unmarshal_Sonic(b *testing.B) {
673 pretouchSonic()
674 benchDecodeStream[ResponseStreamEvent](b, openAIResponsesStream, sonic.ConfigDefault.Unmarshal)
675 }
676
677 func Benchmark_Decode_OpenAIResponseStream_Unmarshal_SonicStd(b *testing.B) {
678 pretouchSonic()
679 benchDecodeStream[ResponseStreamEvent](b, openAIResponsesStream, sonic.ConfigStd.Unmarshal)
680 }
681
682 func Benchmark_Encode_OpenAIResponseRequest_EncodingJson(b *testing.B) {
683 benchEncode(b, openAIResponsesRequest, stdjson.Marshal)
684 }
685
686 func Benchmark_Encode_OpenAIResponseRequest_GoJson(b *testing.B) {
687 benchEncode(b, openAIResponsesRequest, gojson.Marshal)
688 }
689
690 func Benchmark_Encode_OpenAIResponseRequest_GoJsonLikeSonic(b *testing.B) {
691 benchEncode(b, openAIResponsesRequest, marshalLikeSonic)
692 }
693
694 func Benchmark_Encode_OpenAIResponseRequest_Sonic(b *testing.B) {
695 pretouchSonic()
696 benchEncode(b, openAIResponsesRequest, sonic.ConfigDefault.Marshal)
697 }
698
699 func Benchmark_Encode_OpenAIResponseRequest_SonicStd(b *testing.B) {
700 pretouchSonic()
701 benchEncode(b, openAIResponsesRequest, sonic.ConfigStd.Marshal)
702 }
703
704 // ---------------------------------------------------------------- Anthropic Messages benchmarks
705
706 func Benchmark_Decode_AnthropicMessage_Unmarshal_EncodingJson(b *testing.B) {
707 benchDecode[MessagesResponse](b, anthropicResponseJSON, stdjson.Unmarshal)
708 }
709
710 func Benchmark_Decode_AnthropicMessage_Unmarshal_GoJson(b *testing.B) {
711 benchDecode[MessagesResponse](b, anthropicResponseJSON, gojson.Unmarshal)
712 }
713
714 func Benchmark_Decode_AnthropicMessage_Unmarshal_GoJsonUnmarshalOf(b *testing.B) {
715 benchDecodeOf[MessagesResponse](b, anthropicResponseJSON)
716 }
717
718 func Benchmark_Decode_AnthropicMessage_Unmarshal_Sonic(b *testing.B) {
719 pretouchSonic()
720 benchDecode[MessagesResponse](b, anthropicResponseJSON, sonic.ConfigDefault.Unmarshal)
721 }
722
723 func Benchmark_Decode_AnthropicMessage_Unmarshal_SonicStd(b *testing.B) {
724 pretouchSonic()
725 benchDecode[MessagesResponse](b, anthropicResponseJSON, sonic.ConfigStd.Unmarshal)
726 }
727
728 func Benchmark_Decode_AnthropicMessageStream_Unmarshal_EncodingJson(b *testing.B) {
729 benchDecodeStream[MessageStreamEvent](b, anthropicStream, stdjson.Unmarshal)
730 }
731
732 func Benchmark_Decode_AnthropicMessageStream_Unmarshal_GoJson(b *testing.B) {
733 benchDecodeStream[MessageStreamEvent](b, anthropicStream, gojson.Unmarshal)
734 }
735
736 func Benchmark_Decode_AnthropicMessageStream_Unmarshal_GoJsonUnmarshalOf(b *testing.B) {
737 benchDecodeStreamOf[MessageStreamEvent](b, anthropicStream)
738 }
739
740 func Benchmark_Decode_AnthropicMessageStream_Unmarshal_Sonic(b *testing.B) {
741 pretouchSonic()
742 benchDecodeStream[MessageStreamEvent](b, anthropicStream, sonic.ConfigDefault.Unmarshal)
743 }
744
745 func Benchmark_Decode_AnthropicMessageStream_Unmarshal_SonicStd(b *testing.B) {
746 pretouchSonic()
747 benchDecodeStream[MessageStreamEvent](b, anthropicStream, sonic.ConfigStd.Unmarshal)
748 }
749
750 func Benchmark_Encode_AnthropicMessageRequest_EncodingJson(b *testing.B) {
751 benchEncode(b, anthropicRequest, stdjson.Marshal)
752 }
753
754 func Benchmark_Encode_AnthropicMessageRequest_GoJson(b *testing.B) {
755 benchEncode(b, anthropicRequest, gojson.Marshal)
756 }
757
758 func Benchmark_Encode_AnthropicMessageRequest_GoJsonLikeSonic(b *testing.B) {
759 benchEncode(b, anthropicRequest, marshalLikeSonic)
760 }
761
762 func Benchmark_Encode_AnthropicMessageRequest_Sonic(b *testing.B) {
763 pretouchSonic()
764 benchEncode(b, anthropicRequest, sonic.ConfigDefault.Marshal)
765 }
766
767 func Benchmark_Encode_AnthropicMessageRequest_SonicStd(b *testing.B) {
768 pretouchSonic()
769 benchEncode(b, anthropicRequest, sonic.ConfigStd.Marshal)
770 }
771
772 // ---------------------------------------------------------------- the fastest configurations ( see sonic_decode_test.go )
773
774 // benchDecodeStreamSonicFastest decodes every event of a stream by sonic at its fastest, as strings.
775 func benchDecodeStreamSonicFastest[T any](b *testing.B, events [][]byte) {
776 benchDecodeStreamSonicString[T](b, sonic.ConfigFastest, events)
777 }
778
779 // benchDecodeStreamSonicFastestValidating decodes every event of a stream as benchDecodeStreamSonicFastest does,
780 // with the checks of go-json ( see sonicFastestValidating ).
781 func benchDecodeStreamSonicFastestValidating[T any](b *testing.B, events [][]byte) {
782 benchDecodeStreamSonicString[T](b, sonicFastestValidating, events)
783 }
784
785 // benchDecodeStreamSonicString decodes every event of a stream by api, as strings.
786 func benchDecodeStreamSonicString[T any](b *testing.B, api sonic.API, events [][]byte) {
787 strs := make([]string, len(events))
788 n := 0
789 for i, e := range events {
790 strs[i] = string(e)
791 n += len(e)
792 }
793 b.SetBytes(int64(n))
794 b.ReportAllocs()
795 b.ResetTimer()
796 for i := 0; i < b.N; i++ {
797 for _, e := range strs {
798 var v T
799 if err := api.UnmarshalFromString(e, &v); err != nil {
800 b.Fatal(err)
801 }
802 }
803 }
804 }
805
806 // benchDecodeStreamNoCopy decodes every event of a stream by go-json at its fastest.
807 func benchDecodeStreamNoCopy[T any](b *testing.B, events [][]byte) {
808 n := 0
809 for _, e := range events {
810 n += len(e)
811 }
812 b.SetBytes(int64(n))
813 b.ReportAllocs()
814 b.ResetTimer()
815 for i := 0; i < b.N; i++ {
816 for _, e := range events {
817 var v T
818 if err := gojson.UnmarshalOf(e, &v, gojson.DecodeNoCopyString()); err != nil {
819 b.Fatal(err)
820 }
821 }
822 }
823 }
824
825 func Benchmark_Decode_OpenAIChatCompletion_Unmarshal_GoJsonUnmarshalOfNoCopyString(b *testing.B) {
826 benchDecodeNoCopy[ChatCompletionResponse](b, openAIChatResponseJSON)
827 }
828
829 func Benchmark_Decode_OpenAIChatCompletion_Unmarshal_SonicFastest(b *testing.B) {
830 pretouchSonic()
831 benchDecodeSonicFastest[ChatCompletionResponse](b, openAIChatResponseJSON)
832 }
833
834 func Benchmark_Decode_OpenAIChatCompletion_Unmarshal_SonicFastestValidating(b *testing.B) {
835 pretouchSonic()
836 benchDecodeSonicFastestValidating[ChatCompletionResponse](b, openAIChatResponseJSON)
837 }
838
839 func Benchmark_Decode_OpenAIResponse_Unmarshal_GoJsonUnmarshalOfNoCopyString(b *testing.B) {
840 benchDecodeNoCopy[Response](b, openAIResponsesResponseJSON)
841 }
842
843 func Benchmark_Decode_OpenAIResponse_Unmarshal_SonicFastest(b *testing.B) {
844 pretouchSonic()
845 benchDecodeSonicFastest[Response](b, openAIResponsesResponseJSON)
846 }
847
848 func Benchmark_Decode_OpenAIResponse_Unmarshal_SonicFastestValidating(b *testing.B) {
849 pretouchSonic()
850 benchDecodeSonicFastestValidating[Response](b, openAIResponsesResponseJSON)
851 }
852
853 func Benchmark_Decode_AnthropicMessage_Unmarshal_GoJsonUnmarshalOfNoCopyString(b *testing.B) {
854 benchDecodeNoCopy[MessagesResponse](b, anthropicResponseJSON)
855 }
856
857 func Benchmark_Decode_AnthropicMessage_Unmarshal_SonicFastest(b *testing.B) {
858 pretouchSonic()
859 benchDecodeSonicFastest[MessagesResponse](b, anthropicResponseJSON)
860 }
861
862 func Benchmark_Decode_AnthropicMessage_Unmarshal_SonicFastestValidating(b *testing.B) {
863 pretouchSonic()
864 benchDecodeSonicFastestValidating[MessagesResponse](b, anthropicResponseJSON)
865 }
866
867 func Benchmark_Decode_OpenAIChatCompletionStream_Unmarshal_GoJsonUnmarshalOfNoCopyString(b *testing.B) {
868 benchDecodeStreamNoCopy[ChatCompletionStreamResponse](b, openAIChatStream)
869 }
870
871 func Benchmark_Decode_OpenAIChatCompletionStream_Unmarshal_SonicFastest(b *testing.B) {
872 pretouchSonic()
873 benchDecodeStreamSonicFastest[ChatCompletionStreamResponse](b, openAIChatStream)
874 }
875
876 func Benchmark_Decode_OpenAIChatCompletionStream_Unmarshal_SonicFastestValidating(b *testing.B) {
877 pretouchSonic()
878 benchDecodeStreamSonicFastestValidating[ChatCompletionStreamResponse](b, openAIChatStream)
879 }
880
881 func Benchmark_Decode_OpenAIResponseStream_Unmarshal_GoJsonUnmarshalOfNoCopyString(b *testing.B) {
882 benchDecodeStreamNoCopy[ResponseStreamEvent](b, openAIResponsesStream)
883 }
884
885 func Benchmark_Decode_OpenAIResponseStream_Unmarshal_SonicFastest(b *testing.B) {
886 pretouchSonic()
887 benchDecodeStreamSonicFastest[ResponseStreamEvent](b, openAIResponsesStream)
888 }
889
890 func Benchmark_Decode_OpenAIResponseStream_Unmarshal_SonicFastestValidating(b *testing.B) {
891 pretouchSonic()
892 benchDecodeStreamSonicFastestValidating[ResponseStreamEvent](b, openAIResponsesStream)
893 }
894
895 func Benchmark_Decode_AnthropicMessageStream_Unmarshal_GoJsonUnmarshalOfNoCopyString(b *testing.B) {
896 benchDecodeStreamNoCopy[MessageStreamEvent](b, anthropicStream)
897 }
898
899 func Benchmark_Decode_AnthropicMessageStream_Unmarshal_SonicFastest(b *testing.B) {
900 pretouchSonic()
901 benchDecodeStreamSonicFastest[MessageStreamEvent](b, anthropicStream)
902 }
903
904 func Benchmark_Decode_AnthropicMessageStream_Unmarshal_SonicFastestValidating(b *testing.B) {
905 pretouchSonic()
906 benchDecodeStreamSonicFastestValidating[MessageStreamEvent](b, anthropicStream)
907 }
908
909 func Benchmark_Encode_OpenAIChatCompletionRequest_SonicFastest(b *testing.B) {
910 pretouchSonic()
911 benchEncode(b, openAIChatRequest, sonic.ConfigFastest.Marshal)
912 }
913
914 func Benchmark_Encode_OpenAIChatCompletionRequest_SonicFastestValidating(b *testing.B) {
915 pretouchSonic()
916 benchEncode(b, openAIChatRequest, sonic.ConfigFastest.Marshal)
917 }
918
919 func Benchmark_Encode_OpenAIResponseRequest_SonicFastest(b *testing.B) {
920 pretouchSonic()
921 benchEncode(b, openAIResponsesRequest, sonic.ConfigFastest.Marshal)
922 }
923
924 func Benchmark_Encode_OpenAIResponseRequest_SonicFastestValidating(b *testing.B) {
925 pretouchSonic()
926 benchEncode(b, openAIResponsesRequest, sonic.ConfigFastest.Marshal)
927 }
928
929 func Benchmark_Encode_AnthropicMessageRequest_SonicFastest(b *testing.B) {
930 pretouchSonic()
931 benchEncode(b, anthropicRequest, sonic.ConfigFastest.Marshal)
932 }
933
934 func Benchmark_Encode_AnthropicMessageRequest_SonicFastestValidating(b *testing.B) {
935 pretouchSonic()
936 benchEncode(b, anthropicRequest, sonic.ConfigFastest.Marshal)
937 }