import {z} from 'zod' export type CreateApiV1MessagesArgs = {body: {model: string, messages: Array<{role: 'user' | 'assistant', content: string | Array<{type?: string | undefined, text?: string | undefined, source?: {[key: string]: unknown} | undefined, tool_use_id?: string | undefined, content: unknown, cache_control?: {[key: string]: unknown} | undefined} | {[key: string]: unknown}>} | {[key: string]: unknown}>, max_tokens: number, cache_control?: ({type?: 'ephemeral' | undefined, ttl?: number | undefined} | {[key: string]: unknown}) | undefined, container?: string | undefined, inference_geo?: string | undefined, context_management?: ({[key: string]: unknown} | null) | undefined, mcp_servers?: Array<{[key: string]: unknown}> | undefined, metadata?: ({user_id?: string | undefined} | {[key: string]: unknown}) | undefined, output_config?: ({effort?: ('low' | 'medium' | 'high') | undefined, format?: {[key: string]: unknown} | undefined} | {[key: string]: unknown}) | undefined, service_tier?: ('auto' | 'standard_only') | undefined, stop_sequences?: Array | undefined, stream?: boolean | undefined, system?: (string | Array) | undefined, temperature?: number | undefined, thinking?: ({type?: ('enabled' | 'disabled') | undefined, budget_tokens?: number | undefined} | {[key: string]: unknown}) | undefined, tool_choice?: ({type?: ('auto' | 'any' | 'tool' | 'none') | undefined, name?: string | undefined, disable_parallel_tool_use?: boolean | undefined} | {[key: string]: unknown}) | undefined, tools?: (Array<{name?: string | undefined, type?: string | undefined, description?: string | undefined, input_schema?: Record | undefined} | {[key: string]: unknown}>) | undefined, top_k?: number | undefined, top_p?: number | undefined} | {[key: string]: unknown}}; export type CreateApiV1MessagesOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiV1MessagesResponse = z.object({id: z.string(), type: z.literal("message"), role: z.literal("assistant"), container: z.object({id: z.string().optional(), expires_at: z.string().optional()}).optional(), model: z.string(), content: z.array(z.object({type: z.enum(["text", "thinking", "tool_use"]).optional(), text: z.string().optional(), thinking: z.string().optional(), signature: z.string().optional(), id: z.string().optional(), name: z.string().optional(), input: z.object({}).optional(), citations: z.array(z.record(z.string(), z.unknown())).optional()})), stop_reason: z.enum(["end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", "refusal"]), stop_sequence: z.string().nullable().optional(), usage: z.object({input_tokens: z.number().int(), output_tokens: z.number().int(), cache_creation_input_tokens: z.number().int().optional(), cache_read_input_tokens: z.number().int().optional(), cache_creation: z.object({ephemeral_5m_input_tokens: z.number().int().optional(), ephemeral_1h_input_tokens: z.number().int().optional()}).optional(), inference_geo: z.string().optional(), server_tool_use: z.object({web_search_requests: z.number().int().optional(), web_fetch_requests: z.number().int().optional()}).optional(), service_tier: z.string().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 }; /** * Anthropic Claude * * POST /v1/messages */ export const createApiV1Messages = async (args: CreateApiV1MessagesArgs, options?: CreateApiV1MessagesOptions) => { 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(/\/+$/, '')}/v1/messages${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(createApiV1MessagesResponse, await res.json()) };