Skip to content

Open source CapCut alternative.

TypeScript

fix(site): run web search only for fact checks [rebuild]

David Le6cdf456864d0
diff --git a/site/src/app/api/inference/fact-check/route.ts b/site/src/app/api/inference/fact-check/route.ts
index 25c0eacc..a42da702 100644
--- a/site/src/app/api/inference/fact-check/route.ts
+++ b/site/src/app/api/inference/fact-check/route.ts
@@ -21,7 +21,12 @@ import {
} from "@/lib/inference/factCheck";
import { geminiModelRoles } from "@/lib/inference/gemini-models";
import { isJsonObject, toJsonValue } from "@/lib/inference/json";
-import { InferenceProviderError, type JsonObject, type JsonValue } from "@/lib/inference/providers";
+import {
+ InferenceProviderError,
+ type JsonObject,
+ type JsonValue,
+ type ResponseCreateRequest,
+} from "@/lib/inference/providers";
import {
inferenceErrorCode,
inferenceProviderErrorResponse,
@@ -53,13 +58,7 @@ const GROUNDING_REDIRECT_HOST = "vertexaisearch.cloud.google.com";
const REDIRECT_TIMEOUT_MS = 4000;
async function resolveSource(source: FactSource): Promise<FactSource> {
- let host: string;
- try {
- host = new URL(source.url).hostname;
- } catch {
- return source;
- }
- if (host !== GROUNDING_REDIRECT_HOST) return source;
+ if (URL.parse(source.url)?.hostname !== GROUNDING_REDIRECT_HOST) return source;
const res = await fetch(source.url, {
method: "GET",
redirect: "manual",
@@ -71,6 +70,22 @@ async function resolveSource(source: FactSource): Promise<FactSource> {
return { url: location, title: source.title };
}
+/** The first `max` distinct pages behind the search's links. Links resolve a
+ * batch at a time, only as many as the pages still missing, so a search that
+ * returned a dozen links costs as many fetches as the claim reports. */
+async function resolveSources(sources: FactSource[], max: number): Promise<FactSource[]> {
+ const kept: FactSource[] = [];
+ let next = 0;
+ while (kept.length < max && next < sources.length) {
+ const batch = sources.slice(next, next + max - kept.length);
+ next += batch.length;
+ for (const page of await Promise.all(batch.map(resolveSource))) {
+ if (kept.length < max && !kept.some((k) => k.url === page.url)) kept.push(page);
+ }
+ }
+ return kept;
+}
+
function sourcesOf(body: JsonValue): FactSource[] {
const raw = isJsonObject(body) && Array.isArray(body.sources) ? body.sources : [];
return raw.flatMap((s) =>
@@ -123,13 +138,9 @@ export const POST = withDonkeyAuth(async (request) => {
return validationErrorResponse(parsed.error);
}
const settings = await getGlobalSetting("factCheck");
- const { claims, context } = parsed.data;
- if (claims.length > settings.maxClaims) {
- return NextResponse.json(
- { error: "too_many_claims", message: `Check at most ${settings.maxClaims} claims at a time.` },
- { status: 400 },
- );
- }
+ // A claim asked twice is searched and billed once.
+ const claims = [...new Set(parsed.data.claims)];
+ const { context } = parsed.data;
const model = geminiModelRoles.factCheck;
const bypassCredits = shouldBypassDonkeyInferenceCredits(request.donkey);
@@ -152,18 +163,21 @@ export const POST = withDonkeyAuth(async (request) => {
const registry = createProviderRegistry();
const errors: unknown[] = [];
// Each call charges on its own; the response reports their total and the
- // balance the last one left.
+ // lowest balance any of them left, which is the latest one whatever order
+ // their promises settle in.
const tally: { charged: bigint; remaining: bigint | null } = { charged: zeroCreditMicros, remaining: null };
const results = await inPool(claims, settings.concurrency, async (claim): Promise<FactCheckOutcome> => {
try {
- const call = responseCreateRequestSchema.parse({
- donkeyProvider: "gemini",
- model,
- instructions: FACT_CHECK_INSTRUCTIONS,
- input: factCheckPrompt(claim, context),
- tools: [{ type: "web_search" }],
- text: { format: { type: "json_schema", name: "fact_check", schema: FACT_ANSWER_SCHEMA } },
- });
+ const call: ResponseCreateRequest = {
+ ...responseCreateRequestSchema.parse({
+ donkeyProvider: "gemini",
+ model,
+ instructions: FACT_CHECK_INSTRUCTIONS,
+ input: factCheckPrompt(claim, context),
+ text: { format: { type: "json_schema", name: "fact_check", schema: FACT_ANSWER_SCHEMA } },
+ }),
+ search: "google_search",
+ };
const provider = registry.responsesProvider(call);
const result = await provider.createResponse?.(call);
if (!result) {
@@ -186,10 +200,11 @@ export const POST = withDonkeyAuth(async (request) => {
userId: request.donkey.userId,
});
tally.charged += recorded.creditCostMicros;
- tally.remaining = recorded.remainingBalanceMicros;
+ const left = recorded.remainingBalanceMicros;
+ tally.remaining = tally.remaining === null || left < tally.remaining ? left : tally.remaining;
}
const outputText = isJsonObject(body) && typeof body.output_text === "string" ? body.output_text : "";
- const sources = await Promise.all(sourcesOf(body).map(resolveSource));
+ const sources = await resolveSources(sourcesOf(body), settings.maxSourcesPerClaim);
return shapeFactCheck(claim, outputText, sources, {
minSources: settings.minSources,
maxSources: settings.maxSourcesPerClaim,
diff --git a/site/src/clients/chatgpt/server/catalog.ts b/site/src/clients/chatgpt/server/catalog.ts
index db4106c8..d7160f17 100644
--- a/site/src/clients/chatgpt/server/catalog.ts
+++ b/site/src/clients/chatgpt/server/catalog.ts
@@ -33,13 +33,17 @@ const HIDDEN = new Set([
const DESCRIPTIONS: Record<string, string> = {
set_removal: "Cut out a subject or background on any video track. mode auto starts the free person matte; custom tracks the subject described in subject and spends credits; off keeps the stored matte and settings. remove background keeps the subject, and remove subject keeps its surroundings. refine requests the paid quality upgrade when the user asks for it. Matting continues in the editor: inspect_project reports each clip's removal readiness and progress. Check readiness before claiming completion, then capture_frame to inspect the result. The user can select an exact instance with the Cutout inspector's brush and Apply controls. Read background-removal for the workflow.",
- check_facts: "Check factual claims against the web: each claim is searched on Google and comes back with a verdict (supported, contradicted, mixed, or unverifiable), the corrected value when the claim is wrong, a one-line note on what the sources say, and the pages the search found, each with its title and URL. A verdict needs at least two sources behind it, so a claim the search barely covers comes back unverifiable. Check every figure the narration or a title states — a number, a date, a price, a name, a release — before it goes on screen, passing each as its own specific claim worded the way the video says it. Report every contradicted, mixed or unverifiable claim to the user plainly, with what the sources say and where; change their words only when they ask. The output's searchSuggestions are the Google searches behind the verdicts: show them to the user as links, with their text and URLs as given, wherever you report the results. Spends credits: one web search per claim.",
stock_search: "Search the bundled catalogs for footage, images, character references, and sound effects. Stock is free. Use stock_add to import a result, then inspect it before choosing where it belongs in the cut.",
};
+// What ChatGPT needs on top of the shared description.
+const ADDENDA: Record<string, string> = {
+ check_facts: "The output's searchSuggestions are the Google searches behind the verdicts: show them to the user as links, with their text and URLs as given, wherever you report the results.",
+};
+
export const COMMANDS: AiToolDef[] = PROJECT_TOOLS.filter((tool) => !HIDDEN.has(tool.name)).map((tool) => ({
...tool,
- description: DESCRIPTIONS[tool.name] ?? chatgptDescription(tool.description),
+ description: DESCRIPTIONS[tool.name] ?? [chatgptDescription(tool.description), ADDENDA[tool.name]].filter(Boolean).join(" "),
}));
export const COMMAND_NAMES = COMMANDS.map((tool) => tool.name);
diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.ts
index 12db12d8..1f75e990 100644
--- a/site/src/cut/components/AiPanel.tools.ts
+++ b/site/src/cut/components/AiPanel.tools.ts
@@ -9,7 +9,7 @@
import { bool, num, obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";
import { WATCH_DETAIL_NOTES, WATCH_DETAILS } from "@/cut/lib/types";
-import { FACT_CLAIM_MAX_CHARS, FACT_CLAIMS_CEILING } from "@/lib/inference/factCheck";
+import { FACT_CLAIM_MAX_CHARS, FACT_CLAIMS_MAX } from "@/lib/inference/factCheck";
export const AI_PANEL_TOOLS = [
{
@@ -185,14 +185,14 @@ export const AI_PANEL_TOOLS = [
{
name: "check_facts",
description:
- "Check factual claims against the web: each claim is searched on Google and comes back with a verdict (supported, contradicted, mixed, or unverifiable), the corrected value when the claim is wrong, a one-line note on what the sources say, and the pages the search found, each with its title and URL. A verdict needs at least two sources behind it, so a claim the search barely covers comes back unverifiable. Check every figure the narration or a title states — a number, a date, a price, a name, a release — before you show it on screen, passing each as its own specific claim worded the way the video says it. Report every contradicted, mixed or unverifiable claim to the user plainly, with what the sources say and where; change their words only when they ask. Sources come only from the search, so quote them as given. Spends credits: one web search per claim.",
+ "Check factual claims against the web: each claim is searched on Google and comes back with a verdict (supported, contradicted, mixed, or unverifiable), the corrected value when the claim is wrong, a one-line note on what the sources say, and the pages the search found, each with its title and URL. A verdict needs several sources behind it, so a claim the search barely covers comes back unverifiable and says how many it found. Check every figure the narration or a title states — a number, a date, a price, a name, a release — before you show it on screen, passing each as its own specific claim worded the way the video says it. Report every contradicted, mixed or unverifiable claim to the user plainly, with what the sources say and where; change their words only when they ask. Sources come only from the search, so quote them as given. Spends credits: one web search per claim.",
inputSchema: obj(
{
claims: {
type: "array",
items: { type: "string" },
- maxItems: FACT_CLAIMS_CEILING,
- description: `The specific statements to check, one fact each, under ${FACT_CLAIM_MAX_CHARS} characters`,
+ maxItems: FACT_CLAIMS_MAX,
+ description: `The specific statements to check, one fact each, under ${FACT_CLAIM_MAX_CHARS} characters; at most ${FACT_CLAIMS_MAX} per call`,
},
context: str("What the video is about, so an ambiguous claim is searched the way it is meant (optional)"),
},
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 93281076..88a3fd4d 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -124,7 +124,6 @@ import { apiFetch, apiJson, getBackend } from "./backend";
import { refFromAsset, refFromStockVideo, type AssetRef } from "./assetRef";
import { chatOwner, tagChatAsset } from "./chatAssets";
import { checkFacts, factCheckToolOutput } from "./factCheck";
-import { checkFactsInput } from "./webToolInputs";
import { queueMessageFromAgent } from "./chatQueue";
import { applyOwnership, useGenerate, type VideoAttempt, type VideoGenOptions } from "./generate";
import { useGenScene } from "./genScene";
@@ -3880,9 +3879,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
},
check_facts: async (_s, input) => {
- const checked = checkFactsInput(input);
- if (!checked.ok) throw new ToolError(checked.error);
- const { results } = await checkFacts(checked.claims, checked.context);
+ const { results } = await checkFacts(input);
return factCheckToolOutput(results);
},
diff --git a/site/src/cut/lib/audioGen.ts b/site/src/cut/lib/audioGen.ts
index c6b77c8e..c026ad6c 100644
--- a/site/src/cut/lib/audioGen.ts
+++ b/site/src/cut/lib/audioGen.ts
@@ -1,7 +1,7 @@
"use client";
import { bytesFromBase64 } from "./bytes";
-import { NO_CREDITS_MESSAGE } from "./credits";
+import { readHostedError } from "./hostedError";
import { hostedPost } from "./hosted";
import { importFileToProject } from "./media";
import { NoCreditsError } from "./tts";
@@ -23,26 +23,8 @@ export const MUSIC_VARIANTS: { id: MusicVariant; label: string; hint: string }[]
{ id: "song", label: "Full track", hint: "~2 min" },
];
-async function readError(res: Response, fallback: string): Promise<string> {
- if (res.status === 401) return "Sign in to Donkey to generate music.";
- const body = (await res.json().catch(() => null)) as {
- error?: unknown;
- message?: unknown;
- details?: { message?: unknown };
- } | null;
- const message = [body?.message, body?.error].find(
- (v): v is string => typeof v === "string" && v.length > 0
- );
- if (res.status === 402) return NO_CREDITS_MESSAGE;
- // The provider's own error (`details.message`) names the actual rejection (a
- // filtered prompt, a timeout); the top-level message is generic.
- const detail = body?.details?.message;
- const full =
- message && typeof detail === "string" && detail && detail !== message
- ? `${message} (${detail})`
- : message;
- return full ?? fallback;
-}
+const readError = (res: Response, fallback: string) =>
+ readHostedError(res, "Sign in to Donkey to generate music.", fallback);
/** Display name for the track: the prompt, tidied and capped. */
function musicName(prompt: string) {
diff --git a/site/src/cut/lib/factCheck.ts b/site/src/cut/lib/factCheck.ts
index 61924da1..6a189e72 100644
--- a/site/src/cut/lib/factCheck.ts
+++ b/site/src/cut/lib/factCheck.ts
@@ -1,29 +1,17 @@
import type { FactCheckResponse } from "@/lib/inference/factCheck";
-import { NO_CREDITS_MESSAGE } from "./credits";
import { hostedPost } from "./hosted";
+import { readHostedError } from "./hostedError";
// Checking a video's claims against the web, through the hosted fact-check
// route. The page, the cloud runner and the ChatGPT card all reach it with the
// user's session and credits.
-export async function checkFacts(claims: string[], context?: string): Promise<FactCheckResponse> {
- const res = await hostedPost("/api/inference/fact-check", {
- claims,
- ...(context ? { context } : {}),
- });
+/** The tool's input goes as given; the route holds it to the contract and
+ * answers a bad claim with the field that broke it. */
+export async function checkFacts(input: { claims?: unknown; context?: unknown }): Promise<FactCheckResponse> {
+ const res = await hostedPost("/api/inference/fact-check", { claims: input.claims, context: input.context });
if (!res.ok) {
- if (res.status === 401) throw new Error("Sign in to Donkey to check facts.");
- if (res.status === 402) throw new Error(NO_CREDITS_MESSAGE);
- const body = (await res.json().catch(() => null)) as {
- message?: unknown;
- error?: unknown;
- issues?: { path?: string; message?: string }[];
- } | null;
- const issue = body?.issues?.[0];
- const message = [body?.message, issue ? `${issue.path}: ${issue.message}` : undefined, body?.error].find(
- (v): v is string => typeof v === "string" && v.length > 0
- );
- throw new Error(message ?? `The fact check failed (${res.status}).`);
+ throw new Error(await readHostedError(res, "Sign in to Donkey to check facts.", `The fact check failed (${res.status}).`));
}
return (await res.json()) as FactCheckResponse;
}
@@ -36,7 +24,7 @@ export function factCheckToolOutput(results: FactCheckResponse["results"]) {
const verdicts = results.map((r) => {
if ("error" in r || !r.searchSuggestions) return r;
const { searchSuggestions, ...rest } = r;
- if (!suggestions.includes(searchSuggestions)) suggestions.push(searchSuggestions);
+ suggestions.push(searchSuggestions);
return rest;
});
const flagged = results.filter((r) => "error" in r || r.verdict !== "supported").length;
diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.ts
index 268d15d7..2ce4a035 100644
--- a/site/src/cut/lib/generate.ts
+++ b/site/src/cut/lib/generate.ts
@@ -17,6 +17,7 @@ import {
upsertRenderInDoc,
} from "./genvideo/docWriter";
import { NO_CREDITS_MESSAGE } from "./credits";
+import { readHostedError } from "./hostedError";
import { CUT_APP_BASE } from "./nav";
import { hostedFetch, hostedPost } from "./hosted";
import { enrichAsset, importFileToProject, uploadProjectImage } from "./media";
@@ -275,27 +276,8 @@ interface GenerationResponse {
metadata?: Record<string, unknown>;
}
-async function readError(res: Response, fallback: string): Promise<string> {
- if (res.status === 401) return "Sign in to Donkey to generate media.";
- const body = (await res.json().catch(() => null)) as {
- error?: unknown;
- message?: unknown;
- details?: { message?: unknown } | null;
- } | null;
- const message = [body?.message, body?.error].find(
- (v): v is string => typeof v === "string" && v.length > 0
- );
- if (res.status === 402) return NO_CREDITS_MESSAGE;
- // The provider tucks the real reason (a safety block, a rejected prompt) under
- // details.message; the top-level message is only a generic headline. Append it so a
- // failure explains itself instead of stopping at "…generation failed."
- const detail =
- typeof body?.details?.message === "string" && body.details.message.trim()
- ? body.details.message.trim()
- : null;
- if (detail && detail !== message) return message ? `${message} ${detail}` : detail;
- return message ?? fallback;
-}
+const readError = (res: Response, fallback: string) =>
+ readHostedError(res, "Sign in to Donkey to generate media.", fallback);
const providerError = (error: unknown): string | null => {
if (typeof error === "string" && error) return error;
diff --git a/site/src/cut/lib/hostedError.test.ts b/site/src/cut/lib/hostedError.test.ts
new file mode 100644
index 00000000..b48cad12
--- /dev/null
+++ b/site/src/cut/lib/hostedError.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, test } from "bun:test";
+
+import { NO_CREDITS_MESSAGE } from "./credits";
+import { readHostedError } from "./hostedError";
+
+const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status });
+
+describe("readHostedError", () => {
+ test("401 asks to sign in and 402 says the credits line", async () => {
+ expect(await readHostedError(json(401, { message: "x" }), "Sign in.", "Failed.")).toBe("Sign in.");
+ expect(await readHostedError(json(402, { message: "x" }), "Sign in.", "Failed.")).toBe(NO_CREDITS_MESSAGE);
+ });
+
+ test("the provider's reason joins the headline", async () => {
+ const res = json(502, { message: "Generation failed.", details: { message: "Prompt was filtered." } });
+ expect(await readHostedError(res, "Sign in.", "Failed.")).toBe("Generation failed. (Prompt was filtered.)");
+ expect(await readHostedError(json(502, { details: { message: "Rate limited." } }), "Sign in.", "Failed.")).toBe(
+ "Rate limited.",
+ );
+ });
+
+ test("a rejected request names its first bad field before the generic error", async () => {
+ const res = json(400, { error: "Invalid request", issues: [{ path: "claims.0", message: "Too long" }] });
+ expect(await readHostedError(res, "Sign in.", "Failed.")).toBe("claims.0: Too long");
+ });
+
+ test("an unreadable body falls back", async () => {
+ expect(await readHostedError(new Response("oops", { status: 500 }), "Sign in.", "Failed.")).toBe("Failed.");
+ });
+});
diff --git a/site/src/cut/lib/hostedError.ts b/site/src/cut/lib/hostedError.ts
new file mode 100644
index 00000000..200bc850
--- /dev/null
+++ b/site/src/cut/lib/hostedError.ts
@@ -0,0 +1,39 @@
+import { NO_CREDITS_MESSAGE } from "./credits";
+
+// The message a failed hosted call shows: sign in on 401, the credits line on
+// 402, otherwise the route's own words. The provider's reason (a filtered
+// prompt, a rate limit) rides under `details.message` and joins the headline;
+// a rejected request names its first bad field.
+
+const UNAUTHORIZED = 401;
+const PAYMENT_REQUIRED = 402;
+
+interface ErrorBody {
+ message?: unknown;
+ error?: unknown;
+ details?: { message?: unknown } | null;
+ issues?: { path?: unknown; message?: unknown }[];
+}
+
+const text = (v: unknown): string | undefined => (typeof v === "string" && v.trim() ? v.trim() : undefined);
+
+/** The error line for a hosted response that came back not ok. `signIn` is
+ * what a signed-out caller reads, e.g. "Sign in to Donkey to check facts." */
+export async function readHostedError(res: Response, signIn: string, fallback: string): Promise<string> {
+ if (res.status === UNAUTHORIZED) {
+ return signIn;
+ }
+ if (res.status === PAYMENT_REQUIRED) {
+ return NO_CREDITS_MESSAGE;
+ }
+
+ const body = (await res.json().catch(() => null)) as ErrorBody | null;
+ const issue = body?.issues?.[0];
+ const issueText = issue && text(issue.message) ? `${text(issue.path) ?? "request"}: ${text(issue.message)}` : undefined;
+ const message = text(body?.message) ?? issueText ?? text(body?.error);
+ const detail = text(body?.details?.message);
+ if (detail && detail !== message) {
+ return message ? `${message} (${detail})` : detail;
+ }
+ return message ?? fallback;
+}
diff --git a/site/src/cut/lib/toolDisplay.test.ts b/site/src/cut/lib/toolDisplay.test.ts
index 62b5e979..2d177263 100644
--- a/site/src/cut/lib/toolDisplay.test.ts
+++ b/site/src/cut/lib/toolDisplay.test.ts
@@ -22,7 +22,7 @@ const supported = {
describe("check_facts output", () => {
test("suggestions move from each result to display, once each", () => {
const out = factCheckToolOutput([supported, { ...supported, claim: "Again." }, { claim: "Broken.", error: "failed" }]);
- expect(out.display).toEqual({ searchSuggestions: [BLOCK] });
+ expect(toolDisplayOf(out)).toEqual({ searchSuggestions: [BLOCK] });
expect(out.results.some((r) => "searchSuggestions" in r)).toBe(false);
expect(out.note).toContain("1 of 3");
});
diff --git a/site/src/cut/lib/toolDisplay.ts b/site/src/cut/lib/toolDisplay.ts
index 9cadae0d..00c83515 100644
--- a/site/src/cut/lib/toolDisplay.ts
+++ b/site/src/cut/lib/toolDisplay.ts
@@ -1,8 +1,8 @@
// What a tool hands the person and keeps from the model. A tool output's
// `display` key carries markup the chat shows beside the result (Google's
// Search Suggestions for a grounded check); the chat loop moves it off the
-// response the model reads, and the ChatGPT adapter moves it into the
-// widget-only metadata.
+// response the model reads, and the ChatGPT adapter turns it into links in the
+// output the model reads.
export interface ToolDisplay {
/** Search Suggestions blocks, HTML and CSS from the search provider, shown
@@ -18,7 +18,7 @@ export function splitToolDisplay(output: unknown): { output: unknown; display?:
return shaped ? { output: rest, display: shaped } : { output: rest };
}
-export interface SearchLink {
+interface SearchLink {
query: string;
url: string;
}
diff --git a/site/src/cut/lib/tts.ts b/site/src/cut/lib/tts.ts
index 44c2e534..c48516ee 100644
--- a/site/src/cut/lib/tts.ts
+++ b/site/src/cut/lib/tts.ts
@@ -2,7 +2,7 @@
import { geminiModelRoleNames } from "@/lib/inference/gemini-models";
import { bytesFromBase64 } from "./bytes";
-import { NO_CREDITS_MESSAGE } from "./credits";
+import { readHostedError } from "./hostedError";
import { hostedPost } from "./hosted";
import { cutJudge } from "./chatRuntime";
import { askJudge, choice } from "./judge";
@@ -226,26 +226,8 @@ interface PcmClip {
* buy credits alongside the message. */
export class NoCreditsError extends Error {}
-async function readError(res: Response, fallback: string): Promise<string> {
- if (res.status === 401) return "Sign in to Donkey to generate voiceovers.";
- const body = (await res.json().catch(() => null)) as {
- error?: unknown;
- message?: unknown;
- details?: { message?: unknown };
- } | null;
- const message = [body?.message, body?.error].find(
- (v): v is string => typeof v === "string" && v.length > 0
- );
- if (res.status === 402) return NO_CREDITS_MESSAGE;
- // The provider's own error (`details.message`) names the actual rejection
- // ("input too long", a rate limit, …); the top-level message is generic.
- const detail = body?.details?.message;
- const full =
- message && typeof detail === "string" && detail && detail !== message
- ? `${message} (${detail})`
- : message;
- return full ?? fallback;
-}
+const readError = (res: Response, fallback: string) =>
+ readHostedError(res, "Sign in to Donkey to generate voiceovers.", fallback);
/** One hosted Gemini speech call: text in, decoded PCM out. A direction is a
* natural-language delivery instruction ("Say warmly, like an old friend");
diff --git a/site/src/cut/lib/webToolInputs.test.ts b/site/src/cut/lib/webToolInputs.test.ts
deleted file mode 100644
index f02d9786..00000000
--- a/site/src/cut/lib/webToolInputs.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { describe, expect, test } from "bun:test";
-
-import { FACT_CLAIMS_CEILING } from "@/lib/inference/factCheck";
-import { checkFactsInput } from "./webToolInputs";
-
-describe("check_facts input", () => {
- test("claims are trimmed, emptied ones dropped, repeats kept once", () => {
- expect(checkFactsInput({ claims: [" The tower is 330 m tall. ", "", "The tower is 330 m tall."], context: " Paris " })).toEqual({
- ok: true,
- claims: ["The tower is 330 m tall."],
- context: "Paris",
- });
- });
-
- test("claims must be a non-empty list of text", () => {
- expect(checkFactsInput({}).ok).toBe(false);
- expect(checkFactsInput({ claims: [] }).ok).toBe(false);
- expect(checkFactsInput({ claims: "one claim" }).ok).toBe(false);
- expect(checkFactsInput({ claims: [1, 2] }).ok).toBe(false);
- expect(checkFactsInput({ claims: [" "] }).ok).toBe(false);
- });
-
- test("an overlong claim and too many claims are refused", () => {
- expect(checkFactsInput({ claims: ["x".repeat(501)] }).ok).toBe(false);
- const many = Array.from({ length: FACT_CLAIMS_CEILING + 1 }, (_, i) => `Claim ${i}`);
- expect(checkFactsInput({ claims: many }).ok).toBe(false);
- });
-
- test("context must be text", () => {
- expect(checkFactsInput({ claims: ["A"], context: 3 }).ok).toBe(false);
- });
-});
diff --git a/site/src/cut/lib/webToolInputs.ts b/site/src/cut/lib/webToolInputs.ts
deleted file mode 100644
index 915c586d..00000000
--- a/site/src/cut/lib/webToolInputs.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import {
- FACT_CLAIM_MAX_CHARS,
- FACT_CLAIMS_CEILING,
- FACT_CONTEXT_MAX_CHARS,
-} from "@/lib/inference/factCheck";
-
-// check_facts's claims, held to their shape before any request leaves. Pure,
-// so the chat handler and its tests read the same rules.
-
-type Checked<T> = ({ ok: true } & T) | { ok: false; error: string };
-
-export function checkFactsInput(input: Record<string, unknown>): Checked<{ claims: string[]; context?: string }> {
- if (!Array.isArray(input.claims) || input.claims.length === 0)
- return { ok: false, error: "claims must list at least one statement to check." };
- const claims: string[] = [];
- for (const raw of input.claims) {
- if (typeof raw !== "string") return { ok: false, error: "Each claim must be a sentence of text." };
- const claim = raw.replace(/\s+/g, " ").trim();
- if (!claim) continue;
- if (claim.length > FACT_CLAIM_MAX_CHARS)
- return { ok: false, error: `Each claim must be one specific statement, under ${FACT_CLAIM_MAX_CHARS} characters.` };
- if (!claims.includes(claim)) claims.push(claim);
- }
- if (claims.length === 0) return { ok: false, error: "claims must list at least one statement to check." };
- if (claims.length > FACT_CLAIMS_CEILING)
- return { ok: false, error: `Check at most ${FACT_CLAIMS_CEILING} claims at a time.` };
- if (input.context !== undefined && typeof input.context !== "string")
- return { ok: false, error: "context must be text." };
- const context = typeof input.context === "string" ? input.context.trim().slice(0, FACT_CONTEXT_MAX_CHARS) : "";
- return { ok: true, claims, ...(context ? { context } : {}) };
-}
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index 970145e1..9310f4f5 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -347,7 +347,6 @@ export const SETTINGS = defineSettings({
factCheck: {
schema: z
.object({
- maxClaims: z.number().int().min(1).max(40),
// Searches run side by side, this many at a time.
concurrency: z.number().int().min(1).max(10),
// A verdict other than unverifiable needs at least this many sources.
@@ -355,11 +354,11 @@ export const SETTINGS = defineSettings({
maxSourcesPerClaim: z.number().int().min(1).max(10),
})
.strict(),
- default: { maxClaims: 12, concurrency: 4, minSources: 2, maxSourcesPerClaim: 5 },
+ default: { concurrency: 4, minSources: 2, maxSourcesPerClaim: 5 },
public: false,
title: "Fact check",
description:
- "How claims are checked against the web: how many one request takes, how many searches run at once, how many sources a verdict needs, and how many sources each claim reports.",
+ "How claims are checked against the web: how many searches run at once, how many sources a verdict needs, and how many sources each claim reports.",
},
cutColor: {
schema: z
diff --git a/site/src/lib/inference/adapters/gemini-responses.ts b/site/src/lib/inference/adapters/gemini-responses.ts
index 8594aede..4574b6af 100644
--- a/site/src/lib/inference/adapters/gemini-responses.ts
+++ b/site/src/lib/inference/adapters/gemini-responses.ts
@@ -40,6 +40,7 @@ import {
type JsonValue,
type ResponseCreateRequest,
type ResponseCreateResult,
+ type ResponseSearch,
type ResponseStreamEvent,
type ResponseStreamResult,
type TextCompletionResult,
@@ -82,7 +83,7 @@ export function createGeminiResponsesProvider(
statusCode: 400,
code: "gemini_tool_unsupported",
details: {
- supportedTools: allowFunctionTools ? ["function", webSearchToolType] : [],
+ supportedTools: allowFunctionTools ? ["function"] : [],
},
});
}
@@ -91,6 +92,7 @@ export function createGeminiResponsesProvider(
const requestParameters = geminiGenerateContentParameters(
request.body,
model,
+ request.search,
);
return { model, requestParameters };
}
@@ -361,8 +363,9 @@ function streamChunkText(chunk: GenerateContentResponse): string {
function geminiGenerateContentParameters(
body: JsonObject,
model: string,
+ search: ResponseSearch | undefined,
): GenerateContentParameters {
- const tools = geminiTools(body.tools);
+ const tools = geminiTools(body.tools, search);
const generationConfig = generationConfigFromBody(body);
const systemInstruction = systemInstructionFromBody(body);
const config: GenerateContentConfig = {
@@ -382,24 +385,22 @@ function geminiGenerateContentParameters(
};
}
-function geminiTools(rawTools: JsonValue | undefined): Tool[] {
+function geminiTools(rawTools: JsonValue | undefined, search: ResponseSearch | undefined): Tool[] {
const tools: Tool[] = [];
const declarations = functionDeclarationsFromTools(rawTools);
if (declarations.length > 0) {
tools.push({ functionDeclarations: declarations });
}
- // `type: "web_search"` grounds the answer in Google Search; the sources the
+ // The route's search grounds the answer in Google Search; the sources the
// search returned come back as `sources` on the normalized response.
- if (Array.isArray(rawTools) && rawTools.some((tool) => isJsonObject(tool) && tool.type === webSearchToolType)) {
+ if (search === "google_search") {
tools.push({ googleSearch: {} });
}
return tools;
}
-const webSearchToolType = "web_search";
-
/** The web pages a grounded answer drew on, the searches that found them, and
* Google's Search Suggestions block (HTML and CSS the terms require shown
* beside the answer), read off the candidate's grounding metadata. Only what
@@ -1017,7 +1018,7 @@ function hasExplicitUnsupportedTools(
if (!isJsonObject(tool)) {
return true;
}
- return !(allowFunctionTools && (tool.type === "function" || tool.type === webSearchToolType));
+ return !(allowFunctionTools && tool.type === "function");
});
}
diff --git a/site/src/lib/inference/factCheck.test.ts b/site/src/lib/inference/factCheck.test.ts
index 7c52af4e..5d001f5f 100644
--- a/site/src/lib/inference/factCheck.test.ts
+++ b/site/src/lib/inference/factCheck.test.ts
@@ -68,7 +68,7 @@ describe("grounding metadata", () => {
});
describe("the adapter's grounded call", () => {
- test("web_search turns on Google Search, and the response carries the sources", async () => {
+ test("the fact-check search turns on Google Search, and the response carries the sources", async () => {
let sent: Record<string, unknown> | null = null;
const provider = createGeminiResponsesProvider(
{
@@ -89,14 +89,16 @@ describe("the adapter's grounded call", () => {
caches: {},
}) as never,
);
- const request = responseCreateRequestSchema.parse({
- donkeyProvider: "gemini",
- model: "gemini-test",
- instructions: "Check it.",
- input: "Claim: The Eiffel Tower is 300 m tall.",
- tools: [{ type: "web_search" }],
- text: { format: { type: "json_schema", name: "fact_check", schema: FACT_ANSWER_SCHEMA } },
- });
+ const request = {
+ ...responseCreateRequestSchema.parse({
+ donkeyProvider: "gemini",
+ model: "gemini-test",
+ instructions: "Check it.",
+ input: "Claim: The Eiffel Tower is 300 m tall.",
+ text: { format: { type: "json_schema", name: "fact_check", schema: FACT_ANSWER_SCHEMA } },
+ }),
+ search: "google_search" as const,
+ };
expect(provider.canCreateResponse?.(request)).toBe(true);
const result = await provider.createResponse!(request);
const config = (sent as unknown as { config: Record<string, unknown> }).config;
@@ -127,10 +129,12 @@ describe("the adapter's grounded call", () => {
expect(shaped.sources.some((s) => s.url.includes("made-up.example"))).toBe(false);
});
- test("an ungrounded request keeps web_search out unless Gemini was named", () => {
+ test("a request body can never turn the search on, even naming Gemini", () => {
const provider = createGeminiResponsesProvider({}, () => ({}) as never);
- const request = responseCreateRequestSchema.parse({ input: "x", tools: [{ type: "web_search" }] });
- expect(provider.canCreateResponse?.(request)).toBe(false);
+ for (const donkeyProvider of [undefined, "gemini"] as const) {
+ const request = responseCreateRequestSchema.parse({ donkeyProvider, input: "x", tools: [{ type: "web_search" }] });
+ expect(provider.canCreateResponse?.(request)).toBe(false);
+ }
});
});
diff --git a/site/src/lib/inference/factCheck.ts b/site/src/lib/inference/factCheck.ts
index abfaa339..7144cac0 100644
--- a/site/src/lib/inference/factCheck.ts
+++ b/site/src/lib/inference/factCheck.ts
@@ -5,29 +5,27 @@ import { z } from "zod";
// verdict and its note are the model's; every source comes from the search's
// own grounding record, so a URL the model made up can never reach a reply.
-export const FACT_VERDICTS = ["supported", "contradicted", "mixed", "unverifiable"] as const;
-export type FactVerdict = (typeof FACT_VERDICTS)[number];
+const FACT_VERDICTS = ["supported", "contradicted", "mixed", "unverifiable"] as const;
+type FactVerdict = (typeof FACT_VERDICTS)[number];
export const FACT_CLAIM_MAX_CHARS = 500;
-export const FACT_CONTEXT_MAX_CHARS = 2000;
-/** The most claims a request may carry; the route's setting may hold fewer. */
-export const FACT_CLAIMS_CEILING = 40;
+const FACT_CONTEXT_MAX_CHARS = 2000;
+/** The most claims a request may carry. The tool schema teaches the same cap. */
+export const FACT_CLAIMS_MAX = 12;
export const factCheckRequestSchema = z
.object({
- claims: z.array(z.string().trim().min(1).max(FACT_CLAIM_MAX_CHARS)).min(1).max(FACT_CLAIMS_CEILING),
+ claims: z.array(z.string().trim().min(1).max(FACT_CLAIM_MAX_CHARS)).min(1).max(FACT_CLAIMS_MAX),
context: z.string().trim().max(FACT_CONTEXT_MAX_CHARS).optional(),
})
.strict();
-export type FactCheckRequest = z.infer<typeof factCheckRequestSchema>;
-
export interface FactSource {
url: string;
title: string;
}
-export interface FactCheckResult {
+interface FactCheckResult {
claim: string;
verdict: FactVerdict;
/** The right value, when the claim has it wrong. */
diff --git a/site/src/lib/inference/providers.ts b/site/src/lib/inference/providers.ts
index 0c3c5018..57dc21a1 100644
--- a/site/src/lib/inference/providers.ts
+++ b/site/src/lib/inference/providers.ts
@@ -22,7 +22,10 @@ export type JsonValue =
export type JsonObject = { [key: string]: JsonValue };
export type ChatCompletionRequest = z.infer<typeof chatCompletionRequestSchema>;
-export type ResponseCreateRequest = z.infer<typeof responseCreateRequestSchema>;
+// `search` grounds the answer in a web search the provider runs. Only a route
+// that bills the searches sets it; a request body never can.
+export type ResponseSearch = "google_search";
+export type ResponseCreateRequest = z.infer<typeof responseCreateRequestSchema> & { search?: ResponseSearch };
export type AssetGenerationRequest = z.infer<typeof assetGenerationRequestSchema>;
export type InferenceModel = {