-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathformat_translate.go
More file actions
1501 lines (1367 loc) · 37.8 KB
/
format_translate.go
File metadata and controls
1501 lines (1367 loc) · 37.8 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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"log"
"strings"
)
// RequestFormat represents the API format of a request.
type RequestFormat int
const (
FormatUnknown RequestFormat = iota
FormatOpenAI // OpenAI Chat Completions API
FormatClaude // Anthropic Messages API
)
func (f RequestFormat) String() string {
switch f {
case FormatOpenAI:
return "openai"
case FormatClaude:
return "claude"
default:
return "unknown"
}
}
// TranslateDirection indicates which way we're translating.
type TranslateDirection int
const (
TranslateNone TranslateDirection = iota
TranslateClaudeToOAI // Client sent Claude format, upstream expects OpenAI Chat Completions
TranslateOAIToClaude // Client sent OpenAI format, upstream expects Claude
TranslateChatToResponses // Client sent Chat Completions, upstream expects Responses API
TranslateResponsesToClaude // Client sent Responses API, upstream expects Claude Messages
TranslateClaudeToResponses // Client sent Claude format, upstream expects Responses API
)
// detectRequestFormat determines the API format from the request path.
func detectRequestFormat(path string) RequestFormat {
switch {
case path == "/v1/messages" || strings.HasPrefix(path, "/v1/messages?"):
return FormatClaude
case strings.HasPrefix(path, "/v1/chat/completions"):
return FormatOpenAI
default:
return FormatUnknown
}
}
// providerTargetFormat returns the format the provider expects.
func providerTargetFormat(accountType AccountType) RequestFormat {
switch accountType {
case AccountTypeClaude:
return FormatClaude
case AccountTypeZAI:
return FormatClaude
case AccountTypeCodex:
return FormatOpenAI
default:
return FormatUnknown
}
}
// translateRequestBody translates a request body between formats.
func translateRequestBody(body []byte, src, dst RequestFormat) ([]byte, error) {
if src == dst || src == FormatUnknown || dst == FormatUnknown {
return body, nil
}
switch {
case src == FormatClaude && dst == FormatOpenAI:
return translateClaudeReqToOpenAI(body)
case src == FormatOpenAI && dst == FormatClaude:
return translateOpenAIReqToClaude(body)
}
return body, nil
}
// translateResponseBody translates a response body between formats.
// For error responses (status >= 400), use translateErrorBody instead.
func translateResponseBody(body []byte, src, dst RequestFormat, requestModel string) ([]byte, error) {
if src == dst || src == FormatUnknown || dst == FormatUnknown {
return body, nil
}
switch {
case src == FormatOpenAI && dst == FormatClaude:
return translateOpenAIRespToClaude(body, requestModel)
case src == FormatClaude && dst == FormatOpenAI:
return translateClaudeRespToOpenAI(body)
}
return body, nil
}
// translateErrorBody translates an error response body between formats so
// the client gets errors in its expected format.
func translateErrorBody(body []byte, src, dst RequestFormat) []byte {
if src == dst || src == FormatUnknown || dst == FormatUnknown {
return body
}
var parsed map[string]any
if err := json.Unmarshal(body, &parsed); err != nil {
return body // not JSON, return as-is
}
switch {
case src == FormatOpenAI && dst == FormatClaude:
return translateOpenAIErrorToClaude(parsed, body)
case src == FormatClaude && dst == FormatOpenAI:
return translateClaudeErrorToOpenAI(parsed, body)
}
return body
}
// translateOpenAIErrorToClaude converts an OpenAI error response to Claude format.
// OpenAI: {"error":{"message":"...","type":"...","code":"..."}}
// Claude: {"type":"error","error":{"type":"...","message":"..."}}
func translateOpenAIErrorToClaude(parsed map[string]any, original []byte) []byte {
errObj, ok := parsed["error"].(map[string]any)
if !ok {
return original
}
message, _ := errObj["message"].(string)
errType, _ := errObj["type"].(string)
if errType == "" {
errType = "api_error"
}
// Map OpenAI error types to Claude error types
claudeType := mapOAIErrorTypeToClaude(errType)
out, err := json.Marshal(map[string]any{
"type": "error",
"error": map[string]any{
"type": claudeType,
"message": message,
},
})
if err != nil {
return original
}
return out
}
// translateErrorToClaudeFormat converts a Codex/OpenAI error response to Claude
// Messages API error format. Handles both OpenAI-style errors
// ({"error":{"message":"..."}}) and Codex-style errors ({"detail":"..."}).
func translateErrorToClaudeFormat(body []byte, statusCode int) []byte {
var parsed map[string]any
if err := json.Unmarshal(body, &parsed); err != nil {
// Not JSON - wrap the raw text as a Claude error
msg := strings.TrimSpace(string(body))
if msg == "" {
msg = fmt.Sprintf("upstream error: HTTP %d", statusCode)
}
out, _ := json.Marshal(map[string]any{
"type": "error",
"error": map[string]any{
"type": "api_error",
"message": msg,
},
})
return out
}
// Try OpenAI error format: {"error":{"message":"...","type":"..."}}
if _, ok := parsed["error"].(map[string]any); ok {
return translateOpenAIErrorToClaude(parsed, body)
}
// Try Codex detail format: {"detail":"..."}
if detail, ok := parsed["detail"].(string); ok && detail != "" {
errType := "api_error"
if statusCode == 400 {
errType = "invalid_request_error"
} else if statusCode == 429 {
errType = "rate_limit_error"
}
out, _ := json.Marshal(map[string]any{
"type": "error",
"error": map[string]any{
"type": errType,
"message": detail,
},
})
return out
}
// Unknown format, return as-is
return body
}
// translateClaudeErrorToOpenAI converts a Claude error response to OpenAI format.
// Claude: {"type":"error","error":{"type":"...","message":"..."}}
// OpenAI: {"error":{"message":"...","type":"...","code":null}}
func translateClaudeErrorToOpenAI(parsed map[string]any, original []byte) []byte {
if t, _ := parsed["type"].(string); t != "error" {
return original
}
errObj, ok := parsed["error"].(map[string]any)
if !ok {
return original
}
message, _ := errObj["message"].(string)
errType, _ := errObj["type"].(string)
if errType == "" {
errType = "api_error"
}
oaiType := mapClaudeErrorTypeToOAI(errType)
out, err := json.Marshal(map[string]any{
"error": map[string]any{
"message": message,
"type": oaiType,
"code": nil,
},
})
if err != nil {
return original
}
return out
}
func mapOAIErrorTypeToClaude(oaiType string) string {
switch oaiType {
case "invalid_request_error":
return "invalid_request_error"
case "authentication_error":
return "authentication_error"
case "insufficient_quota", "billing_hard_limit_reached":
return "overloaded_error"
case "rate_limit_error":
return "rate_limit_error"
case "server_error", "service_unavailable_error":
return "api_error"
default:
return "api_error"
}
}
func mapClaudeErrorTypeToOAI(claudeType string) string {
switch claudeType {
case "invalid_request_error":
return "invalid_request_error"
case "authentication_error":
return "authentication_error"
case "rate_limit_error":
return "rate_limit_error"
case "overloaded_error":
return "server_error"
case "not_found_error":
return "invalid_request_error"
default:
return "server_error"
}
}
// --- Claude -> OpenAI request translation ---
func translateClaudeReqToOpenAI(body []byte) ([]byte, error) {
var claude map[string]any
if err := json.Unmarshal(body, &claude); err != nil {
return nil, fmt.Errorf("parse claude request: %w", err)
}
oai := map[string]any{}
// model
if m, ok := claude["model"].(string); ok {
oai["model"] = m
}
// Build messages
var msgs []map[string]any
// System message from top-level "system" field
if sys := extractClaudeSystem(claude["system"]); sys != "" {
msgs = append(msgs, map[string]any{"role": "system", "content": sys})
}
// Convert messages
if rawMsgs, ok := claude["messages"].([]any); ok {
for _, rm := range rawMsgs {
m, ok := rm.(map[string]any)
if !ok {
continue
}
converted := convertClaudeMsgToOpenAI(m)
msgs = append(msgs, converted...)
}
}
oai["messages"] = msgs
// Direct copy fields
for _, key := range []string{"model", "temperature", "top_p", "max_tokens"} {
if v, ok := claude[key]; ok {
oai[key] = v
}
}
// stop_sequences -> stop
if ss, ok := claude["stop_sequences"]; ok {
oai["stop"] = ss
}
// stream
if s, ok := claude["stream"].(bool); ok {
oai["stream"] = s
if s {
oai["stream_options"] = map[string]any{"include_usage": true}
}
}
// tools
if tools, ok := claude["tools"].([]any); ok && len(tools) > 0 {
oai["tools"] = convertClaudeToolsToOpenAI(tools)
}
// tool_choice
if tc, ok := claude["tool_choice"]; ok {
oai["tool_choice"] = convertClaudeToolChoiceToOpenAI(tc)
}
return json.Marshal(oai)
}
func extractClaudeSystem(sys any) string {
if sys == nil {
return ""
}
// String
if s, ok := sys.(string); ok {
return s
}
// Array of content blocks
if blocks, ok := sys.([]any); ok {
var parts []string
for _, b := range blocks {
if block, ok := b.(map[string]any); ok {
if t, ok := block["text"].(string); ok {
parts = append(parts, t)
}
}
}
if len(parts) > 0 {
result := parts[0]
for i := 1; i < len(parts); i++ {
result += "\n\n" + parts[i]
}
return result
}
}
return ""
}
func convertClaudeMsgToOpenAI(m map[string]any) []map[string]any {
role, _ := m["role"].(string)
content := m["content"]
// String content - simple case
if s, ok := content.(string); ok {
return []map[string]any{{"role": role, "content": s}}
}
// Array of content blocks
blocks, ok := content.([]any)
if !ok || len(blocks) == 0 {
return []map[string]any{{"role": role, "content": ""}}
}
// Check for tool_result blocks (these become separate tool messages)
var textParts []string
var toolCalls []map[string]any
var toolResults []map[string]any
var contentParts []map[string]any // multimodal content parts for OpenAI
hasImages := false
for _, b := range blocks {
block, ok := b.(map[string]any)
if !ok {
continue
}
blockType, _ := block["type"].(string)
switch blockType {
case "text":
if t, ok := block["text"].(string); ok {
textParts = append(textParts, t)
contentParts = append(contentParts, map[string]any{
"type": "text",
"text": t,
})
}
case "image":
// Convert Claude image block to OpenAI image_url
if source, ok := block["source"].(map[string]any); ok {
mediaType, _ := source["media_type"].(string)
data, _ := source["data"].(string)
if mediaType != "" && data != "" {
dataURL := "data:" + mediaType + ";base64," + data
contentParts = append(contentParts, map[string]any{
"type": "image_url",
"image_url": map[string]any{
"url": dataURL,
},
})
hasImages = true
}
}
case "tool_use":
tc := map[string]any{
"id": block["id"],
"type": "function",
"function": map[string]any{
"name": block["name"],
"arguments": marshalToolInput(block["input"]),
},
}
toolCalls = append(toolCalls, tc)
case "tool_result":
toolResults = append(toolResults, block)
case "thinking", "redacted_thinking":
// Skip thinking blocks - OpenAI doesn't support them in messages
}
}
var msgs []map[string]any
// If this is an assistant message with tool calls
if role == "assistant" && len(toolCalls) > 0 {
msg := map[string]any{"role": "assistant"}
if len(textParts) > 0 {
msg["content"] = joinStrings(textParts)
} else {
msg["content"] = nil
}
msg["tool_calls"] = toolCalls
msgs = append(msgs, msg)
return msgs
}
// If there are tool results, they become separate tool messages
if len(toolResults) > 0 {
for _, tr := range toolResults {
toolMsg := map[string]any{
"role": "tool",
"tool_call_id": tr["tool_use_id"],
"content": extractToolResultContent(tr["content"]),
}
msgs = append(msgs, toolMsg)
}
return msgs
}
// Plain text or multimodal message
msg := map[string]any{"role": role}
if hasImages {
// Use multimodal content array when images are present
msg["content"] = contentParts
} else if len(textParts) > 0 {
msg["content"] = joinStrings(textParts)
} else {
msg["content"] = ""
}
msgs = append(msgs, msg)
return msgs
}
func marshalToolInput(input any) string {
if input == nil {
return "{}"
}
if s, ok := input.(string); ok {
return s
}
b, err := json.Marshal(input)
if err != nil {
return "{}"
}
return string(b)
}
func extractToolResultContent(content any) string {
if content == nil {
return ""
}
if s, ok := content.(string); ok {
return s
}
// Array of content blocks
if blocks, ok := content.([]any); ok {
var parts []string
for _, b := range blocks {
if block, ok := b.(map[string]any); ok {
if t, ok := block["text"].(string); ok {
parts = append(parts, t)
}
}
}
return joinStrings(parts)
}
return ""
}
func convertClaudeToolsToOpenAI(tools []any) []map[string]any {
var out []map[string]any
for _, t := range tools {
tool, ok := t.(map[string]any)
if !ok {
continue
}
// Sanitize input_schema: strip fields that OpenAI rejects
params := tool["input_schema"]
if schema, ok := params.(map[string]any); ok {
params = sanitizeToolSchema(schema)
}
oaiTool := map[string]any{
"type": "function",
"function": map[string]any{
"name": tool["name"],
"parameters": params,
},
}
if desc, ok := tool["description"].(string); ok {
oaiTool["function"].(map[string]any)["description"] = desc
}
out = append(out, oaiTool)
}
return out
}
// sanitizeToolSchema recursively strips JSON Schema fields that OpenAI rejects.
// Currently strips: "format":"uri" (and other format values that cause issues).
func sanitizeToolSchema(schema map[string]any) map[string]any {
// Strip problematic format values
if f, ok := schema["format"].(string); ok {
switch f {
case "uri", "uri-reference", "iri", "iri-reference",
"uri-template", "json-pointer", "relative-json-pointer",
"regex", "idn-email", "idn-hostname":
delete(schema, "format")
}
}
// Recurse into properties
if props, ok := schema["properties"].(map[string]any); ok {
for key, val := range props {
if propSchema, ok := val.(map[string]any); ok {
props[key] = sanitizeToolSchema(propSchema)
}
}
}
// Recurse into items (array schemas)
if items, ok := schema["items"].(map[string]any); ok {
schema["items"] = sanitizeToolSchema(items)
}
// Recurse into additionalProperties
if ap, ok := schema["additionalProperties"].(map[string]any); ok {
schema["additionalProperties"] = sanitizeToolSchema(ap)
}
// Recurse into allOf/anyOf/oneOf
for _, key := range []string{"allOf", "anyOf", "oneOf"} {
if arr, ok := schema[key].([]any); ok {
for i, item := range arr {
if itemSchema, ok := item.(map[string]any); ok {
arr[i] = sanitizeToolSchema(itemSchema)
}
}
}
}
return schema
}
func convertClaudeToolChoiceToOpenAI(tc any) any {
if tc == nil {
return nil
}
// String values
if s, ok := tc.(string); ok {
switch s {
case "auto":
return "auto"
case "any":
return "required"
case "none":
return "none"
}
}
// Object form: {"type": "auto"}, {"type": "any"}, {"type": "tool", "name": "..."}
if obj, ok := tc.(map[string]any); ok {
tcType, _ := obj["type"].(string)
switch tcType {
case "auto":
return "auto"
case "any":
return "required"
case "tool":
return map[string]any{
"type": "function",
"function": map[string]any{
"name": obj["name"],
},
}
}
}
return "auto"
}
// --- OpenAI -> Claude request translation ---
func translateOpenAIReqToClaude(body []byte) ([]byte, error) {
var oai map[string]any
if err := json.Unmarshal(body, &oai); err != nil {
return nil, fmt.Errorf("parse openai request: %w", err)
}
claude := map[string]any{}
// model
if m, ok := oai["model"].(string); ok {
claude["model"] = m
}
// Build messages, extracting system messages
var systemParts []string
var claudeMsgs []map[string]any
if rawMsgs, ok := oai["messages"].([]any); ok {
// First pass: collect system messages and group tool results
for _, rm := range rawMsgs {
m, ok := rm.(map[string]any)
if !ok {
continue
}
role, _ := m["role"].(string)
switch role {
case "system":
if c, ok := m["content"].(string); ok {
systemParts = append(systemParts, c)
}
case "tool":
// Tool results in Claude go as user messages with tool_result content blocks
block := map[string]any{
"type": "tool_result",
"tool_use_id": m["tool_call_id"],
"content": m["content"],
}
// Try to merge into previous user message if it has tool_result blocks
if len(claudeMsgs) > 0 {
last := claudeMsgs[len(claudeMsgs)-1]
if lastRole, _ := last["role"].(string); lastRole == "user" {
if lastContent, ok := last["content"].([]any); ok {
last["content"] = append(lastContent, block)
continue
}
}
}
claudeMsgs = append(claudeMsgs, map[string]any{
"role": "user",
"content": []any{block},
})
case "assistant":
claudeMsgs = append(claudeMsgs, convertOpenAIMsgToClaude(m))
case "user":
claudeMsgs = append(claudeMsgs, convertOpenAIUserMsgToClaude(m))
}
}
}
if len(systemParts) > 0 {
claude["system"] = joinStrings(systemParts)
}
claude["messages"] = claudeMsgs
// max_tokens - Claude requires this field
if mt, ok := oai["max_tokens"]; ok {
claude["max_tokens"] = mt
} else if mt, ok := oai["max_completion_tokens"]; ok {
claude["max_tokens"] = mt
} else {
claude["max_tokens"] = 8192
}
// Direct copy
for _, key := range []string{"temperature", "top_p"} {
if v, ok := oai[key]; ok {
claude[key] = v
}
}
// stop -> stop_sequences
if stop, ok := oai["stop"]; ok {
switch v := stop.(type) {
case string:
claude["stop_sequences"] = []string{v}
default:
claude["stop_sequences"] = v
}
}
// stream
if s, ok := oai["stream"].(bool); ok {
claude["stream"] = s
}
// tools
if tools, ok := oai["tools"].([]any); ok && len(tools) > 0 {
claude["tools"] = convertOpenAIToolsToClaude(tools)
}
// tool_choice
if tc, ok := oai["tool_choice"]; ok {
claude["tool_choice"] = convertOpenAIToolChoiceToClaude(tc)
}
return json.Marshal(claude)
}
func convertOpenAIMsgToClaude(m map[string]any) map[string]any {
msg := map[string]any{"role": "assistant"}
// Check for tool_calls
toolCalls, hasTC := m["tool_calls"].([]any)
content := m["content"]
var blocks []any
// Add text content if present (string form)
if s, ok := content.(string); ok && s != "" {
blocks = append(blocks, map[string]any{"type": "text", "text": s})
}
// Handle multimodal content array (e.g., from OpenAI responses with images)
if parts, ok := content.([]any); ok {
for _, p := range parts {
part, ok := p.(map[string]any)
if !ok {
continue
}
partType, _ := part["type"].(string)
switch partType {
case "text":
if t, ok := part["text"].(string); ok && t != "" {
blocks = append(blocks, map[string]any{"type": "text", "text": t})
}
case "image_url":
// Convert OpenAI image_url to Claude image block
if imgURL, ok := part["image_url"].(map[string]any); ok {
if block := convertImageURLToClaude(imgURL); block != nil {
blocks = append(blocks, block)
}
}
}
}
}
// Add reasoning_content as thinking block if present
if rc, ok := m["reasoning_content"].(string); ok && rc != "" {
// Prepend thinking block before other content
thinkBlock := map[string]any{"type": "thinking", "thinking": rc}
blocks = append([]any{thinkBlock}, blocks...)
}
// Add tool_use blocks from tool_calls
if hasTC {
for _, tc := range toolCalls {
call, ok := tc.(map[string]any)
if !ok {
continue
}
fn, _ := call["function"].(map[string]any)
if fn == nil {
continue
}
block := map[string]any{
"type": "tool_use",
"id": call["id"],
"name": fn["name"],
}
// Parse arguments string to object
if argsStr, ok := fn["arguments"].(string); ok {
var args any
if err := json.Unmarshal([]byte(argsStr), &args); err == nil {
block["input"] = args
} else {
block["input"] = map[string]any{}
}
} else if args, ok := fn["arguments"].(map[string]any); ok {
block["input"] = args
} else {
block["input"] = map[string]any{}
}
blocks = append(blocks, block)
}
}
if len(blocks) > 0 {
msg["content"] = blocks
} else {
// Preserve original content (string or null)
msg["content"] = content
}
return msg
}
// convertOpenAIUserMsgToClaude converts an OpenAI user message to Claude format,
// handling both string and multimodal content arrays.
func convertOpenAIUserMsgToClaude(m map[string]any) map[string]any {
content := m["content"]
// String content: pass through
if _, ok := content.(string); ok {
return map[string]any{"role": "user", "content": content}
}
// Multimodal content array
if parts, ok := content.([]any); ok {
var blocks []any
for _, p := range parts {
part, ok := p.(map[string]any)
if !ok {
continue
}
partType, _ := part["type"].(string)
switch partType {
case "text":
if t, ok := part["text"].(string); ok && t != "" {
blocks = append(blocks, map[string]any{"type": "text", "text": t})
}
case "image_url":
if imgURL, ok := part["image_url"].(map[string]any); ok {
if block := convertImageURLToClaude(imgURL); block != nil {
blocks = append(blocks, block)
}
}
}
}
if len(blocks) > 0 {
return map[string]any{"role": "user", "content": blocks}
}
}
return map[string]any{"role": "user", "content": content}
}
// convertImageURLToClaude converts an OpenAI image_url object to a Claude image block.
// Handles data URIs (data:image/png;base64,...) by extracting media_type and data.
func convertImageURLToClaude(imgURL map[string]any) map[string]any {
urlStr, _ := imgURL["url"].(string)
if urlStr == "" {
return nil
}
// Handle data URIs: data:image/png;base64,iVBOR...
if strings.HasPrefix(urlStr, "data:") {
// Parse: data:<media_type>;base64,<data>
rest := urlStr[5:] // strip "data:"
semiIdx := strings.Index(rest, ";")
if semiIdx < 0 {
return nil
}
mediaType := rest[:semiIdx]
after := rest[semiIdx+1:]
if !strings.HasPrefix(after, "base64,") {
return nil
}
data := after[7:] // strip "base64,"
return map[string]any{
"type": "image",
"source": map[string]any{
"type": "base64",
"media_type": mediaType,
"data": data,
},
}
}
// For regular URLs, use Claude's URL source type
return map[string]any{
"type": "image",
"source": map[string]any{
"type": "url",
"url": urlStr,
},
}
}
func convertOpenAIToolsToClaude(tools []any) []map[string]any {
var out []map[string]any
for _, t := range tools {
tool, ok := t.(map[string]any)
if !ok {
continue
}
fn, _ := tool["function"].(map[string]any)
if fn == nil {
continue
}
ct := map[string]any{
"name": fn["name"],
"input_schema": fn["parameters"],
}
if desc, ok := fn["description"].(string); ok {
ct["description"] = desc
}
out = append(out, ct)
}
return out
}
func convertOpenAIToolChoiceToClaude(tc any) any {
if tc == nil {
return nil
}
if s, ok := tc.(string); ok {
switch s {
case "auto":
return map[string]any{"type": "auto"}
case "required":
return map[string]any{"type": "any"}
case "none":
return map[string]any{"type": "auto", "disable_parallel_tool_use": true}
}
}
if obj, ok := tc.(map[string]any); ok {
if fn, ok := obj["function"].(map[string]any); ok {
return map[string]any{
"type": "tool",
"name": fn["name"],
}
}
}
return map[string]any{"type": "auto"}
}
// --- OpenAI -> Claude response translation ---
func translateOpenAIRespToClaude(body []byte, requestModel string) ([]byte, error) {
var oai map[string]any
if err := json.Unmarshal(body, &oai); err != nil {
return nil, fmt.Errorf("parse openai response: %w", err)
}
id, _ := oai["id"].(string)
model, _ := oai["model"].(string)
if model == "" {
model = requestModel
}
claude := map[string]any{
"id": id,
"type": "message",
"role": "assistant",
"model": model,
}
// Convert choices to content blocks
var content []map[string]any
stopReason := "end_turn"
if choices, ok := oai["choices"].([]any); ok && len(choices) > 0 {
choice, _ := choices[0].(map[string]any)
if choice != nil {
if fr, ok := choice["finish_reason"].(string); ok {
stopReason = oaiFinishReasonToClaude(fr)
}
if msg, ok := choice["message"].(map[string]any); ok {
// Reasoning/thinking content (o1/o3 models)
// Check reasoning_content (standard OpenAI field)
if rc, ok := msg["reasoning_content"].(string); ok && rc != "" {
content = append(content, map[string]any{
"type": "thinking",
"thinking": rc,
})
}
// Check reasoning_details (OpenRouter format)
if rds, ok := msg["reasoning_details"].([]any); ok {
for _, rd := range rds {
if detail, ok := rd.(map[string]any); ok {
if text := extractReasoningText(detail); text != "" {
content = append(content, map[string]any{
"type": "thinking",
"thinking": text,
})
}
}
}
}
// Text content
if c, ok := msg["content"].(string); ok && c != "" {
content = append(content, map[string]any{"type": "text", "text": c})
}
// Tool calls
if tcs, ok := msg["tool_calls"].([]any); ok {
for _, tc := range tcs {