Skip to content
refs
History
82 lines · 4.2 KBRaw
1import { SecretBox } from "@refs/ci";
2import type { ModelProvider } from "./contract/views.ts";
3
4export const DEFAULT_MODEL = "@cf/zai-org/glm-5.3";
5const GATEWAY = "default";
6const MAX_OUTPUT_TOKENS = 8192;
7
8const PROVIDERS: Record<ModelProvider, { readonly label: string; readonly endpoint: string; readonly limit: "max_tokens" | "max_completion_tokens" }> = {
9 anthropic: { label: "Anthropic", endpoint: "v1/chat/completions", limit: "max_tokens" },
10 openai: { label: "OpenAI", endpoint: "chat/completions", limit: "max_completion_tokens" },
11 openrouter: { label: "OpenRouter", endpoint: "v1/chat/completions", limit: "max_tokens" },
12};
13
14export interface ModelChoice {
15 readonly provider: ModelProvider;
16 readonly model: string;
17 readonly key: string;
18}
19
20export type ToolCall = { id: string; type: "function"; function: { name: string; arguments: string } };
21export type ChatMessage = { role: "system" | "user" | "assistant" | "tool"; content: string | null; tool_calls?: ToolCall[]; tool_call_id?: string };
22type Completion = { choices?: { message?: { content?: string | null; tool_calls?: ToolCall[]; reasoning_content?: string | null; reasoning?: string | null } }[] };
23
24export class ModelError extends Error {}
25
26export const modelName = (choice: ModelChoice | null) => (choice ? `${choice.provider}/${choice.model}` : DEFAULT_MODEL);
27
28/** 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. */
29export async function chat(env: Env, choice: ModelChoice | null, messages: ChatMessage[], tools: unknown[]): Promise<{ message: ChatMessage; thinking: string | null }> {
30 const body = { messages, ...(tools.length ? { tools } : {}) };
31 let out: Completion;
32 if (!choice) {
33 out = (await env.AI.run(DEFAULT_MODEL as never, { ...body, reasoning_effort: "high" } as never, { gateway: { id: GATEWAY } })) as Completion;
34 } else {
35 const provider = PROVIDERS[choice.provider];
36 const response = await env.AI.gateway(GATEWAY).run({
37 provider: choice.provider,
38 endpoint: provider.endpoint,
39 headers: { authorization: `Bearer ${choice.key}`, "content-type": "application/json" } as never,
40 query: { ...body, model: choice.model, [provider.limit]: MAX_OUTPUT_TOKENS },
41 });
42 if (!response.ok) throw new ModelError(failure(choice, response.status, await response.text()));
43 out = await response.json();
44 }
45 const message = out.choices?.[0]?.message;
46 return {
47 message: { role: "assistant", content: message?.content ?? null, ...(message?.tool_calls?.length ? { tool_calls: message.tool_calls } : {}) },
48 thinking: message?.reasoning_content || message?.reasoning || null,
49 };
50}
51
52/** A provider error in words a person can act on. Providers echo the key in some errors, so the text never carries it. */
53export function failure(choice: ModelChoice, status: number, text: string): string {
54 const label = PROVIDERS[choice.provider].label;
55 if (status === 401 || status === 403) return `${label} rejected the API key.`;
56 if (status === 402) return `${label} says the account has no credit left.`;
57 if (status === 429) return `${label} refused the request because of a rate limit. Try again later.`;
58 let said = text;
59 try {
60 const parsed = JSON.parse(text);
61 said = String(parsed?.error?.message ?? parsed?.message ?? text);
62 } catch {}
63 const clean = said.split(choice.key).join("…").replace(/\b(sk|key)-[\w-]{6,}/gi, "…").replace(/\s+/g, " ").slice(0, 200);
64 return `${label} returned ${status}: ${clean}`;
65}
66
67export async function sealer(env: Env): Promise<SecretBox | null> {
68 const key = (env as unknown as { CI_SECRETS_KEY?: string }).CI_SECRETS_KEY;
69 return key ? SecretBox.fromBase64(key) : null;
70}
71
72/** Sends one small request with the key. Returns why it failed, or null when the key and model work. */
73export async function testModel(env: Env, choice: ModelChoice): Promise<string | null> {
74 try {
75 await chat(env, choice, [{ role: "user", content: "Reply with OK." }], []);
76 return null;
77 } catch (error) {
78 return error instanceof ModelError ? error.message : `${PROVIDERS[choice.provider].label} could not be reached. Try again.`;
79 }
80}
81
82export const isProvider = (value: string): value is ModelProvider => Object.hasOwn(PROVIDERS, value);