import {z} from 'zod' export type SystemMessage = {role: 'system', content: string | Array<{type: 'text', text: string}>, name?: string | undefined}; export type UserMessage = {role: 'user', content: string | Array<{type: 'text', text: string} | {type: 'image_url', image_url: {url: string}}>, name?: string | undefined}; export type AssistantMessage = {role: 'assistant', content?: (string | Array<{type: 'text', text: string}> | null) | undefined, name?: string | undefined, reasoning?: (string | null) | undefined, tool_calls?: Array<{id: string, type: 'function', function: {name: string, arguments: string}}> | undefined}; export type ToolMessage = {role: 'tool', content: string | Array<{type: 'text', text: string}>, tool_call_id: string}; export type DeveloperMessage = {role: 'developer', content: string | Array<{type: 'text', text: string}>, name?: string | undefined}; export type ResponseFormatText = {type: 'text'}; export type ResponseFormatJsonSchema = {type: 'json_schema', json_schema: {name: string, description?: string | undefined, schema?: Record | undefined, strict?: boolean | undefined}}; export type ResponseFormatJsonObject = {type: 'json_object'}; export type ChatCompletionRequest = {messages: Array, model: string, clear_thinking?: (boolean | null) | undefined, frequency_penalty?: (number | null) | undefined, logit_bias?: ({[key: string]: number} | null) | undefined, logprobs?: boolean | undefined, max_completion_tokens?: (number | null) | undefined, parallel_tool_calls?: (boolean | null) | undefined, prediction?: ({type: 'content', content: string | Array<{type: 'text', text: string}>} | null) | undefined, presence_penalty?: (number | null) | undefined, prompt_cache_key?: (string | null) | undefined, reasoning_effort?: ('low' | 'medium' | 'high' | 'none' | null) | undefined, response_format?: (ResponseFormatText | ResponseFormatJsonSchema | ResponseFormatJsonObject | null) | undefined, seed?: (number | null) | undefined, service_tier?: ('priority' | 'default' | 'auto' | 'flex' | null) | undefined, stop?: (string | null) | undefined, stream?: (boolean | null) | undefined, temperature?: (number | null) | undefined, tool_choice?: ('none' | 'auto' | 'required' | {type: 'function', function: {name: string}}) | undefined, tools?: (Array<{type: 'function', function: {name: string, description?: string | undefined, parameters?: Record | undefined}}> | null) | undefined, top_logprobs?: (number | null) | undefined, top_p?: (number | null) | undefined, user?: (string | null) | undefined}; export type CreateApiV1ChatCompletionsArgs = {'Content-Type'?: ('application/json' | 'application/vnd.msgpack') | undefined, 'Content-Encoding'?: 'gzip' | undefined, queue_threshold?: string | undefined, body: ChatCompletionRequest}; export type CreateApiV1ChatCompletionsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const chatCompletionResponse = z.object({id: z.string().optional(), choices: z.array(z.object({finish_reason: z.enum(["stop", "length", "content_filter", "tool_calls"]).optional(), index: z.number().int().optional(), logprobs: z.object({}).nullable().optional(), reasoning_logprobs: z.object({}).nullable().optional(), message: z.object({content: z.string().nullable().optional(), role: z.string().optional(), reasoning: z.string().optional(), tool_calls: z.array(z.object({id: z.string().optional(), type: z.literal("function").optional(), function: z.object({name: z.string().optional(), arguments: z.string().optional()}).optional()})).nullable().optional()}).optional()})).optional(), created: z.number().int().optional(), model: z.string().optional(), object: z.literal("chat.completion").optional(), system_fingerprint: z.string().optional(), service_tier: z.string().nullable().optional(), service_tier_used: z.enum(["priority", "default", "flex"]).nullable().optional(), usage: z.object({prompt_tokens: z.number().int().optional(), completion_tokens: z.number().int().optional(), total_tokens: z.number().int().optional(), image_tokens: z.number().int().optional(), prompt_tokens_details: z.object({cached_tokens: z.number().int().optional()}).optional(), completion_tokens_details: z.object({accepted_prediction_tokens: z.number().int().optional(), rejected_prediction_tokens: z.number().int().optional(), reasoning_tokens: z.number().int().optional()}).optional()}).optional(), time_info: z.object({queue_time: z.number().optional(), prompt_time: z.number().optional(), completion_time: z.number().optional(), total_time: z.number().optional(), created: z.number().optional()}).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.cerebras.ai", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Content-Type'] != null) headers.set("Content-Type", String(args['Content-Type'])) if (args['Content-Encoding'] != null) headers.set("Content-Encoding", String(args['Content-Encoding'])) if (args.queue_threshold != null) headers.set("queue_threshold", String(args.queue_threshold)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) 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()) };