import {z} from 'zod' export type AnthropicContentBlock = {type: 'text', text: string} | {type: 'image', source: {type: 'base64', media_type: string, data: string}}; export type AnthropicMessage = {role: 'user' | 'assistant', content: string | Array}; export type AnthropicMessagesRequest = {model: string, messages: Array, max_tokens?: number | undefined, temperature?: number | undefined, stream?: boolean | undefined, system?: (string | Array>) | undefined, flagged_categories?: Array | undefined}; export type CreateApiV1MessagesArgs = {'X-Free-Tier'?: 'true' | undefined, body: AnthropicMessagesRequest}; export type CreateApiV1MessagesOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const anthropicContentBlock = z.union([z.object({type: z.literal("text"), text: z.string()}), z.object({type: z.literal("image"), source: z.object({type: z.literal("base64"), media_type: z.string(), data: z.string()})})]); export const anthropicUsage = z.object({input_tokens: z.number().int().optional(), output_tokens: z.number().int().optional()}); export const anthropicMessagesResponse = z.object({id: z.string(), type: z.literal("message"), role: z.literal("assistant"), model: z.string(), content: z.array(anthropicContentBlock), stop_reason: z.string().nullable().optional(), stop_sequence: z.string().nullable().optional(), usage: anthropicUsage.optional(), remaining_credits: z.number().int().nullable().optional(), estimated_credits_used: z.number().int().optional(), estimated_cost_usd: z.number().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 }; /** * Create a message * * POST /v1/messages * * Also accepts auth: AnthropicApiKeyAuth */ export const createApiV1Messages = async (args: CreateApiV1MessagesArgs, options?: CreateApiV1MessagesOptions) => { const {baseUrl = "https://api.abliteration.ai", 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 (args['X-Free-Tier'] != null) headers.set("X-Free-Tier", String(args['X-Free-Tier'])) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/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(anthropicMessagesResponse, await res.json()) };