import {z} from 'zod' export type V1Reasoning = {redactedData?: string | undefined, signature?: string | undefined, text?: string | undefined}; export type V1ToolCall = {id?: string | undefined, input?: Record | undefined, name?: string | undefined}; export type V1ToolResult = {content?: string | undefined, id?: string | undefined, isError?: boolean | undefined}; export type V1ContentBlock = {reasoning?: V1Reasoning | undefined, text?: string | undefined, toolCall?: V1ToolCall | undefined, toolResult?: V1ToolResult | undefined}; export type V1CompletionMessage = {content?: Array | undefined, data?: string | undefined, role?: string | undefined}; export type V1Tool = {description?: string | undefined, displayName?: string | undefined, inputSchema?: string | undefined, meta?: Record | undefined, name?: string | undefined, outputSchema?: string | undefined}; export type V1CompleteRequest = {includeReasoning?: boolean | undefined, messages?: Array | undefined, outputJsonSchema?: string | undefined, tools?: Array | undefined}; export type CreateApiV1AiCompleteArgs = {body: V1CompleteRequest}; export type CreateApiV1AiCompleteOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const v1Reasoning = z.object({redactedData: z.string().optional(), signature: z.string().optional(), text: z.string().optional()}); export const v1ToolCall = z.object({id: z.string().optional(), input: z.object({}).optional(), name: z.string().optional()}); export const v1ToolResult = z.object({content: z.string().optional(), id: z.string().optional(), isError: z.boolean().optional()}); export const v1ContentBlock = z.object({reasoning: v1Reasoning.optional(), text: z.string().optional(), toolCall: v1ToolCall.optional(), toolResult: v1ToolResult.optional()}); export const v1CompletionMessage = z.object({content: z.array(v1ContentBlock).optional(), data: z.string().optional(), role: z.string().optional()}); export const v1CompleteResponse = z.object({cacheWriteInputTokens: z.number().int().optional(), cachedInputTokens: z.number().int().optional(), inputTokens: z.number().int().optional(), message: v1CompletionMessage.optional(), outputTokens: z.number().int().optional(), provider: z.string().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 }; /** * Complete sends the messages of a chat to the AI and asks it to generate a new message. * * POST /v1/ai/complete */ export const createApiV1AiComplete = async (args: CreateApiV1AiCompleteArgs, options: CreateApiV1AiCompleteOptions) => { const {baseUrl, 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(/\/+$/, '')}/v1/ai/complete${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(v1CompleteResponse, await res.json()) };