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

client.ts

86 lines2.7 KB

1import { GoogleGenAI } from '@google/genai'
2import { generateId as _generateId, getApiKeyFromEnv } from '@tanstack/ai-utils'
3import type { GoogleGenAIOptions } from '@google/genai'
4​
5export interface GeminiClientConfig extends GoogleGenAIOptions {
6 /**
7 * Base URL for every request. Maps onto `httpOptions.baseUrl` and wins
8 * over it when both are set. Same option name as the other adapters, so a
9 * gateway config can be spread into any of them.
10 */
11 baseURL?: string
12 /**
13 * Headers sent with every request. Maps onto `httpOptions.headers` and wins
14 * over it when both are set. Same option name as the other adapters.
15 */
16 defaultHeaders?: Record<string, string>
18​
19/**
20 * Creates a Google Generative AI client instance.
21 *
22 * AI Studio mode needs `apiKey`. Vertex / Enterprise mode (`vertexai` or
23 * `enterprise`) uses project, location, and Google Cloud credentials instead.
24 */
25export function createGeminiClient(config: GeminiClientConfig): GoogleGenAI {
26 const vertexMode = config.vertexai === true || config.enterprise === true
27 if (
28 !vertexMode &&
29 (config.apiKey === undefined || config.apiKey.length === 0)
30 ) {
31 throw new Error(
32 'A Gemini API key is required when vertexai and enterprise are not set. Pass apiKey, or set GOOGLE_API_KEY or GEMINI_API_KEY.',
33 )
34 }
35 const { baseURL, defaultHeaders, ...options } = config
36 if (baseURL !== undefined || defaultHeaders !== undefined) {
37 options.httpOptions = {
38 ...options.httpOptions,
39 ...(baseURL !== undefined ? { baseUrl: baseURL } : {}),
40 ...(defaultHeaders !== undefined ? { headers: defaultHeaders } : {}),
41 }
42 }
43 return new GoogleGenAI(options)
45​
46/**
47 * Gets Google API key from environment variables
48 * @throws Error if GOOGLE_API_KEY or GEMINI_API_KEY is not found
49 */
50export function getGeminiApiKeyFromEnv(): string {
51 try {
52 return getApiKeyFromEnv('GOOGLE_API_KEY')
53 } catch {
54 try {
55 return getApiKeyFromEnv('GEMINI_API_KEY')
56 } catch {
57 throw new Error(
58 'GOOGLE_API_KEY or GEMINI_API_KEY is not set. Please set one of these environment variables or pass the API key directly.',
59 )
60 }
61 }
63​
64/**
65 * Generates a unique ID with a prefix
66 */
67export function generateId(prefix: string): string {
68 return _generateId(prefix)
70​
71/**
72 * True when a Gemini API error says the input does not fit in the model's
73 * context window. The API has no error status for it. It answers 400
74 * `INVALID_ARGUMENT`, the same as every bad request, so the message text is
75 * the only signal.
76 */
77export function isGeminiContextOverflow(error: unknown): boolean {
78 return (
79 error instanceof Error &&
80 'status' in error &&
81 error.status === 400 &&
82 /input token count.*exceeds the maximum number of tokens/.test(
83 error.message,
84 )
85 )