import {z} from 'zod' export type FunctionCall = {name: string, arguments: string}; export type ChatCompletionMessageToolCall = {id: string, type: 'function', function: FunctionCall}; export type ChatCompletionRequestMessage = {role: 'assistant', content?: (string | null) | undefined, tool_calls?: (Array | null) | undefined} | {role: 'system', content: string} | {role: 'tool', content: string, tool_call_id: string} | {role: 'user', content: string}; export type SarvamModelIds = 'sarvam-105b' | 'sarvam-30b'; export type ReasoningEffort = 'low' | 'medium' | 'high'; export type StopConfiguration = string | Array; export type FunctionDefinition = {name: string, description?: (string | null) | undefined, parameters?: ({[key: string]: unknown} | null) | undefined}; export type ChatCompletionTool = {type: 'function', function: FunctionDefinition}; export type ToolChoiceOption0 = 'none' | 'auto' | 'required'; export type ChatCompletionNamedToolChoiceFunction = {name: string}; export type ChatCompletionNamedToolChoice = {type: 'function', function: ChatCompletionNamedToolChoiceFunction}; export type ToolChoiceOption = ToolChoiceOption0 | ChatCompletionNamedToolChoice; export type JsonSchemaDefinitionSchema = Record; export type JsonSchemaDefinition = {name: string, description?: (string | null) | undefined, schema?: (JsonSchemaDefinitionSchema | null) | undefined, strict?: (boolean | null) | undefined}; export type ResponseFormat = {type: 'text'} | {type: 'json_object'} | {type: 'json_schema', json_schema: JsonSchemaDefinition}; export type CreateChatCompletionRequest = {messages: Array, model: SarvamModelIds, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, reasoning_effort?: (ReasoningEffort | null) | undefined, max_tokens?: (number | null) | undefined, stream?: (boolean | null) | undefined, stop?: (StopConfiguration | null) | undefined, n?: (number | null) | undefined, seed?: (number | null) | undefined, frequency_penalty?: (number | null) | undefined, presence_penalty?: (number | null) | undefined, wiki_grounding?: (boolean | null) | undefined, tools?: (Array | null) | undefined, tool_choice?: (ToolChoiceOption | null) | undefined, response_format?: (ResponseFormat | null) | undefined}; export type CreateApiV1ChatCompletionsArgs = {Authorization: string, 'api-subscription-key'?: (string | null) | undefined, body: CreateChatCompletionRequest}; export type CreateApiV1ChatCompletionsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const finishReason = z.enum(["stop", "length", "tool_calls", "content_filter", "function_call"]); export const role = z.literal("assistant"); export const functionCall = z.object({name: z.string(), arguments: z.string()}); export const chatCompletionMessageToolCall = z.object({id: z.string(), type: z.literal("function"), function: functionCall}); export const chatCompletionResponseMessage = z.object({content: z.string().nullable(), refusal: z.string().nullable().optional(), reasoning_content: z.string().nullable().optional(), role: role, tool_calls: z.array(chatCompletionMessageToolCall).nullable().optional()}); export const choice = z.object({finish_reason: finishReason, index: z.number().int(), logprobs: z.record(z.string(), z.unknown()).nullable().optional(), message: chatCompletionResponseMessage}); export const completionUsage = z.object({completion_tokens: z.number().int(), prompt_tokens: z.number().int(), total_tokens: z.number().int(), completion_tokens_details: z.record(z.string(), z.unknown()).nullable().optional(), prompt_tokens_details: z.record(z.string(), z.unknown()).nullable().optional()}); export const createChatCompletionResponse = z.object({id: z.string(), choices: z.array(choice), created: z.number().int(), model: z.string(), object: z.literal("chat.completion"), service_tier: z.string().nullable().optional(), system_fingerprint: z.string().nullable().optional(), usage: completionUsage.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 }; /** * Chat Completions * * POST /v1/chat/completions */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options?: CreateApiV1ChatCompletionsOptions) => { const {baseUrl = "https://api.sarvam.ai", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (args['api-subscription-key'] != null) headers.set("api-subscription-key", String(args['api-subscription-key'])) 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(createChatCompletionResponse, await res.json()) };