import {z} from 'zod' export type CacheControl = {type?: 'ephemeral' | undefined, ttl?: string | undefined}; export type AnthropicContentBlock = {type: 'text' | 'image' | 'document' | 'tool_use' | 'server_tool_use' | 'tool_result' | 'web_search_result' | 'mcp_tool_use' | 'mcp_tool_result' | 'thinking' | 'redacted_thinking', text?: string | undefined, thinking?: string | undefined, signature?: string | undefined, data?: string | undefined, tool_use_id?: string | undefined, id?: string | undefined, name?: string | undefined, input?: Record | undefined, server_name?: string | undefined, content?: (string | Array) | undefined, source?: ({type: 'base64' | 'url' | 'text' | 'content_block', media_type?: string | undefined, data?: string | undefined, url?: string | undefined}) | undefined, cache_control?: CacheControl | undefined, citations?: ({enabled?: boolean | undefined}) | undefined, context?: string | undefined, title?: string | undefined}; export type AnthropicMessage = {role: 'user' | 'assistant', content: string | Array}; export type AnthropicMessageRequest = {model: string, max_tokens: number, messages: Array, system?: (string | Array) | undefined, cache_control?: CacheControl | undefined, metadata?: ({user_id?: string | undefined}) | undefined, stream?: boolean | undefined, temperature?: number | undefined, top_p?: number | undefined, top_k?: number | undefined, stop_sequences?: Array | undefined, tools?: (Array<{type?: ('custom' | 'bash_20250124' | 'computer_20250124' | 'computer_20251124' | 'code_execution_20250522' | 'code_execution_20250825' | 'code_execution_20260120' | 'text_editor_20250124' | 'text_editor_20250429' | 'text_editor_20250728' | 'web_search_20250305' | 'web_search_20260209' | 'web_fetch_20250910' | 'web_fetch_20260209' | 'web_fetch_20260309' | 'memory_20250818' | 'tool_search_tool_bm25' | 'tool_search_tool_bm25_20251119' | 'tool_search_tool_regex' | 'tool_search_tool_regex_20251119') | undefined, name?: string | undefined, description?: string | undefined, input_schema?: Record | undefined, cache_control?: CacheControl | undefined, display_width_px?: number | undefined, display_height_px?: number | undefined, display_number?: number | undefined, enable_zoom?: boolean | undefined, max_uses?: number | undefined, allowed_domains?: Array | undefined, blocked_domains?: Array | undefined, user_location?: ({type?: 'approximate' | undefined, city?: string | undefined, country?: string | undefined, timezone?: string | undefined}) | undefined}>) | undefined, tool_choice?: ({type?: ('auto' | 'any' | 'tool' | 'none') | undefined, name?: string | undefined, disable_parallel_tool_use?: boolean | undefined}) | undefined, mcp_servers?: (Array<{type?: string | undefined, name?: string | undefined, url?: string | undefined, authorization_token?: string | undefined, tool_configuration?: ({enabled?: boolean | undefined, allowed_tools?: Array | undefined}) | undefined}>) | undefined, thinking?: ({type?: ('enabled' | 'disabled') | undefined, budget_tokens?: number | undefined}) | undefined, output_format?: Record | undefined, fallbacks?: Array | undefined}; export type CreateApiLangchainAnthropicV1MessagesArgs = {body: AnthropicMessageRequest}; export type CreateApiLangchainAnthropicV1MessagesOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const cacheControl = z.object({type: z.literal("ephemeral").optional(), ttl: z.string().optional()}); export const anthropicContentBlock: z.ZodType = z.object({type: z.enum(["text", "image", "document", "tool_use", "server_tool_use", "tool_result", "web_search_result", "mcp_tool_use", "mcp_tool_result", "thinking", "redacted_thinking"]), text: z.string().optional(), thinking: z.string().optional(), signature: z.string().optional(), data: z.string().optional(), tool_use_id: z.string().optional(), id: z.string().optional(), name: z.string().optional(), input: z.object({}).optional(), server_name: z.string().optional(), content: z.union([z.string(), z.array(z.lazy(() => anthropicContentBlock))]).optional(), source: z.object({type: z.enum(["base64", "url", "text", "content_block"]), media_type: z.string().optional(), data: z.string().optional(), url: z.string().optional()}).optional(), cache_control: cacheControl.optional(), citations: z.object({enabled: z.boolean().optional()}).optional(), context: z.string().optional(), title: z.string().optional()}); export const anthropicMessageResponse = z.object({id: z.string().optional(), type: z.string().optional(), role: z.string().optional(), content: z.array(anthropicContentBlock).optional(), model: z.string().optional(), stop_reason: z.string().optional(), stop_sequence: z.string().nullable().optional(), usage: z.object({input_tokens: z.number().int().optional(), output_tokens: z.number().int().optional(), 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()}).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 message (LangChain - Anthropic format) * * POST /langchain/anthropic/v1/messages * * Also accepts auth: BasicAuth, VirtualKeyAuth, ApiKeyAuth */ export const createApiLangchainAnthropicV1Messages = async (args: CreateApiLangchainAnthropicV1MessagesArgs, options?: CreateApiLangchainAnthropicV1MessagesOptions) => { const {baseUrl = "http://localhost:8080", 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(/\/+$/, '')}/langchain/anthropic/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(anthropicMessageResponse, await res.json()) };