import {z} from 'zod' export type CohereMessage = {role: 'system' | 'user' | 'assistant' | 'tool', content?: (string | Array<{type: 'text' | 'image_url' | 'thinking' | 'document', text?: string | undefined, image_url?: ({url?: string | undefined}) | undefined, thinking?: string | undefined, document?: ({data?: Record | undefined, id?: string | undefined}) | undefined}>) | undefined, tool_calls?: (Array<{id?: string | undefined, type?: 'function' | undefined, function?: ({name?: string | undefined, arguments?: string | undefined}) | undefined}>) | undefined, tool_call_id?: string | undefined, tool_plan?: string | undefined}; export type CohereChatRequest = {model: string, messages: Array, tools?: (Array<{type?: 'function' | undefined, function?: ({name?: string | undefined, description?: string | undefined, parameters?: Record | undefined}) | undefined}>) | undefined, tool_choice?: ('AUTO' | 'NONE' | 'REQUIRED') | undefined, temperature?: number | undefined, p?: number | undefined, k?: number | undefined, max_tokens?: number | undefined, stop_sequences?: Array | undefined, frequency_penalty?: number | undefined, presence_penalty?: number | undefined, stream?: boolean | undefined, safety_mode?: ('CONTEXTUAL' | 'STRICT' | 'NONE') | undefined, log_probs?: boolean | undefined, strict_tool_choice?: boolean | undefined, thinking?: ({type?: ('enabled' | 'disabled') | undefined, token_budget?: number | undefined}) | undefined, response_format?: ({type?: ('text' | 'json_object') | undefined, schema?: Record | undefined}) | undefined}; export type CreateApiPydanticaiCohereV2ChatArgs = {body: CohereChatRequest}; export type CreateApiPydanticaiCohereV2ChatOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const cohereChatResponse = z.object({id: z.string().optional(), finish_reason: z.enum(["COMPLETE", "STOP_SEQUENCE", "MAX_TOKENS", "TOOL_CALL", "ERROR", "TIMEOUT"]).optional(), message: z.object({role: z.string().optional(), content: z.array(z.object({type: z.enum(["text", "image_url", "thinking", "document"]), text: z.string().optional(), image_url: z.object({url: z.string().optional()}).optional(), thinking: z.string().optional(), document: z.object({data: z.object({}).optional(), id: z.string().optional()}).optional()})).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()})).optional(), tool_plan: z.string().optional()}).optional(), usage: z.object({billed_units: z.object({input_tokens: z.number().int().optional(), output_tokens: z.number().int().optional(), search_units: z.number().int().optional(), classifications: z.number().int().optional()}).optional(), tokens: z.object({input_tokens: z.number().int().optional(), output_tokens: z.number().int().optional()}).optional(), cached_tokens: z.number().int().optional()}).optional(), logprobs: z.array(z.object({token_ids: z.array(z.number().int()).optional(), text: z.string().optional(), logprobs: z.array(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 }; /** * Chat with model (PydanticAI - Cohere format) * * POST /pydanticai/cohere/v2/chat * * Also accepts auth: BasicAuth, VirtualKeyAuth, ApiKeyAuth */ export const createApiPydanticaiCohereV2Chat = async (args: CreateApiPydanticaiCohereV2ChatArgs, options?: CreateApiPydanticaiCohereV2ChatOptions) => { const {baseUrl = "http://localhost:8080", 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 (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/pydanticai/cohere/v2/chat${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(cohereChatResponse, await res.json()) };