@namzu/google 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/wire.ts ADDED
@@ -0,0 +1,194 @@
1
+ import { createHash } from 'node:crypto'
2
+ import type { ChatCompletionParams, ReasoningEffort } from '@namzu/sdk'
3
+ import { toToolResultBlocks } from '@namzu/sdk'
4
+ export interface Part {
5
+ text?: string
6
+ thought?: boolean
7
+ thoughtSignature?: string
8
+ functionCall?: { name: string; args?: Record<string, unknown>; id?: string }
9
+ [key: string]: unknown
10
+ }
11
+ export interface Content {
12
+ role: string
13
+ parts: Part[]
14
+ }
15
+ export interface Replay {
16
+ kind: 'namzu-google'
17
+ version: 1
18
+ scope: string
19
+ digest: string
20
+ route: unknown
21
+ parts: Part[]
22
+ text: string
23
+ calls: unknown
24
+ }
25
+ export function effortLevels(model: string): readonly ReasoningEffort[] | undefined {
26
+ if (model === 'gemini-3-flash-preview') return ['minimal', 'low', 'medium', 'high']
27
+ if (model === 'gemini-3-pro-preview') return ['low', 'high']
28
+ if (/^gemini-2\.5-/.test(model)) return []
29
+ return undefined
30
+ }
31
+ export function routeFor(p: ChatCompletionParams) {
32
+ return p.providerRoute ?? { providerId: 'google', model: p.model, chainIndex: 0 }
33
+ }
34
+ export function partDigest(parts: Part[]): string {
35
+ return createHash('sha256').update(JSON.stringify(parts)).digest('hex')
36
+ }
37
+ export function buildRequest(p: ChatCompletionParams, scope = 'api-key'): Record<string, unknown> {
38
+ for (const key of ['parallelToolCalls', 'repetitionPenalty'] as const)
39
+ if (p[key] !== undefined) throw new Error(`Gemini does not support explicit ${key}.`)
40
+ if (p.cacheControl?.type === 'ephemeral')
41
+ throw new Error('Gemini does not support explicit ephemeral cache control.')
42
+ // enforceToolInputSchema is an optional optimization hint. Native tool schemas
43
+ // are sent below; unsupported strict generation is not claimed.
44
+ const generationConfig: Record<string, unknown> = {}
45
+ for (const [from, to] of [
46
+ ['maxTokens', 'maxOutputTokens'],
47
+ ['temperature', 'temperature'],
48
+ ['topP', 'topP'],
49
+ ['topK', 'topK'],
50
+ ['stop', 'stopSequences'],
51
+ ['frequencyPenalty', 'frequencyPenalty'],
52
+ ['presencePenalty', 'presencePenalty'],
53
+ ] as const)
54
+ if (p[from] !== undefined) generationConfig[to] = p[from]
55
+ if (p.responseFormat) {
56
+ generationConfig.responseMimeType = 'application/json'
57
+ if (p.responseFormat.type === 'json_schema')
58
+ generationConfig.responseJsonSchema = p.responseFormat.json_schema.schema
59
+ }
60
+ if (p.effort || p.thinking) {
61
+ const t: Record<string, unknown> = {}
62
+ if (p.effort) {
63
+ if (!effortLevels(p.model)?.includes(p.effort))
64
+ throw new Error(`Gemini does not publish effort ${p.effort} for ${p.model}.`)
65
+ t.thinkingLevel = p.effort.toUpperCase()
66
+ }
67
+ if (p.thinking) {
68
+ const cfg = p.thinking
69
+ if (cfg.type === 'disabled') {
70
+ if (!/^gemini-2\.5-flash/.test(p.model))
71
+ throw new Error(`Thinking cannot be disabled for ${p.model}.`)
72
+ t.thinkingBudget = 0
73
+ } else if (cfg.type === 'enabled') {
74
+ if (
75
+ !/^gemini-2\.5-/.test(p.model) ||
76
+ !Number.isInteger(cfg.budgetTokens) ||
77
+ (cfg.budgetTokens ?? 0) <= 0
78
+ )
79
+ throw new Error(
80
+ 'Manual Gemini thinking requires a Gemini 2.5 model and positive integer budgetTokens.',
81
+ )
82
+ t.thinkingBudget = cfg.budgetTokens
83
+ } else if (/^gemini-2\.5-/.test(p.model)) t.thinkingBudget = -1
84
+ else if (!effortLevels(p.model)?.length)
85
+ throw new Error(`Unknown adaptive thinking support for ${p.model}.`)
86
+ if (cfg.type !== 'enabled' && cfg.budgetTokens !== undefined)
87
+ throw new Error('budgetTokens requires enabled thinking.')
88
+ t.includeThoughts = cfg.display === 'summarized'
89
+ }
90
+ generationConfig.thinkingConfig = t
91
+ }
92
+ const contents: Content[] = []
93
+ const system: Part[] = []
94
+ const names = new Map<string, string>()
95
+ const nativeIds = new Map<string, string | undefined>()
96
+ for (const m of p.messages) {
97
+ if (m.role === 'system') {
98
+ system.push({ text: m.content })
99
+ continue
100
+ }
101
+ let parts: Part[] = []
102
+ if (m.role === 'assistant') {
103
+ for (const call of m.toolCalls ?? []) names.set(call.id, call.function.name)
104
+ const r = m.source?.replayState as Replay | undefined
105
+ if (
106
+ r?.kind === 'namzu-google' &&
107
+ r.version === 1 &&
108
+ r.scope === scope &&
109
+ Array.isArray(r.parts) &&
110
+ r.digest === partDigest(r.parts) &&
111
+ JSON.stringify(r.route) === JSON.stringify(routeFor(p)) &&
112
+ m.source?.providerId === routeFor(p).providerId &&
113
+ m.source?.model === p.model &&
114
+ m.source?.chainIndex === routeFor(p).chainIndex &&
115
+ r.text === (m.content ?? '') &&
116
+ JSON.stringify(r.calls) === JSON.stringify(m.toolCalls ?? []) &&
117
+ Array.isArray(r.parts)
118
+ )
119
+ parts = r.parts
120
+ else {
121
+ if (m.content) parts.push({ text: m.content })
122
+ for (const call of m.toolCalls ?? [])
123
+ parts.push({
124
+ functionCall: {
125
+ name: call.function.name,
126
+ args: JSON.parse(call.function.arguments),
127
+ id: call.id,
128
+ },
129
+ })
130
+ }
131
+ const nativeCalls = parts.filter((part) => part.functionCall).map((part) => part.functionCall)
132
+ for (const [index, call] of (m.toolCalls ?? []).entries())
133
+ nativeIds.set(call.id, nativeCalls[index]?.id)
134
+ } else if (m.role === 'tool') {
135
+ const name = names.get(m.toolCallId)
136
+ if (!name) throw new Error('Gemini tool result has no matching function call.')
137
+ const blocks = toToolResultBlocks(m.content)
138
+ parts.push({
139
+ functionResponse: {
140
+ name,
141
+ ...(nativeIds.get(m.toolCallId) !== undefined ? { id: nativeIds.get(m.toolCallId) } : {}),
142
+ response: {
143
+ [m.isError ? 'error' : 'output']: blocks
144
+ .filter((b) => b.type === 'text')
145
+ .map((b) => b.text)
146
+ .join('\n'),
147
+ },
148
+ },
149
+ })
150
+ for (const b of blocks)
151
+ if (b.type !== 'text') {
152
+ if ('modelOmission' in b && b.modelOmission)
153
+ parts.push({ text: '[Attachment omitted from model context]' })
154
+ else parts.push({ inlineData: { mimeType: b.mediaType, data: b.data } })
155
+ }
156
+ } else {
157
+ if (m.content) parts.push({ text: m.content })
158
+ for (const a of m.attachments ?? []) {
159
+ if (a.type === 'stored')
160
+ throw new Error('Resolve stored attachments before calling Gemini.')
161
+ if ('modelOmission' in a && a.modelOmission)
162
+ parts.push({ text: '[Attachment omitted from model context]' })
163
+ else {
164
+ if (a.type === 'document' && a.citations)
165
+ throw new Error('Gemini document citations are not supported by this driver.')
166
+ parts.push({ inlineData: { mimeType: a.mediaType, data: a.data } })
167
+ }
168
+ }
169
+ }
170
+ if (parts.length) contents.push({ role: m.role === 'assistant' ? 'model' : 'user', parts })
171
+ }
172
+ const req: Record<string, unknown> = { contents, generationConfig }
173
+ if (system.length) req.systemInstruction = { parts: system }
174
+ if (p.tools?.length)
175
+ req.tools = [
176
+ {
177
+ functionDeclarations: p.tools.map((t) => ({
178
+ name: t.function.name,
179
+ description: t.function.description,
180
+ parametersJsonSchema: t.function.parameters,
181
+ })),
182
+ },
183
+ ]
184
+ if (p.toolChoice)
185
+ req.toolConfig = {
186
+ functionCallingConfig:
187
+ typeof p.toolChoice === 'string'
188
+ ? {
189
+ mode: { auto: 'AUTO', none: 'NONE', required: 'ANY' }[p.toolChoice],
190
+ }
191
+ : { mode: 'ANY', allowedFunctionNames: [p.toolChoice.function.name] },
192
+ }
193
+ return req
194
+ }