google-vertex.ts 16 KB

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