import {z} from 'zod' export type MessagesTextBlock = {type: 'text', text: string}; export type MessagesBase64ImageSource = {type: 'base64', data: string, media_type: string}; export type MessagesUrlImageSource = {type: 'url', url: string}; export type MessagesImageSource = MessagesBase64ImageSource | MessagesUrlImageSource; export type MessagesImageBlock = {type: 'image', source: MessagesImageSource}; export type MessagesThinkingBlock = {type: 'thinking', thinking: string, signature?: (string | null) | undefined}; export type MessagesToolUseBlock = {type: 'tool_use', id?: (string | null) | undefined, name: string, input: {[key: string]: unknown}}; export type MessagesToolResultBlock = {type: 'tool_result', tool_use_id: string, content?: (string | Array<{[key: string]: unknown}> | null) | undefined}; export type MessagesCompatibilityBlock = {type: 'document' | 'search_result' | 'redacted_thinking' | 'server_tool_use' | 'web_search_tool_result' | 'web_fetch_tool_result' | 'code_execution_tool_result' | 'bash_code_execution_tool_result' | 'text_editor_code_execution_tool_result' | 'tool_search_tool_result' | 'container_upload'}; export type MessagesContentBlock = MessagesTextBlock | MessagesImageBlock | MessagesThinkingBlock | MessagesToolUseBlock | MessagesToolResultBlock | MessagesCompatibilityBlock; export type MessagesInputMessage = {role: 'user' | 'assistant', content: string | Array}; export type MessagesSystemTextBlock = {type: 'text', text: string}; export type MessagesToolDefinition = {name: string, type?: (string | null) | undefined, description?: (string | null) | undefined, input_schema?: ({[key: string]: unknown} | null) | undefined, strict?: (boolean | null) | undefined}; export type MessagesToolChoice = {type: 'auto' | 'any' | 'tool' | 'none', name?: (string | null) | undefined, disable_parallel_tool_use?: (boolean | null) | undefined}; export type MessagesThinkingConfig = {type: 'enabled' | 'disabled' | 'adaptive', budget_tokens?: (number | null) | undefined}; export type MessagesOutputFormat = {type?: ('json_schema' | null) | undefined, schema?: ({[key: string]: unknown} | null) | undefined}; export type MessagesOutputConfig = {effort?: ('low' | 'medium' | 'high' | 'max' | null) | undefined, format?: (MessagesOutputFormat | null) | undefined}; export type ServerlessMessagesBody = {messages: Array, max_tokens?: (number | null) | undefined, model: string, system?: (string | Array | null) | undefined, stream?: (boolean | null) | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, top_k?: (number | null) | undefined, stop_sequences?: (Array | null) | undefined, tools?: (Array | null) | undefined, tool_choice?: (MessagesToolChoice | null) | undefined, thinking?: (MessagesThinkingConfig | null) | undefined, output_config?: (MessagesOutputConfig | null) | undefined, cache_control?: ({[key: string]: unknown} | null) | undefined, container?: ({[key: string]: unknown} | null) | undefined, context_manager?: ({[key: string]: unknown} | null) | undefined, inference_geo?: ({[key: string]: unknown} | null) | undefined, metadata?: ({[key: string]: unknown} | null) | undefined, service_tier?: (string | {[key: string]: unknown} | null) | undefined} | {[key: string]: unknown}; export type CreateApiServerlessV1MessagesArgs = {'X-Friendli-Team'?: (string | null) | undefined, body: ServerlessMessagesBody}; export type CreateApiServerlessV1MessagesOptions = {baseUrl?: string | undefined, token?: string | undefined, fetch?: typeof fetch | undefined}; export const messagesResponseThinkingBlock = z.object({type: z.literal("thinking"), thinking: z.string(), signature: z.string()}); export const messagesResponseTextBlock = z.object({type: z.literal("text"), text: z.string()}); export const messagesResponseToolUseBlock = z.object({type: z.literal("tool_use"), id: z.string(), name: z.string(), input: z.record(z.string(), z.unknown())}); export const messagesResponseContentBlock = z.discriminatedUnion("type", [messagesResponseThinkingBlock, messagesResponseTextBlock, messagesResponseToolUseBlock]); export const messagesUsage = z.object({input_tokens: z.number().int().gte(0), output_tokens: z.number().int().gte(0), cache_read_input_tokens: z.number().int().gte(0).nullable().optional()}); export const serverlessMessagesSuccess = z.object({id: z.string(), type: z.literal("message"), role: z.literal("assistant"), content: z.array(messagesResponseContentBlock), stop_reason: z.enum(["end_turn", "max_tokens", "tool_use", "stop_sequence"]).nullable().optional(), stop_sequence: z.string().nullable().optional(), usage: messagesUsage, model: z.string().nullable().optional()}).and(z.record(z.string(), z.unknown())); 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 }; /** * Messages * * POST /serverless/v1/messages */ export const createApiServerlessV1Messages = async (args: CreateApiServerlessV1MessagesArgs, options?: CreateApiServerlessV1MessagesOptions) => { 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/messages${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(serverlessMessagesSuccess, await res.json()) };