import {z} from 'zod' export type CreateApiV1betaModelsModelFunctionArgs = {model: string, function: string, body: {contents: Array<{role?: ('user' | 'model') | undefined, parts?: (Array<{text?: string | undefined, inlineData?: {[key: string]: unknown} | undefined, fileData?: {[key: string]: unknown} | undefined, functionCall?: {[key: string]: unknown} | undefined, functionResponse?: {[key: string]: unknown} | undefined} | {[key: string]: unknown}>) | undefined} | {[key: string]: unknown}>, systemInstruction?: ({role?: string | undefined, parts?: (Array<{text?: string | undefined} | {[key: string]: unknown}>) | undefined} | {[key: string]: unknown}) | undefined, tools?: Array<{[key: string]: unknown}> | undefined, toolConfig?: {[key: string]: unknown} | undefined, safetySettings?: (Array<{category?: ('HARM_CATEGORY_HARASSMENT' | 'HARM_CATEGORY_HATE_SPEECH' | 'HARM_CATEGORY_SEXUALLY_EXPLICIT' | 'HARM_CATEGORY_DANGEROUS_CONTENT' | 'HARM_CATEGORY_CIVIC_INTEGRITY') | undefined, threshold?: ('OFF' | 'BLOCK_NONE' | 'BLOCK_ONLY_HIGH' | 'BLOCK_MEDIUM_AND_ABOVE' | 'BLOCK_LOW_AND_ABOVE') | undefined} | {[key: string]: unknown}>) | undefined, cachedContent?: string | undefined, store?: boolean | undefined, generationConfig?: ({responseModalities?: (Array<'TEXT' | 'IMAGE' | 'AUDIO'>) | undefined, temperature?: number | undefined, maxOutputTokens?: number | undefined, topP?: number | undefined, topK?: number | undefined, stopSequences?: Array | undefined, seed?: number | undefined, presencePenalty?: number | undefined, frequencyPenalty?: number | undefined, responseMimeType?: string | undefined, responseSchema?: {[key: string]: unknown} | undefined, responseJsonSchema: unknown, candidateCount?: number | undefined, thinkingConfig?: ({includeThoughts?: boolean | undefined, thinkingBudget?: number | undefined, thinkingLevel?: ('MINIMAL' | 'LOW' | 'MEDIUM' | 'HIGH') | undefined} | {[key: string]: unknown}) | undefined, responseLogprobs?: boolean | undefined, logprobs?: number | undefined, speechConfig?: {[key: string]: unknown} | undefined, imageConfig?: ({aspectRatio?: string | undefined, imageSize?: string | undefined} | {[key: string]: unknown}) | undefined, mediaResolution?: ('MEDIA_RESOLUTION_LOW' | 'MEDIA_RESOLUTION_MEDIUM' | 'MEDIA_RESOLUTION_HIGH') | undefined} | {[key: string]: unknown}) | undefined} | {[key: string]: unknown}}; export type CreateApiV1betaModelsModelFunctionOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiV1betaModelsModelFunctionResponse = z.object({candidates: z.array(z.object({content: z.object({role: z.string().optional(), parts: z.array(z.object({text: z.string().optional(), thought: z.boolean().optional()})).optional()}).optional(), finishReason: z.enum(["STOP", "MAX_TOKENS", "SAFETY", "RECITATION", "LANGUAGE", "OTHER", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "MALFORMED_FUNCTION_CALL"]).optional(), tokenCount: z.number().int().optional(), avgLogprobs: z.number().optional(), groundingMetadata: z.record(z.string(), z.unknown()).optional(), urlContextMetadata: z.record(z.string(), z.unknown()).optional(), citationMetadata: z.record(z.string(), z.unknown()).optional(), finishMessage: z.string().optional(), index: z.number().int().optional(), safetyRatings: z.array(z.object({category: z.string().optional(), probability: z.string().optional()})).optional()})).optional(), usageMetadata: 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(), promptTokensDetails: z.array(z.object({modality: z.string().optional(), tokenCount: z.number().int().optional()})).optional(), candidatesTokensDetails: z.array(z.object({modality: z.string().optional(), tokenCount: z.number().int().optional()})).optional()}).optional(), modelVersion: z.string().optional(), responseId: z.string().optional(), modelStatus: z.object({modelStage: z.string().optional(), retirementTime: z.string().optional(), message: z.string().optional()}).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 }; /** * Gemini Text API * * POST /v1beta/models/{model}:{function} */ export const createApiV1betaModelsModelFunction = async (args: CreateApiV1betaModelsModelFunctionArgs, options?: CreateApiV1betaModelsModelFunctionOptions) => { const {baseUrl = "https://api.deerapi.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1beta/models/${encodeURIComponent(String(args.model))}:${encodeURIComponent(String(args.function))}${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(createApiV1betaModelsModelFunctionResponse, await res.json()) };