import {z} from 'zod' export type ResponseInputContent = {type: 'input_text' | 'input_image' | 'input_file', text?: string | undefined, image_url?: string | undefined, file_id?: string | undefined, file_url?: string | undefined, file_data?: string | undefined, filename?: string | undefined, detail?: ('low' | 'high' | 'auto') | undefined}; export type ResponseInputItem = {type?: string | undefined, role?: ('user' | 'assistant' | 'system' | 'developer') | undefined, content?: (string | Array) | undefined, id?: string | undefined, call_id?: string | undefined, output: unknown} | {[key: string]: unknown}; export type ResponseTextConfig = {format?: {[key: string]: unknown} | undefined, verbosity?: ('low' | 'medium' | 'high') | undefined}; export type ResponsesRequest = {model?: string | undefined, input?: (string | Array) | undefined, instructions?: string | undefined, previous_response_id?: string | undefined, conversation?: (string | {id: string}) | undefined, background?: boolean | undefined, include?: (Array<'file_search_call.results' | 'web_search_call.results' | 'web_search_call.action.sources' | 'message.input_image.image_url' | 'computer_call_output.output.image_url' | 'code_interpreter_call.outputs' | 'reasoning.encrypted_content' | 'message.output_text.logprobs'>) | undefined, max_output_tokens?: number | undefined, max_tool_calls?: number | undefined, metadata?: {[key: string]: string} | undefined, parallel_tool_calls?: boolean | undefined, prompt?: ({id: string, version?: string | undefined, variables?: {[key: string]: unknown} | undefined}) | undefined, prompt_cache_key?: string | undefined, prompt_cache_retention?: ('in-memory' | '24h') | undefined, reasoning?: ({effort?: ('none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh') | undefined, summary?: ('auto' | 'concise' | 'detailed') | undefined}) | undefined, safety_identifier?: string | undefined, service_tier?: ('auto' | 'default' | 'flex' | 'scale' | 'priority') | undefined, store?: boolean | undefined, stream?: boolean | undefined, stream_options?: ({include_obfuscation?: boolean | undefined}) | undefined, temperature?: number | undefined, text?: ResponseTextConfig | undefined, tool_choice?: ('none' | 'auto' | 'required' | {[key: string]: unknown}) | undefined, tools?: Array<{[key: string]: unknown}> | undefined, top_logprobs?: number | undefined, top_p?: number | undefined, truncation?: ('auto' | 'disabled') | undefined}; export type CreateApiV1ResponsesArgs = {body: ResponsesRequest}; export type CreateApiV1ResponsesOptions = {baseUrl?: string | undefined, Authorization?: string | undefined, fetch?: typeof fetch | undefined}; export const responseOutputContent = z.object({type: z.enum(["output_text", "refusal"]), text: z.string().optional(), refusal: z.string().optional(), annotations: z.array(z.record(z.string(), z.unknown())).optional(), logprobs: z.array(z.record(z.string(), z.unknown())).optional()}); export const responseOutputItem = z.object({type: z.string().optional(), id: z.string().optional(), status: z.string().optional(), role: z.literal("assistant").optional(), content: z.array(responseOutputContent).optional(), call_id: z.string().optional(), name: z.string().optional(), arguments: z.string().optional()}).and(z.record(z.string(), z.unknown())); export const responseUsage = z.object({input_tokens: z.number().int().optional(), input_tokens_details: z.object({cached_tokens: z.number().int().optional()}).optional(), output_tokens: z.number().int().optional(), output_tokens_details: z.object({reasoning_tokens: z.number().int().optional()}).optional(), total_tokens: z.number().int().optional()}); export const responseObject = z.object({id: z.string(), object: z.literal("response"), created_at: z.number(), status: z.enum(["completed", "failed", "in_progress", "cancelled", "queued", "incomplete"]), error: z.object({code: z.string().optional(), message: z.string().optional()}).nullable().optional(), incomplete_details: z.object({reason: z.enum(["max_output_tokens", "content_filter"]).optional()}).nullable().optional(), model: z.string(), output: z.array(responseOutputItem), output_text: z.string().optional(), previous_response_id: z.string().nullable().optional(), store: z.boolean().optional(), usage: responseUsage.optional(), metadata: z.record(z.string(), z.string()).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 a model response * * POST /v1/responses */ export const createApiV1Responses = async (args: CreateApiV1ResponsesArgs, options?: CreateApiV1ResponsesOptions) => { const {baseUrl = "https://api.ttapi.io", fetch: fetchFn = fetch, Authorization} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (Authorization !== undefined) headers.set("Authorization", Authorization) 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(responseObject, await res.json()) };