import {z} from 'zod' export type RoutingStrategyWire = 'reliability' | 'balanced' | 'latency' | 'throughput' | 'cache'; export type MessageRole = 'user' | 'assistant' | 'system'; export type ImageMediaType = 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp'; export type ImageSourceParam = {media_type: ImageMediaType, data: string, type: 'base64'} | {url: string, type: 'url'}; export type PdfMediaType = 'application/pdf'; export type PlainTextMediaType = 'text/plain'; export type DocumentContentBlockParam = {text: string, type: 'text'} | {source: ImageSourceParam, type: 'image'}; export type ContentBlockSourceParamContent = Array | string; export type DocumentSourceParam = {media_type?: PdfMediaType | undefined, data: string, type: 'base64'} | {url: string, type: 'url'} | {media_type?: PlainTextMediaType | undefined, data: string, type: 'text'} | {content: ContentBlockSourceParamContent, type: 'content'}; export type TextBlockParamPart = {text: string, type: 'text'}; export type ToolResultContentBlockParam = {text: string, type: 'text'} | {source: ImageSourceParam, type: 'image'} | {title?: (string | null) | undefined, source?: (string | null) | undefined, content?: Array | undefined, citations?: ({[key: string]: unknown} | null) | undefined, type: 'search_result'} | {source: DocumentSourceParam, title?: (string | null) | undefined, type: 'document'} | {tool_name?: (string | null) | undefined, type: 'tool_reference'} | {type: 'web_fetch_tool_result'} | {type: 'code_execution_tool_result'} | {type: 'bash_code_execution_tool_result'} | {type: 'text_editor_code_execution_tool_result'} | {type: 'tool_search_tool_result'} | {type: 'container_upload'}; export type ToolResultBlockParamContent = Array | string; export type ContentBlockParam = {text: string, type: 'text'} | {source: ImageSourceParam, type: 'image'} | {source: DocumentSourceParam, title?: (string | null) | undefined, type: 'document'} | {title?: (string | null) | undefined, source?: (string | null) | undefined, content?: Array | undefined, citations?: ({[key: string]: unknown} | null) | undefined, type: 'search_result'} | {thinking: string, signature?: (string | null) | undefined, type: 'thinking'} | {data: string, type: 'redacted_thinking'} | {id: string, name: string, input?: {[key: string]: unknown} | undefined, type: 'tool_use'} | {tool_use_id: string, content?: ToolResultBlockParamContent | undefined, type: 'tool_result'} | {id?: (string | null) | undefined, name?: (string | null) | undefined, input?: ({[key: string]: unknown} | null) | undefined, type: 'server_tool_use'} | {tool_use_id?: (string | null) | undefined, content?: (Array<{[key: string]: unknown}> | {[key: string]: unknown} | null) | undefined, type: 'web_search_tool_result'} | {type: 'web_fetch_tool_result'} | {type: 'code_execution_tool_result'} | {type: 'bash_code_execution_tool_result'} | {type: 'text_editor_code_execution_tool_result'} | {type: 'tool_search_tool_result'} | {type: 'container_upload'}; export type MessageParamContent = Array | string; export type MessageParam = {role: MessageRole, content: MessageParamContent}; export type WebSearchToolVersion = 'web_search_20250305' | 'web_search_20260209'; export type WebSearchToolName = 'web_search'; export type ToolUnionParam = {name: string, description?: (string | null) | undefined, input_schema: {[key: string]: unknown}, strict?: (boolean | null) | undefined} | {type: WebSearchToolVersion, name: WebSearchToolName, user_location?: ({[key: string]: unknown} | null) | undefined, search_context_size?: ('low' | 'medium' | 'high' | null) | undefined, external_web_access?: (boolean | null) | undefined, max_uses?: (number | null) | undefined, allowed_domains?: (Array | null) | undefined, blocked_domains?: (Array | null) | undefined, allowed_callers?: (Array | null) | undefined, defer_loading?: (boolean | null) | undefined, strict?: (boolean | null) | undefined} | {type: string, name?: (string | null) | undefined} | {[key: string]: unknown}; export type MessagesRequest = {model: string, max_tokens: number, messages: Array, routing?: ({strategy: RoutingStrategyWire} | null) | undefined, system?: (Array | string | null) | undefined, stream?: boolean | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, top_k?: (number | null) | undefined, stop_sequences?: (Array | null) | undefined, metadata?: ({[key: string]: unknown} | null) | undefined, tools?: (Array | null) | undefined, tool_choice?: ({disable_parallel_tool_use?: (boolean | null) | undefined, type: 'auto'} | {disable_parallel_tool_use?: (boolean | null) | undefined, type: 'any'} | {name: string, disable_parallel_tool_use?: (boolean | null) | undefined, type: 'tool'} | {type: 'none'} | null) | undefined, thinking?: ({budget_tokens?: (number | null) | undefined, type: 'enabled'} | {type: 'disabled'} | {type: 'adaptive'} | null) | undefined, output_config?: ({effort?: ('low' | 'medium' | 'high' | 'xhigh' | 'max' | null) | undefined, format?: ({[key: string]: unknown} | null) | undefined} | null) | undefined}; export type CreateApiV1MessagesArgs = {'x-naga-routing-strategy'?: RoutingStrategyWire | undefined, body: MessagesRequest}; export type CreateApiV1MessagesOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const messagesCaller = z.object({type: z.string()}); export const messagesWebSearchInput = z.object({query: z.string().nullable().optional()}); export const messagesWebSearchResult = z.object({type: z.string(), url: z.string(), title: z.string().nullable(), encrypted_content: z.string().nullable(), page_age: z.string().nullable()}); export const messagesImageSource = z.union([z.object({media_type: z.string(), data: z.string(), type: z.literal("base64")}), z.object({url: z.string(), type: z.literal("url")})]); export const messagesSearchResultText = z.object({type: z.string(), text: z.string()}); export const messagesContentBlock = z.union([z.object({thinking: z.string(), signature: z.string(), type: z.literal("thinking")}), z.object({data: z.string(), type: z.literal("redacted_thinking")}), z.object({text: z.string(), citations: z.unknown(), type: z.literal("text")}), z.object({id: z.string(), name: z.string(), input: z.unknown(), caller: messagesCaller, type: z.literal("tool_use")}), z.object({id: z.string(), name: z.string(), input: messagesWebSearchInput, caller: messagesCaller, type: z.literal("server_tool_use")}), z.object({tool_use_id: z.string(), content: z.array(messagesWebSearchResult), caller: messagesCaller, type: z.literal("web_search_tool_result")}), z.object({source: messagesImageSource, type: z.literal("image")}), z.object({source: z.string(), title: z.string(), content: z.array(messagesSearchResultText), citations: z.unknown(), type: z.literal("search_result")})]); export const messagesUsage = z.object({input_tokens: z.number().int(), output_tokens: z.number().int(), cache_creation: z.unknown(), cache_creation_input_tokens: z.number().int().nullable(), cache_read_input_tokens: z.number().int().nullable(), server_tool_use: z.object({web_search_requests: z.number().int(), web_fetch_requests: z.number().int()}).nullable(), service_tier: z.unknown(), inference_geo: z.unknown(), output_tokens_details: z.unknown()}); export const messagesMessage = z.object({id: z.string(), type: z.string(), role: z.string(), content: z.array(messagesContentBlock), model: z.string(), stop_reason: z.string().nullable(), stop_sequence: z.unknown(), stop_details: z.unknown(), container: z.unknown(), usage: messagesUsage}); export const anthropicMessageResponseType = z.literal("message"); export const anthropicMessageResponseRole = z.literal("assistant"); export const anthropicImageSourceResponseType = z.literal("url"); export const anthropicImageSourceResponse = z.object({type: anthropicImageSourceResponseType, url: z.string()}); export const anthropicTextBlockResponsePart = z.object({text: z.string(), type: z.literal("text")}); export const anthropicToolUseBlockResponseInput = z.union([z.object({}), z.string()]); export const anthropicContentBlockResponse = z.union([z.object({text: z.string(), type: z.literal("text")}), z.object({thinking: z.string(), signature: z.string().nullable().optional(), type: z.literal("thinking")}), z.object({source: anthropicImageSourceResponse, type: z.literal("image")}), z.object({title: z.string().nullable().optional(), source: z.string().nullable().optional(), content: z.array(anthropicTextBlockResponsePart).optional(), type: z.literal("search_result")}), z.object({id: z.string().nullable().optional(), name: z.string().nullable().optional(), input: anthropicToolUseBlockResponseInput.optional(), type: z.literal("tool_use")})]); export const anthropicMessageResponse = z.object({id: z.string(), type: anthropicMessageResponseType.optional(), role: anthropicMessageResponseRole.optional(), model: z.string(), content: z.array(anthropicContentBlockResponse), stop_reason: z.string().nullable().optional(), stop_sequence: z.string().nullable(), usage: z.object({input_tokens: z.number().int(), output_tokens: z.number().int(), cache_read_input_tokens: z.number().int().nullable().optional()}).nullable().optional(), created: z.number().int()}); export const createApiV1MessagesResponse = z.union([messagesMessage, anthropicMessageResponse]); 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 * * Also accepts auth: xApiKeyAuth */ export const createApiV1Messages = async (args: CreateApiV1MessagesArgs, options?: CreateApiV1MessagesOptions) => { const {baseUrl = "https://api.naga.ac", 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 (args['x-naga-routing-strategy'] != null) headers.set("x-naga-routing-strategy", String(args['x-naga-routing-strategy'])) 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()) };