-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathgemini-format.ts
More file actions
201 lines (175 loc) · 7.07 KB
/
gemini-format.ts
File metadata and controls
201 lines (175 loc) · 7.07 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
import { Anthropic } from "@anthropic-ai/sdk"
import { Content, Part } from "@google/genai"
type ThoughtSignatureContentBlock = {
type: "thoughtSignature"
thoughtSignature?: string
}
type ReasoningContentBlock = {
type: "reasoning"
text: string
}
type ExtendedContentBlockParam = Anthropic.ContentBlockParam | ThoughtSignatureContentBlock | ReasoningContentBlock
type ExtendedAnthropicContent = string | ExtendedContentBlockParam[]
// Extension type to safely add thoughtSignature to Part
type PartWithThoughtSignature = Part & {
thoughtSignature?: string
}
function isThoughtSignatureContentBlock(block: ExtendedContentBlockParam): block is ThoughtSignatureContentBlock {
return block.type === "thoughtSignature"
}
export function convertAnthropicContentToGemini(
content: ExtendedAnthropicContent,
options?: { includeThoughtSignatures?: boolean; toolIdToName?: Map<string, string> },
): Part[] {
const includeThoughtSignatures = options?.includeThoughtSignatures ?? true
const toolIdToName = options?.toolIdToName
// First pass: find thoughtSignature if it exists in the content blocks
let activeThoughtSignature: string | undefined
if (Array.isArray(content)) {
const sigBlock = content.find((block) => isThoughtSignatureContentBlock(block)) as ThoughtSignatureContentBlock
if (sigBlock?.thoughtSignature) {
activeThoughtSignature = sigBlock.thoughtSignature
}
}
// Determine the signature to attach to function calls.
// If we're in a mode that expects signatures (includeThoughtSignatures is true):
// - Use the actual signature if we found one in the history/content.
// - If no real signature exists, omit it (undefined) so the API accepts the request.
// Gemini 3.1+ models reject the synthetic "skip_thought_signature_validator" bypass
// that worked with earlier Gemini 3 models.
let functionCallSignature: string | undefined
if (includeThoughtSignatures) {
functionCallSignature = activeThoughtSignature
}
if (typeof content === "string") {
return [{ text: content }]
}
const parts = content.flatMap((block): Part | Part[] => {
// Handle thoughtSignature blocks first
if (isThoughtSignatureContentBlock(block)) {
// We process thought signatures globally and attach them to the relevant parts
// or create a placeholder part if no other content exists.
return []
}
switch (block.type) {
case "text":
return { text: block.text }
case "image":
if (block.source.type !== "base64") {
throw new Error("Unsupported image source type")
}
return { inlineData: { data: block.source.data, mimeType: block.source.media_type } }
case "tool_use":
// Gemini 3 validation rules:
// - In a parallel function calling response, only the FIRST functionCall part has a signature.
// - In sequential steps, each step's first functionCall must include its signature.
// When converting from our history, we don't always have enough information to perfectly
// recreate the original per-part distribution, but we can and should avoid attaching the
// signature to every parallel call in a single assistant message.
return {
functionCall: {
name: block.name,
args: block.input as Record<string, unknown>,
},
// Inject the thoughtSignature into the functionCall part if required.
// This is necessary for Gemini 3+ thinking models to validate the tool call.
...(functionCallSignature ? { thoughtSignature: functionCallSignature } : {}),
} as Part
case "tool_result": {
if (!block.content) {
return []
}
// Get tool name from the map (built from tool_use blocks in message history).
// The map must contain the tool name - if it doesn't, this indicates a bug
// where the conversation history is incomplete or tool_use blocks are missing.
const toolName = toolIdToName?.get(block.tool_use_id)
if (!toolName) {
throw new Error(
`Unable to find tool name for tool_use_id "${block.tool_use_id}". ` +
`This indicates the conversation history is missing the corresponding tool_use block. ` +
`Available tool IDs: ${Array.from(toolIdToName?.keys() ?? []).join(", ") || "none"}`,
)
}
if (typeof block.content === "string") {
return {
functionResponse: { name: toolName, response: { name: toolName, content: block.content } },
}
}
if (!Array.isArray(block.content)) {
return []
}
const textParts: string[] = []
const imageParts: Part[] = []
for (const item of block.content) {
if (item.type === "text") {
textParts.push(item.text)
} else if (item.type === "image" && item.source.type === "base64") {
const { data, media_type } = item.source
imageParts.push({ inlineData: { data, mimeType: media_type } })
}
}
// Create content text with a note about images if present
const contentText =
textParts.join("\n\n") + (imageParts.length > 0 ? "\n\n(See next part for image)" : "")
// Return function response followed by any images
return [
{ functionResponse: { name: toolName, response: { name: toolName, content: contentText } } },
...imageParts,
]
}
default:
// Skip unsupported content block types (e.g., "reasoning", "thinking", "redacted_thinking", "document")
// These are typically metadata from other providers that don't need to be sent to Gemini
console.warn(`Skipping unsupported content block type: ${block.type}`)
return []
}
})
// Post-processing:
// 1) Ensure thought signature is attached if required
// 2) For multiple function calls in a single message, keep the signature only on the first
// functionCall part to match Gemini 3 parallel-calling behavior.
if (includeThoughtSignatures && activeThoughtSignature) {
const hasSignature = parts.some((p) => "thoughtSignature" in p)
if (!hasSignature) {
if (parts.length > 0) {
// Attach to the first part (usually text)
// We use the intersection type to allow adding the property safely
;(parts[0] as PartWithThoughtSignature).thoughtSignature = activeThoughtSignature
} else {
// Create a placeholder part if no other content exists
const placeholder: PartWithThoughtSignature = { text: "", thoughtSignature: activeThoughtSignature }
parts.push(placeholder)
}
}
}
if (includeThoughtSignatures) {
let seenFirstFunctionCall = false
for (const part of parts) {
if (part && typeof part === "object" && "functionCall" in part && (part as any).functionCall) {
const partWithSig = part as PartWithThoughtSignature
if (!seenFirstFunctionCall) {
seenFirstFunctionCall = true
} else {
// Remove signature from subsequent function calls in this message.
delete partWithSig.thoughtSignature
}
}
}
}
return parts
}
export function convertAnthropicMessageToGemini(
message: Anthropic.Messages.MessageParam,
options?: { includeThoughtSignatures?: boolean; toolIdToName?: Map<string, string> },
): Content[] {
const parts = convertAnthropicContentToGemini(message.content, options)
if (parts.length === 0) {
return []
}
return [
{
role: message.role === "assistant" ? "model" : "user",
parts,
},
]
}