import {z} from 'zod' export type TextChunk = {text: string, type?: 'text' | undefined}; export type SystemMessage = {role?: 'system' | undefined, content: string | Array}; export type ImageURLChunk = {image_url: {detail?: (string | null) | undefined, url: string} | string, type?: 'image_url' | undefined}; export type DocumentURLChunk = {document_name?: (string | null) | undefined, type?: string | undefined, document_url: string}; export type ReferenceChunk = {reference_ids: Array, type?: 'reference' | undefined}; export type ContentChunk = TextChunk | ImageURLChunk | DocumentURLChunk | ReferenceChunk; export type UserMessage = {role?: 'user' | undefined, content: string | Array | null}; export type FunctionCall = {name: string, arguments: {[key: string]: unknown} | string}; export type ToolTypes = 'function'; export type ToolCall = {function: FunctionCall, index?: number | undefined, id?: string | undefined, type?: ToolTypes | undefined}; export type AssistantMessage = {role?: 'assistant' | undefined, prefix?: boolean | undefined, tool_calls?: (Array | null) | undefined, content?: (string | Array | null) | undefined}; export type ToolMessage = {role?: 'tool' | undefined, tool_call_id?: (string | null) | undefined, name?: (string | null) | undefined, content: string | Array | null}; export type ChatModerationRequest = {truncate_for_context_length?: boolean | undefined, input: Array | Array>, model: string}; export type CreateApiChatModerationsArgs = {body: ChatModerationRequest}; export type CreateApiChatModerationsOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const classificationObject = z.object({category_scores: z.record(z.string(), z.number()).optional(), categories: z.record(z.string(), z.boolean()).optional()}); export const classificationResponse = z.object({model: z.string().optional(), id: z.string().optional(), results: z.array(classificationObject).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 }; /** * Moderations Chat * * POST /chat/moderations */ export const createApiChatModerations = async (args: CreateApiChatModerationsArgs, options?: CreateApiChatModerationsOptions) => { const {baseUrl = "https://api.mistral.ai/v1", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKey !== undefined) headers.set('authorization', `Bearer ${ApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/chat/moderations${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(classificationResponse, await res.json()) };