import {z} from 'zod' export type CacheConfig = {ttl?: number | undefined, type: string}; export type OpenAIContextManagement = {compact_threshold?: number | undefined, provider_native?: boolean | undefined, type: string}; export type ConversationParam = {id: string}; export type FallbackConfig = {model: string}; export type EvaluatorRef = {execute_on: 'input' | 'output' | 'both', id: string, is_guardrail?: boolean | undefined, options?: {[key: string]: unknown} | undefined, sample_rate?: number | undefined, timeout?: number | undefined}; export type ResponseIdentity = {display_name?: string | undefined, email?: string | undefined, id: string, metadata?: (Array<{[key: string]: unknown}> | null) | undefined, tags?: (Array | null) | undefined}; export type ResponseExecutionLimits = {max_cost?: number | undefined, max_depth?: number | undefined, max_execution_time?: number | undefined, max_iterations?: number | undefined, tool_timeout?: number | undefined}; export type LoadBalancerModelConfig = {model: string, weight: number}; export type LoadBalancerConfig = {models: Array | null, type: 'weight_based' | 'round_robin' | 'latency_based'}; export type MemoryParam = {entity_id: string}; export type PublicPlugin = {entities?: (Array | null) | undefined, entity_thresholds?: {[key: string]: number} | undefined, id: 'pii_redaction' | 'response_healing' | 'trace_scrubbing', language?: string | undefined, mask?: (Array<'all' | 'system' | 'input' | 'output' | 'metadata' | 'variables'> | null) | undefined, on_failure?: ('block' | 'passthrough') | undefined, regions?: (Array | null) | undefined, threshold?: number | undefined}; export type OpenAIPromptCacheOptions = {mode?: ('implicit' | 'explicit') | undefined, ttl?: ('30m' | '12h') | undefined}; export type ReasoningParam = {context?: ('auto' | 'current_turn' | 'all_turns') | undefined, effort?: ('none' | 'instant' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max') | undefined, summary?: ('concise' | 'detailed' | 'auto') | undefined}; export type ResponseRetryConfig = {count: number, on_codes?: (Array | null) | undefined}; export type SecurityConfig = {mask?: (Array | null) | undefined}; export type StreamOptions = {include_obfuscation: boolean}; export type ThinkingParam = {budget_tokens: number | null, display?: ('summarized' | 'omitted' | 'updates') | undefined, thinking_level?: ('minimal' | 'low' | 'medium' | 'high') | undefined, type: 'enabled' | 'disabled' | 'adaptive' | 'between_tools' | null}; export type ResponseThread = {id: string, tags?: (Array | null) | undefined}; export type TimeoutConfig = {call_timeout: number}; export type OrqAdvisorTool = {max_tokens?: number | undefined, max_transcript_tokens?: number | undefined, max_uses?: number | undefined, model: string, reasoning_effort?: ('none' | 'instant' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max') | undefined, temperature?: number | undefined, type: 'orq:advisor'}; export type OrqSidekickTool = {max_tokens?: number | undefined, max_uses?: number | undefined, model: string, output_format?: string | undefined, reasoning_effort?: ('none' | 'instant' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max') | undefined, system_prompt?: string | undefined, temperature?: number | undefined, type: 'orq:subagent' | 'orq:sidekick'}; export type CreateApiV3RouterResponsesArgs = {body: {background?: boolean | undefined, cache?: CacheConfig | undefined, cache_control?: ({ttl?: ('5m' | '1h') | undefined, type: 'ephemeral'}) | undefined, context_management?: (Array | null) | undefined, conversation?: ConversationParam | undefined, fallback_on_codes?: (Array | null) | undefined, fallbacks?: (Array | null) | undefined, frequency_penalty?: number | undefined, guardrails?: Array | undefined, identity?: ResponseIdentity | undefined, include?: Array | undefined, input?: (string | Array<{arguments?: string | undefined, async?: boolean | undefined, call_id?: string | undefined, content?: (string | Array<{cache_control?: ({ttl?: ('5m' | '1h') | undefined, type: 'ephemeral'}) | undefined, prompt_cache_breakpoint?: ({mode: 'explicit', ttl?: ('30m' | '12h') | undefined}) | undefined, text: string, type: 'input_text'} | {cache_control?: ({ttl?: ('5m' | '1h') | undefined, type: 'ephemeral'}) | undefined, detail?: ('auto' | 'low' | 'high') | undefined, file_id?: string | undefined, image_url?: string | undefined, prompt_cache_breakpoint?: ({mode: 'explicit', ttl?: ('30m' | '12h') | undefined}) | undefined, type: 'input_image'} | {cache_control?: ({ttl?: ('5m' | '1h') | undefined, type: 'ephemeral'}) | undefined, file_data?: string | undefined, file_id?: string | undefined, file_url?: string | undefined, filename?: string | undefined, mime_type?: string | undefined, prompt_cache_breakpoint?: ({mode: 'explicit', ttl?: ('30m' | '12h') | undefined}) | undefined, type: 'input_file'}>) | undefined, id?: string | undefined, name?: string | undefined, output?: string | undefined, reasoning?: ({effort?: ('none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max') | undefined}) | undefined, role?: ('user' | 'assistant' | 'system' | 'developer') | undefined, status?: ('in_progress' | 'completed' | 'incomplete') | undefined, type?: ('message' | 'function_call' | 'function_call_output' | 'item_reference' | 'reasoning' | 'custom_tool_call' | 'custom_tool_call_output' | 'computer_call' | 'computer_call_output' | 'local_shell_call' | 'local_shell_call_output' | 'shell_call' | 'shell_call_output' | 'apply_patch_call' | 'apply_patch_call_output' | 'tool_search_call' | 'tool_search_output' | 'additional_tools' | 'compaction' | 'program' | 'program_output' | 'mcp_call' | 'mcp_list_tools' | 'mcp_approval_request' | 'mcp_approval_response' | 'configuration_update') | undefined}>) | undefined, instructions?: string | undefined, integration_id?: string | undefined, limits?: ResponseExecutionLimits | undefined, load_balancer?: LoadBalancerConfig | undefined, max_output_tokens?: number | undefined, max_tool_calls?: number | undefined, memory?: MemoryParam | undefined, metadata?: {[key: string]: string} | undefined, model?: string | undefined, parallel_tool_calls?: boolean | undefined, plugins?: (Array | null) | undefined, presence_penalty?: number | undefined, previous_response_id?: string | undefined, prompt_cache_key?: string | undefined, prompt_cache_options?: OpenAIPromptCacheOptions | undefined, reasoning?: ReasoningParam | undefined, retry?: ResponseRetryConfig | undefined, safety_identifier?: string | undefined, security?: SecurityConfig | undefined, service_tier?: ('auto' | 'default' | 'flex' | 'fast' | 'ultrafast' | 'scale' | 'priority') | undefined, speed?: ('standard' | 'fast') | undefined, stop_sequences?: Array | undefined, store?: boolean | undefined, stream?: boolean | undefined, stream_options?: StreamOptions | undefined, temperature?: number | undefined, template_engine?: ('text' | 'jinja' | 'mustache') | undefined, text?: ({format?: ({type: 'text'} | {description?: string | undefined, name: string, schema: {[key: string]: unknown}, strict?: boolean | undefined, type: 'json_schema'}) | undefined, verbosity?: ('low' | 'medium' | 'high') | undefined}) | undefined, thinking?: ThinkingParam | undefined, thread?: ResponseThread | undefined, timeout?: TimeoutConfig | undefined, tool_choice?: ('auto' | 'none' | 'required' | {name: string, type: 'function'}) | undefined, tools?: (Array<{async?: boolean | undefined, cache_control?: ({ttl?: ('5m' | '1h') | undefined, type: 'ephemeral'}) | undefined, defer_loading?: boolean | undefined, description?: string | undefined, name: string, parameters?: {[key: string]: unknown} | undefined, strict?: boolean | undefined, type: 'function'} | {async?: boolean | undefined, description?: string | undefined, name: string, type: 'custom'} | OrqAdvisorTool | OrqSidekickTool | {files?: Array<{file_id: string, name: string}> | undefined, max_results?: number | undefined, network?: ({allowlist?: Array | undefined, mode?: ('disabled' | 'allowlist') | undefined}) | undefined, timezone?: string | undefined, tool_id?: string | undefined, type: 'orq:web_search' | 'orq:web_fetch' | 'orq:datetime' | 'orq:search_models' | 'orq:tool_search' | 'orq:image_generation' | 'orq:apply_patch' | 'orq:fusion' | 'orq:shell' | 'orq:query_knowledge_base' | 'orq:retrieve_knowledge_bases' | 'orq:current_date' | 'orq:google_search' | 'orq:web_scraper' | 'orq:code_interpreter' | 'orq:mcp' | 'orq:http' | 'orq:function'} | {allowed_tools?: ({read_only?: boolean | undefined, tool_names?: Array | undefined}) | undefined, headers?: {[key: string]: string} | undefined, key?: string | undefined, server_description?: string | undefined, server_url?: string | undefined, type: 'mcp'}>) | undefined, top_k?: number | undefined, top_logprobs?: number | undefined, top_p?: number | undefined, variables?: {[key: string]: unknown} | undefined}}; export type CreateApiV3RouterResponsesOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const conversationParam = z.object({id: z.string()}); export const responseError = z.object({code: z.string(), message: z.string()}); export const incompleteDetails = z.object({reason: z.string()}); export const memoryParam = z.object({entity_id: z.string()}); export const openAIPromptCacheOptions = z.object({mode: z.enum(["implicit", "explicit"]).optional(), ttl: z.enum(["30m", "12h"]).optional()}); export const reasoning = z.object({context: z.enum(["auto", "current_turn", "all_turns"]).optional(), effort: z.enum(["none", "instant", "minimal", "low", "medium", "high", "xhigh", "max"]).optional(), summary: z.enum(["concise", "detailed", "auto", "null"]).nullable().optional()}); export const responseTelemetry = z.object({span_id: z.string(), trace_id: z.string()}); export const cacheWriteTokensDetails = z.object({ttl_12h_tokens: z.number().int(), ttl_30m_tokens: z.number().int()}); export const inputTokensDetails = z.object({cache_creation_1h_tokens: z.number().int().optional(), cache_creation_5m_tokens: z.number().int().optional(), cache_creation_tokens: z.number().int(), cache_write_tokens: z.number().int(), cache_write_tokens_details: cacheWriteTokensDetails.optional(), cached_tokens: z.number().int()}); export const outputTokensDetails = z.object({reasoning_tokens: z.number().int()}); export const serverToolUseDetails = z.object({advisor_requests: z.number().int().optional(), code_interpreter_sessions: z.number().int().optional(), datetime_requests: z.number().int().optional(), fusion_requests: z.number().int().optional(), image_generation_calls: z.number().int().optional(), search_models_requests: z.number().int().optional(), shell_commands: z.number().int().optional(), subagent_requests: z.number().int().optional(), tool_search_requests: z.number().int().optional(), web_fetch_requests: z.number().int().optional(), web_search_requests: z.number().int().optional()}); export const publicUsage = z.object({input_cost: z.number().optional(), input_tokens: z.number().int(), input_tokens_details: inputTokensDetails, output_cost: z.number().optional(), output_tokens: z.number().int(), output_tokens_details: outputTokensDetails, server_tool_use: serverToolUseDetails.optional(), speed: z.enum(["standard", "fast"]).optional(), total_cost: z.number().optional(), total_tokens: z.number().int(), web_search_requests: z.number().int().optional()}); export const createApiV3RouterResponsesResponse = z.object({background: z.boolean(), completed_at: z.number().int().nullable(), conversation: conversationParam.optional(), created_at: z.number().int(), error: responseError.nullable(), frequency_penalty: z.number(), id: z.string(), incomplete_details: incompleteDetails.nullable(), input: z.array(z.unknown()).nullable(), instructions: z.string().nullable(), max_output_tokens: z.number().int().nullable(), max_tool_calls: z.number().int().nullable(), memory: memoryParam.optional(), metadata: z.record(z.string(), z.string()), model: z.string(), object: z.string(), output: z.array(z.unknown()).nullable(), parallel_tool_calls: z.boolean(), presence_penalty: z.number(), previous_response_id: z.string().nullable(), prompt_cache_key: z.string().nullable(), prompt_cache_options: openAIPromptCacheOptions.nullable(), prompt_cache_retention: z.string().nullable(), reasoning: reasoning.nullable(), safety_identifier: z.string().nullable(), service_tier: z.enum(["auto", "default", "flex", "fast", "ultrafast", "scale", "priority"]), status: z.enum(["queued", "in_progress", "completed", "failed", "incomplete"]), store: z.boolean(), telemetry: responseTelemetry.optional(), temperature: z.number(), text: z.unknown(), tool_choice: z.unknown(), tools: z.array(z.unknown()).nullable(), top_k: z.number().int().optional(), top_logprobs: z.number().int(), top_p: z.number(), truncation: z.enum(["disabled", "auto"]), usage: publicUsage.nullable(), user: z.string().nullable(), variables: z.record(z.string(), z.unknown()).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 response * * POST /v3/router/responses */ export const createApiV3RouterResponses = async (args: CreateApiV3RouterResponsesArgs, options?: CreateApiV3RouterResponsesOptions) => { const {baseUrl = "https://my.orq.ai", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKey !== undefined) headers.set('authorization', `Bearer ${ApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/v3/router/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(createApiV3RouterResponsesResponse, await res.json()) };