Skip to content

Open source alternative to Semrush and Ahrefs

Restore ChatGPT citations and current models in Prompt Explorer (EVE-358) (#773)

Carter Smith393cf894c3d5
diff --git a/src/client/features/ai-search/components/PromptExplorerResults.tsx b/src/client/features/ai-search/components/PromptExplorerResults.tsx
index b11e285c..dcf25cd9 100644
--- a/src/client/features/ai-search/components/PromptExplorerResults.tsx
+++ b/src/client/features/ai-search/components/PromptExplorerResults.tsx
@@ -57,7 +57,7 @@ function ModelResultCard({
model={modelResult.model}
modelName={null}
tokens={null}
- webSearch={false}
+ webSearch={null}
brandMentioned={null}
highlightBrand={null}
status="error"
@@ -171,7 +171,8 @@ function ModelHeader({
model: PromptExplorerModelResult["model"];
modelName: string | null;
tokens: number | null;
- webSearch: boolean;
+ /** null = not applicable (error card): render neither web-search state. */
+ webSearch: boolean | null;
brandMentioned: boolean | null;
highlightBrand: string | null;
status: "success" | "error";
@@ -195,6 +196,13 @@ function ModelHeader({
<Globe className="size-3" />
web search
</span>
+ ) : webSearch === false ? (
+ // The model chose not to browse for this answer — that's why there
+ // are no cited sources on this card.
+ <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
+ <Globe className="size-3" />
+ no web search
+ </span>
) : null}
</div>
{tokens != null ? (
diff --git a/src/server/features/ai-search/services/promptExplorer.test.ts b/src/server/features/ai-search/services/promptExplorer.test.ts
index 1a43c142..f24f98a2 100644
--- a/src/server/features/ai-search/services/promptExplorer.test.ts
+++ b/src/server/features/ai-search/services/promptExplorer.test.ts
@@ -1,9 +1,23 @@
import { describe, expect, it, vi } from "vitest";
import type { LlmResponseResult } from "@/server/lib/dataforseoLlmSchemas";
-import { extractCitations } from "./promptExplorer";
+import { explorePrompt, extractCitations } from "./promptExplorer";
vi.mock("cloudflare:workers", () => ({ waitUntil: vi.fn() }));
+const { llmResponse } = vi.hoisted(() => ({ llmResponse: vi.fn() }));
+vi.mock("@/server/lib/dataforseo", () => ({
+ createDataforseoClient: () => ({ aiSearch: { llmResponse } }),
+}));
+vi.mock("@/server/lib/dataforseo/llm-models", () => ({
+ resolveLatestLlmModelName: vi.fn(async () => "gpt-5.5"),
+}));
+vi.mock("@/server/lib/r2-cache", () => ({
+ AI_SEARCH_PROMPT_CACHE_NAMESPACE: "ai-search-prompt",
+ buildCacheKey: vi.fn(async () => "cache-key"),
+ getCached: vi.fn(async () => null),
+ setCached: vi.fn(async () => {}),
+}));
+
// DataForSEO's LLM Responses payload nests references as untyped
// `{ title, url }` objects under items[].sections[].annotations — mirroring the
// SDK's AnnotationInfo, which has no citation-type discriminator.
@@ -62,3 +76,74 @@ describe("extractCitations", () => {
expect(citations[0]?.url).toBe("https://example.com/a");
});
});
+
+const modelResponse = (webSearch: boolean): LlmResponseResult => ({
+ model_name: "gpt-5",
+ web_search: webSearch,
+ output_tokens: 10,
+ items: [
+ {
+ type: "message",
+ sections: [
+ {
+ type: "text",
+ text: "answer",
+ annotations: webSearch
+ ? [{ title: "Source", url: "https://example.com/post" }]
+ : [],
+ },
+ ],
+ },
+ ],
+});
+
+describe("explorePrompt web-search retry", () => {
+ const input = {
+ projectId: "p1",
+ prompt: "what is the best open source seo tool",
+ models: ["chat_gpt" as const],
+ webSearch: true,
+ };
+ const billing = {
+ organizationId: "org_1",
+ userId: "user_1",
+ userEmail: "[email protected]",
+ };
+
+ it("retries once when search was requested but the model answered from memory", async () => {
+ llmResponse
+ .mockResolvedValueOnce(modelResponse(false))
+ .mockResolvedValueOnce(modelResponse(true));
+
+ const result = await explorePrompt(input, billing);
+
+ expect(llmResponse).toHaveBeenCalledTimes(2);
+ expect(result.results[0]).toMatchObject({
+ status: "success",
+ webSearch: true,
+ citations: [{ url: "https://example.com/post" }],
+ });
+ });
+
+ it("does not retry when the first response already searched", async () => {
+ llmResponse.mockResolvedValueOnce(modelResponse(true));
+
+ await explorePrompt(input, billing);
+
+ expect(llmResponse).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps the first answer when the retry fails", async () => {
+ llmResponse
+ .mockResolvedValueOnce(modelResponse(false))
+ .mockRejectedValueOnce(new Error("upstream timeout"));
+
+ const result = await explorePrompt(input, billing);
+
+ expect(result.results[0]).toMatchObject({
+ status: "success",
+ webSearch: false,
+ text: "answer",
+ });
+ });
+});
diff --git a/src/server/features/ai-search/services/promptExplorer.ts b/src/server/features/ai-search/services/promptExplorer.ts
index c0141be4..24476cdf 100644
--- a/src/server/features/ai-search/services/promptExplorer.ts
+++ b/src/server/features/ai-search/services/promptExplorer.ts
@@ -1,6 +1,7 @@
import { waitUntil } from "cloudflare:workers";
import type { BillingCustomerContext } from "@/server/billing/subscription";
import { createDataforseoClient } from "@/server/lib/dataforseo";
+import { resolveLatestLlmModelName } from "@/server/lib/dataforseo/llm-models";
import type { LlmResponseResult } from "@/server/lib/dataforseoLlmSchemas";
import { AppError } from "@/server/lib/errors";
import {
@@ -93,10 +94,14 @@ type RunModelArgs = {
async function runModel(
args: RunModelArgs,
): Promise<PromptExplorerModelResult> {
+ // Part of the cache key so a model upgrade refetches rather than serving
+ // cached answers from the previous model.
+ const modelName = await resolveLatestLlmModelName(args.model);
const cacheKey = await buildCacheKey(AI_SEARCH_PROMPT_CACHE_NAMESPACE, {
organizationId: args.billingCustomer.organizationId,
projectId: args.input.projectId,
model: args.model,
+ modelName,
// Collapse only whitespace differences. Casing is deliberately preserved:
// prompts like "Compare Go vs go" or case-sensitive code snippets must
// not collide with their lowercase twins.
@@ -104,7 +109,7 @@ async function runModel(
webSearch: args.input.webSearch,
webSearchCountryCode: args.input.webSearchCountryCode ?? null,
// Bumped when prompt/payload shape changes — busts stale cache entries.
- systemPromptV: 5,
+ systemPromptV: 6,
});
const cached = promptExplorerModelResultSchema.safeParse(
@@ -116,7 +121,24 @@ async function runModel(
return reapplyHighlightBrand(cached.data, args.highlightBrand);
}
- const rawResponse = await fetchModelResponse(args);
+ let rawResponse = await fetchModelResponse(args, modelName);
+ // `web_search: true` only permits searching; models the upstream can't
+ // force (Claude is the only one that accepts `force_web_search` — see
+ // dataforseo/ai.ts) regularly answer from memory and return zero citations
+ // (~40% search rate observed for gpt-5). The browse decision is
+ // non-deterministic per call, so one paid retry meaningfully raises the
+ // odds of a cited answer; keep the retry only if it actually searched.
+ // A failed retry keeps the first answer, which is already paid for.
+ if (args.input.webSearch && !rawResponse.web_search) {
+ const retried = await fetchModelResponse(args, modelName).catch((err) => {
+ console.error(
+ `ai-search.prompt-response.${args.model}.retry failed:`,
+ err,
+ );
+ return null;
+ });
+ if (retried?.web_search) rawResponse = retried;
+ }
const shaped = shapeSuccess(args.model, rawResponse);
waitUntil(
@@ -130,20 +152,13 @@ async function runModel(
return reapplyHighlightBrand(shaped, args.highlightBrand);
}
-// Each value must be a member of ACCEPTED_LLM_MODEL_NAMES in dataforseo/ai.ts,
-// which mirrors DataForSEO's llm_responses/models catalog. DataForSEO dropped
-// the Claude Sonnet 4.0 family, so we target the 4.5 alias (latest dated 4.5).
-const MODEL_NAMES: Record<PromptExplorerModel, string> = {
- chat_gpt: "gpt-5",
- claude: "claude-sonnet-4-5",
- gemini: "gemini-2.5-pro",
- perplexity: "sonar-reasoning-pro",
-};
-
-function fetchModelResponse(args: RunModelArgs): Promise<LlmResponseResult> {
+function fetchModelResponse(
+ args: RunModelArgs,
+ modelName: string,
+): Promise<LlmResponseResult> {
return args.dataforseo.aiSearch.llmResponse({
modelSlug: args.model,
- modelName: MODEL_NAMES[args.model],
+ modelName,
userPrompt: args.input.prompt,
webSearch: args.input.webSearch,
webSearchCountryCode: args.input.webSearchCountryCode,
diff --git a/src/server/lib/dataforseo/ai.ts b/src/server/lib/dataforseo/ai.ts
index 4a079df0..92dc3b99 100644
--- a/src/server/lib/dataforseo/ai.ts
+++ b/src/server/lib/dataforseo/ai.ts
@@ -14,6 +14,10 @@ import {
import { createDataforseoBillingClassifier } from "@/server/lib/dataforseoBillingClassification";
import { AppError } from "@/server/lib/errors";
import { dataforseoPost } from "@/server/lib/dataforseo/core";
+import {
+ isKnownLlmModelName,
+ type LlmResponseModelSlug,
+} from "@/server/lib/dataforseo/llm-models";
import type { LlmPlatform, LlmTarget } from "@/server/lib/dataforseo/shared";
import {
assertOk,
@@ -253,30 +257,6 @@ export async function fetchLlmCrossAggregatedMetrics(
// LLM Responses (per-model)
// ---------------------------------------------------------------------------
-export type LlmResponseModelSlug =
- | "chat_gpt"
- | "claude"
- | "gemini"
- | "perplexity";
-
-/**
- * Accepted `model_name` values per slug, mirroring DataForSEO's
- * `/ai_optimization/{model}/llm_responses/models` catalog (verified 2026-06-30).
- * We validate against this before dispatching because DataForSEO BILLS a task
- * that fails with `Invalid Field: 'model_name'` — a stale or mistyped model name
- * would otherwise pay for a guaranteed-rejected call. DataForSEO resolves a
- * basic alias (e.g. `claude-sonnet-4-5`) to its latest dated version.
- */
-const ACCEPTED_LLM_MODEL_NAMES: Record<
- LlmResponseModelSlug,
- ReadonlySet<string>
-> = {
- chat_gpt: new Set(["gpt-5"]),
- claude: new Set(["claude-sonnet-4-5", "claude-sonnet-4-6"]),
- gemini: new Set(["gemini-2.5-pro"]),
- perplexity: new Set(["sonar-reasoning-pro", "sonar-pro", "sonar"]),
-};
-
type LlmResponsesInput = {
userPrompt: string;
modelSlug: LlmResponseModelSlug;
@@ -291,6 +271,7 @@ type LlmResponseRequestFields = {
user_prompt: string;
model_name: string;
web_search: boolean;
+ force_web_search?: boolean;
max_output_tokens: number;
web_search_country_iso_code?: string;
};
@@ -299,23 +280,36 @@ export async function fetchLlmResponse(
input: LlmResponsesInput,
): Promise<DataforseoApiResponse<LlmResponseResult>> {
// Fail fast on an unknown model_name: DataForSEO charges for tasks that fail
- // with `Invalid Field: 'model_name'`, so we must never dispatch one.
- if (!ACCEPTED_LLM_MODEL_NAMES[input.modelSlug].has(input.modelName)) {
+ // with `Invalid Field: 'model_name'`, so we must never dispatch one. The
+ // check runs against the live (cached, free) model catalog so newly released
+ // models work without a code change.
+ if (!(await isKnownLlmModelName(input.modelSlug, input.modelName))) {
throw new AppError(
"VALIDATION_ERROR",
`Unsupported DataForSEO model_name "${input.modelName}" for ${input.modelSlug}`,
);
}
- // DataForSEO's Gemini endpoint rejects `web_search_country_iso_code` with a
- // 40501 "Invalid Field" error. The other three models accept it.
- const supportsCountry = input.modelSlug !== "gemini";
+ // `web_search: true` is permission, not an instruction — models regularly
+ // answer from parametric memory (observed ~40% search rate for gpt-5) and
+ // then return no citations. Claude accepts `force_web_search` to make the
+ // search actually happen; every ChatGPT model rejects it with 40501
+ // "this model does not support 'force_web_search'" (verified 2026-08-25),
+ // and Gemini/Perplexity don't document it, so only Claude gets the field.
+ const webSearch = input.webSearch ?? LLM_RESPONSE_WEB_SEARCH_DEFAULT;
+ // The country only geolocates the search: every model rejects it with 40501
+ // "you must enable 'web_search'" when search is off (verified 2026-09-30).
+ // DataForSEO's Gemini endpoint rejects it with a 40501 "Invalid Field" error.
+ const sendCountry = webSearch && input.modelSlug !== "gemini";
const fields: LlmResponseRequestFields = {
user_prompt: input.userPrompt,
model_name: input.modelName,
- web_search: input.webSearch ?? LLM_RESPONSE_WEB_SEARCH_DEFAULT,
+ web_search: webSearch,
+ ...(webSearch && input.modelSlug === "claude"
+ ? { force_web_search: true }
+ : {}),
max_output_tokens: clampLimit(input.maxOutputTokens ?? 1024, 256, 4096),
- ...(supportsCountry && input.webSearchCountryCode
+ ...(sendCountry && input.webSearchCountryCode
? { web_search_country_iso_code: input.webSearchCountryCode }
: {}),
};
diff --git a/src/server/lib/dataforseo/endpoints.test.ts b/src/server/lib/dataforseo/endpoints.test.ts
index 67b972e9..c963f5ff 100644
--- a/src/server/lib/dataforseo/endpoints.test.ts
+++ b/src/server/lib/dataforseo/endpoints.test.ts
@@ -4,6 +4,14 @@ vi.mock("@/server/lib/runtime-env", () => ({
getRequiredEnvValue: vi.fn(async () => "test-api-key"),
}));
+// Skip the live model-catalog fetch (covered in llm-models.test.ts); the
+// unknown "claude-sonnet-4-0" keeps the reject-before-dispatch test honest.
+vi.mock("@/server/lib/dataforseo/llm-models", () => ({
+ isKnownLlmModelName: vi.fn(
+ async (_slug: string, name: string) => name !== "claude-sonnet-4-0",
+ ),
+}));
+
import { fetchQuestionsAnswers } from "@/server/lib/dataforseo/business";
import {
fetchLlmCrossAggregatedMetrics,
@@ -150,7 +158,7 @@ describe("DataForSEO SDK-backed endpoints", () => {
]);
});
- it("preserves web_search for Perplexity LLM responses", async () => {
+ it("drops the search country when web search is off — DataForSEO rejects it", async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(
Response.json({
status_code: 20000,
@@ -203,6 +211,53 @@ describe("DataForSEO SDK-backed endpoints", () => {
model_name: "sonar",
web_search: false,
max_output_tokens: 1024,
+ },
+ ]);
+ });
+});
+
+const okLlmResponse = () =>
+ Response.json({
+ status_code: 20000,
+ tasks: [{ status_code: 20000, path: ["v3"], cost: 0.001, result: [{}] }],
+ });
+
+describe("fetchLlmResponse force_web_search", () => {
+ it("sends it only for Claude — ChatGPT rejects it with a 40501 Invalid Field", async () => {
+ const fetchMock = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(okLlmResponse())
+ .mockResolvedValueOnce(okLlmResponse());
+ vi.stubGlobal("fetch", fetchMock);
+
+ const base = { userPrompt: "What is OpenSEO?", webSearch: true } as const;
+ const claude = {
+ modelSlug: "claude",
+ modelName: "claude-sonnet-4-6",
+ } as const;
+ const chatGpt = {
+ modelSlug: "chat_gpt",
+ modelName: "gpt-5",
+ webSearchCountryCode: "US",
+ } as const;
+ await fetchLlmResponse({ ...base, ...claude });
+ await fetchLlmResponse({ ...base, ...chatGpt });
+
+ expect(parseDataforseoRequestBody(fetchMock.mock.calls[0]?.[1])).toEqual([
+ {
+ user_prompt: "What is OpenSEO?",
+ model_name: "claude-sonnet-4-6",
+ web_search: true,
+ force_web_search: true,
+ max_output_tokens: 1024,
+ },
+ ]);
+ expect(parseDataforseoRequestBody(fetchMock.mock.calls[1]?.[1])).toEqual([
+ {
+ user_prompt: "What is OpenSEO?",
+ model_name: "gpt-5",
+ web_search: true,
+ max_output_tokens: 1024,
web_search_country_iso_code: "US",
},
]);
diff --git a/src/server/lib/dataforseo/llm-models.test.ts b/src/server/lib/dataforseo/llm-models.test.ts
new file mode 100644
index 00000000..b3f344cf
--- /dev/null
+++ b/src/server/lib/dataforseo/llm-models.test.ts
@@ -0,0 +1,97 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/server/lib/runtime-env", () => ({
+ getRequiredEnvValue: vi.fn(async () => "test-api-key"),
+}));
+
+import {
+ isKnownLlmModelName,
+ resolveLatestLlmModelName,
+} from "@/server/lib/dataforseo/llm-models";
+
+function stubCatalog(names: string[]) {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn<typeof fetch>().mockResolvedValue(
+ Response.json({
+ status_code: 20000,
+ tasks: [
+ {
+ status_code: 20000,
+ path: ["v3"],
+ cost: 0,
+ result: names.map((model_name) => ({ model_name })),
+ },
+ ],
+ }),
+ ),
+ );
+}
+
+// The catalog is cached per slug for an hour at module level. Moving the clock
+// two hours per test makes every test read its own stubbed catalog.
+let clock = Date.UTC(2026, 0, 1);
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ clock += 2 * 60 * 60 * 1000;
+ vi.setSystemTime(clock);
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe("resolveLatestLlmModelName", () => {
+ it("honors the ChatGPT pin while the catalog lists it", async () => {
+ stubCatalog(["gpt-5.6-luna", "gpt-5.5", "gpt-5"]);
+ await expect(resolveLatestLlmModelName("chat_gpt")).resolves.toBe(
+ "gpt-5.6-luna",
+ );
+ });
+
+ it("picks the highest plain flagship alias when the pin is gone", async () => {
+ stubCatalog([
+ "o4-mini",
+ "gpt-5.6-terra",
+ "gpt-5.5",
+ "gpt-5.5-2026-04-23",
+ "gpt-5-mini",
+ "gpt-5",
+ ]);
+ await expect(resolveLatestLlmModelName("chat_gpt")).resolves.toBe(
+ "gpt-5.5",
+ );
+
+ stubCatalog([
+ "claude-opus-5",
+ "claude-sonnet-4-6",
+ "claude-sonnet-5",
+ "claude-sonnet-4-5-20250929",
+ ]);
+ await expect(resolveLatestLlmModelName("claude")).resolves.toBe(
+ "claude-sonnet-5",
+ );
+ });
+
+ it("falls back to a listed snapshot name when no flagship alias is listed", async () => {
+ stubCatalog(["sonar-pro", "sonar"]);
+ await expect(resolveLatestLlmModelName("perplexity")).resolves.toBe(
+ "sonar-pro",
+ );
+ });
+
+ it("uses the static snapshot when the catalog endpoint is unreachable", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn<typeof fetch>().mockRejectedValue(new Error("upstream down")),
+ );
+
+ await expect(resolveLatestLlmModelName("claude")).resolves.toBe(
+ "claude-sonnet-5",
+ );
+ await expect(
+ isKnownLlmModelName("claude", "claude-sonnet-4-0"),
+ ).resolves.toBe(false);
+ });
+});
diff --git a/src/server/lib/dataforseo/llm-models.ts b/src/server/lib/dataforseo/llm-models.ts
new file mode 100644
index 00000000..6a6c6f70
--- /dev/null
+++ b/src/server/lib/dataforseo/llm-models.ts
@@ -0,0 +1,144 @@
+import { z } from "zod";
+import { dataforseoGet } from "@/server/lib/dataforseo/core";
+import { assertOk } from "@/server/lib/dataforseo/envelope";
+
+export type LlmResponseModelSlug =
+ | "chat_gpt"
+ | "claude"
+ | "gemini"
+ | "perplexity";
+
+/**
+ * Model names come from DataForSEO's FREE ($0) per-provider catalog
+ * (`/v3/ai_optimization/{slug}/llm_responses/models`), so the app tracks new
+ * model families without code changes. This matters twice over: a hardcoded
+ * pin goes stale (we shipped gpt-5 while the catalog had gpt-5.5), and
+ * DataForSEO BILLS tasks that fail with `Invalid Field: 'model_name'`, so a
+ * name must be validated against the catalog before a paid dispatch.
+ */
+
+const catalogRowSchema = z.object({ model_name: z.string() });
+
+/**
+ * Snapshot fallback (2026-08-25) used when the catalog endpoint is
+ * unreachable or lists no flagship alias: the aliases we know DataForSEO
+ * accepts, newest first.
+ */
+const FALLBACK_MODEL_NAMES: Record<LlmResponseModelSlug, string[]> = {
+ chat_gpt: [
+ "gpt-5.6-luna",
+ "gpt-5.5",
+ "gpt-5.4",
+ "gpt-5.2",
+ "gpt-5.1",
+ "gpt-5",
+ ],
+ claude: ["claude-sonnet-5", "claude-sonnet-4-6", "claude-sonnet-4-5"],
+ gemini: ["gemini-2.5-pro"],
+ perplexity: ["sonar-reasoning-pro", "sonar-pro", "sonar"],
+};
+
+/**
+ * Explicit preferred model per provider, taking precedence over the plain-
+ * alias rule below while the catalog still lists it (a dropped pin falls back
+ * to the rule instead of dispatching a billed-invalid name). ChatGPT is pinned
+ * to the 5.6 tier by maintainer choice — the plain-alias rule can't rank tier
+ * variants (terra/sol/luna), and 5.6 is newer than the plain gpt-5.5 alias.
+ * Live-verified accepted + cited (2026-08-25).
+ */
+const PINNED_MODEL_NAMES: Partial<Record<LlmResponseModelSlug, string>> = {
+ chat_gpt: "gpt-5.6-luna",
+};
+
+/**
+ * The flagship alias per provider: a plain, undated, un-suffixed family name.
+ * Dated releases ("gpt-5.5-2026-04-23") duplicate their alias, and suffixed
+ * variants (mini/nano/-lite, or tier names like "gpt-5.6-terra"/"-sol") are
+ * size/speed tiers whose consumer-default semantics we can't know — so the
+ * highest plain alias is what "latest" means here. DataForSEO resolves an
+ * alias to its latest dated version server-side.
+ */
+const LATEST_RULES: Record<LlmResponseModelSlug, RegExp> = {
+ chat_gpt: /^gpt-(\d+(?:\.\d+)*)$/,
+ claude: /^claude-sonnet-(\d+(?:-\d+)*)$/,
+ gemini: /^gemini-(\d+(?:\.\d+)*)-pro$/,
+ perplexity: /^sonar-reasoning-pro$/,
+};
+
+function compareVersions(a: number[], b: number[]): number {
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
+ const diff = (a[i] ?? 0) - (b[i] ?? 0);
+ if (diff !== 0) return diff;
+ }
+ return 0;
+}
+
+function pickLatestLlmModelName(
+ slug: LlmResponseModelSlug,
+ names: string[],
+): string {
+ const pinned = PINNED_MODEL_NAMES[slug];
+ if (pinned && names.includes(pinned)) return pinned;
+ const rule = LATEST_RULES[slug];
+ let best: { name: string; version: number[] } | null = null;
+ for (const name of names) {
+ const match = rule.exec(name);
+ if (!match) continue;
+ const version = (match[1] ?? "0").split(/[.-]/).map(Number);
+ if (!best || compareVersions(version, best.version) > 0) {
+ best = { name, version };
+ }
+ }
+ // No flagship alias in the catalog: take the newest snapshot name it still
+ // lists, so the pick passes the catalog check in fetchLlmResponse.
+ const fallback = FALLBACK_MODEL_NAMES[slug];
+ return best?.name ?? fallback.find((n) => names.includes(n)) ?? fallback[0];
+}
+
+const CATALOG_TTL_MS = 60 * 60 * 1000;
+
+// Per-isolate cache: the catalog is free but there's no reason to refetch it
+// on every prompt. Failures are not cached, so a transient outage self-heals.
+const catalogCache = new Map<
+ LlmResponseModelSlug,
+ { names: string[]; fetchedAt: number }
+>();
+
+async function getLlmModelNames(slug: LlmResponseModelSlug): Promise<string[]> {
+ const cached = catalogCache.get(slug);
+ if (cached && Date.now() - cached.fetchedAt < CATALOG_TTL_MS) {
+ return cached.names;
+ }
+ try {
+ const response = await dataforseoGet(
+ `/v3/ai_optimization/${slug}/llm_responses/models`,
+ );
+ const task = assertOk(response);
+ const names = (task.result ?? []).flatMap((row) => {
+ const parsed = catalogRowSchema.safeParse(row);
+ return parsed.success ? [parsed.data.model_name] : [];
+ });
+ if (names.length === 0) return FALLBACK_MODEL_NAMES[slug];
+ catalogCache.set(slug, { names, fetchedAt: Date.now() });
+ return names;
+ } catch (error) {
+ console.warn(`dataforseo.llm-models.catalog-fetch failed (${slug})`, error);
+ return FALLBACK_MODEL_NAMES[slug];
+ }
+}
+
+/** The model to use for a provider, picked from the live catalog. */
+export async function resolveLatestLlmModelName(
+ slug: LlmResponseModelSlug,
+): Promise<string> {
+ return pickLatestLlmModelName(slug, await getLlmModelNames(slug));
+}
+
+/** Whether DataForSEO's catalog accepts this model name. Checked before every
+ * paid dispatch because an unknown `model_name` fails as a BILLED task. */
+export async function isKnownLlmModelName(
+ slug: LlmResponseModelSlug,
+ modelName: string,
+): Promise<boolean> {
+ return (await getLlmModelNames(slug)).includes(modelName);
+}
diff --git a/src/server/lib/dataforseo/pricing.ts b/src/server/lib/dataforseo/pricing.ts
index e1afb46e..3e9cc4d1 100644
--- a/src/server/lib/dataforseo/pricing.ts
+++ b/src/server/lib/dataforseo/pricing.ts
@@ -43,9 +43,9 @@ import {
fetchLlmResponse,
fetchLlmTopPages,
LLM_RESPONSE_WEB_SEARCH_DEFAULT,
- type LlmResponseModelSlug,
resolveLlmMentionsLimit,
} from "@/server/lib/dataforseo/ai";
+import type { LlmResponseModelSlug } from "@/server/lib/dataforseo/llm-models";
import {
costPerSerpAtDepth,
serpKeywordCostMultiplier,