import {z} from 'zod' export type AnthropicModel = string; export type AnthropicCacheControlEphemeral = {ttl?: ('5m' | '1h') | undefined, type: 'ephemeral'}; export type AnthropicRequestCharLocationCitation = {cited_text: string, document_index: number, document_title: string | null, end_char_index: number, start_char_index: number, type: 'char_location'}; export type AnthropicRequestPageLocationCitation = {cited_text: string, document_index: number, document_title: string | null, end_page_number: number, start_page_number: number, type: 'page_location'}; export type AnthropicRequestContentBlockLocationCitation = {cited_text: string, document_index: number, document_title: string | null, end_block_index: number, start_block_index: number, type: 'content_block_location'}; export type AnthropicRequestWebSearchResultLocationCitation = {cited_text: string, encrypted_index: string, title: string | null, type: 'web_search_result_location', url: string}; export type AnthropicRequestSearchResultLocationCitation = {cited_text: string, end_block_index: number, search_result_index: number, source: string, start_block_index: number, title: string | null, type: 'search_result_location'}; export type AnthropicBase64ImageSource = {data: string, media_type: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp', type: 'base64'}; export type AnthropicURLImageSource = {type: 'url', url: string}; export type AnthropicRequestCitationsConfig = {enabled?: boolean | undefined}; export type AnthropicBase64PDFSource = {data: string, media_type: 'application/pdf', type: 'base64'}; export type AnthropicPlainTextSource = {data: string, media_type: 'text/plain', type: 'text'}; export type AnthropicContentBlockSource = {content: string | Array<{cache_control?: (AnthropicCacheControlEphemeral | null) | undefined, citations?: (Array | null) | undefined, text: string, type: 'text'} | {cache_control?: (AnthropicCacheControlEphemeral | null) | undefined, source: AnthropicBase64ImageSource | AnthropicURLImageSource, type: 'image'}>, type: 'content'}; export type AnthropicURLPDFSource = {type: 'url', url: string}; export type AnthropicRequestTextBlock = {cache_control?: (AnthropicCacheControlEphemeral | null) | undefined, citations?: (Array | null) | undefined, text: string, type: 'text'}; export type AnthropicRequestImageBlock = {cache_control?: (AnthropicCacheControlEphemeral | null) | undefined, source: AnthropicBase64ImageSource | AnthropicURLImageSource, type: 'image'}; export type AnthropicRequestDocumentBlock = {cache_control?: (AnthropicCacheControlEphemeral | null) | undefined, citations?: (AnthropicRequestCitationsConfig | null) | undefined, context?: (string | null) | undefined, source: AnthropicBase64PDFSource | AnthropicPlainTextSource | AnthropicContentBlockSource | AnthropicURLPDFSource, title?: (string | null) | undefined, type: 'document'}; export type AnthropicInputContentBlock = {cache_control?: (AnthropicCacheControlEphemeral | null) | undefined, citations?: (Array | null) | undefined, text: string, type: 'text'} | {cache_control?: (AnthropicCacheControlEphemeral | null) | undefined, source: AnthropicBase64ImageSource | AnthropicURLImageSource, type: 'image'} | {cache_control?: (AnthropicCacheControlEphemeral | null) | undefined, citations?: (AnthropicRequestCitationsConfig | null) | undefined, context?: (string | null) | undefined, source: AnthropicBase64PDFSource | AnthropicPlainTextSource | AnthropicContentBlockSource | AnthropicURLPDFSource, title?: (string | null) | undefined, type: 'document'} | {signature: string, thinking: string, type: 'thinking'} | {data: string, type: 'redacted_thinking'} | {cache_control?: (AnthropicCacheControlEphemeral | null) | undefined, id: string, input: {[key: string]: unknown}, name: string, type: 'tool_use'} | {cache_control?: (AnthropicCacheControlEphemeral | null) | undefined, content?: (string | Array) | undefined, is_error?: boolean | undefined, tool_use_id: string, type: 'tool_result'}; export type AnthropicInputMessage = {content: string | Array, role: 'user' | 'assistant'}; export type AnthropicMetadata = {user_id?: (string | null) | undefined}; export type AnthropicEffortLevel = 'low' | 'medium' | 'high' | 'max'; export type AnthropicJsonOutputFormat = {schema: {[key: string]: unknown}, type: 'json_schema'}; export type AnthropicOutputConfig = {effort?: (AnthropicEffortLevel | null) | undefined, format?: (AnthropicJsonOutputFormat | null) | undefined}; export type AnthropicThinkingConfigEnabled = {budget_tokens: number, type: 'enabled'}; export type AnthropicThinkingConfigDisabled = {type: 'disabled'}; export type AnthropicThinkingConfigAdaptive = {type: 'adaptive'}; export type AnthropicThinkingConfigParam = AnthropicThinkingConfigEnabled | AnthropicThinkingConfigDisabled | AnthropicThinkingConfigAdaptive; export type AnthropicToolChoiceAuto = {disable_parallel_tool_use?: boolean | undefined, type: 'auto'}; export type AnthropicToolChoiceAny = {disable_parallel_tool_use?: boolean | undefined, type: 'any'}; export type AnthropicToolChoiceTool = {disable_parallel_tool_use?: boolean | undefined, name: string, type: 'tool'}; export type AnthropicToolChoiceNone = {type: 'none'}; export type AnthropicToolChoice = AnthropicToolChoiceAuto | AnthropicToolChoiceAny | AnthropicToolChoiceTool | AnthropicToolChoiceNone; export type AnthropicInputSchema = {properties?: ({[key: string]: unknown} | null) | undefined, required?: (Array | null) | undefined, type: 'object'} | {[key: string]: unknown}; export type AnthropicTool = {type?: ('custom' | null) | undefined, description?: string | undefined, name: string, input_schema: AnthropicInputSchema, strict?: boolean | undefined}; export type AnthropicCreateMessageParams = {model: AnthropicModel, messages: Array, max_tokens?: number | undefined, metadata?: AnthropicMetadata | undefined, output_config?: AnthropicOutputConfig | undefined, stop_sequences?: Array | undefined, stream?: boolean | undefined, system?: (string | Array) | undefined, temperature?: number | undefined, thinking?: AnthropicThinkingConfigParam | undefined, tool_choice?: AnthropicToolChoice | undefined, tools?: Array | undefined, top_k?: number | undefined, top_p?: number | undefined, raw_output?: (boolean | null) | undefined}; export type CreateApiV1MessagesArgs = {body: AnthropicCreateMessageParams}; export type CreateApiV1MessagesOptions = {baseUrl: string, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const anthropicResponseCharLocationCitation = z.object({cited_text: z.string(), document_index: z.number().int().gte(0), document_title: z.string().nullable(), end_char_index: z.number().int(), file_id: z.string().nullable(), start_char_index: z.number().int().gte(0), type: z.literal("char_location")}); export const anthropicResponsePageLocationCitation = z.object({cited_text: z.string(), document_index: z.number().int().gte(0), document_title: z.string().nullable(), end_page_number: z.number().int(), file_id: z.string().nullable(), start_page_number: z.number().int().gte(1), type: z.literal("page_location")}); export const anthropicResponseContentBlockLocationCitation = z.object({cited_text: z.string(), document_index: z.number().int().gte(0), document_title: z.string().nullable(), end_block_index: z.number().int(), file_id: z.string().nullable(), start_block_index: z.number().int().gte(0), type: z.literal("content_block_location")}); export const anthropicResponseWebSearchResultLocationCitation = z.object({cited_text: z.string(), encrypted_index: z.string(), title: z.string().max(512).nullable(), type: z.literal("web_search_result_location"), url: z.string()}); export const anthropicResponseSearchResultLocationCitation = z.object({cited_text: z.string(), end_block_index: z.number().int(), search_result_index: z.number().int().gte(0), source: z.string(), start_block_index: z.number().int().gte(0), title: z.string().nullable(), type: z.literal("search_result_location")}); export const anthropicResponseTextBlock = z.object({citations: z.array(z.discriminatedUnion("type", [anthropicResponseCharLocationCitation, anthropicResponsePageLocationCitation, anthropicResponseContentBlockLocationCitation, anthropicResponseWebSearchResultLocationCitation, anthropicResponseSearchResultLocationCitation])).nullable(), text: z.string().max(5000000), type: z.literal("text")}); export const anthropicResponseThinkingBlock = z.object({signature: z.string(), thinking: z.string(), type: z.literal("thinking")}); export const anthropicResponseRedactedThinkingBlock = z.object({data: z.string(), type: z.literal("redacted_thinking")}); export const anthropicResponseToolUseBlock = z.object({id: z.string(), input: z.record(z.string(), z.unknown()), name: z.string().min(1), type: z.literal("tool_use")}); export const anthropicContentBlock = z.discriminatedUnion("type", [anthropicResponseTextBlock, anthropicResponseThinkingBlock, anthropicResponseRedactedThinkingBlock, anthropicResponseToolUseBlock]); export const anthropicModel = z.string(); export const anthropicStopReason = z.enum(["end_turn", "max_tokens", "stop_sequence", "tool_use", "pause_turn", "refusal"]); export const anthropicRawOutput = z.object({prompt_fragments: z.array(z.union([z.string(), z.number().int()])), prompt_token_ids: z.array(z.number().int()), completion: z.string(), completion_token_ids: z.array(z.number().int()).nullable().optional(), images: z.array(z.string()).nullable().optional(), grammar: z.string().nullable().optional()}); export const anthropicMessage = z.object({id: z.string(), type: z.literal("message"), role: z.literal("assistant"), content: z.array(anthropicContentBlock), model: anthropicModel, stop_reason: anthropicStopReason.nullable(), stop_sequence: z.string().nullable(), raw_output: anthropicRawOutput.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 }; /** * 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(anthropicMessage, await res.json()) };