import {z} from 'zod' export type ContentItem = {type?: string | undefined, text: string, annotations?: Array<{[key: string]: unknown}> | undefined}; export type InputTextContentPart = {type: 'input_text', text: string}; export type ImageDetail = 'low' | 'high' | 'auto'; export type InputImageContentPart = {type: 'input_image', image_url?: (string | null) | undefined, file_id?: (string | null) | undefined, detail?: ImageDetail | undefined}; export type InputItemMessage = {type: 'message', id?: (string | null) | undefined, status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined, role?: (string | null) | undefined, content?: (string | Array | Array | Array | null) | undefined}; export type ReasoningSummaryItem = {type: 'summary_text', text: string}; export type InputItemReasoning = {type: 'reasoning', id: string, status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined, role?: (string | null) | undefined, content?: (string | Array | Array | Array | null) | undefined, summary?: Array | undefined}; export type InputItemFunctionCall = {type: 'function_call', id: string, call_id: string, status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined, name?: (string | null) | undefined, arguments?: (string | null) | undefined}; export type InputItemFunctionCallOutput = {type: 'function_call_output', call_id: string, id?: (string | null) | undefined, status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined, output?: (string | null) | undefined}; export type InputItemShellCall = {type: 'shell_call', id: string, call_id: string, status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined, name?: (string | null) | undefined, arguments?: (string | null) | undefined}; export type InputItemShellCallOutput = {type: 'shell_call_output', call_id: string, id?: (string | null) | undefined, status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined, output?: (string | null) | undefined}; export type InputItemMcpApprovalRequest = {type: 'mcp_approval_request', id: string, name?: (string | null) | undefined, server_label?: (string | null) | undefined, arguments?: (string | null) | undefined}; export type InputItemMcpApprovalResponses = {type: 'mcp_approval_response', id: string, approval_request_id: string, approve: boolean, reason?: (string | null) | undefined, name?: (string | null) | undefined, arguments?: (string | null) | undefined}; export type InputItemMcpListTools = {type: 'mcp_list_tools', id: string, server_label?: (string | null) | undefined, tools?: ({[key: string]: unknown} | Array | null) | undefined, error?: (string | null) | undefined}; export type McpToolExecutionError = {type?: 'mcp_tool_execution_error' | undefined, content: string}; export type InputItemMcpCall = {type: 'mcp_call', id: string, name: string, arguments?: (string | null) | undefined, server_label?: (string | null) | undefined, output?: (string | null) | undefined, error?: (McpToolExecutionError | null) | undefined}; export type InputItemFileSearchCall = {type: 'file_search_call', id?: string | undefined, status: 'in_progress' | 'searching' | 'completed' | 'incomplete' | 'failed', queries?: Array | undefined, results?: (Array<{[key: string]: unknown}> | null) | undefined}; export type InputItemWebSearchCall = {type: 'web_search_call', id?: string | undefined, status: 'in_progress' | 'searching' | 'completed' | 'failed', action?: ({[key: string]: unknown} | null) | undefined, results?: (Array<{[key: string]: unknown}> | null) | undefined}; export type InputItemCompaction = {type: 'compaction', id?: (string | null) | undefined, encrypted_content: string}; export type PromptConfig = {id: string, variables?: {[key: string]: string} | undefined}; export type ConversationRef = {id: string}; export type Function = {type: 'function', name: string, parameters?: ({[key: string]: unknown} | null) | undefined, strict?: boolean | undefined, description?: (string | null) | undefined}; export type MCPTool = {type: 'mcp', server_url: string, require_approval?: ('always' | 'never') | undefined, server_label: string, allowed_tools?: ({[key: string]: unknown} | Array | null) | undefined, authorization?: (string | null) | undefined, headers?: ({[key: string]: string} | null) | undefined, server_description?: (string | null) | undefined, on_unavailable?: ('fail' | 'skip') | undefined}; export type FileSearchAttachment = {searchStoreId: string, fileId: string, documentId: string, fileName: string}; export type FileSearchTool = {type: 'file_search', attachments?: Array | undefined, citations?: boolean | undefined, search_store_ids?: Array | undefined}; export type SkillReference = {type: 'skill_reference', skill_id: string, version?: (number | null) | undefined}; export type ShellEnvironment = {type: string, skills?: Array | undefined}; export type ShellTool = {type: 'shell', environment: ShellEnvironment}; export type WebSearchFilters = {allowed_domains?: Array | undefined, blocked_domains?: Array | undefined}; export type WebSearchTool = {type: 'web_search', depth?: ('fast' | 'standard' | 'deep') | undefined, filters?: (WebSearchFilters | null) | undefined}; export type ResponseRequest = {model: string, input: string | Array, instructions?: (string | null) | undefined, previous_response_id?: (string | null) | undefined, prompt?: (PromptConfig | null) | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, max_output_tokens?: (number | null) | undefined, stream?: boolean | undefined, stop?: (Array | null) | undefined, modify_request?: boolean | undefined, conversation?: (ConversationRef | null) | undefined, tools?: (Array | null) | undefined, tool_choice?: ('auto' | 'required' | 'none' | {[key: string]: unknown} | null) | undefined, parallel_tool_calls?: boolean | undefined, include?: (Array<'message.output_text.logprobs' | 'reasoning.encrypted_content'> | null) | undefined, store?: boolean | undefined, metadata?: ({[key: string]: string} | null) | undefined, truncation?: (string | null) | undefined, text?: ({[key: string]: unknown} | null) | undefined, presence_penalty?: (number | null) | undefined, frequency_penalty?: (number | null) | undefined, top_logprobs?: (number | null) | undefined, max_tool_calls?: (number | null) | undefined, service_tier?: (string | null) | undefined, background?: boolean | undefined, reasoning?: ({[key: string]: unknown} | null) | undefined}; export type CreateApiV1ResponsesArgs = {body: ResponseRequest}; export type CreateApiV1ResponsesOptions = {baseUrl?: string | undefined, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const contentItem = z.object({type: z.string().optional(), text: z.string(), annotations: z.array(z.record(z.string(), z.unknown())).optional()}); export const inputTextContentPart = z.object({type: z.literal("input_text"), text: z.string()}); export const imageDetail = z.enum(["low", "high", "auto"]); export const inputImageContentPart = z.object({type: z.literal("input_image"), image_url: z.string().nullable().optional(), file_id: z.string().nullable().optional(), detail: imageDetail.optional()}); export const inputItemMessage = z.object({type: z.literal("message"), id: z.string().nullable().optional(), status: z.enum(["in_progress", "completed", "incomplete"]).nullable().optional(), role: z.string().nullable().optional(), content: z.union([z.string(), z.array(z.string()), z.array(contentItem), z.array(z.discriminatedUnion("type", [inputTextContentPart, inputImageContentPart]))]).nullable().optional()}); export const reasoningSummaryItem = z.object({type: z.literal("summary_text"), text: z.string()}); export const inputItemReasoning = z.object({type: z.literal("reasoning"), id: z.string(), status: z.enum(["in_progress", "completed", "incomplete"]).nullable().optional(), role: z.string().nullable().optional(), content: z.union([z.string(), z.array(z.string()), z.array(contentItem), z.array(z.discriminatedUnion("type", [inputTextContentPart, inputImageContentPart]))]).nullable().optional(), summary: z.array(reasoningSummaryItem).optional()}); export const inputItemFunctionCall = z.object({type: z.literal("function_call"), id: z.string(), call_id: z.string(), status: z.enum(["in_progress", "completed", "incomplete"]).nullable().optional(), name: z.string().nullable().optional(), arguments: z.string().nullable().optional()}); export const inputItemFunctionCallOutput = z.object({type: z.literal("function_call_output"), call_id: z.string(), id: z.string().nullable().optional(), status: z.enum(["in_progress", "completed", "incomplete"]).nullable().optional(), output: z.string().nullable().optional()}); export const inputItemShellCall = z.object({type: z.literal("shell_call"), id: z.string(), call_id: z.string(), status: z.enum(["in_progress", "completed", "incomplete"]).nullable().optional(), name: z.string().nullable().optional(), arguments: z.string().nullable().optional()}); export const inputItemShellCallOutput = z.object({type: z.literal("shell_call_output"), call_id: z.string(), id: z.string().nullable().optional(), status: z.enum(["in_progress", "completed", "incomplete"]).nullable().optional(), output: z.string().nullable().optional()}); export const inputItemMcpApprovalRequest = z.object({type: z.literal("mcp_approval_request"), id: z.string(), name: z.string().nullable().optional(), server_label: z.string().nullable().optional(), arguments: z.string().nullable().optional()}); export const inputItemMcpApprovalResponses = z.object({type: z.literal("mcp_approval_response"), id: z.string(), approval_request_id: z.string(), approve: z.boolean(), reason: z.string().nullable().optional(), name: z.string().nullable().optional(), arguments: z.string().nullable().optional()}); export const inputItemMcpListTools = z.object({type: z.literal("mcp_list_tools"), id: z.string(), server_label: z.string().nullable().optional(), tools: z.union([z.record(z.string(), z.unknown()), z.array(z.unknown())]).nullable().optional(), error: z.string().nullable().optional()}); export const mcpToolExecutionError = z.object({type: z.literal("mcp_tool_execution_error").optional(), content: z.string()}); export const inputItemMcpCall = z.object({type: z.literal("mcp_call"), id: z.string(), name: z.string(), arguments: z.string().nullable().optional(), server_label: z.string().nullable().optional(), output: z.string().nullable().optional(), error: mcpToolExecutionError.nullable().optional()}); export const inputItemFileSearchCall = z.object({type: z.literal("file_search_call"), id: z.string().optional(), status: z.enum(["in_progress", "searching", "completed", "incomplete", "failed"]), queries: z.array(z.string()).optional(), results: z.array(z.record(z.string(), z.unknown())).nullable().optional()}); export const inputItemWebSearchCall = z.object({type: z.literal("web_search_call"), id: z.string().optional(), status: z.enum(["in_progress", "searching", "completed", "failed"]), action: z.record(z.string(), z.unknown()).nullable().optional(), results: z.array(z.record(z.string(), z.unknown())).nullable().optional()}); export const inputItemCompaction = z.object({type: z.literal("compaction"), id: z.string().nullable().optional(), encrypted_content: z.string().max(10485760)}); export const function = z.object({type: z.literal("function"), name: z.string(), parameters: z.record(z.string(), z.unknown()).nullable().optional(), strict: z.boolean().optional(), description: z.string().nullable().optional()}); export const mCPTool = z.object({type: z.literal("mcp"), server_url: z.string(), require_approval: z.enum(["always", "never"]).optional(), server_label: z.string(), allowed_tools: z.union([z.record(z.string(), z.unknown()), z.array(z.string())]).nullable().optional(), authorization: z.string().nullable().optional(), headers: z.record(z.string(), z.string()).nullable().optional(), server_description: z.string().nullable().optional(), on_unavailable: z.enum(["fail", "skip"]).optional()}); export const fileSearchAttachment = z.object({searchStoreId: z.string(), fileId: z.string(), documentId: z.string(), fileName: z.string()}); export const fileSearchTool = z.object({type: z.literal("file_search"), attachments: z.array(fileSearchAttachment).optional(), citations: z.boolean().optional(), search_store_ids: z.array(z.string()).optional()}); export const skillReference = z.object({type: z.literal("skill_reference"), skill_id: z.string(), version: z.number().int().nullable().optional()}); export const shellEnvironment = z.object({type: z.string(), skills: z.array(skillReference).optional()}); export const shellTool = z.object({type: z.literal("shell"), environment: shellEnvironment}); export const webSearchFilters = z.object({allowed_domains: z.array(z.string()).optional(), blocked_domains: z.array(z.string()).optional()}); export const webSearchTool = z.object({type: z.literal("web_search"), depth: z.enum(["fast", "standard", "deep"]).optional(), filters: webSearchFilters.nullable().optional()}); export const usageInfo = z.object({input_tokens: z.number().int(), output_tokens: z.number().int(), total_tokens: z.number().int()}); export const conversationRef = z.object({id: z.string()}); export const responseResponse = z.object({id: z.string(), object: z.string().optional(), created_at: z.number().int(), completed_at: z.number().int().nullable().optional(), status: z.string().optional(), incomplete_details: z.record(z.string(), z.unknown()).nullable().optional(), model: z.string(), previous_response_id: z.string().nullable().optional(), instructions: z.string().nullable().optional(), output: z.array(z.discriminatedUnion("type", [inputItemMessage, inputItemReasoning, inputItemFunctionCall, inputItemFunctionCallOutput, inputItemShellCall, inputItemShellCallOutput, inputItemMcpApprovalRequest, inputItemMcpApprovalResponses, inputItemMcpListTools, inputItemMcpCall, inputItemFileSearchCall, inputItemWebSearchCall, inputItemCompaction])), error: z.record(z.string(), z.unknown()).nullable().optional(), tools: z.array(z.discriminatedUnion("type", [function, mCPTool, fileSearchTool, shellTool, webSearchTool])).optional(), tool_choice: z.union([z.enum(["auto", "required", "none"]), z.record(z.string(), z.unknown())]).nullable().optional(), truncation: z.string().nullable().optional(), parallel_tool_calls: z.boolean().optional(), text: z.record(z.string(), z.unknown()).nullable().optional(), top_p: z.number().nullable().optional(), temperature: z.number().nullable().optional(), presence_penalty: z.number().nullable().optional(), frequency_penalty: z.number().nullable().optional(), top_logprobs: z.number().int().nullable().optional(), reasoning: z.record(z.string(), z.unknown()).nullable().optional(), usage: usageInfo.nullable().optional(), max_output_tokens: z.number().int().nullable().optional(), max_tool_calls: z.number().int().nullable().optional(), store: z.boolean().optional(), background: z.boolean().optional(), service_tier: z.string().nullable().optional(), metadata: z.record(z.string(), z.string()).nullable().optional(), prompt_cache_key: z.string().nullable().optional(), conversation: conversationRef.nullable().optional(), safety_identifier: z.string().nullable().optional(), trace_id: 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 }; /** * Post Responses Endpoint * * POST /v1/responses */ export const createApiV1Responses = async (args: CreateApiV1ResponsesArgs, options?: CreateApiV1ResponsesOptions) => { const {baseUrl = "https://api.pharia.example.com", fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) 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(responseResponse, await res.json()) };