import {z} from 'zod' export type GeminiPart = {text?: string | undefined, inlineData?: {mimeType: string, data: string} | undefined, fileData?: ({mimeType?: string | undefined, fileUri: string}) | undefined, functionCall?: ({name?: string | undefined, args?: {[key: string]: unknown} | undefined}) | undefined, functionResponse?: ({name?: string | undefined, response?: {[key: string]: unknown} | undefined}) | undefined, executableCode?: {[key: string]: unknown} | undefined, codeExecutionResult?: {[key: string]: unknown} | undefined, thought?: boolean | undefined, thoughtSignature?: string | undefined} | {[key: string]: unknown}; export type GeminiContent = {role?: ('user' | 'model' | 'system') | undefined, parts: Array}; export type GeminiSafetySetting = {category: 'HARM_CATEGORY_HARASSMENT' | 'HARM_CATEGORY_HATE_SPEECH' | 'HARM_CATEGORY_SEXUALLY_EXPLICIT' | 'HARM_CATEGORY_DANGEROUS_CONTENT' | 'HARM_CATEGORY_CIVIC_INTEGRITY', threshold: 'HARM_BLOCK_THRESHOLD_UNSPECIFIED' | 'BLOCK_LOW_AND_ABOVE' | 'BLOCK_MEDIUM_AND_ABOVE' | 'BLOCK_ONLY_HIGH' | 'BLOCK_NONE' | 'OFF'}; export type GeminiGenerationConfig = {stopSequences?: Array | undefined, responseMimeType?: ('text/plain' | 'application/json' | 'text/x.enum') | undefined, responseSchema?: {[key: string]: unknown} | undefined, responseJsonSchema?: {[key: string]: unknown} | undefined, responseModalities?: (Array<'TEXT' | 'IMAGE' | 'AUDIO'>) | undefined, candidateCount?: number | undefined, maxOutputTokens?: number | undefined, temperature?: number | undefined, topP?: number | undefined, topK?: number | undefined, seed?: number | undefined, presencePenalty?: number | undefined, frequencyPenalty?: number | undefined, responseLogprobs?: boolean | undefined, logprobs?: number | undefined, enableEnhancedCivicAnswers?: boolean | undefined, thinkingConfig?: ({includeThoughts?: boolean | undefined, thinkingBudget?: number | undefined, thinkingLevel?: ('THINKING_LEVEL_UNSPECIFIED' | 'MINIMAL' | 'LOW' | 'MEDIUM' | 'HIGH') | undefined}) | undefined, imageConfig?: ({aspectRatio?: string | undefined, imageSize?: ('512' | '1K' | '2K' | '4K') | undefined}) | undefined, mediaResolution?: ('MEDIA_RESOLUTION_UNSPECIFIED' | 'MEDIA_RESOLUTION_LOW' | 'MEDIA_RESOLUTION_MEDIUM' | 'MEDIA_RESOLUTION_HIGH') | undefined, responseFormat?: {[key: string]: unknown} | undefined}; export type GeminiGenerateContentRequest = {contents: Array, tools?: Array<{[key: string]: unknown}> | undefined, toolConfig?: {[key: string]: unknown} | undefined, safetySettings?: Array | undefined, systemInstruction?: GeminiContent | undefined, generationConfig?: GeminiGenerationConfig | undefined, cachedContent?: string | undefined, serviceTier?: ('unspecified' | 'standard' | 'flex' | 'priority') | undefined, store?: boolean | undefined}; export type CreateApiV1betaModelsModelGenerateContentArgs = {model: string, body: GeminiGenerateContentRequest}; export type CreateApiV1betaModelsModelGenerateContentOptions = {baseUrl?: string | undefined, CustomApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const geminiPart = z.object({text: z.string().optional(), inlineData: z.object({mimeType: z.string(), data: z.string()}).optional(), fileData: z.object({mimeType: z.string().optional(), fileUri: z.string()}).optional(), functionCall: z.object({name: z.string().optional(), args: z.record(z.string(), z.unknown()).optional()}).optional(), functionResponse: z.object({name: z.string().optional(), response: z.record(z.string(), z.unknown()).optional()}).optional(), executableCode: z.record(z.string(), z.unknown()).optional(), codeExecutionResult: z.record(z.string(), z.unknown()).optional(), thought: z.boolean().optional(), thoughtSignature: z.string().optional()}).and(z.record(z.string(), z.unknown())); export const geminiContent = z.object({role: z.enum(["user", "model", "system"]).optional(), parts: z.array(geminiPart)}); export const geminiCandidate = z.object({content: geminiContent.optional(), finishReason: z.enum(["FINISH_REASON_UNSPECIFIED", "STOP", "MAX_TOKENS", "SAFETY", "RECITATION", "LANGUAGE", "OTHER", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "MALFORMED_FUNCTION_CALL", "IMAGE_SAFETY", "UNEXPECTED_TOOL_CALL"]).optional(), finishMessage: z.string().optional(), safetyRatings: z.array(z.record(z.string(), z.unknown())).optional(), citationMetadata: z.record(z.string(), z.unknown()).optional(), groundingMetadata: z.record(z.string(), z.unknown()).optional(), avgLogprobs: z.number().optional(), index: z.number().int().optional()}); export const geminiUsageMetadata = z.object({promptTokenCount: z.number().int().optional(), cachedContentTokenCount: z.number().int().optional(), candidatesTokenCount: z.number().int().optional(), toolUsePromptTokenCount: z.number().int().optional(), thoughtsTokenCount: z.number().int().optional(), totalTokenCount: z.number().int().optional(), serviceTier: z.string().optional()}); export const geminiGenerateContentResponse = z.object({candidates: z.array(geminiCandidate).optional(), promptFeedback: z.object({blockReason: z.string().optional(), safetyRatings: z.array(z.record(z.string(), z.unknown())).optional()}).optional(), usageMetadata: geminiUsageMetadata.optional(), modelVersion: z.string().optional(), responseId: z.string().optional(), modelStatus: z.record(z.string(), z.unknown()).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Generate Gemini content * * POST /v1beta/models/{model}:generateContent */ export const createApiV1betaModelsModelGenerateContent = async (args: CreateApiV1betaModelsModelGenerateContentArgs, options?: CreateApiV1betaModelsModelGenerateContentOptions) => { const {baseUrl = "https://api.ttapi.io", fetch: fetchFn = fetch, CustomApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (CustomApiKey !== undefined) headers.set("TT-API-KEY", CustomApiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1beta/models/${encodeURIComponent(String(args.model))}:generateContent${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(geminiGenerateContentResponse, await res.json()) };