Open History to see the last commit
1/**
2 * Gemini chat request map, read from the Generative Language discovery
3 * document plus the thinking page's per-model budget numbers.
4 * `generationConfig.maxOutputTokens` is published, and ChatRequestMap has
5 * no field for it, so `maxTokensField` stays null.
6 */
7import type { GeminiBudgetBody } from './gemini-features.ts'
8import { cachedDocs } from './model-facts.ts'
9import type { ChatRequestMap, EffortLevelMap } from './request-map.ts'
10import { SHARED_EFFORT_LEVELS } from './request-map.ts'
11import type { FactSource, ModelReasoning } from './types.ts'
12import { fetchText, sha256Text } from './types.ts'
13
14export const GEMINI_DISCOVERY_URL =
15 'https://generativelanguage.googleapis.com/$discovery/rest?version=v1beta'
16
17interface DiscoveryProperty {
18 description?: string
19 enum?: Array<string>
20}
21
22interface DiscoverySchema {
23 properties?: Record<string, DiscoveryProperty>
24}
25
26interface DiscoveryDoc {
27 schemas?: Record<string, DiscoverySchema>
28}
29
30export interface GeminiWire {
31 /** `ThinkingConfig.thinkingLevel` enum, without `THINKING_LEVEL_UNSPECIFIED`. */
32 thinkingLevels: Array<string> | null
33 hasThinkingBudget: boolean
34 /** False when `Content.role` allows only `user` and `model`. */
35 developerRole: false | null
36}
37
38const ROLE_IS_USER_OR_MODEL = /must be either 'user' or 'model'/i
39
40export function parseGeminiWire(doc: DiscoveryDoc): GeminiWire {
41 const thinking = doc.schemas?.ThinkingConfig?.properties
42 const levels = thinking?.thinkingLevel?.enum?.filter(
43 (value) => value !== 'THINKING_LEVEL_UNSPECIFIED',
44 )
45 const thinkingLevels = levels && levels.length > 0 ? levels : null
46 const hasThinkingBudget = thinking?.thinkingBudget !== undefined
47 const role = doc.schemas?.Content?.properties?.role?.description ?? ''
48 const developerRole = ROLE_IS_USER_OR_MODEL.test(role) ? false : null
49 if (!thinkingLevels && !hasThinkingBudget && developerRole === null) {
50 throw new Error('gemini discovery: no request-map fields')
51 }
52 return { thinkingLevels, hasThinkingBudget, developerRole }
53}
54
55function effortLevels(
56 efforts: Array<string>,
57 enums: Array<string>,
58): EffortLevelMap {
59 const out = {} as EffortLevelMap
60 for (const level of SHARED_EFFORT_LEVELS) {
61 const wire = level.toUpperCase()
62 out[level] =
63 level !== 'off' && efforts.includes(level) && enums.includes(wire)
64 ? wire
65 : null
66 }
67 return out
68}
69
70function thinkingBody(
71 field: 'thinkingLevel' | 'thinkingBudget',
72 value: string | number,
73): Record<string, unknown> {
74 return { generationConfig: { thinkingConfig: { [field]: value } } }
75}
76
77/**
78 * A non-null map needs a verified `developerRole` or a verified thinking
79 * body. Effort `on` is `thinkingLevel: HIGH` from the discovery enum.
80 * Budget `on` is the thinking page's dynamic `thinkingBudget` (Gemini
81 * publishes -1 for dynamic, not an effort). `off` is only the disable
82 * cell's number.
83 */
84export function geminiRequestMap(
85 wire: GeminiWire,
86 reasoning: ModelReasoning | null,
87 budget: GeminiBudgetBody | null,
88): ChatRequestMap | null {
89 let thinking: ChatRequestMap['thinking'] = null
90 if (
91 reasoning?.mode === 'effort' &&
92 reasoning.efforts?.includes('high') &&
93 wire.thinkingLevels?.includes('HIGH')
94 ) {
95 thinking = {
96 on: thinkingBody('thinkingLevel', 'HIGH'),
97 off: null,
98 levels: effortLevels(reasoning.efforts, wire.thinkingLevels),
99 }
100 } else if (
101 reasoning?.mode === 'budget' &&
102 budget !== null &&
103 wire.hasThinkingBudget
104 ) {
105 thinking = {
106 on: thinkingBody('thinkingBudget', budget.on),
107 off:
108 budget.off === null ? null : thinkingBody('thinkingBudget', budget.off),
109 levels: null,
110 }
111 }
112 if (wire.developerRole === null && thinking === null) return null
113 return {
114 thinking,
115 maxTokensField: null,
116 developerRole: wire.developerRole,
117 replayReasoningContent: null,
118 store: null,
119 strictTools: null,
120 sessionAffinity: null,
121 cacheControl: null,
122 toolStream: null,
123 reasoningEffort: null,
124 }
125}
126
127export async function geminiWire(kv?: KVNamespace): Promise<{
128 fields: GeminiWire
129 source: FactSource
130}> {
131 const loaded = await cachedDocs(kv, GEMINI_DISCOVERY_URL, async () => {
132 const text = await fetchText(GEMINI_DISCOVERY_URL)
133 const parsed: unknown = JSON.parse(text)
134 const doc =
135 typeof parsed === 'object' && parsed !== null
136 ? (parsed as DiscoveryDoc)
137 : {}
138 return { fields: parseGeminiWire(doc), hash: await sha256Text(text) }
139 })
140 return {
141 fields: loaded.fields,
142 source: {
143 derivation: 'docs-derived',
144 sourceUrl: GEMINI_DISCOVERY_URL,
145 sourceHash: loaded.hash,
146 path: 'GenerateContentRequest',
147 },
148 }
149}