import {z} from 'zod' export type WebAnnotation = {type: 'url_citation', title: string, url: string, start_index: number, end_index: number, cited_text?: (string | null) | undefined, encrypted_index?: (string | null) | undefined}; export type FileAnnotation = {type: 'file_citation', index: number, file_id: string, filename: string}; export type MapAnnotation = {type: 'map_citation', title: string, url: string, place_id?: (string | null) | undefined, start_index: number, end_index: number, cited_text?: (string | null) | undefined}; export type ContainerFileAnnotation = {type: 'container_file_citation', container_id: string, start_index?: (number | null) | undefined, end_index?: (number | null) | undefined, filename?: (string | null) | undefined, file_id?: (string | null) | undefined}; export type TextContent = {type?: 'text' | undefined, text: string, id?: (string | null) | undefined, annotations?: (Array | null) | undefined, thought_signature?: (string | null) | undefined}; export type ThinkingContent = {signature?: (string | null) | undefined, type?: 'thinking' | undefined, thinking: string, id?: (string | null) | undefined}; export type CodeContent = {type?: 'code' | undefined, code: string, id?: (string | null) | undefined, container_id?: (string | null) | undefined}; export type ImageURL = {url: string, detail?: (string | null) | undefined}; export type ImageContent = {type?: 'image_url' | undefined, image_url: ImageURL, image_variable?: (string | null) | undefined}; export type Media = {title?: string | undefined, type?: (string | null) | undefined, url?: (string | null) | undefined, format?: ('base64' | 'url' | 'neither') | undefined}; export type MediaContent = {type?: 'media' | undefined, media: Media}; export type MediaVariable = {type?: 'media_variable' | undefined, name: string}; export type OutputMediaContent = {type?: 'output_media' | undefined, id?: (string | null) | undefined, url: string, mime_type?: string | undefined, media_type?: ('image' | 'video' | 'audio') | undefined, provider_metadata?: (Record | null) | undefined}; export type ServerToolUseContent = {type?: 'server_tool_use' | undefined, id: string, name: string, input?: Record | undefined}; export type WebSearchResult = {type?: 'web_search_result' | undefined, url?: string | undefined, title?: string | undefined, encrypted_content?: string | undefined, page_age?: (string | null) | undefined}; export type WebSearchToolResultContent = {type?: 'web_search_tool_result' | undefined, tool_use_id: string, content?: Array | undefined}; export type CodeExecutionResultContent = {type?: 'code_execution_result' | undefined, output: string, outcome?: string | undefined}; export type McpListToolsContent = {type?: 'mcp_list_tools' | undefined, id?: (string | null) | undefined, server_label?: string | undefined, tools?: Array> | undefined, error?: (string | Record | null) | undefined}; export type McpCallContent = {type?: 'mcp_call' | undefined, id?: (string | null) | undefined, name?: string | undefined, server_label?: string | undefined, arguments?: string | undefined, output?: (string | null) | undefined, error?: (string | Record | null) | undefined, approval_request_id?: (string | null) | undefined}; export type McpApprovalRequestContent = {type?: 'mcp_approval_request' | undefined, id?: (string | null) | undefined, name?: string | undefined, arguments?: string | undefined, server_label?: string | undefined}; export type McpApprovalResponseContent = {type?: 'mcp_approval_response' | undefined, approval_request_id: string, approve: boolean}; export type BashCodeExecutionToolResultContent = {type?: 'bash_code_execution_tool_result' | undefined, tool_use_id: string, content?: Record | undefined}; export type TextEditorCodeExecutionToolResultContent = {type?: 'text_editor_code_execution_tool_result' | undefined, tool_use_id: string, content?: Record | undefined}; export type ShellCallContent = {type?: 'shell_call' | undefined, id?: (string | null) | undefined, call_id?: (string | null) | undefined, action?: Record | undefined, status?: (string | null) | undefined}; export type ShellCallOutputContent = {type?: 'shell_call_output' | undefined, id?: (string | null) | undefined, call_id?: (string | null) | undefined, output?: Array> | undefined, status?: (string | null) | undefined}; export type ApplyPatchCallContent = {type?: 'apply_patch_call' | undefined, id?: (string | null) | undefined, call_id?: (string | null) | undefined, operation?: Record | undefined, status?: (string | null) | undefined}; export type ApplyPatchCallOutputContent = {type?: 'apply_patch_call_output' | undefined, id?: (string | null) | undefined, call_id?: (string | null) | undefined, output?: (string | null) | undefined, status?: (string | null) | undefined}; export type CompletionPrompt = {content: Array, input_variables?: Array | undefined, template_format?: ('f-string' | 'jinja2') | undefined, type?: 'completion' | undefined} | {[key: string]: unknown}; export type SystemMessage = {input_variables?: Array | undefined, template_format?: ('f-string' | 'jinja2') | undefined, content: Array, role?: 'system' | undefined, name?: (string | null) | undefined}; export type UserMessage = {input_variables?: Array | undefined, template_format?: ('f-string' | 'jinja2') | undefined, content: Array, role?: 'user' | undefined, name?: (string | null) | undefined}; export type FunctionCall = {name: string, arguments: string}; export type ToolCall = {tool_id?: (string | null) | undefined, id: string, type?: 'function' | undefined, function: FunctionCall}; export type AssistantMessage = {input_variables?: Array | undefined, template_format?: ('f-string' | 'jinja2') | undefined, content?: (Array | null) | undefined, role?: 'assistant' | undefined, function_call?: (FunctionCall | null) | undefined, name?: (string | null) | undefined, tool_calls?: (Array | null) | undefined}; export type FunctionMessage = {input_variables?: Array | undefined, template_format?: ('f-string' | 'jinja2') | undefined, content?: (Array | null) | undefined, role?: 'function' | undefined, name: string}; export type ToolMessage = {input_variables?: Array | undefined, template_format?: ('f-string' | 'jinja2') | undefined, content: Array, role?: 'tool' | undefined, tool_call_id: string, name?: (string | null) | undefined}; export type PlaceholderMessage = {input_variables?: Array | undefined, template_format?: ('f-string' | 'jinja2') | undefined, content?: (Array | null) | undefined, raw_request_display_role?: string | undefined, role?: 'placeholder' | undefined, name: string}; export type DeveloperMessage = {input_variables?: Array | undefined, template_format?: ('f-string' | 'jinja2') | undefined, content: Array, role?: 'developer' | undefined, name?: (string | null) | undefined}; export type Function = {name: string, description?: string | undefined, strict?: boolean | undefined, parameters?: Record | undefined}; export type FunctionTool = {type?: 'function' | undefined, function: Function}; export type BuiltInTool = {id: string, name: string, description: string, provider: string, type: 'web_search' | 'file_search' | 'code_interpreter' | 'image_generation' | 'google_maps' | 'url_context' | 'mcp' | 'bash' | 'shell' | 'apply_patch' | 'text_editor', config: Record}; export type Tool = FunctionTool | BuiltInTool; export type MessageFunctionCall = {name: string}; export type ChatToolChoice = {type?: 'function' | undefined, function: MessageFunctionCall}; export type ChatPrompt = {messages: Array, functions?: (Array | null) | undefined, tools?: (Array | null) | undefined, function_call?: (string | MessageFunctionCall | null) | undefined, tool_choice?: (string | ChatToolChoice | null) | undefined, type?: 'chat' | undefined, input_variables?: Array | undefined}; export type LogRequest = {provider: string, model: string, input: CompletionPrompt | ChatPrompt, output: CompletionPrompt | ChatPrompt, request_start_time: string, request_end_time: string, parameters?: Record | undefined, tags?: Array | undefined, metadata?: {[key: string]: string} | undefined, prompt_name?: (string | null) | undefined, prompt_id?: (number | null) | undefined, prompt_version_number?: (number | null) | undefined, prompt_input_variables?: Record | undefined, input_tokens?: number | undefined, output_tokens?: number | undefined, price?: number | undefined, function_name?: string | undefined, score?: number | undefined, api_type?: (string | null) | undefined, status?: ('SUCCESS' | 'WARNING' | 'ERROR') | undefined, error_type?: ('PROVIDER_TIMEOUT' | 'PROVIDER_QUOTA_LIMIT' | 'PROVIDER_RATE_LIMIT' | 'PROVIDER_PARTIAL_RESPONSE' | 'PROVIDER_AUTH_ERROR' | 'PROVIDER_ERROR' | 'TEMPLATE_RENDER_ERROR' | 'VARIABLE_MISSING_OR_EMPTY' | 'UNKNOWN_ERROR' | null) | undefined, error_message?: (string | null) | undefined}; export type CreateApiLogRequestArgs = {body: LogRequest}; export type CreateApiLogRequestOptions = {baseUrl: string, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const webAnnotation = z.object({type: z.literal("url_citation"), title: z.string(), url: z.string(), start_index: z.number().int(), end_index: z.number().int(), cited_text: z.string().nullable().optional(), encrypted_index: z.string().nullable().optional()}); export const fileAnnotation = z.object({type: z.literal("file_citation"), index: z.number().int(), file_id: z.string(), filename: z.string()}); export const mapAnnotation = z.object({type: z.literal("map_citation"), title: z.string(), url: z.string(), place_id: z.string().nullable().optional(), start_index: z.number().int(), end_index: z.number().int(), cited_text: z.string().nullable().optional()}); export const containerFileAnnotation = z.object({type: z.literal("container_file_citation"), container_id: z.string(), start_index: z.number().int().nullable().optional(), end_index: z.number().int().nullable().optional(), filename: z.string().nullable().optional(), file_id: z.string().nullable().optional()}); export const textContent = z.object({type: z.literal("text").optional(), text: z.string(), id: z.string().nullable().optional(), annotations: z.array(z.union([webAnnotation, fileAnnotation, mapAnnotation, containerFileAnnotation])).nullable().optional(), thought_signature: z.string().nullable().optional()}); export const thinkingContent = z.object({signature: z.string().nullable().optional(), type: z.literal("thinking").optional(), thinking: z.string(), id: z.string().nullable().optional()}); export const codeContent = z.object({type: z.literal("code").optional(), code: z.string(), id: z.string().nullable().optional(), container_id: z.string().nullable().optional()}); export const imageURL = z.object({url: z.string(), detail: z.string().nullable().optional()}); export const imageContent = z.object({type: z.literal("image_url").optional(), image_url: imageURL, image_variable: z.string().nullable().optional()}); export const media = z.object({title: z.string().optional(), type: z.string().nullable().optional(), url: z.string().nullable().optional(), format: z.enum(["base64", "url", "neither"]).optional()}); export const mediaContent = z.object({type: z.literal("media").optional(), media: media}); export const mediaVariable = z.object({type: z.literal("media_variable").optional(), name: z.string()}); export const outputMediaContent = z.object({type: z.literal("output_media").optional(), id: z.string().nullable().optional(), url: z.string(), mime_type: z.string().optional(), media_type: z.enum(["image", "video", "audio"]).optional(), provider_metadata: z.object({}).nullable().optional()}); export const serverToolUseContent = z.object({type: z.literal("server_tool_use").optional(), id: z.string(), name: z.string(), input: z.object({}).optional()}); export const webSearchResult = z.object({type: z.literal("web_search_result").optional(), url: z.string().optional(), title: z.string().optional(), encrypted_content: z.string().optional(), page_age: z.string().nullable().optional()}); export const webSearchToolResultContent = z.object({type: z.literal("web_search_tool_result").optional(), tool_use_id: z.string(), content: z.array(webSearchResult).optional()}); export const codeExecutionResultContent = z.object({type: z.literal("code_execution_result").optional(), output: z.string(), outcome: z.string().optional()}); export const mcpListToolsContent = z.object({type: z.literal("mcp_list_tools").optional(), id: z.string().nullable().optional(), server_label: z.string().optional(), tools: z.array(z.object({})).optional(), error: z.union([z.string(), z.object({})]).nullable().optional()}); export const mcpCallContent = z.object({type: z.literal("mcp_call").optional(), id: z.string().nullable().optional(), name: z.string().optional(), server_label: z.string().optional(), arguments: z.string().optional(), output: z.string().nullable().optional(), error: z.union([z.string(), z.object({})]).nullable().optional(), approval_request_id: z.string().nullable().optional()}); export const mcpApprovalRequestContent = z.object({type: z.literal("mcp_approval_request").optional(), id: z.string().nullable().optional(), name: z.string().optional(), arguments: z.string().optional(), server_label: z.string().optional()}); export const mcpApprovalResponseContent = z.object({type: z.literal("mcp_approval_response").optional(), approval_request_id: z.string(), approve: z.boolean()}); export const bashCodeExecutionToolResultContent = z.object({type: z.literal("bash_code_execution_tool_result").optional(), tool_use_id: z.string(), content: z.object({}).optional()}); export const textEditorCodeExecutionToolResultContent = z.object({type: z.literal("text_editor_code_execution_tool_result").optional(), tool_use_id: z.string(), content: z.object({}).optional()}); export const shellCallContent = z.object({type: z.literal("shell_call").optional(), id: z.string().nullable().optional(), call_id: z.string().nullable().optional(), action: z.object({}).optional(), status: z.string().nullable().optional()}); export const shellCallOutputContent = z.object({type: z.literal("shell_call_output").optional(), id: z.string().nullable().optional(), call_id: z.string().nullable().optional(), output: z.array(z.object({})).optional(), status: z.string().nullable().optional()}); export const applyPatchCallContent = z.object({type: z.literal("apply_patch_call").optional(), id: z.string().nullable().optional(), call_id: z.string().nullable().optional(), operation: z.object({}).optional(), status: z.string().nullable().optional()}); export const applyPatchCallOutputContent = z.object({type: z.literal("apply_patch_call_output").optional(), id: z.string().nullable().optional(), call_id: z.string().nullable().optional(), output: z.string().nullable().optional(), status: z.string().nullable().optional()}); export const completionPrompt = z.object({content: z.array(z.discriminatedUnion("type", [textContent, thinkingContent, codeContent, imageContent, mediaContent, mediaVariable, outputMediaContent, serverToolUseContent, webSearchToolResultContent, codeExecutionResultContent, mcpListToolsContent, mcpCallContent, mcpApprovalRequestContent, mcpApprovalResponseContent, bashCodeExecutionToolResultContent, textEditorCodeExecutionToolResultContent, shellCallContent, shellCallOutputContent, applyPatchCallContent, applyPatchCallOutputContent])), input_variables: z.array(z.string()).optional(), template_format: z.enum(["f-string", "jinja2"]).optional(), type: z.literal("completion").optional()}).and(z.record(z.string(), z.unknown())); export const systemMessage = z.object({input_variables: z.array(z.string()).optional(), template_format: z.enum(["f-string", "jinja2"]).optional(), content: z.array(z.discriminatedUnion("type", [textContent, thinkingContent, codeContent, imageContent, mediaContent, mediaVariable, outputMediaContent, serverToolUseContent, webSearchToolResultContent, codeExecutionResultContent, mcpListToolsContent, mcpCallContent, mcpApprovalRequestContent, mcpApprovalResponseContent, bashCodeExecutionToolResultContent, textEditorCodeExecutionToolResultContent, shellCallContent, shellCallOutputContent, applyPatchCallContent, applyPatchCallOutputContent])), role: z.literal("system").optional(), name: z.string().nullable().optional()}); export const userMessage = z.object({input_variables: z.array(z.string()).optional(), template_format: z.enum(["f-string", "jinja2"]).optional(), content: z.array(z.discriminatedUnion("type", [textContent, thinkingContent, codeContent, imageContent, mediaContent, mediaVariable, outputMediaContent, serverToolUseContent, webSearchToolResultContent, codeExecutionResultContent, mcpListToolsContent, mcpCallContent, mcpApprovalRequestContent, mcpApprovalResponseContent, bashCodeExecutionToolResultContent, textEditorCodeExecutionToolResultContent, shellCallContent, shellCallOutputContent, applyPatchCallContent, applyPatchCallOutputContent])), role: z.literal("user").optional(), name: z.string().nullable().optional()}); export const functionCall = z.object({name: z.string(), arguments: z.string()}); export const toolCall = z.object({tool_id: z.string().nullable().optional(), id: z.string(), type: z.literal("function").optional(), function: functionCall}); export const assistantMessage = z.object({input_variables: z.array(z.string()).optional(), template_format: z.enum(["f-string", "jinja2"]).optional(), content: z.array(z.discriminatedUnion("type", [textContent, thinkingContent, codeContent, imageContent, mediaContent, mediaVariable, outputMediaContent, serverToolUseContent, webSearchToolResultContent, codeExecutionResultContent, mcpListToolsContent, mcpCallContent, mcpApprovalRequestContent, mcpApprovalResponseContent, bashCodeExecutionToolResultContent, textEditorCodeExecutionToolResultContent, shellCallContent, shellCallOutputContent, applyPatchCallContent, applyPatchCallOutputContent])).nullable().optional(), role: z.literal("assistant").optional(), function_call: functionCall.nullable().optional(), name: z.string().nullable().optional(), tool_calls: z.array(toolCall).nullable().optional()}); export const functionMessage = z.object({input_variables: z.array(z.string()).optional(), template_format: z.enum(["f-string", "jinja2"]).optional(), content: z.array(z.discriminatedUnion("type", [textContent, thinkingContent, codeContent, imageContent, mediaContent, mediaVariable, outputMediaContent, serverToolUseContent, webSearchToolResultContent, codeExecutionResultContent, mcpListToolsContent, mcpCallContent, mcpApprovalRequestContent, mcpApprovalResponseContent, bashCodeExecutionToolResultContent, textEditorCodeExecutionToolResultContent, shellCallContent, shellCallOutputContent, applyPatchCallContent, applyPatchCallOutputContent])).nullable().optional(), role: z.literal("function").optional(), name: z.string()}); export const toolMessage = z.object({input_variables: z.array(z.string()).optional(), template_format: z.enum(["f-string", "jinja2"]).optional(), content: z.array(z.discriminatedUnion("type", [textContent, thinkingContent, codeContent, imageContent, mediaContent, mediaVariable, outputMediaContent, serverToolUseContent, webSearchToolResultContent, codeExecutionResultContent, mcpListToolsContent, mcpCallContent, mcpApprovalRequestContent, mcpApprovalResponseContent, bashCodeExecutionToolResultContent, textEditorCodeExecutionToolResultContent, shellCallContent, shellCallOutputContent, applyPatchCallContent, applyPatchCallOutputContent])), role: z.literal("tool").optional(), tool_call_id: z.string(), name: z.string().nullable().optional()}); export const placeholderMessage = z.object({input_variables: z.array(z.string()).optional(), template_format: z.enum(["f-string", "jinja2"]).optional(), content: z.array(z.discriminatedUnion("type", [textContent, thinkingContent, codeContent, imageContent, mediaContent, mediaVariable, outputMediaContent, serverToolUseContent, webSearchToolResultContent, codeExecutionResultContent, mcpListToolsContent, mcpCallContent, mcpApprovalRequestContent, mcpApprovalResponseContent, bashCodeExecutionToolResultContent, textEditorCodeExecutionToolResultContent, shellCallContent, shellCallOutputContent, applyPatchCallContent, applyPatchCallOutputContent])).nullable().optional(), raw_request_display_role: z.string().optional(), role: z.literal("placeholder").optional(), name: z.string()}); export const developerMessage = z.object({input_variables: z.array(z.string()).optional(), template_format: z.enum(["f-string", "jinja2"]).optional(), content: z.array(z.discriminatedUnion("type", [textContent, thinkingContent, codeContent, imageContent, mediaContent, mediaVariable, outputMediaContent, serverToolUseContent, webSearchToolResultContent, codeExecutionResultContent, mcpListToolsContent, mcpCallContent, mcpApprovalRequestContent, mcpApprovalResponseContent, bashCodeExecutionToolResultContent, textEditorCodeExecutionToolResultContent, shellCallContent, shellCallOutputContent, applyPatchCallContent, applyPatchCallOutputContent])), role: z.literal("developer").optional(), name: z.string().nullable().optional()}); export const function = z.object({name: z.string(), description: z.string().optional(), strict: z.boolean().optional(), parameters: z.object({}).optional()}); export const functionTool = z.object({type: z.literal("function").optional(), function: function}); export const builtInTool = z.object({id: z.string(), name: z.string(), description: z.string(), provider: z.string(), type: z.enum(["web_search", "file_search", "code_interpreter", "image_generation", "google_maps", "url_context", "mcp", "bash", "shell", "apply_patch", "text_editor"]), config: z.object({})}); export const tool = z.discriminatedUnion("type", [functionTool, builtInTool]); export const messageFunctionCall = z.object({name: z.string()}); export const chatToolChoice = z.object({type: z.literal("function").optional(), function: messageFunctionCall}); export const chatPrompt = z.object({messages: z.array(z.discriminatedUnion("role", [systemMessage, userMessage, assistantMessage, functionMessage, toolMessage, placeholderMessage, developerMessage])), functions: z.array(function).nullable().optional(), tools: z.array(tool).nullable().optional(), function_call: z.union([z.string(), messageFunctionCall]).nullable().optional(), tool_choice: z.union([z.string(), chatToolChoice]).nullable().optional(), type: z.literal("chat").optional(), input_variables: z.array(z.string()).optional()}); export const model = z.object({provider: z.string(), model_config_display_name: z.string().max(255).nullable().optional(), base_model: z.string().max(100).nullable().optional(), name: z.string(), parameters: z.object({}).optional(), display_params: z.object({}).optional(), api_type: z.string().nullable().optional()}); export const metadata = z.object({model: model.nullable().optional()}).and(z.record(z.string(), z.unknown())); export const promptVersion = z.object({prompt_template: z.discriminatedUnion("type", [completionPrompt, chatPrompt]), commit_message: z.string().max(72).nullable().optional(), metadata: metadata.nullable().optional()}); export const logRequestResponse = z.object({id: z.number().int(), prompt_version: promptVersion, status: z.enum(["SUCCESS", "WARNING", "ERROR"]).optional(), error_type: z.string().nullable().optional(), error_message: z.string().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 }; /** * Log Request * * POST /log-request */ export const createApiLogRequest = async (args: CreateApiLogRequestArgs, options: CreateApiLogRequestOptions) => { const {baseUrl, fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKeyAuth !== undefined) headers.set("X-API-KEY", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/log-request${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(logRequestResponse, await res.json()) };