import {z} from 'zod' export type SystemMessage = {role: 'system', content: string, name?: (string | null) | undefined}; export type TextContent = {type: 'text', text: string}; export type AudioData = {url: string}; export type AudioContent = {type: 'audio_url', audio_url: AudioData}; export type ImageData = {url: string}; export type ImageContent = {type: 'image_url', image_url: ImageData}; export type VideoData = {url: string}; export type VideoContent = {type: 'video_url', video_url: VideoData}; export type UserMessageContentMultiModal = TextContent | AudioContent | ImageContent | VideoContent; export type UserMessage = {role: 'user', content: string | Array, name?: (string | null) | undefined}; export type AssistantMessageToolCallFunction = {name: string, arguments: string}; export type AssistantMessageToolCall = {id: string, type: 'function', function: AssistantMessageToolCallFunction}; export type AssistantMessage = {role: 'assistant', content?: (string | null) | undefined, reasoning_content?: (string | null) | undefined, reasoning?: (string | null) | undefined, name?: (string | null) | undefined, tool_calls?: (Array | null) | undefined}; export type ToolMessage = {role: 'tool', content: string, tool_call_id: string, name?: (string | null) | undefined}; export type Message = SystemMessage | UserMessage | AssistantMessage | ToolMessage; export type StreamOptions = {include_usage?: (boolean | null) | undefined}; export type ChatCompleteBodyToolChoiceFunction = {name: string}; export type ChatCompleteBodyToolChoice = {type: 'function', function: ChatCompleteBodyToolChoiceFunction}; export type Function = {description?: (string | null) | undefined, name: string, parameters: {[key: string]: unknown}}; export type Tool = {type: 'function', function: Function}; export type ResponseFormatJsonSchemaSchema = {schema: {[key: string]: unknown}}; export type ResponseFormatJsonSchema = {type: 'json_schema', json_schema: ResponseFormatJsonSchemaSchema}; export type ResponseFormatJsonObject = {type: 'json_object'}; export type ResponseFormatRegex = {type: 'regex', schema: string}; export type ResponseFormatText = {type: 'text'}; export type ResponseFormat = ResponseFormatJsonSchema | ResponseFormatJsonObject | ResponseFormatRegex | ResponseFormatText; export type ServerlessChatCompletionBody = {model: string, messages: Array, chat_template_kwargs?: ({[key: string]: unknown} | null) | undefined, eos_token?: (Array | null) | undefined, frequency_penalty?: (number | null) | undefined, logit_bias?: ({[key: string]: unknown} | null) | undefined, logprobs?: (boolean | null) | undefined, max_tokens?: (number | null) | undefined, min_p?: (number | null) | undefined, n?: (number | null) | undefined, parallel_tool_calls?: (boolean | null) | undefined, presence_penalty?: (number | null) | undefined, repetition_penalty?: (number | null) | undefined, reasoning_effort?: ('low' | 'medium' | 'high' | null) | undefined, reasoning_budget?: (number | null) | undefined, seed?: (Array | number | null) | undefined, stop?: (Array | null) | undefined, stream?: (boolean | null) | undefined, stream_options?: (StreamOptions | null) | undefined, parse_reasoning?: (boolean | null) | undefined, include_reasoning?: (boolean | null) | undefined, temperature?: (number | null) | undefined, tool_choice?: (ChatCompleteBodyToolChoice | string) | undefined, top_k?: (number | null) | undefined, top_logprobs?: (number | null) | undefined, top_p?: (number | null) | undefined, xtc_threshold?: (number | null) | undefined, xtc_probability?: (number | null) | undefined, tools?: (Array | null) | undefined, min_tokens?: (number | null) | undefined, response_format?: (ResponseFormat | null) | undefined}; export type CreateApiServerlessV1ChatCompletionsArgs = {'X-Friendli-Team'?: (string | null) | undefined, body: ServerlessChatCompletionBody}; export type CreateApiServerlessV1ChatCompletionsOptions = {baseUrl?: string | undefined, token?: string | undefined, fetch?: typeof fetch | undefined}; export const chatLogprobsContentTopLogprob = z.object({token: z.string(), logprob: z.number(), bytes: z.array(z.number().int()).nullable().optional()}); export const chatLogprobsContent = z.object({token: z.string(), logprob: z.number(), bytes: z.array(z.number().int()).nullable().optional(), top_logprobs: z.array(chatLogprobsContentTopLogprob)}); export const chatLogprobs = z.object({content: z.array(chatLogprobsContent).nullable().optional()}); export const functionResult = z.object({arguments: z.string(), name: z.string()}); export const toolCallResult = z.object({type: z.literal("function"), id: z.string(), function: functionResult}); export const chatChoiceMessage = z.object({content: z.string().nullable().optional(), role: z.string(), tool_calls: z.array(toolCallResult).nullable().optional()}); export const chatChoice = z.object({index: z.number().int(), logprobs: chatLogprobs.nullable().optional(), message: chatChoiceMessage, finish_reason: z.enum(["stop", "length", "tool_calls"])}); export const promptTokensDetails = z.object({cached_tokens: z.number().int().nullable().optional()}); export const chatUsage = z.object({prompt_tokens: z.number().int(), completion_tokens: z.number().int(), total_tokens: z.number().int(), prompt_tokens_details: promptTokensDetails.nullable().optional()}); export const serverlessChatCompleteSuccess = z.object({id: z.string(), choices: z.array(chatChoice), usage: chatUsage, object: z.literal("chat.completion"), created: z.number().int(), model: z.string().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 /serverless/v1/chat/completions */ export const createApiServerlessV1ChatCompletions = async (args: CreateApiServerlessV1ChatCompletionsArgs, options?: CreateApiServerlessV1ChatCompletionsOptions) => { const {baseUrl = "https://api.friendli.ai", fetch: fetchFn = fetch, token} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-Friendli-Team'] != null) headers.set("X-Friendli-Team", String(args['X-Friendli-Team'])) if (token !== undefined) headers.set('authorization', `Bearer ${token}`) const url = `${baseUrl.replace(/\/+$/, '')}/serverless/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(serverlessChatCompleteSuccess, await res.json()) };