google.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. import {
  2. type GenerateContentConfig,
  3. type GenerateContentParameters,
  4. GoogleGenAI,
  5. type ThinkingConfig,
  6. } from "@google/genai";
  7. import { calculateCost, clampThinkingLevel } from "../models.ts";
  8. import type {
  9. Api,
  10. AssistantMessage,
  11. Context,
  12. Model,
  13. SimpleStreamOptions,
  14. StreamFunction,
  15. StreamOptions,
  16. TextContent,
  17. ThinkingBudgets,
  18. ThinkingContent,
  19. ThinkingLevel,
  20. ToolCall,
  21. } from "../types.ts";
  22. import { AssistantMessageEventStream } from "../utils/event-stream.ts";
  23. import { notifyProviderError } from "../utils/provider-error.ts";
  24. import { sanitizeSurrogates } from "../utils/sanitize-unicode.ts";
  25. import type { GoogleThinkingLevel } from "./google-shared.ts";
  26. import {
  27. convertMessages,
  28. convertTools,
  29. isThinkingPart,
  30. mapStopReason,
  31. mapToolChoice,
  32. retainThoughtSignature,
  33. } from "./google-shared.ts";
  34. import { buildBaseOptions } from "./simple-options.ts";
  35. export interface GoogleOptions extends StreamOptions {
  36. toolChoice?: "auto" | "none" | "any";
  37. thinking?: {
  38. enabled: boolean;
  39. budgetTokens?: number; // -1 for dynamic, 0 to disable
  40. level?: GoogleThinkingLevel;
  41. };
  42. }
  43. // Counter for generating unique tool call IDs
  44. let toolCallCounter = 0;
  45. export const streamGoogle: StreamFunction<"google-generative-ai", GoogleOptions> = (
  46. model: Model<"google-generative-ai">,
  47. context: Context,
  48. options?: GoogleOptions,
  49. ): AssistantMessageEventStream => {
  50. const stream = new AssistantMessageEventStream();
  51. (async () => {
  52. const output: AssistantMessage = {
  53. role: "assistant",
  54. content: [],
  55. api: "google-generative-ai" as Api,
  56. provider: model.provider,
  57. model: model.id,
  58. usage: {
  59. input: 0,
  60. output: 0,
  61. cacheRead: 0,
  62. cacheWrite: 0,
  63. totalTokens: 0,
  64. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  65. },
  66. stopReason: "stop",
  67. timestamp: Date.now(),
  68. };
  69. try {
  70. const apiKey = options?.apiKey;
  71. if (!apiKey) {
  72. throw new Error(`No API key for provider: ${model.provider}`);
  73. }
  74. const client = createClient(model, apiKey, options?.headers);
  75. let params = buildParams(model, context, options);
  76. const nextParams = await options?.onPayload?.(params, model);
  77. if (nextParams !== undefined) {
  78. params = nextParams as GenerateContentParameters;
  79. }
  80. const googleStream = await client.models.generateContentStream(params);
  81. stream.push({ type: "start", partial: output });
  82. let currentBlock: TextContent | ThinkingContent | null = null;
  83. const blocks = output.content;
  84. const blockIndex = () => blocks.length - 1;
  85. for await (const chunk of googleStream) {
  86. // @google/genai documents GenerateContentResponse.responseId as an output-only field
  87. // used to identify each response. Keep the first non-empty one from the stream.
  88. output.responseId ||= chunk.responseId;
  89. const candidate = chunk.candidates?.[0];
  90. if (candidate?.content?.parts) {
  91. for (const part of candidate.content.parts) {
  92. if (part.text !== undefined) {
  93. const isThinking = isThinkingPart(part);
  94. if (
  95. !currentBlock ||
  96. (isThinking && currentBlock.type !== "thinking") ||
  97. (!isThinking && currentBlock.type !== "text")
  98. ) {
  99. if (currentBlock) {
  100. if (currentBlock.type === "text") {
  101. stream.push({
  102. type: "text_end",
  103. contentIndex: blocks.length - 1,
  104. content: currentBlock.text,
  105. partial: output,
  106. });
  107. } else {
  108. stream.push({
  109. type: "thinking_end",
  110. contentIndex: blockIndex(),
  111. content: currentBlock.thinking,
  112. partial: output,
  113. });
  114. }
  115. }
  116. if (isThinking) {
  117. currentBlock = { type: "thinking", thinking: "", thinkingSignature: undefined };
  118. output.content.push(currentBlock);
  119. stream.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output });
  120. } else {
  121. currentBlock = { type: "text", text: "" };
  122. output.content.push(currentBlock);
  123. stream.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
  124. }
  125. }
  126. if (currentBlock.type === "thinking") {
  127. currentBlock.thinking += part.text;
  128. currentBlock.thinkingSignature = retainThoughtSignature(
  129. currentBlock.thinkingSignature,
  130. part.thoughtSignature,
  131. );
  132. stream.push({
  133. type: "thinking_delta",
  134. contentIndex: blockIndex(),
  135. delta: part.text,
  136. partial: output,
  137. });
  138. } else {
  139. currentBlock.text += part.text;
  140. currentBlock.textSignature = retainThoughtSignature(
  141. currentBlock.textSignature,
  142. part.thoughtSignature,
  143. );
  144. stream.push({
  145. type: "text_delta",
  146. contentIndex: blockIndex(),
  147. delta: part.text,
  148. partial: output,
  149. });
  150. }
  151. }
  152. if (part.functionCall) {
  153. if (currentBlock) {
  154. if (currentBlock.type === "text") {
  155. stream.push({
  156. type: "text_end",
  157. contentIndex: blockIndex(),
  158. content: currentBlock.text,
  159. partial: output,
  160. });
  161. } else {
  162. stream.push({
  163. type: "thinking_end",
  164. contentIndex: blockIndex(),
  165. content: currentBlock.thinking,
  166. partial: output,
  167. });
  168. }
  169. currentBlock = null;
  170. }
  171. // Generate unique ID if not provided or if it's a duplicate
  172. const providedId = part.functionCall.id;
  173. const needsNewId =
  174. !providedId || output.content.some((b) => b.type === "toolCall" && b.id === providedId);
  175. const toolCallId = needsNewId
  176. ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`
  177. : providedId;
  178. const toolCall: ToolCall = {
  179. type: "toolCall",
  180. id: toolCallId,
  181. name: part.functionCall.name || "",
  182. arguments: (part.functionCall.args as Record<string, any>) ?? {},
  183. ...(part.thoughtSignature && { thoughtSignature: part.thoughtSignature }),
  184. };
  185. output.content.push(toolCall);
  186. stream.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
  187. stream.push({
  188. type: "toolcall_delta",
  189. contentIndex: blockIndex(),
  190. delta: JSON.stringify(toolCall.arguments),
  191. partial: output,
  192. });
  193. stream.push({ type: "toolcall_end", contentIndex: blockIndex(), toolCall, partial: output });
  194. }
  195. }
  196. }
  197. if (candidate?.finishReason) {
  198. output.stopReason = mapStopReason(candidate.finishReason);
  199. if (output.content.some((b) => b.type === "toolCall")) {
  200. output.stopReason = "toolUse";
  201. }
  202. }
  203. if (chunk.usageMetadata) {
  204. output.usage = {
  205. input:
  206. (chunk.usageMetadata.promptTokenCount || 0) - (chunk.usageMetadata.cachedContentTokenCount || 0),
  207. output:
  208. (chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0),
  209. cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0,
  210. cacheWrite: 0,
  211. totalTokens: chunk.usageMetadata.totalTokenCount || 0,
  212. cost: {
  213. input: 0,
  214. output: 0,
  215. cacheRead: 0,
  216. cacheWrite: 0,
  217. total: 0,
  218. },
  219. };
  220. calculateCost(model, output.usage);
  221. }
  222. }
  223. if (currentBlock) {
  224. if (currentBlock.type === "text") {
  225. stream.push({
  226. type: "text_end",
  227. contentIndex: blockIndex(),
  228. content: currentBlock.text,
  229. partial: output,
  230. });
  231. } else {
  232. stream.push({
  233. type: "thinking_end",
  234. contentIndex: blockIndex(),
  235. content: currentBlock.thinking,
  236. partial: output,
  237. });
  238. }
  239. }
  240. if (options?.signal?.aborted) {
  241. throw new Error("Request was aborted");
  242. }
  243. if (output.stopReason === "aborted" || output.stopReason === "error") {
  244. throw new Error("An unknown error occurred");
  245. }
  246. stream.push({ type: "done", reason: output.stopReason, message: output });
  247. stream.end();
  248. } catch (error) {
  249. notifyProviderError(options?.onProviderError, error, model);
  250. // Remove internal index property used during streaming
  251. for (const block of output.content) {
  252. if ("index" in block) {
  253. delete (block as { index?: number }).index;
  254. }
  255. }
  256. output.stopReason = options?.signal?.aborted ? "aborted" : "error";
  257. output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
  258. stream.push({ type: "error", reason: output.stopReason, error: output });
  259. stream.end();
  260. }
  261. })();
  262. return stream;
  263. };
  264. export const streamSimpleGoogle: StreamFunction<"google-generative-ai", SimpleStreamOptions> = (
  265. model: Model<"google-generative-ai">,
  266. context: Context,
  267. options?: SimpleStreamOptions,
  268. ): AssistantMessageEventStream => {
  269. const apiKey = options?.apiKey;
  270. if (!apiKey) {
  271. throw new Error(`No API key for provider: ${model.provider}`);
  272. }
  273. const base = buildBaseOptions(model, options, apiKey);
  274. if (!options?.reasoning) {
  275. return streamGoogle(model, context, { ...base, thinking: { enabled: false } } satisfies GoogleOptions);
  276. }
  277. const clampedReasoning = clampThinkingLevel(model, options.reasoning);
  278. const effort = (clampedReasoning === "off" ? "high" : clampedReasoning) as ClampedThinkingLevel;
  279. const googleModel = model as Model<"google-generative-ai">;
  280. if (isGemini3ProModel(googleModel) || isGemini3FlashModel(googleModel) || isGemma4Model(googleModel)) {
  281. return streamGoogle(model, context, {
  282. ...base,
  283. thinking: {
  284. enabled: true,
  285. level: getThinkingLevel(effort, googleModel),
  286. },
  287. } satisfies GoogleOptions);
  288. }
  289. return streamGoogle(model, context, {
  290. ...base,
  291. thinking: {
  292. enabled: true,
  293. budgetTokens: getGoogleBudget(googleModel, effort, options.thinkingBudgets),
  294. },
  295. } satisfies GoogleOptions);
  296. };
  297. function createClient(
  298. model: Model<"google-generative-ai">,
  299. apiKey?: string,
  300. optionsHeaders?: Record<string, string>,
  301. ): GoogleGenAI {
  302. const httpOptions: { baseUrl?: string; apiVersion?: string; headers?: Record<string, string> } = {};
  303. if (model.baseUrl) {
  304. httpOptions.baseUrl = model.baseUrl;
  305. httpOptions.apiVersion = ""; // baseUrl already includes version path, don't append
  306. }
  307. if (model.headers || optionsHeaders) {
  308. httpOptions.headers = { ...model.headers, ...optionsHeaders };
  309. }
  310. return new GoogleGenAI({
  311. apiKey,
  312. httpOptions: Object.keys(httpOptions).length > 0 ? httpOptions : undefined,
  313. });
  314. }
  315. function buildParams(
  316. model: Model<"google-generative-ai">,
  317. context: Context,
  318. options: GoogleOptions = {},
  319. ): GenerateContentParameters {
  320. const contents = convertMessages(model, context);
  321. const generationConfig: GenerateContentConfig = {};
  322. if (options.temperature !== undefined) {
  323. generationConfig.temperature = options.temperature;
  324. }
  325. if (options.maxTokens !== undefined) {
  326. generationConfig.maxOutputTokens = options.maxTokens;
  327. }
  328. const config: GenerateContentConfig = {
  329. ...(Object.keys(generationConfig).length > 0 && generationConfig),
  330. ...(context.systemPrompt && { systemInstruction: sanitizeSurrogates(context.systemPrompt) }),
  331. ...(context.tools && context.tools.length > 0 && { tools: convertTools(context.tools) }),
  332. };
  333. if (context.tools && context.tools.length > 0 && options.toolChoice) {
  334. config.toolConfig = {
  335. functionCallingConfig: {
  336. mode: mapToolChoice(options.toolChoice),
  337. },
  338. };
  339. } else {
  340. config.toolConfig = undefined;
  341. }
  342. if (options.thinking?.enabled && model.reasoning) {
  343. const thinkingConfig: ThinkingConfig = { includeThoughts: true };
  344. if (options.thinking.level !== undefined) {
  345. // Cast to any since our GoogleThinkingLevel mirrors Google's ThinkingLevel enum values
  346. thinkingConfig.thinkingLevel = options.thinking.level as any;
  347. } else if (options.thinking.budgetTokens !== undefined) {
  348. thinkingConfig.thinkingBudget = options.thinking.budgetTokens;
  349. }
  350. config.thinkingConfig = thinkingConfig;
  351. } else if (model.reasoning && options.thinking && !options.thinking.enabled) {
  352. config.thinkingConfig = getDisabledThinkingConfig(model);
  353. }
  354. if (options.signal) {
  355. if (options.signal.aborted) {
  356. throw new Error("Request aborted");
  357. }
  358. config.abortSignal = options.signal;
  359. }
  360. const params: GenerateContentParameters = {
  361. model: model.id,
  362. contents,
  363. config,
  364. };
  365. return params;
  366. }
  367. type ClampedThinkingLevel = Exclude<ThinkingLevel, "xhigh" | "max">;
  368. function isGemma4Model(model: Model<"google-generative-ai">): boolean {
  369. return /gemma-?4/.test(model.id.toLowerCase());
  370. }
  371. function isGemini3ProModel(model: Model<"google-generative-ai">): boolean {
  372. return /gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase());
  373. }
  374. function isGemini3FlashModel(model: Model<"google-generative-ai">): boolean {
  375. return /gemini-3(?:\.\d+)?-flash/.test(model.id.toLowerCase());
  376. }
  377. function getDisabledThinkingConfig(model: Model<"google-generative-ai">): ThinkingConfig {
  378. // Google docs: Gemini 3.1 Pro cannot disable thinking, and Gemini 3 Flash / Flash-Lite
  379. // do not support full thinking-off either. For Gemini 3 models, use the lowest supported
  380. // thinkingLevel without includeThoughts so hidden thinking remains invisible to pi.
  381. if (isGemini3ProModel(model)) {
  382. return { thinkingLevel: "LOW" as any };
  383. }
  384. if (isGemini3FlashModel(model)) {
  385. return { thinkingLevel: "MINIMAL" as any };
  386. }
  387. if (isGemma4Model(model)) {
  388. return { thinkingLevel: "MINIMAL" as any };
  389. }
  390. // Gemini 2.x supports disabling via thinkingBudget = 0.
  391. return { thinkingBudget: 0 };
  392. }
  393. function getThinkingLevel(effort: ClampedThinkingLevel, model: Model<"google-generative-ai">): GoogleThinkingLevel {
  394. if (isGemini3ProModel(model)) {
  395. switch (effort) {
  396. case "minimal":
  397. case "low":
  398. return "LOW";
  399. case "medium":
  400. case "high":
  401. return "HIGH";
  402. }
  403. }
  404. if (isGemma4Model(model)) {
  405. switch (effort) {
  406. case "minimal":
  407. case "low":
  408. return "MINIMAL";
  409. case "medium":
  410. case "high":
  411. return "HIGH";
  412. }
  413. }
  414. switch (effort) {
  415. case "minimal":
  416. return "MINIMAL";
  417. case "low":
  418. return "LOW";
  419. case "medium":
  420. return "MEDIUM";
  421. case "high":
  422. return "HIGH";
  423. }
  424. }
  425. function getGoogleBudget(
  426. model: Model<"google-generative-ai">,
  427. effort: ClampedThinkingLevel,
  428. customBudgets?: ThinkingBudgets,
  429. ): number {
  430. if (customBudgets?.[effort] !== undefined) {
  431. return customBudgets[effort]!;
  432. }
  433. if (model.id.includes("2.5-pro")) {
  434. const budgets: Record<ClampedThinkingLevel, number> = {
  435. minimal: 128,
  436. low: 2048,
  437. medium: 8192,
  438. high: 32768,
  439. };
  440. return budgets[effort];
  441. }
  442. if (model.id.includes("2.5-flash-lite")) {
  443. const budgets: Record<ClampedThinkingLevel, number> = {
  444. minimal: 512,
  445. low: 2048,
  446. medium: 8192,
  447. high: 24576,
  448. };
  449. return budgets[effort];
  450. }
  451. if (model.id.includes("2.5-flash")) {
  452. const budgets: Record<ClampedThinkingLevel, number> = {
  453. minimal: 128,
  454. low: 2048,
  455. medium: 8192,
  456. high: 24576,
  457. };
  458. return budgets[effort];
  459. }
  460. return -1;
  461. }