import {z} from 'zod' export type ContentBlock = {type?: string | undefined, text?: (string | null) | undefined, id?: (string | null) | undefined, name?: (string | null) | undefined, input?: ({[key: string]: unknown} | null) | undefined, tool_use_id?: (string | null) | undefined, content?: (string | Array | null) | undefined} | {[key: string]: unknown}; export type ImageSource = {type: 'base64' | 'url', media_type?: (string | null) | undefined, data?: (string | null) | undefined, url?: (string | null) | undefined}; export type ImageContentBlock = {type?: 'image' | undefined, source: ImageSource}; export type AnthropicMessage = {role: string, content: string | Array}; export type SystemContentBlock = {type?: string | undefined, text?: string | undefined, cache_control?: ({[key: string]: unknown} | null) | undefined}; export type AnthropicOutputConfig = {effort?: (string | null) | undefined, task_budget?: ({[key: string]: unknown} | null) | undefined, format?: ({[key: string]: unknown} | null) | undefined} | {[key: string]: unknown}; export type AnthropicMessagesRequest = {model: string, messages: Array, max_tokens?: number | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, top_k?: (number | null) | undefined, stream?: boolean | undefined, store?: boolean | undefined, system?: (string | Array | null) | undefined, cache_control?: ({[key: string]: unknown} | null) | undefined, tools?: (Array<{[key: string]: unknown}> | null) | undefined, tool_choice?: ({[key: string]: unknown} | null) | undefined, stop_sequences?: (Array | null) | undefined, output_config?: (AnthropicOutputConfig | null) | undefined, speed?: ('standard' | 'fast' | null) | undefined, thinking?: ({[key: string]: unknown} | null) | undefined, schema?: (Array | {[key: string]: unknown} | null) | undefined, task_type?: (string | null) | undefined, include_confidence?: boolean | undefined, include_spans?: boolean | undefined}; export type CreateApiV1MessagesArgs = {body: AnthropicMessagesRequest}; export type CreateApiV1MessagesOptions = {baseUrl: string, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const anthropicUsage = z.object({input_tokens: z.number().int().optional(), output_tokens: z.number().int().optional(), cache_read_input_tokens: z.number().int().optional(), cache_creation_input_tokens: z.number().int().optional(), thinking_tokens: z.number().int().nullable().optional(), server_tool_use: z.record(z.string(), z.number().int()).nullable().optional(), service_tier: z.string().nullable().optional(), speed: z.string().nullable().optional()}); export const anthropicMessagesResponse = z.object({id: z.string(), type: z.string().optional(), role: z.string().optional(), content: z.array(z.record(z.string(), z.unknown())), model: z.string(), stop_reason: z.string().nullable().optional(), stop_sequence: z.string().nullable().optional(), usage: anthropicUsage, fastino_inference_id: z.string().nullable().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 }; /** * Messages * * POST /v1/messages * * Also accepts auth: BearerAuth */ export const createApiV1Messages = async (args: CreateApiV1MessagesArgs, options: CreateApiV1MessagesOptions) => { const {baseUrl, fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKeyAuth !== undefined) headers.set("X-API-Key", ApiKeyAuth) 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(anthropicMessagesResponse, await res.json()) };