import {z} from 'zod' export type MessageRole = 'user' | 'assistant' | 'system' | 'tool'; export type ImageURLStruct = {url: string, detail?: ('low' | 'high' | 'auto') | undefined}; export type ContentBlock = {type: 'text', text: string} | {type: 'image_url', image_url: ImageURLStruct}; export type FunctionCall = {name: string, arguments: string}; export type ToolCall = {id?: string | undefined, type?: 'function' | undefined, function: FunctionCall}; export type Citation = {start_index: number, end_index: number, title: string, url?: string | undefined, sources: unknown, type?: string | undefined}; export type Annotation = {type: string, url_citation: Citation}; export type BifrostMessage = {role: MessageRole, content?: (string | Array) | undefined, tool_call_id?: string | undefined, tool_calls?: Array | undefined, refusal?: string | undefined, annotations?: Array | undefined, thought?: string | undefined}; export type ChatCompletionRequest = {model: string, messages: Array, max_tokens?: number | undefined, fallbacks?: Array | undefined}; export type CreateApiGenaiV1betaModelsModelArgs = {model: string, body: ChatCompletionRequest}; export type CreateApiGenaiV1betaModelsModelOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const messageRole = z.enum(["user", "assistant", "system", "tool"]); export const imageURLStruct = z.object({url: z.string(), detail: z.enum(["low", "high", "auto"]).optional()}); export const contentBlock = z.discriminatedUnion("type", [z.object({type: z.literal("text"), text: z.string()}), z.object({type: z.literal("image_url"), image_url: imageURLStruct})]); export const functionCall = z.object({name: z.string(), arguments: z.string()}); export const toolCall = z.object({id: z.string().optional(), type: z.literal("function").optional(), function: functionCall}); export const citation = z.object({start_index: z.number().int(), end_index: z.number().int(), title: z.string(), url: z.string().optional(), sources: z.unknown(), type: z.string().optional()}); export const annotation = z.object({type: z.string(), url_citation: citation}); export const bifrostMessage = z.object({role: messageRole, content: z.union([z.string(), z.array(contentBlock)]).optional(), tool_call_id: z.string().optional(), tool_calls: z.array(toolCall).optional(), refusal: z.string().optional(), annotations: z.array(annotation).optional(), thought: z.string().optional()}); export const logProb = z.object({bytes: z.array(z.number().int()).optional(), logprob: z.number(), token: z.string()}); export const contentLogProb = z.object({bytes: z.array(z.number().int()).optional(), logprob: z.number(), token: z.string(), top_logprobs: z.array(logProb).optional()}); export const logProbs = z.object({content: z.array(contentLogProb).optional(), refusal: z.array(logProb).optional()}); export const bifrostResponseChoice = z.object({index: z.number().int(), message: bifrostMessage, finish_reason: z.enum(["stop", "length", "tool_calls", "content_filter", "function_call"]).optional(), stop: z.string().optional(), log_probs: logProbs.optional()}); export const completionTokensDetails = z.object({reasoning_tokens: z.number().int().optional(), audio_tokens: z.number().int().optional(), accepted_prediction_tokens: z.number().int().optional(), rejected_prediction_tokens: z.number().int().optional()}); export const lLMUsage = z.object({prompt_tokens: z.number().int().optional(), completion_tokens: z.number().int().optional(), total_tokens: z.number().int().optional(), completion_tokens_details: completionTokensDetails.optional()}); export const modelProvider = z.enum(["openai", "anthropic", "azure", "bedrock", "cohere", "vertex", "mistral", "ollama", "groq", "sgl"]); export const functionParameters = z.object({type: z.string(), description: z.string().optional(), properties: z.record(z.string(), z.unknown()).optional(), required: z.array(z.string()).optional(), enum: z.array(z.string()).optional()}); export const function = z.object({name: z.string(), description: z.string(), parameters: functionParameters}); export const tool = z.object({id: z.string().optional(), type: z.literal("function"), function: function}); export const toolChoiceFunction = z.object({name: z.string()}); export const toolChoice = z.object({type: z.enum(["none", "auto", "any", "function", "required"]), function: toolChoiceFunction.optional()}); export const modelParameters = z.object({temperature: z.number().gte(0).lte(2).optional(), top_p: z.number().gte(0).lte(1).optional(), top_k: z.number().int().gte(1).optional(), max_tokens: z.number().int().gte(1).optional(), stop_sequences: z.array(z.string()).optional(), presence_penalty: z.number().gte(-2).lte(2).optional(), frequency_penalty: z.number().gte(-2).lte(2).optional(), tools: z.array(tool).optional(), tool_choice: toolChoice.optional(), parallel_tool_calls: z.boolean().optional()}); export const billedLLMUsage = z.object({prompt_tokens: z.number().optional(), completion_tokens: z.number().optional(), search_units: z.number().optional(), classifications: z.number().optional()}); export const bifrostResponseExtraFields = z.object({provider: modelProvider.optional(), model_params: modelParameters.optional(), latency: z.number().optional(), chat_history: z.array(bifrostMessage).optional(), billed_usage: billedLLMUsage.optional(), raw_response: z.object({}).optional()}); export const bifrostResponse = z.object({id: z.string().optional(), object: z.enum(["chat.completion", "text.completion"]).optional(), choices: z.array(bifrostResponseChoice).optional(), model: z.string().optional(), created: z.number().int().optional(), service_tier: z.string().optional(), system_fingerprint: z.string().optional(), usage: lLMUsage.optional(), extra_fields: bifrostResponseExtraFields.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 }; /** * Google Gemini Compatible Completions * * POST /genai/v1beta/models/{model} */ export const createApiGenaiV1betaModelsModel = async (args: CreateApiGenaiV1betaModelsModelArgs, options?: CreateApiGenaiV1betaModelsModelOptions) => { const {baseUrl = "http://localhost:8080", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/genai/v1beta/models/${encodeURIComponent(String(args.model))}${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(bifrostResponse, await res.json()) };