import { env } from "cloudflare:workers"; import type { ClefRequest, ClefResponse } from "./decide"; import { mockProvider } from "./mock"; import type { ChatMessage, MergeFixProvider, TokenUsage } from "./plan"; import { ModelCallError } from "./plan"; import type { ByokKey } from "./store"; const MAX_OUTPUT_TOKENS = 2048; type ChatReply = { response?: unknown; choices?: Array<{ message?: { content?: unknown } }>; usage?: { prompt_tokens?: number; completion_tokens?: number; input_tokens?: number; output_tokens?: number }; }; function readReply(reply: ChatReply): { text: string; usage: TokenUsage } { const raw = reply.choices?.[0]?.message?.content ?? reply.response; if (typeof raw !== "string") throw new ModelCallError("The model returned no text"); return { text: raw, usage: { inputTokens: reply.usage?.prompt_tokens ?? reply.usage?.input_tokens ?? 0, outputTokens: reply.usage?.completion_tokens ?? reply.usage?.output_tokens ?? 0, }, }; } type Unchecked = { run(model: string, inputs: unknown, options?: AiOptions): Promise }; /** * Both models go through the instance's AI Gateway, tagged with the billed account so Gateway analytics * line up with `ai_usage`. With a bring-your-own key the generative call uses the account's provider * via Gateway's OpenAI-compatible endpoint; Clef always runs on Workers AI. */ export function gatewayProvider(input: { accountId: string; runId: string; byok: ByokKey | null }): MergeFixProvider { if (env.MERGEFIX_PROVIDER === "mock") return mockProvider(); const gatewayId = env.MERGEFIX_GATEWAY_ID || "default"; const metadata = { account_id: input.accountId, run_id: input.runId, feature: "mergefix" }; const ai = env.AI as unknown as Unchecked; return { async generate({ messages }: { messages: ChatMessage[] }) { if (input.byok) { const response = await env.AI.gateway(gatewayId).run({ provider: "compat", endpoint: "chat/completions", headers: { authorization: `Bearer ${input.byok.apiKey}`, "content-type": "application/json", "cf-aig-metadata": JSON.stringify(metadata), } as unknown as AIGatewayUniversalRequest["headers"], query: { model: `${input.byok.provider}/${input.byok.model}`, messages, max_tokens: MAX_OUTPUT_TOKENS }, }); if (!response.ok) throw new ModelCallError(`The model provider returned ${response.status}`); return readReply((await response.json()) as ChatReply); } const reply = await ai.run( env.MERGEFIX_MODEL, { messages, max_tokens: MAX_OUTPUT_TOKENS }, { gateway: { id: gatewayId, metadata } }, ); return readReply(reply as ChatReply); }, async decide(request: ClefRequest): Promise { const model = request.model === "clef-flash" ? "@cf/cloudflare/clef-flash" : "@cf/cloudflare/clef"; const reply = (await ai.run(model, request, { gateway: { id: gatewayId, metadata } })) as ClefResponse; if (!reply || typeof reply.answers !== "object") throw new ModelCallError("Clef returned no answers"); return reply; }, }; } export function clefModel(): ClefRequest["model"] { return env.MERGEFIX_CLEF_MODEL === "clef-flash" ? "clef-flash" : "clef"; }