Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

fix(json): stop repairing extractions cut off at the output token limit (#4810)

Gergő Móricze139f08f0529
diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.ts
index 5a49389a5..a0c8c3a3b 100644
--- a/apps/api/src/controllers/auth.ts
+++ b/apps/api/src/controllers/auth.ts
@@ -691,7 +691,7 @@ async function buildAuthenticatedRateLimiter(
return getAutumnRateLimiter(mode, multiplier, flags);
}
-export type AuthenticateOptions = {
+type AuthenticateOptions = {
allowKeyless?: boolean;
// Route opt-in: a trusted agent-interop request may authenticate with a
// hosted_mcp_oauth key, which agent runs started from the hosted MCP carry.
diff --git a/apps/api/src/scraper/scrapeURL/transformers/llmExtract-output-limit.test.ts b/apps/api/src/scraper/scrapeURL/transformers/llmExtract-output-limit.test.ts
new file mode 100644
index 000000000..61c051f4f
--- /dev/null
+++ b/apps/api/src/scraper/scrapeURL/transformers/llmExtract-output-limit.test.ts
@@ -0,0 +1,103 @@
+import { vi } from "vitest";
+
+vi.mock("ai", async importOriginal => {
+ const actual = await importOriginal<typeof import("ai")>();
+ return { ...actual, generateObject: vi.fn(), generateText: vi.fn() };
+});
+
+import { generateObject, generateText, NoObjectGeneratedError } from "ai";
+import type { Mock } from "vitest";
+import { generateCompletions, isTruncatedJson } from "./llmExtract";
+import { CostTracking } from "../../../lib/cost-tracking";
+
+const noopLogger = {
+ warn: () => {},
+ info: () => {},
+ error: () => {},
+ debug: () => {},
+ child: () => noopLogger,
+} as any;
+
+function run() {
+ return generateCompletions({
+ logger: noopLogger,
+ options: {
+ schema: {
+ type: "object",
+ properties: { items: { type: "array", items: { type: "string" } } },
+ },
+ },
+ markdown: "page",
+ model: { modelId: "gpt-4o-mini" } as any,
+ retryModel: { modelId: "gpt-4.1-mini" } as any,
+ costTrackingOptions: { costTracking: new CostTracking(), metadata: {} },
+ metadata: { teamId: "test-team" },
+ });
+}
+
+// Mirrors the SDK: the repair hook runs on the unparseable text, and the call
+// fails if it returns null.
+function respondWith(text: string, finishReason: "length" | "stop") {
+ (generateObject as Mock).mockImplementationOnce(async args => {
+ const repaired = await args.experimental_repairText({
+ text,
+ error: new Error("parse failed"),
+ });
+ if (repaired !== null) {
+ return {
+ object: JSON.parse(repaired),
+ usage: { inputTokens: 1, outputTokens: 1 },
+ };
+ }
+ throw new NoObjectGeneratedError({
+ message: "No object generated: could not parse the response.",
+ text,
+ response: {} as any,
+ usage: {} as any,
+ finishReason,
+ });
+ });
+}
+
+beforeEach(() => {
+ (generateObject as Mock).mockReset();
+ (generateText as Mock).mockReset();
+});
+
+describe("isTruncatedJson", () => {
+ it.each([
+ ['{"items": ["a", "b"', true],
+ ['{"items": ["a", "unterminated', true],
+ ['```json\n{"items": [', true],
+ ['{"quote": "\\"}', true],
+ ['{"items": ["a", "b"]}', false],
+ ['```json\n{"items": ["a"]}\n```', false],
+ ['{"brace": "}", "bracket": "["}', false],
+ ["not json at all", false],
+ ['{"items": [1, 2}', false],
+ ['[{"a": 1]', false],
+ ['{"a": 1}}', false],
+ ])("%s -> %s", (text, expected) => {
+ expect(isTruncatedJson(text)).toBe(expected);
+ });
+});
+
+describe("generateCompletions at the output token limit", () => {
+ it("returns nothing and skips the LLM repair when output was cut off", async () => {
+ respondWith('{"items": ["a", "b", "c', "length");
+
+ await expect(run()).rejects.toThrow(
+ "the extracted data exceeded the model's maximum output length",
+ );
+ expect(generateText).not.toHaveBeenCalled();
+ });
+
+ it("still repairs complete output wrapped in a code block", async () => {
+ respondWith('```json\n{"items": ["a"]}\n```', "stop");
+
+ const result = await run();
+
+ expect(result.extract).toEqual({ items: ["a"] });
+ expect(generateText).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/api/src/scraper/scrapeURL/transformers/llmExtract.ts b/apps/api/src/scraper/scrapeURL/transformers/llmExtract.ts
index 08aa15d22..9945a8175 100644
--- a/apps/api/src/scraper/scrapeURL/transformers/llmExtract.ts
+++ b/apps/api/src/scraper/scrapeURL/transformers/llmExtract.ts
@@ -158,6 +158,38 @@ function normalizeSchema(x: any): any {
}
}
+/**
+ * Whether text is JSON cut off before its end: an unclosed string, object or
+ * array. That only happens when the model ran out of output tokens, and no
+ * repair can recover the part that was never generated. A closing bracket that
+ * doesn't match the open one is malformed rather than cut off, so the repair
+ * still gets a chance at it.
+ */
+export function isTruncatedJson(text: string): boolean {
+ const open: string[] = [];
+ let inString = false;
+ let escaped = false;
+ for (const char of text) {
+ if (inString) {
+ if (escaped) escaped = false;
+ else if (char === "\\") escaped = true;
+ else if (char === '"') inString = false;
+ } else if (char === '"') {
+ inString = true;
+ } else if (char === "{" || char === "[") {
+ open.push(char);
+ } else if (char === "}" || char === "]") {
+ if (open.pop() !== (char === "}" ? "{" : "[")) return false;
+ }
+ }
+ return inString || open.length > 0;
+}
+
+// Thrown when structured output hit the model's output token limit. The
+// partial JSON is not returned.
+const OUTPUT_LIMIT_MESSAGE =
+ "the extracted data exceeded the model's maximum output length, so nothing was returned. Try a schema or prompt that asks for fewer items.";
+
interface TrimResult {
text: string;
numTokens: number;
@@ -606,6 +638,11 @@ export async function generateCompletions({
const repairConfig = {
experimental_repairText: async ({ text, error }) => {
+ // Output cut off at the token limit; see OUTPUT_LIMIT_MESSAGE.
+ if (typeof text === "string" && isTruncatedJson(text)) {
+ return null;
+ }
+
// AI may output a markdown JSON code block. Remove it - mogery
logger.debug("Repairing text", {
textType: typeof text,
@@ -889,6 +926,9 @@ export async function generateCompletions({
}
} else if (NoObjectGeneratedError.isInstance(error)) {
logger.warn("No object generated", { error });
+ if (error.finishReason === "length") {
+ throw new Error(OUTPUT_LIMIT_MESSAGE);
+ }
if (
error.text &&
error.text.startsWith("```json") &&