import {z} from 'zod' export type TextMessageContent = string; export type TextContentPart = {type: 'text', text: string}; export type ImageUrl = {url: string, detail?: ('auto' | 'low' | 'high') | undefined}; export type ImageContentPart = {type: 'image_url', image_url: ImageUrl}; export type InputAudio = {data: string, format: 'wav' | 'mp3'}; export type InputAudioContentPart = {type: 'input_audio', input_audio: InputAudio}; export type ContentPart = TextContentPart | ImageContentPart | InputAudioContentPart; export type MultimodalMessageContent = Array; export type ToolCall = {id: string, type: 'function', function: {name: string, arguments: string}}; export type Message = {role: 'system' | 'user' | 'assistant' | 'tool', content?: (TextMessageContent | MultimodalMessageContent | null) | undefined, tool_calls?: Array | undefined, tool_call_id?: string | undefined}; export type LogitBias = {token_id: string, bias_value: number}; export type WebSearchConfig = {engine?: ('exa' | 'google') | undefined, max_results?: number | undefined, max_steps?: number | undefined}; export type WebSearchOptions = {search_context_size?: ('low' | 'medium' | 'high') | undefined, user_location?: ({type?: 'approximate' | undefined, country?: string | undefined, city?: string | undefined}) | undefined}; export type ImageConfig = {aspect_ratio?: string | undefined, image_size?: string | undefined, partial_images?: number | undefined, n?: number | undefined}; export type ReasoningConfig = {effort?: ('unspecified' | 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh') | undefined, max_tokens?: number | undefined, exclude?: boolean | undefined}; export type ProviderConfig = {order?: Array | undefined, allow_fallbacks?: boolean | undefined}; export type ExtraBody = {models?: Array | undefined, ignore?: Array | undefined, sort?: Array | undefined, reasoning?: ReasoningConfig | undefined, provider?: ProviderConfig | undefined, prompt_variables?: {[key: string]: string} | undefined, web_search?: WebSearchConfig | undefined, web_search_options?: WebSearchOptions | undefined}; export type ChatCompletionRequest = {model: string, messages: Array, stream?: boolean | undefined, temperature?: number | undefined, top_p?: number | undefined, max_tokens?: number | undefined, max_completion_tokens?: number | undefined, presence_penalty?: number | undefined, frequency_penalty?: number | undefined, seed?: number | undefined, stop?: Array | undefined, logit_bias?: Array | undefined, reasoning_effort?: ('none' | 'low' | 'minimal' | 'medium' | 'high' | 'xhigh') | undefined, user?: string | undefined, web_search?: WebSearchConfig | undefined, web_search_options?: WebSearchOptions | undefined, modalities?: (Array<'text' | 'image'>) | undefined, image_config?: ImageConfig | undefined, extra_body?: ExtraBody | undefined}; export type CreateApiV1ChatCompletionsArgs = {body: ChatCompletionRequest}; export type CreateApiV1ChatCompletionsOptions = {baseUrl?: string | undefined, inworldBasic?: string | undefined, fetch?: typeof fetch | undefined}; export const choice = z.object({index: z.number().int().optional(), message: z.object({role: z.string().optional(), content: z.string().nullable().optional(), tool_calls: z.array(z.object({id: z.string().optional(), type: z.string().optional(), function: z.object({name: z.string().optional(), arguments: z.string().optional()}).optional()})).optional()}).optional(), finish_reason: z.string().optional()}); export const attempt = z.object({model: z.string().optional(), success: z.boolean().optional(), time_to_first_token_ms: z.number().int().optional()}); export const metadata = z.object({attempts: z.array(attempt).optional(), generation_id: z.string().optional(), reasoning: z.string().optional(), total_duration_ms: z.number().int().optional()}); export const chatCompletionResponse = z.object({id: z.string().optional(), object: z.string().optional(), created: z.number().int().optional(), model: z.string().optional(), choices: z.array(choice).optional(), usage: z.object({prompt_tokens: z.number().int().optional(), completion_tokens: z.number().int().optional(), total_tokens: z.number().int().optional()}).optional(), metadata: metadata.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 chat completion * * POST /v1/chat/completions */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options?: CreateApiV1ChatCompletionsOptions) => { const {baseUrl = "https://api.inworld.ai", fetch: fetchFn = fetch, inworldBasic} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (inworldBasic !== undefined) headers.set("Authorization", inworldBasic) const url = `${baseUrl.replace(/\/+$/, '')}/v1/chat/completions${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(chatCompletionResponse, await res.json()) };