import {z} from 'zod' export type TextBlock = {type: 'text', text: string}; export type ToolUseBlock = {type: 'tool_use', id: string, name: string, input: {[key: string]: unknown}}; export type ToolResultBlock = {type: 'tool_result', tool_use_id: string, content: string | Array, is_error?: boolean | undefined}; export type InputMessage = {role: 'user' | 'assistant', content: string | Array}; export type ToolDefinition = {name: string, description?: string | undefined, input_schema: {[key: string]: unknown}}; export type ToolChoice = {type: 'auto', disable_parallel_tool_use?: boolean | undefined} | {type: 'any'} | {type: 'tool', name: string} | {type: 'none'}; export type MessagesRequest = {model: string, messages: Array, max_tokens: number, system?: (string | Array) | undefined, temperature?: number | undefined, top_p?: number | undefined, top_k?: number | undefined, stop_sequences?: Array | undefined, stream?: boolean | undefined, tools?: Array | undefined, tool_choice?: ToolChoice | undefined, metadata?: ({user_id?: string | undefined}) | undefined}; export type CreateApiV1MessagesArgs = {body: MessagesRequest}; export type CreateApiV1MessagesOptions = {baseUrl: string, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const textBlock = z.object({type: z.literal("text"), text: z.string()}); export const toolUseBlock = z.object({type: z.literal("tool_use"), id: z.string(), name: z.string(), input: z.record(z.string(), z.unknown())}); export const usage = z.object({input_tokens: z.number().int().optional(), output_tokens: z.number().int().optional(), cache_read_input_tokens: z.number().int().optional()}).and(z.record(z.string(), z.unknown())); export const messagesResponse = z.object({id: z.string(), type: z.literal("message"), role: z.literal("assistant"), content: z.array(z.union([textBlock, toolUseBlock])), model: z.string(), stop_reason: z.enum(["end_turn", "max_tokens", "stop_sequence", "tool_use"]), stop_sequence: z.string().nullable().optional(), usage: usage}); 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 }; /** * Create a message * * POST /v1/messages */ export const createApiV1Messages = async (args: CreateApiV1MessagesArgs, options: CreateApiV1MessagesOptions) => { const {baseUrl, 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(messagesResponse, await res.json()) };