Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

gemini-live-thinking.ts

61 lines1.9 KB

1import { cachedDocs } from './model-facts.ts'
2import { fetchText, sha256Text } from './types.ts'
3import type { ModelReasoning } from './types.ts'
4​
5export const GEMINI_LIVE_GUIDE_URL =
6 'https://ai.google.dev/gemini-api/docs/live-guide.md.txt'
7export function parseGeminiNativeAudioThinking(markdown: string): {
8 rawId: string
9 reasoning: ModelReasoning
10} {
11 const prose = markdown.replace(/```[\s\S]*?```/g, '')
12 const section = prose.match(
13 /^### Thinking\s*\n([\s\S]*?)(?=^### |(?![\s\S]))/m,
14 )?.[1]
15 const sentences =
16 section?.split(/\n\s*\n/).flatMap((paragraph) =>
17 paragraph
18 .replace(/\s+/g, ' ')
19 .trim()
20 .split(/(?<=[.!?])\s+/),
21 ) ?? []
22 const rawId = sentences
23 .map(
24 (sentence) =>
25 sentence.match(
26 /^The latest native audio output model `([a-z0-9.-]+)` supports\b/,
27 )?.[1],
28 )
29 .find(Boolean)
30 const budget = sentences.some((sentence) =>
31 /^The `thinkingBudget` parameter guides the model on the number of thinking tokens\b/.test(
32 sentence,
33 ),
34 )
35 const disable = sentences.some((sentence) =>
36 /^You can disable thinking by setting `thinkingBudget` to `0`\./.test(
37 sentence,
38 ),
39 )
40 if (!rawId || !budget || !disable)
41 throw new Error(
42 'gemini live guide: native model/budget/disable contract unreadable',
43 )
44 return { rawId, reasoning: { mode: 'budget', mandatory: false } }
46export async function geminiNativeAudioThinking(
47 rawIds: ReadonlyArray<string>,
48 kv?: KVNamespace,
49) {
50 // Names select which own guide to check; only its literal model ID binds facts.
51 if (!rawIds.some((id) => id.includes('native-audio'))) return null
52 return cachedDocs(kv, GEMINI_LIVE_GUIDE_URL, async () => {
53 const markdown = await fetchText(GEMINI_LIVE_GUIDE_URL, {
54 signal: AbortSignal.timeout(20_000),
55 })
56 return {
57 ...parseGeminiNativeAudioThinking(markdown),
58 hash: await sha256Text(markdown),
59 }
60 })