Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): add provider-agnostic AI layer with AssemblyAI LLM Gateway support

Richie McIlroyda5be1031f86
diff --git a/apps/web/__tests__/unit/ai-provider.test.ts b/apps/web/__tests__/unit/ai-provider.test.ts
new file mode 100644
index 000000000..c61ef1cff
--- /dev/null
+++ b/apps/web/__tests__/unit/ai-provider.test.ts
@@ -0,0 +1,363 @@
+import { describe, expect, it, vi } from "vitest";
+
+const serverEnvMock = vi.hoisted(() =>
+ vi.fn<() => Record<string, string | undefined>>(() => ({})),
+);
+
+vi.mock("@cap/env", () => ({
+ serverEnv: serverEnvMock,
+}));
+
+import {
+ getAiModel,
+ getAiProviderChain,
+ getConfiguredAiProviders,
+ isAiConfigured,
+} from "@/lib/ai/provider";
+
+const envWith = (env: Record<string, string | undefined>) => {
+ serverEnvMock.mockReturnValue(env);
+};
+
+describe("getConfiguredAiProviders", () => {
+ it("auto-detects generation providers by key presence in order groq, openai, anthropic", () => {
+ envWith({
+ GROQ_API_KEY: "groq-key",
+ OPENAI_API_KEY: "openai-key",
+ ANTHROPIC_API_KEY: "anthropic-key",
+ });
+
+ expect(getConfiguredAiProviders()).toEqual(["groq", "openai", "anthropic"]);
+ expect(getConfiguredAiProviders("generation")).toEqual([
+ "groq",
+ "openai",
+ "anthropic",
+ ]);
+ });
+
+ it("auto-detects chat providers anthropic-first, preserving each feature's historical primary", () => {
+ envWith({
+ GROQ_API_KEY: "groq-key",
+ OPENAI_API_KEY: "openai-key",
+ ANTHROPIC_API_KEY: "anthropic-key",
+ });
+
+ expect(getConfiguredAiProviders("chat")).toEqual([
+ "anthropic",
+ "openai",
+ "groq",
+ ]);
+ expect(getConfiguredAiProviders("chat-streaming")).toEqual([
+ "anthropic",
+ "openai",
+ "groq",
+ ]);
+ });
+
+ it("puts the explicit AI_PROVIDER first for every role", () => {
+ envWith({
+ AI_PROVIDER: "groq",
+ GROQ_API_KEY: "groq-key",
+ ANTHROPIC_API_KEY: "anthropic-key",
+ });
+
+ expect(getConfiguredAiProviders("chat")).toEqual(["groq", "anthropic"]);
+ });
+
+ it("puts the explicit AI_PROVIDER first and appends the rest", () => {
+ envWith({
+ AI_PROVIDER: "anthropic",
+ GROQ_API_KEY: "groq-key",
+ OPENAI_API_KEY: "openai-key",
+ ANTHROPIC_API_KEY: "anthropic-key",
+ });
+
+ expect(getConfiguredAiProviders()).toEqual(["anthropic", "groq", "openai"]);
+ });
+
+ it("never auto-detects assemblyai even when ASSEMBLY_API_KEY is set", () => {
+ envWith({
+ ASSEMBLY_API_KEY: "assembly-key",
+ GROQ_API_KEY: "groq-key",
+ });
+
+ expect(getConfiguredAiProviders()).toEqual(["groq"]);
+ });
+
+ it("puts assemblyai first when explicitly selected and keeps the fallback chain", () => {
+ envWith({
+ AI_PROVIDER: "assemblyai",
+ ASSEMBLY_API_KEY: "assembly-key",
+ GROQ_API_KEY: "groq-key",
+ OPENAI_API_KEY: "openai-key",
+ ANTHROPIC_API_KEY: "anthropic-key",
+ });
+
+ expect(getConfiguredAiProviders()).toEqual([
+ "assemblyai",
+ "groq",
+ "openai",
+ "anthropic",
+ ]);
+ });
+
+ it("warns and falls through when the explicit provider is missing credentials", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ envWith({
+ AI_PROVIDER: "assemblyai",
+ GROQ_API_KEY: "groq-key",
+ });
+
+ expect(getConfiguredAiProviders()).toEqual(["groq"]);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('AI_PROVIDER is set to "assemblyai"'),
+ );
+ });
+
+ it("auto-detects openai-compatible when AI_BASE_URL and AI_MODEL are set", () => {
+ envWith({
+ GROQ_API_KEY: "groq-key",
+ AI_BASE_URL: "http://localhost:11434/v1",
+ AI_MODEL: "llama3.3",
+ });
+
+ expect(getConfiguredAiProviders()).toEqual(["groq", "openai-compatible"]);
+ });
+
+ it("does not auto-detect openai-compatible from an explicit assemblyai gateway url", () => {
+ envWith({
+ AI_PROVIDER: "assemblyai",
+ ASSEMBLY_API_KEY: "assembly-key",
+ AI_BASE_URL: "https://llm-gateway.eu.assemblyai.com/v1",
+ AI_MODEL: "claude-sonnet-5",
+ });
+
+ expect(getConfiguredAiProviders()).toEqual(["assemblyai"]);
+ });
+});
+
+describe("isAiConfigured", () => {
+ it("is false without any provider credentials", () => {
+ envWith({});
+ expect(isAiConfigured()).toBe(false);
+ });
+
+ it("is false with only ASSEMBLY_API_KEY and no explicit opt-in", () => {
+ envWith({ ASSEMBLY_API_KEY: "assembly-key" });
+ expect(isAiConfigured()).toBe(false);
+ });
+
+ it("is true when assemblyai is explicitly opted into", () => {
+ envWith({
+ AI_PROVIDER: "assemblyai",
+ ASSEMBLY_API_KEY: "assembly-key",
+ });
+ expect(isAiConfigured()).toBe(true);
+ });
+
+ it("is true with an auto-detectable key", () => {
+ envWith({ GROQ_API_KEY: "groq-key" });
+ expect(isAiConfigured()).toBe(true);
+ });
+});
+
+describe("role model defaults", () => {
+ it("uses the assemblyai defaults per role", () => {
+ envWith({
+ AI_PROVIDER: "assemblyai",
+ ASSEMBLY_API_KEY: "assembly-key",
+ });
+
+ expect(getAiModel("generation")?.modelId).toBe("gpt-oss-120b");
+ expect(getAiModel("chat")?.modelId).toBe("claude-sonnet-4-6");
+ expect(getAiModel("chat-streaming")?.modelId).toBe("gpt-5-mini");
+ });
+
+ it("uses the groq defaults per role", () => {
+ envWith({ GROQ_API_KEY: "groq-key" });
+
+ expect(getAiModel("generation")?.modelId).toBe("openai/gpt-oss-120b");
+ expect(getAiModel("chat")?.modelId).toBe("openai/gpt-oss-120b");
+ expect(getAiModel("chat-streaming")?.modelId).toBe("openai/gpt-oss-120b");
+ });
+
+ it("uses the openai defaults per role", () => {
+ envWith({ OPENAI_API_KEY: "openai-key" });
+
+ expect(getAiModel("generation")?.modelId).toBe("gpt-4o-mini");
+ expect(getAiModel("chat")?.modelId).toBe("gpt-4o-mini");
+ expect(getAiModel("chat-streaming")?.modelId).toBe("gpt-4o-mini");
+ });
+
+ it("uses the anthropic defaults per role", () => {
+ envWith({ ANTHROPIC_API_KEY: "anthropic-key" });
+
+ expect(getAiModel("generation")?.modelId).toBe("claude-haiku-4-5");
+ expect(getAiModel("chat")?.modelId).toBe("claude-sonnet-5");
+ expect(getAiModel("chat-streaming")?.modelId).toBe("claude-sonnet-5");
+ });
+
+ it("sets the default max output tokens per role", () => {
+ envWith({ GROQ_API_KEY: "groq-key" });
+
+ expect(getAiModel("generation")?.defaultMaxOutputTokens).toBe(8000);
+ expect(getAiModel("chat")?.defaultMaxOutputTokens).toBe(512);
+ expect(getAiModel("chat-streaming")?.defaultMaxOutputTokens).toBe(2000);
+ });
+
+ it("lazily constructs models with the selected model id", () => {
+ envWith({ OPENAI_API_KEY: "openai-key" });
+
+ const selection = getAiModel("generation");
+ const model = selection?.model() as { modelId?: string } | undefined;
+ expect(model?.modelId).toBe("gpt-4o-mini");
+ });
+});
+
+describe("env model overrides", () => {
+ it("applies per-role overrides to the explicit provider", () => {
+ envWith({
+ AI_PROVIDER: "groq",
+ GROQ_API_KEY: "groq-key",
+ AI_MODEL: "generation-model",
+ AI_CHAT_MODEL: "chat-model",
+ AI_STREAM_MODEL: "stream-model",
+ });
+
+ expect(getAiModel("generation")?.modelId).toBe("generation-model");
+ expect(getAiModel("chat")?.modelId).toBe("chat-model");
+ expect(getAiModel("chat-streaming")?.modelId).toBe("stream-model");
+ });
+
+ it("does not leak overrides into fallback providers", () => {
+ envWith({
+ AI_PROVIDER: "assemblyai",
+ ASSEMBLY_API_KEY: "assembly-key",
+ GROQ_API_KEY: "groq-key",
+ AI_MODEL: "custom-model",
+ });
+
+ const chain = getAiProviderChain("generation");
+ expect(chain[0]?.provider).toBe("assemblyai");
+ expect(chain[0]?.modelId).toBe("custom-model");
+ expect(chain[1]?.provider).toBe("groq");
+ expect(chain[1]?.modelId).toBe("openai/gpt-oss-120b");
+ });
+
+ it("cascades openai-compatible role models from AI_MODEL", () => {
+ envWith({
+ AI_PROVIDER: "openai-compatible",
+ AI_BASE_URL: "http://localhost:11434/v1",
+ AI_MODEL: "base-model",
+ });
+
+ expect(getAiModel("generation")?.modelId).toBe("base-model");
+ expect(getAiModel("chat")?.modelId).toBe("base-model");
+ expect(getAiModel("chat-streaming")?.modelId).toBe("base-model");
+ });
+
+ it("cascades openai-compatible streaming models through AI_CHAT_MODEL", () => {
+ envWith({
+ AI_PROVIDER: "openai-compatible",
+ AI_BASE_URL: "http://localhost:11434/v1",
+ AI_MODEL: "base-model",
+ AI_CHAT_MODEL: "chat-model",
+ });
+
+ expect(getAiModel("chat")?.modelId).toBe("chat-model");
+ expect(getAiModel("chat-streaming")?.modelId).toBe("chat-model");
+ });
+});
+
+describe("streaming capability", () => {
+ it("keeps assemblyai in the chat-streaming chain for OpenAI-family models", () => {
+ envWith({
+ AI_PROVIDER: "assemblyai",
+ ASSEMBLY_API_KEY: "assembly-key",
+ });
+
+ const chain = getAiProviderChain("chat-streaming");
+ expect(chain[0]?.provider).toBe("assemblyai");
+ expect(chain[0]?.supportsStreaming).toBe(true);
+ });
+
+ it("filters assemblyai out of the chat-streaming chain for non-OpenAI models", () => {
+ envWith({
+ AI_PROVIDER: "assemblyai",
+ ASSEMBLY_API_KEY: "assembly-key",
+ AI_STREAM_MODEL: "claude-sonnet-5",
+ GROQ_API_KEY: "groq-key",
+ });
+
+ const chain = getAiProviderChain("chat-streaming");
+ expect(chain.map((selection) => selection.provider)).toEqual(["groq"]);
+
+ // The non-streaming selection still exists for non-streaming roles.
+ expect(getAiProviderChain("chat")[0]?.provider).toBe("assemblyai");
+ });
+});
+
+describe("supportsTemperature", () => {
+ it("is false for gpt-5 family models", () => {
+ envWith({
+ AI_PROVIDER: "assemblyai",
+ ASSEMBLY_API_KEY: "assembly-key",
+ });
+
+ expect(getAiModel("chat-streaming")?.modelId).toBe("gpt-5-mini");
+ expect(getAiModel("chat-streaming")?.supportsTemperature).toBe(false);
+ });
+
+ it("is true for gpt-oss models", () => {
+ envWith({
+ AI_PROVIDER: "assemblyai",
+ ASSEMBLY_API_KEY: "assembly-key",
+ GROQ_API_KEY: "groq-key",
+ });
+
+ expect(getAiModel("generation")?.supportsTemperature).toBe(true);
+ expect(getAiProviderChain("generation")[1]?.supportsTemperature).toBe(true);
+ });
+
+ it("is false for claude models on the assemblyai gateway but true on anthropic", () => {
+ envWith({
+ AI_PROVIDER: "assemblyai",
+ ASSEMBLY_API_KEY: "assembly-key",
+ ANTHROPIC_API_KEY: "anthropic-key",
+ });
+
+ const chain = getAiProviderChain("chat");
+ expect(chain[0]?.provider).toBe("assemblyai");
+ expect(chain[0]?.modelId).toBe("claude-sonnet-4-6");
+ // The gateway 400s on temperature for claude models
+ expect(chain[0]?.supportsTemperature).toBe(false);
+ expect(chain[1]?.provider).toBe("anthropic");
+ expect(chain[1]?.supportsTemperature).toBe(true);
+ });
+});
+
+describe("provider options", () => {
+ it("exposes parallel tool call disabling options per provider", () => {
+ envWith({
+ AI_PROVIDER: "assemblyai",
+ ASSEMBLY_API_KEY: "assembly-key",
+ GROQ_API_KEY: "groq-key",
+ OPENAI_API_KEY: "openai-key",
+ ANTHROPIC_API_KEY: "anthropic-key",
+ });
+
+ const chain = getAiProviderChain("chat");
+ const byProvider = Object.fromEntries(
+ chain.map((selection) => [selection.provider, selection.providerOptions]),
+ );
+
+ expect(byProvider.assemblyai).toBeUndefined();
+ expect(byProvider.groq).toEqual({ groq: { parallelToolCalls: false } });
+ expect(byProvider.openai).toEqual({
+ openai: { parallelToolCalls: false },
+ });
+ expect(byProvider.anthropic).toEqual({
+ anthropic: { disableParallelToolUse: true },
+ });
+ });
+});
diff --git a/apps/web/__tests__/unit/ai-run.test.ts b/apps/web/__tests__/unit/ai-run.test.ts
new file mode 100644
index 000000000..136a00ee5
--- /dev/null
+++ b/apps/web/__tests__/unit/ai-run.test.ts
@@ -0,0 +1,116 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { AiModelSelection } from "@/lib/ai/provider";
+
+const getAiProviderChainMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@/lib/ai/provider", () => ({
+ getAiProviderChain: getAiProviderChainMock,
+}));
+
+import { AiUnavailableError, runWithAiProviders } from "@/lib/ai/run";
+
+const makeSelection = (provider: string): AiModelSelection => ({
+ provider: provider as AiModelSelection["provider"],
+ modelId: `${provider}-model`,
+ model: () => {
+ throw new Error("model should not be constructed in these tests");
+ },
+ supportsStreaming: true,
+ supportsTemperature: true,
+ defaultMaxOutputTokens: 8000,
+});
+
+describe("runWithAiProviders", () => {
+ beforeEach(() => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ });
+
+ it("returns the first successful result without touching later providers", async () => {
+ getAiProviderChainMock.mockReturnValue([
+ makeSelection("groq"),
+ makeSelection("openai"),
+ ]);
+ const run = vi.fn().mockResolvedValue("first");
+
+ await expect(runWithAiProviders("generation", run)).resolves.toBe("first");
+ expect(run).toHaveBeenCalledTimes(1);
+ expect(run.mock.calls[0]?.[0]?.provider).toBe("groq");
+ });
+
+ it("falls through to the next provider on failure", async () => {
+ getAiProviderChainMock.mockReturnValue([
+ makeSelection("groq"),
+ makeSelection("openai"),
+ ]);
+ const run = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("groq down"))
+ .mockResolvedValueOnce("second");
+
+ await expect(runWithAiProviders("generation", run)).resolves.toBe("second");
+ expect(run).toHaveBeenCalledTimes(2);
+ expect(run.mock.calls[1]?.[0]?.provider).toBe("openai");
+ });
+
+ it("stops and rethrows when stopOnError returns true", async () => {
+ getAiProviderChainMock.mockReturnValue([
+ makeSelection("groq"),
+ makeSelection("openai"),
+ ]);
+ const failure = new Error("side effect already happened");
+ const run = vi.fn().mockRejectedValue(failure);
+
+ await expect(
+ runWithAiProviders("chat", run, { stopOnError: () => true }),
+ ).rejects.toBe(failure);
+ expect(run).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports provider errors through onProviderError", async () => {
+ getAiProviderChainMock.mockReturnValue([
+ makeSelection("groq"),
+ makeSelection("openai"),
+ ]);
+ const failure = new Error("groq down");
+ const run = vi
+ .fn()
+ .mockRejectedValueOnce(failure)
+ .mockResolvedValueOnce("second");
+ const onProviderError = vi.fn();
+
+ await runWithAiProviders("generation", run, { onProviderError });
+
+ expect(onProviderError).toHaveBeenCalledTimes(1);
+ expect(onProviderError.mock.calls[0]?.[0]).toBe(failure);
+ expect(onProviderError.mock.calls[0]?.[1]?.provider).toBe("groq");
+ });
+
+ it("throws AiUnavailableError when no provider is configured", async () => {
+ getAiProviderChainMock.mockReturnValue([]);
+ const run = vi.fn();
+
+ await expect(runWithAiProviders("generation", run)).rejects.toThrowError(
+ AiUnavailableError,
+ );
+ expect(run).not.toHaveBeenCalled();
+ });
+
+ it("throws AiUnavailableError with the last error when every provider fails", async () => {
+ getAiProviderChainMock.mockReturnValue([
+ makeSelection("groq"),
+ makeSelection("openai"),
+ ]);
+ const lastFailure = new Error("openai down");
+ const run = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("groq down"))
+ .mockRejectedValueOnce(lastFailure);
+
+ const promise = runWithAiProviders("generation", run);
+ await expect(promise).rejects.toThrowError(AiUnavailableError);
+ await promise.catch((error) => {
+ expect((error as AiUnavailableError).cause).toBe(lastFailure);
+ });
+ expect(run).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/web/lib/ai/provider.ts b/apps/web/lib/ai/provider.ts
new file mode 100644
index 000000000..334c1ae82
--- /dev/null
+++ b/apps/web/lib/ai/provider.ts
@@ -0,0 +1,307 @@
+import { createAnthropic } from "@ai-sdk/anthropic";
+import { createGroq } from "@ai-sdk/groq";
+import { createOpenAI } from "@ai-sdk/openai";
+import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
+import { serverEnv } from "@cap/env";
+import type { JSONValue, LanguageModel } from "ai";
+
+export type AiProviderId =
+ | "assemblyai"
+ | "openai"
+ | "anthropic"
+ | "groq"
+ | "openai-compatible";
+
+export type AiModelRole = "generation" | "chat" | "chat-streaming";
+
+type AiSdkProviderOptions = Record<string, Record<string, JSONValue>>;
+
+export interface AiModelOptions {
+ /**
+ * Ask the provider to repair malformed JSON output (AssemblyAI LLM
+ * gateway only — its gpt-oss models reject `response_format`). Only set
+ * this for calls that expect a JSON response; the repair step would
+ * mangle plain-text output.
+ */
+ jsonRepair?: boolean;
+}
+
+export interface AiModelSelection {
+ provider: AiProviderId;
+ modelId: string;
+ /**
+ * Lazily creates the language model. Call this where the request is
+ * made (eg. inside a workflow step) — model instances must never cross
+ * a workflow "use step" boundary.
+ */
+ model: (options?: AiModelOptions) => LanguageModel;
+ supportsStreaming: boolean;
+ supportsTemperature: boolean;
+ defaultMaxOutputTokens: number;
+ /**
+ * Provider options that disable parallel tool calls. Pass to
+ * `generateText` only when tools are supplied — some providers reject
+ * the underlying parameter without tools. Undefined for providers with
+ * no such option (callers must guard inside tool `execute` instead).
+ */
+ providerOptions?: AiSdkProviderOptions;
+}
+
+const ASSEMBLYAI_GATEWAY_BASE_URL = "https://llm-gateway.assemblyai.com/v1";
+
+const ROLE_MAX_OUTPUT_TOKENS: Record<AiModelRole, number> = {
+ generation: 8000,
+ chat: 512,
+ // Generous relative to the ~800-token answers we expect: on models with
+ // thinking on by default (eg. claude-sonnet-5) the cap covers thinking
+ // AND visible text, and a tight cap can leave an empty visible answer.
+ "chat-streaming": 2000,
+};
+
+const DEFAULT_MODELS: Record<
+ Exclude<AiProviderId, "openai-compatible">,
+ Record<AiModelRole, string>
+> = {
+ assemblyai: {
+ generation: "gpt-oss-120b",
+ // Not claude-sonnet-5: it thinks by default and thinking shares the
+ // (small) chat token budget, which can leave an empty visible reply
+ // through the gateway. Override with AI_CHAT_MODEL to change.
+ chat: "claude-sonnet-4-6",
+ // The AssemblyAI gateway only streams OpenAI-family models.
+ "chat-streaming": "gpt-5-mini",
+ },
+ groq: {
+ generation: "openai/gpt-oss-120b",
+ chat: "openai/gpt-oss-120b",
+ "chat-streaming": "openai/gpt-oss-120b",
+ },
+ openai: {
+ generation: "gpt-4o-mini",
+ chat: "gpt-4o-mini",
+ "chat-streaming": "gpt-4o-mini",
+ },
+ anthropic: {
+ generation: "claude-haiku-4-5",
+ chat: "claude-sonnet-5",
+ "chat-streaming": "claude-sonnet-5",
+ },
+};
+
+// `assemblyai` is intentionally absent: it is never auto-detected, so
+// transcription-only instances don't silently start incurring LLM charges.
+// The order is per role to preserve each feature's historical primary
+// provider when `AI_PROVIDER` is unset: generation ran on Groq first, while
+// the chat features (messenger, docs Ask AI) ran on Anthropic first.
+const AUTO_DETECT_ORDER: Record<AiModelRole, readonly AiProviderId[]> = {
+ generation: ["groq", "openai", "anthropic", "openai-compatible"],
+ chat: ["anthropic", "openai", "groq", "openai-compatible"],
+ "chat-streaming": ["anthropic", "openai", "groq", "openai-compatible"],
+};
+
+function isProviderConfigured(provider: AiProviderId): boolean {
+ const env = serverEnv();
+ switch (provider) {
+ case "assemblyai":
+ return Boolean(env.ASSEMBLY_API_KEY);
+ case "openai":
+ return Boolean(env.OPENAI_API_KEY);
+ case "anthropic":
+ return Boolean(env.ANTHROPIC_API_KEY);
+ case "groq":
+ return Boolean(env.GROQ_API_KEY);
+ case "openai-compatible":
+ return Boolean(env.AI_BASE_URL && env.AI_MODEL);
+ }
+}
+
+function missingCredentialHint(provider: AiProviderId): string {
+ switch (provider) {
+ case "assemblyai":
+ return "ASSEMBLY_API_KEY is not set";
+ case "openai":
+ return "OPENAI_API_KEY is not set";
+ case "anthropic":
+ return "ANTHROPIC_API_KEY is not set";
+ case "groq":
+ return "GROQ_API_KEY is not set";
+ case "openai-compatible":
+ return "AI_BASE_URL and AI_MODEL are required";
+ }
+}
+
+export function getConfiguredAiProviders(
+ role: AiModelRole = "generation",
+): AiProviderId[] {
+ const explicit = serverEnv().AI_PROVIDER;
+ const providers: AiProviderId[] = [];
+
+ if (explicit) {
+ if (isProviderConfigured(explicit)) {
+ providers.push(explicit);
+ } else {
+ console.warn(
+ `[ai] AI_PROVIDER is set to "${explicit}" but it is not usable (${missingCredentialHint(explicit)}); falling back to auto-detected providers`,
+ );
+ }
+ }
+
+ for (const provider of AUTO_DETECT_ORDER[role]) {
+ if (providers.includes(provider)) continue;
+ // AI_BASE_URL belongs to the AssemblyAI gateway when it is the
+ // explicit provider — don't auto-detect a second provider from it.
+ if (provider === "openai-compatible" && explicit === "assemblyai") continue;
+ if (!isProviderConfigured(provider)) continue;
+ providers.push(provider);
+ }
+
+ return providers;
+}
+
+export function isAiConfigured(): boolean {
+ return getConfiguredAiProviders().length > 0;
+}
+
+function envModelOverride(role: AiModelRole): string | undefined {
+ const env = serverEnv();
+ switch (role) {
+ case "generation":
+ return env.AI_MODEL;
+ case "chat":
+ return env.AI_CHAT_MODEL;
+ case "chat-streaming":
+ return env.AI_STREAM_MODEL;
+ }
+}
+
+function openAiCompatibleModelId(role: AiModelRole): string | undefined {
+ const env = serverEnv();
+ switch (role) {
+ case "generation":
+ return env.AI_MODEL;
+ case "chat":
+ return env.AI_CHAT_MODEL ?? env.AI_MODEL;
+ case "chat-streaming":
+ return env.AI_STREAM_MODEL ?? env.AI_CHAT_MODEL ?? env.AI_MODEL;
+ }
+}
+
+function resolveModelId(
+ provider: AiProviderId,
+ role: AiModelRole,
+): string | undefined {
+ if (provider === "openai-compatible") return openAiCompatibleModelId(role);
+ // The AI_MODEL / AI_CHAT_MODEL / AI_STREAM_MODEL overrides name models
+ // for the explicitly selected provider only — fallback providers keep
+ // their own defaults so the fallback chain stays valid.
+ const override =
+ serverEnv().AI_PROVIDER === provider ? envModelOverride(role) : undefined;
+ return override ?? DEFAULT_MODELS[provider][role];
+}
+
+function createModel(
+ provider: AiProviderId,
+ modelId: string,
+ options?: AiModelOptions,
+): LanguageModel {
+ const env = serverEnv();
+ switch (provider) {
+ case "groq":
+ return createGroq({ apiKey: env.GROQ_API_KEY })(modelId);
+ case "openai":
+ // `.chat` — the provider defaults to the Responses API otherwise.
+ return createOpenAI({ apiKey: env.OPENAI_API_KEY }).chat(modelId);
+ case "anthropic":
+ return createAnthropic({ apiKey: env.ANTHROPIC_API_KEY })(modelId);
+ case "assemblyai":
+ return createOpenAICompatible({
+ name: "assemblyai",
+ baseURL: env.AI_BASE_URL ?? ASSEMBLYAI_GATEWAY_BASE_URL,
+ apiKey: env.ASSEMBLY_API_KEY,
+ supportsStructuredOutputs: false,
+ ...(options?.jsonRepair
+ ? {
+ transformRequestBody: (body) => ({
+ ...body,
+ post_processing_steps: [{ type: "json-repair" }],
+ }),
+ }
+ : {}),
+ })(modelId);
+ case "openai-compatible": {
+ const baseURL = env.AI_BASE_URL;
+ if (!baseURL) {
+ throw new Error(
+ "AI_BASE_URL must be set to use the openai-compatible AI provider",
+ );
+ }
+ return createOpenAICompatible({
+ name: "openai-compatible",
+ baseURL,
+ apiKey: env.AI_API_KEY,
+ })(modelId);
+ }
+ }
+}
+
+function parallelToolCallProviderOptions(
+ provider: AiProviderId,
+): AiSdkProviderOptions | undefined {
+ switch (provider) {
+ case "openai":
+ return { openai: { parallelToolCalls: false } };
+ case "groq":
+ return { groq: { parallelToolCalls: false } };
+ case "anthropic":
+ return { anthropic: { disableParallelToolUse: true } };
+ default:
+ return undefined;
+ }
+}
+
+function supportsStreaming(provider: AiProviderId, modelId: string): boolean {
+ // The AssemblyAI LLM gateway only streams OpenAI-family models.
+ if (provider === "assemblyai") return modelId.startsWith("gpt");
+ return true;
+}
+
+function supportsTemperature(provider: AiProviderId, modelId: string): boolean {
+ // gpt-5 and OpenAI o-series reasoning models reject `temperature`.
+ const bareModelId = modelId.split("/").pop() ?? modelId;
+ if (/^(gpt-5|o\d)/.test(bareModelId)) return false;
+ // The AssemblyAI gateway rejects `temperature` for Claude models
+ // (400: "model claude-sonnet-5 does not support temperature"); it
+ // accepts it for gpt-oss and Gemini models.
+ if (provider === "assemblyai" && bareModelId.startsWith("claude"))
+ return false;
+ return true;
+}
+
+export function getAiProviderChain(role: AiModelRole): AiModelSelection[] {
+ const selections: AiModelSelection[] = [];
+
+ for (const provider of getConfiguredAiProviders(role)) {
+ const modelId = resolveModelId(provider, role);
+ if (!modelId) continue;
+
+ selections.push({
+ provider,
+ modelId,
+ model: (options) => createModel(provider, modelId, options),
+ supportsStreaming: supportsStreaming(provider, modelId),
+ supportsTemperature: supportsTemperature(provider, modelId),
+ defaultMaxOutputTokens: ROLE_MAX_OUTPUT_TOKENS[role],
+ providerOptions: parallelToolCallProviderOptions(provider),
+ });
+ }
+
+ if (role === "chat-streaming") {
+ return selections.filter((selection) => selection.supportsStreaming);
+ }
+
+ return selections;
+}
+
+export function getAiModel(role: AiModelRole): AiModelSelection | null {
+ return getAiProviderChain(role)[0] ?? null;
+}
diff --git a/apps/web/lib/ai/run.ts b/apps/web/lib/ai/run.ts
new file mode 100644
index 000000000..70dddde0f
--- /dev/null
+++ b/apps/web/lib/ai/run.ts
@@ -0,0 +1,75 @@
+import { APICallError } from "ai";
+import {
+ type AiModelRole,
+ type AiModelSelection,
+ getAiProviderChain,
+} from "./provider";
+
+export class AiUnavailableError extends Error {
+ constructor(message: string, options?: { cause?: unknown }) {
+ super(message, options);
+ this.name = "AiUnavailableError";
+ }
+}
+
+export interface RunWithAiProvidersOptions {
+ /**
+ * Return true to stop iterating the provider chain and rethrow the
+ * error — eg. after a side effect (like sending an email) has already
+ * happened and retrying on another provider would repeat it.
+ */
+ stopOnError?: (error: unknown, selection: AiModelSelection) => boolean;
+ onProviderError?: (error: unknown, selection: AiModelSelection) => void;
+}
+
+/**
+ * Runs `run` against each configured AI provider for `role` in order,
+ * returning the first successful result. The AI SDK's built-in retries
+ * (429/5xx) run per provider before the chain moves on.
+ */
+export async function runWithAiProviders<T>(
+ role: AiModelRole,
+ run: (selection: AiModelSelection) => Promise<T>,
+ options: RunWithAiProvidersOptions = {},
+): Promise<T> {
+ const chain = getAiProviderChain(role);
+ if (chain.length === 0) {
+ throw new AiUnavailableError(
+ `No AI provider configured for the "${role}" role`,
+ );
+ }
+
+ let lastError: unknown;
+ for (const selection of chain) {
+ try {
+ return await run(selection);
+ } catch (error) {
+ lastError = error;
+ logProviderError(role, selection, error);
+ options.onProviderError?.(error, selection);
+ if (options.stopOnError?.(error, selection)) throw error;
+ }
+ }
+
+ throw new AiUnavailableError(
+ `All AI providers failed for the "${role}" role`,
+ { cause: lastError },
+ );
+}
+
+function logProviderError(
+ role: AiModelRole,
+ selection: AiModelSelection,
+ error: unknown,
+) {
+ // APICallError.responseBody captures provider error details (eg. the
+ // AssemblyAI gateway's request_id) that the message alone omits.
+ const responseBody = APICallError.isInstance(error)
+ ? error.responseBody
+ : undefined;
+ console.error(
+ `[ai] ${selection.provider} (${selection.modelId}) failed for the "${role}" role`,
+ error,
+ ...(responseBody ? [responseBody] : []),
+ );
+}