import {z} from 'zod' export type RoutingStrategyWire = 'reliability' | 'balanced' | 'latency' | 'throughput' | 'cache'; export type InputMessageRole = 'user' | 'assistant' | 'system' | 'developer'; export type ResponseContentPart = {text: string, type: 'input_text'} | {text: string, annotations?: (Array<{[key: string]: unknown}> | null) | undefined, logprobs?: (Array<{[key: string]: unknown}> | null) | undefined, type: 'output_text'} | {image_url?: (string | null) | undefined, file_id?: (string | null) | undefined, detail?: ('auto' | 'low' | 'high' | null) | undefined, type: 'input_image'} | {input_audio: {[key: string]: unknown}, type: 'input_audio'} | {filename?: (string | null) | undefined, file_data?: (string | null) | undefined, file_url?: (string | null) | undefined, file_id?: (string | null) | undefined, input_file?: ({[key: string]: unknown} | null) | undefined, type: 'input_file'}; export type FunctionCallOutputContentPart = {text: string, type: 'input_text'} | {image_url?: (string | null) | undefined, file_id?: (string | null) | undefined, detail?: ('auto' | 'low' | 'high' | null) | undefined, type: 'input_image'} | {filename?: (string | null) | undefined, file_data?: (string | null) | undefined, file_url?: (string | null) | undefined, file_id?: (string | null) | undefined, input_file?: ({[key: string]: unknown} | null) | undefined, type: 'input_file'}; export type FunctionCallOutputOutput = Array | string; export type ComputerEnvironment = 'windows' | 'mac' | 'linux' | 'ubuntu' | 'browser'; export type CodeInterpreterToolContainer = {[key: string]: unknown} | string; export type ResponseTool = {name?: (string | null) | undefined, description?: (string | null) | undefined, parameters?: ({[key: string]: unknown} | null) | undefined, strict?: (boolean | null) | undefined, function?: ({name: string, description?: (string | null) | undefined, parameters?: ({[key: string]: unknown} | null) | undefined, strict?: (boolean | null) | undefined} | null) | undefined, type: 'function'} | {filters?: ({[key: string]: unknown} | null) | undefined, search_context_size?: ('low' | 'medium' | 'high' | null) | undefined, user_location?: ({[key: string]: unknown} | 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: 'web_search'} | {filters?: ({[key: string]: unknown} | null) | undefined, search_context_size?: ('low' | 'medium' | 'high' | null) | undefined, user_location?: ({[key: string]: unknown} | 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: 'web_search_2025_08_26'} | {search_context_size?: ('low' | 'medium' | 'high' | null) | undefined, user_location?: ({[key: string]: unknown} | null) | undefined, type: 'web_search_preview'} | {search_context_size?: ('low' | 'medium' | 'high' | null) | undefined, user_location?: ({[key: string]: unknown} | null) | undefined, type: 'web_search_preview_2025_03_11'} | {vector_store_ids: Array, filters: unknown, max_num_results?: (number | null) | undefined, ranking_options?: ({[key: string]: unknown} | null) | undefined, type: 'file_search'} | {display_height: number, display_width: number, environment: ComputerEnvironment, type: 'computer_use_preview'} | {container: CodeInterpreterToolContainer, type: 'code_interpreter'} | {server_label: string, allowed_tools: unknown, authorization?: (string | null) | undefined, connector_id?: (string | null) | undefined, headers?: ({[key: string]: string} | null) | undefined, require_approval: unknown, server_description?: (string | null) | undefined, server_url?: (string | null) | undefined, type: 'mcp'} | {background?: ('transparent' | 'opaque' | 'auto' | null) | undefined, input_fidelity?: ('high' | 'low' | null) | undefined, input_image_mask?: ({[key: string]: unknown} | null) | undefined, model?: ('gpt-image-1' | 'gpt-image-1-mini' | null) | undefined, moderation?: ('auto' | 'low' | null) | undefined, output_compression?: (number | null) | undefined, output_format?: ('png' | 'webp' | 'jpeg' | null) | undefined, partial_images?: (number | null) | undefined, quality?: ('low' | 'medium' | 'high' | 'auto' | null) | undefined, size?: ('1024x1024' | '1024x1536' | '1536x1024' | 'auto' | null) | undefined, type: 'image_generation'} | {type: 'local_shell'} | {type: 'shell'} | {type: 'apply_patch'} | {name: string, description?: (string | null) | undefined, format?: ({[key: string]: unknown} | null) | undefined, type: 'custom'} | {type: 'computer'} | {execution?: (string | null) | undefined, description?: (string | null) | undefined, parameters?: ({[key: string]: unknown} | null) | undefined, type: 'tool_search'} | {name: string, description?: (string | null) | undefined, tools?: Array | undefined, type: 'namespace'} | {type: 'skills'}; export type ResponseInputItem = {role: InputMessageRole, content?: (Array | string | null) | undefined, name?: (string | null) | undefined, id?: (string | null) | undefined, status?: (string | null) | undefined, phase?: ('commentary' | 'final_answer' | null) | undefined, type: 'message'} | {call_id: string, name: string, arguments?: string | undefined, id?: (string | null) | undefined, status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined, namespace?: (string | null) | undefined, type: 'function_call'} | {call_id: string, output?: FunctionCallOutputOutput | undefined, id?: (string | null) | undefined, status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined, type: 'function_call_output'} | {id?: (string | null) | undefined, content?: (Array<{[key: string]: unknown}> | null) | undefined, summary?: (Array<{[key: string]: unknown}> | null) | undefined, encrypted_content?: (string | null) | undefined, status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined, format?: (string | null) | undefined, signature?: (string | null) | undefined, type: 'reasoning'} | {id?: (string | null) | undefined, status?: (string | null) | undefined, result?: (string | null) | undefined, created_by?: (string | null) | undefined, url?: (string | null) | undefined, mime_type?: (string | null) | undefined, type: 'image_generation_call'} | {id: string, type: 'item_reference'} | {id?: (string | null) | undefined, status?: (string | null) | undefined, action?: ({[key: string]: unknown} | null) | undefined, type: 'web_search_call'} | {type: 'file_search_call'} | {type: 'computer_call'} | {type: 'computer_call_output'} | {type: 'code_interpreter_call'} | {type: 'local_shell_call'} | {type: 'local_shell_call_output'} | {type: 'shell_call'} | {type: 'shell_call_output'} | {type: 'apply_patch_call'} | {type: 'apply_patch_call_output'} | {type: 'mcp_list_tools'} | {type: 'mcp_approval_request'} | {type: 'mcp_approval_response'} | {type: 'mcp_call'} | {call_id: string, arguments: unknown, type: 'tool_search_call'} | {call_id: string, tools?: Array | undefined, type: 'tool_search_output'} | {id?: (string | null) | undefined, role?: (string | null) | undefined, tools: Array, type: 'additional_tools'} | {type: 'compaction'} | {call_id: string, name: string, input?: string | undefined, namespace?: (string | null) | undefined, id?: (string | null) | undefined, type: 'custom_tool_call'} | {call_id: string, output: FunctionCallOutputOutput, type: 'custom_tool_call_output'}; export type ResponsesInput = Array | string; export type ToolChoiceFunctionType = 'function'; export type AllowedToolsType = 'allowed_tools'; export type AllowedEntryType = 'web_search' | 'web_search_preview' | 'web_search_preview_2025_03_11' | 'custom' | 'file_search' | 'computer' | 'computer_use_preview' | 'computer_use' | 'image_generation' | 'code_interpreter' | 'mcp' | 'apply_patch' | 'shell'; export type ToolChoiceAllowedEntry = {type: ToolChoiceFunctionType, name: string} | {type: AllowedEntryType, name?: (string | null) | undefined}; export type HostedWebSearchChoiceType = 'web_search' | 'web_search_preview' | 'web_search_preview_2025_03_11'; export type DroppedChoiceType = 'custom' | 'file_search' | 'computer' | 'computer_use_preview' | 'computer_use' | 'image_generation' | 'code_interpreter' | 'mcp' | 'apply_patch' | 'shell'; export type ResponseTextFormatType = 'text' | 'json_object' | 'json_schema'; export type ResponsesRequest = {model: string, input: ResponsesInput, routing?: ({strategy: RoutingStrategyWire} | null) | undefined, instructions?: (string | null) | undefined, max_output_tokens?: (number | null) | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, tools?: (Array | null) | undefined, tool_choice?: ('auto' | 'none' | 'required' | {type: ToolChoiceFunctionType, name: string} | {type: ToolChoiceFunctionType, function: {[key: string]: string}} | {type: AllowedToolsType, mode?: ('auto' | 'required' | null) | undefined, tools: Array} | {type: HostedWebSearchChoiceType} | {type: DroppedChoiceType, name?: (string | null) | undefined} | null) | undefined, parallel_tool_calls?: (boolean | null) | undefined, truncation?: ('auto' | 'disabled' | null) | undefined, reasoning?: ({effort?: ('none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | null) | undefined, summary?: ('concise' | 'detailed' | 'auto' | null) | undefined, generate_summary?: ('concise' | 'detailed' | 'auto' | null) | undefined} | null) | undefined, text?: ({format?: ({type: ResponseTextFormatType, name?: (string | null) | undefined, description?: (string | null) | undefined, schema?: ({[key: string]: unknown} | null) | undefined, strict?: (boolean | null) | undefined} | null) | undefined, verbosity?: ('low' | 'medium' | 'high' | null) | undefined} | null) | undefined, stream?: boolean | undefined}; export type CreateApiV1ResponsesArgs = {'x-naga-routing-strategy'?: RoutingStrategyWire | undefined, body: ResponsesRequest}; export type CreateApiV1ResponsesOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const itemStatus = z.enum(["in_progress", "completed", "incomplete"]); export const messagePhase = z.enum(["commentary", "final_answer"]); export const responsesOutputItem = z.union([z.object({type: z.literal("message"), id: z.string(), status: itemStatus, role: z.enum(["user", "assistant", "system", "developer", "tool"]), content: z.array(z.object({})), phase: messagePhase.optional()}), z.object({type: z.literal("reasoning"), id: z.string(), summary: z.array(z.object({})), content: z.array(z.object({})), encrypted_content: z.string().nullable().optional(), format: z.string().nullable().optional()}), z.object({type: z.literal("reasoning"), id: z.string(), encrypted_content: z.string(), summary: z.array(z.object({})), format: z.string().nullable().optional()}), z.object({type: z.literal("function_call"), id: z.string(), call_id: z.string(), name: z.string(), arguments: z.string(), status: itemStatus}), z.object({type: z.literal("function_call_output"), id: z.string(), call_id: z.string(), output: z.unknown(), status: itemStatus}), z.object({type: z.literal("web_search_call"), id: z.string(), status: z.enum(["in_progress", "completed", "incomplete", "searching", "failed"]), action: z.object({}).optional(), results: z.array(z.object({})).optional()}), z.object({type: z.literal("image_generation_call"), id: z.string(), status: z.literal("completed"), result: z.string().nullable().optional(), url: z.string().nullable().optional(), mime_type: z.string().nullable().optional()}), z.object({type: z.literal("image_generation_call"), id: z.string(), status: z.literal("in_progress"), result: z.unknown(), mime_type: z.string().nullable().optional()})]); export const responsesInputTokensDetails = z.object({cached_tokens: z.number().int(), audio_tokens: z.number().int().nullable().optional()}); export const responsesOutputTokensDetails = z.object({reasoning_tokens: z.number().int(), image_tokens: z.number().int().nullable().optional()}); export const responsesResponse = z.object({instructions: z.string().nullable(), tools: z.array(z.unknown()), tool_choice: z.unknown(), temperature: z.unknown(), top_p: z.unknown(), parallel_tool_calls: z.boolean(), metadata: z.unknown(), text: z.unknown(), truncation: z.unknown(), max_output_tokens: z.number().int().nullable(), reasoning: z.unknown(), id: z.string(), object: z.literal("response"), created_at: z.number().int(), status: z.string(), output: z.array(responsesOutputItem), error: z.object({code: z.string(), message: z.string()}).nullable(), incomplete_details: z.object({reason: z.enum(["max_output_tokens", "content_filter", "tool_use_required", "upstream_timeout", "upstream_disconnect", "gateway_cancelled", "other"])}).nullable(), usage: z.object({input_tokens: z.number().int(), input_tokens_details: responsesInputTokensDetails, output_tokens: z.number().int(), output_tokens_details: responsesOutputTokensDetails, total_tokens: z.number().int()}).nullable(), model: z.string().nullable()}); 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 response * * POST /v1/responses * * Also accepts auth: xApiKeyAuth */ export const createApiV1Responses = async (args: CreateApiV1ResponsesArgs, options?: CreateApiV1ResponsesOptions) => { 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/responses${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(responsesResponse, await res.json()) };