import { SecretBox } from "@refs/ci"; import type { ModelProvider } from "./contract/views.ts"; export const DEFAULT_MODEL = "@cf/zai-org/glm-5.3"; const GATEWAY = "default"; const MAX_OUTPUT_TOKENS = 8192; const PROVIDERS: Record = { anthropic: { label: "Anthropic", endpoint: "v1/chat/completions", limit: "max_tokens" }, openai: { label: "OpenAI", endpoint: "chat/completions", limit: "max_completion_tokens" }, openrouter: { label: "OpenRouter", endpoint: "v1/chat/completions", limit: "max_tokens" }, }; export interface ModelChoice { readonly provider: ModelProvider; readonly model: string; readonly key: string; } export type ToolCall = { id: string; type: "function"; function: { name: string; arguments: string } }; export type ChatMessage = { role: "system" | "user" | "assistant" | "tool"; content: string | null; tool_calls?: ToolCall[]; tool_call_id?: string }; type Completion = { choices?: { message?: { content?: string | null; tool_calls?: ToolCall[]; reasoning_content?: string | null; reasoning?: string | null } }[] }; export class ModelError extends Error {} export const modelName = (choice: ModelChoice | null) => (choice ? `${choice.provider}/${choice.model}` : DEFAULT_MODEL); /** One chat completion. With no choice, it runs the default model on Workers AI, which refs pays for. `thinking` is the model's reasoning, when it shares it. */ export async function chat(env: Env, choice: ModelChoice | null, messages: ChatMessage[], tools: unknown[]): Promise<{ message: ChatMessage; thinking: string | null }> { const body = { messages, ...(tools.length ? { tools } : {}) }; let out: Completion; if (!choice) { out = (await env.AI.run(DEFAULT_MODEL as never, { ...body, reasoning_effort: "high" } as never, { gateway: { id: GATEWAY } })) as Completion; } else { const provider = PROVIDERS[choice.provider]; const response = await env.AI.gateway(GATEWAY).run({ provider: choice.provider, endpoint: provider.endpoint, headers: { authorization: `Bearer ${choice.key}`, "content-type": "application/json" } as never, query: { ...body, model: choice.model, [provider.limit]: MAX_OUTPUT_TOKENS }, }); if (!response.ok) throw new ModelError(failure(choice, response.status, await response.text())); out = await response.json(); } const message = out.choices?.[0]?.message; return { message: { role: "assistant", content: message?.content ?? null, ...(message?.tool_calls?.length ? { tool_calls: message.tool_calls } : {}) }, thinking: message?.reasoning_content || message?.reasoning || null, }; } /** A provider error in words a person can act on. Providers echo the key in some errors, so the text never carries it. */ export function failure(choice: ModelChoice, status: number, text: string): string { const label = PROVIDERS[choice.provider].label; if (status === 401 || status === 403) return `${label} rejected the API key.`; if (status === 402) return `${label} says the account has no credit left.`; if (status === 429) return `${label} refused the request because of a rate limit. Try again later.`; let said = text; try { const parsed = JSON.parse(text); said = String(parsed?.error?.message ?? parsed?.message ?? text); } catch {} const clean = said.split(choice.key).join("…").replace(/\b(sk|key)-[\w-]{6,}/gi, "…").replace(/\s+/g, " ").slice(0, 200); return `${label} returned ${status}: ${clean}`; } export async function sealer(env: Env): Promise { const key = (env as unknown as { CI_SECRETS_KEY?: string }).CI_SECRETS_KEY; return key ? SecretBox.fromBase64(key) : null; } /** Sends one small request with the key. Returns why it failed, or null when the key and model work. */ export async function testModel(env: Env, choice: ModelChoice): Promise { try { await chat(env, choice, [{ role: "user", content: "Reply with OK." }], []); return null; } catch (error) { return error instanceof ModelError ? error.message : `${PROVIDERS[choice.provider].label} could not be reached. Try again.`; } } export const isProvider = (value: string): value is ModelProvider => Object.hasOwn(PROVIDERS, value);