Skip to content

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

feat(api): add deterministic response hints and preserve them in SDKs

Eric Ciarla67541413c228
diff --git a/apps/api/AGENT_HINTS.md b/apps/api/AGENT_HINTS.md
new file mode 100644
index 000000000..452a532ac
--- /dev/null
+++ b/apps/api/AGENT_HINTS.md
@@ -0,0 +1,41 @@
+# Response guidance for agents
+
+The v2 `POST /search`, `/scrape`, `/parse`, and `/map` routes may return an optional top-level `agent_hints: string[]`. Each response contains at most three hints: one cross-endpoint suggestion, one distinct result-specific step, and a feedback request when the receiver supports the completed operation. Existing data, errors, warning fields, tool definitions, and HTTP statuses remain unchanged.
+
+Clients can suppress all hints for one request with:
+
+```http
+X-Firecrawl-Agent-Hints: false
+```
+
+The header applies to the business request. No request-body schema changes are required. SDKs and other adapters should retain the top-level field when unwrapping `data` and should preserve it on error results. The strings recommend conditional next steps; receiving one does not execute another request or indicate user authorization.
+
+## SDK and adapter delivery
+
+The accompanying JavaScript and Python SDK changes preserve `agent_hints` alongside normal flattened Document, SearchData, MapData, AlexandriaScrapeData, and FindToolsData results and on typed errors. Python covers synchronous and asynchronous clients. Markdown, HTML, and provider records retain their existing content.
+
+Raw HTTP callers can opt out with the header above. This change does not add a client-wide SDK hint option; applications can omit the metadata when passing results to a model. The SDK release must precede upgrading pinned CLI/MCP dependencies for their keyed SDK paths to retain the field.
+
+## Initial rules
+
+- Search/Scrape tool definitions: inspect tools that support the caller's task and execute through `/v2/scrape` using the documented inputs. Tool presence or a domain match does not establish relevance.
+- Search excerpts: offer Scrape when a web result has no markdown, HTML, or raw HTML. Inspect actual output per result, not the requested scrape setting.
+- Alexandria catalogue summaries: use the selected item's existing `next` call to obtain full definitions. Complete definitions do not trigger another expansion.
+- Alexandria catalogue continuation: follow the page's `next` only if more tools are needed. Provider-record pagination is not inferred from arbitrary `next` fields.
+- Empty catalogue with no continuation: offer web Search for the remaining need, without claiming the entire catalogue lacks a suitable provider.
+- Source page 404/410: offer Search for a current location or alternative. An API cache-miss 404, 429, authentication failure, or timeout does not fire this rule.
+- Typed Find Tools `invalid_option` rejecting a free-text `query`: direct it to `/v2/search` with the `alexandria` source. Other errors retain their original error information without speculative recovery advice.
+
+Selection reads only request/response fields already in memory. It makes no network/model calls, reads no session/database state, and does not scan page text or classify user intent. No hint appears solely to fill an available slot. Feedback remains independent of cross-product promotion.
+
+## Feedback eligibility
+
+Controllers explicitly identify completed jobs supported by `/v2/feedback`: ordinary Search, Scrape, Parse, and Map. The hint gives the endpoint discriminator, actual job ID, accepted rating values, and substantive evidence requirements. Search includes its configured submission window and rating-specific validation requirements. The agent must choose its own honest rating after assessing the result.
+
+Feedback hints are omitted for database-authentication-disabled deployments, preview teams, opted-out teams, zero-data-retention operations, unsuccessful responses, and paths without an explicitly registered feedback job. This version does not change feedback acceptance policy or persistence.
+
+Alexandria execution currently persists request/billing records rather than a row accepted by the feedback receiver's `scrapes` lookup. Its `scrape_id` is therefore **not** advertised as a valid feedback ID. Adding Alexandria feedback requires explicit receiver/persistence work. Feedback and status-polling routes are not decorated, avoiding recursive or per-poll feedback requests. Existing receiver idempotency applies to repeated submissions for the same endpoint/job.
+
+## Validation
+
+The focused selector tests exercise mixed tools/content, incomplete versus full definitions, catalogue paging, empty results, invalid Find Tools queries, error suppression, and the hint cap. Express route fixtures exercise response preservation, opt-out, feedback eligibility and unpersisted Alexandria IDs. Hosted snips cover a completed scrape, map opt-out, and validation failure through the actual API. The snips use the harness and existing test service; they are not a live paid API smoke test.
diff --git a/apps/api/src/__tests__/snips/v2/agent-hints.test.ts b/apps/api/src/__tests__/snips/v2/agent-hints.test.ts
new file mode 100644
index 000000000..ec71ef0a0
--- /dev/null
+++ b/apps/api/src/__tests__/snips/v2/agent-hints.test.ts
@@ -0,0 +1,65 @@
+import { describeIf, TEST_PRODUCTION, TEST_SUITE_WEBSITE } from "../lib";
+import request, { idmux, Identity, scrapeTimeout, TEST_API_URL } from "./lib";
+
+let identity: Identity;
+beforeAll(async () => {
+ identity = await idmux({
+ name: "agent-hints",
+ concurrency: 10,
+ credits: 1000,
+ });
+}, 20000);
+
+// Feedback requires the hosted database. The selector/route fixture tests also
+// exercise self-hosted and unavailable-feedback behavior without external calls.
+describeIf(TEST_PRODUCTION)("Agent hints", () => {
+ it(
+ "includes feedback for the actual completed scrape",
+ async () => {
+ const response = await request(TEST_API_URL)
+ .post("/v2/scrape")
+ .set("Authorization", `Bearer ${identity.apiKey}`)
+ .send({ url: TEST_SUITE_WEBSITE, timeout: scrapeTimeout });
+ expect(response.statusCode).toBe(200);
+ expect(response.body.success).toBe(true);
+ expect(response.body.agent_hints.length).toBeLessThanOrEqual(3);
+ expect(response.body.agent_hints.join(" ")).toContain(
+ "POST /v2/feedback",
+ );
+ expect(response.body.agent_hints.join(" ")).toContain(
+ '"endpoint":"scrape"',
+ );
+ expect(response.body.agent_hints.join(" ")).toContain(
+ response.body.data.metadata.scrapeId,
+ );
+ },
+ scrapeTimeout + 10000,
+ );
+
+ it(
+ "honors the opt-out header on a completed map",
+ async () => {
+ const response = await request(TEST_API_URL)
+ .post("/v2/map")
+ .set("Authorization", `Bearer ${identity.apiKey}`)
+ .set("X-Firecrawl-Agent-Hints", "false")
+ .send({ url: TEST_SUITE_WEBSITE, limit: 1, timeout: scrapeTimeout });
+ expect(response.statusCode).toBe(200);
+ expect(response.body).not.toHaveProperty("agent_hints");
+ },
+ scrapeTimeout + 10000,
+ );
+
+ it("preserves validation errors without inventing a feedback job", async () => {
+ const response = await request(TEST_API_URL)
+ .post("/v2/scrape")
+ .set("Authorization", `Bearer ${identity.apiKey}`)
+ .send({ url: "not-a-url" });
+ expect(response.statusCode).toBe(400);
+ expect(response.body.success).toBe(false);
+ expect(typeof response.body.error).toBe("string");
+ expect((response.body.agent_hints ?? []).join(" ")).not.toContain(
+ "/v2/feedback",
+ );
+ });
+});
diff --git a/apps/api/src/controllers/v2/map.ts b/apps/api/src/controllers/v2/map.ts
index 363ed14e2..772752bf4 100644
--- a/apps/api/src/controllers/v2/map.ts
+++ b/apps/api/src/controllers/v2/map.ts
@@ -1,3 +1,4 @@
+import { setAgentHintFeedback } from "../../middlewares/agent-hints";
import { Response } from "express";
import {
mapRequestSchema,
@@ -179,6 +180,8 @@ export async function mapController(
);
});
+ setAgentHintFeedback(res, mapId);
+
return res.status(200).json({
success: true,
id: mapId,
@@ -359,5 +362,7 @@ export async function mapController(
...(warning && { warning }),
};
+ setAgentHintFeedback(res, result.job_id);
+
return res.status(200).json(response);
}
diff --git a/apps/api/src/controllers/v2/parse.ts b/apps/api/src/controllers/v2/parse.ts
index c70846f03..a105fcf24 100644
--- a/apps/api/src/controllers/v2/parse.ts
+++ b/apps/api/src/controllers/v2/parse.ts
@@ -1,3 +1,4 @@
+import { setAgentHintFeedback } from "../../middlewares/agent-hints";
import { NextFunction, Request, Response } from "express";
import { config } from "../../config";
import { logger as _logger } from "../../lib/logger";
@@ -745,6 +746,8 @@ export async function parseController(
concurrencyQueueDurationMs: lockTime || undefined,
});
+ setAgentHintFeedback(res, jobId, zeroDataRetention);
+
return res.status(200).json({
success: true,
data: {
diff --git a/apps/api/src/controllers/v2/scrape.ts b/apps/api/src/controllers/v2/scrape.ts
index 83af538d8..ce8e754bc 100644
--- a/apps/api/src/controllers/v2/scrape.ts
+++ b/apps/api/src/controllers/v2/scrape.ts
@@ -1,3 +1,4 @@
+import { setAgentHintFeedback } from "../../middlewares/agent-hints";
import { Response } from "express";
import { providerScrapeController } from "./scrape-alexandria";
import { discoverTools } from "../../search/alexandria";
@@ -729,6 +730,8 @@ export async function scrapeController(
})
: undefined;
+ setAgentHintFeedback(res, jobId, zeroDataRetention);
+
return res.status(200).json({
success: true,
data: {
diff --git a/apps/api/src/controllers/v2/search.ts b/apps/api/src/controllers/v2/search.ts
index 656d6e6c3..db2ec90fb 100644
--- a/apps/api/src/controllers/v2/search.ts
+++ b/apps/api/src/controllers/v2/search.ts
@@ -1,3 +1,4 @@
+import { setAgentHintFeedback } from "../../middlewares/agent-hints";
import { NextFunction, Request, Response } from "express";
import { externalRequestId } from "../../lib/external-request-id";
import { config } from "../../config";
@@ -532,6 +533,8 @@ async function searchControllerInner(
scrapeful: result.shouldScrape,
});
+ setAgentHintFeedback(res, jobId, zeroDataRetention);
+
return res.status(200).json({
success: true,
data: result.response,
diff --git a/apps/api/src/controllers/v2/types.ts b/apps/api/src/controllers/v2/types.ts
index aa671ad2e..274566fe1 100644
--- a/apps/api/src/controllers/v2/types.ts
+++ b/apps/api/src/controllers/v2/types.ts
@@ -1541,6 +1541,7 @@ export type VideoItem = {
};
export type ErrorResponse = {
+ agent_hints?: string[];
success: false;
code?: ErrorCodes;
error: string;
@@ -1553,6 +1554,7 @@ export type ScrapeResponse =
| ErrorResponse
| {
success: true;
+ agent_hints?: string[];
warning?: string;
data: Document & {
tools?: import("../../services/alexandria/contracts").DiscoveredTool[];
@@ -1821,6 +1823,7 @@ export type MapResponse =
| ErrorResponse
| {
success: true;
+ agent_hints?: string[];
id: string;
links?: MapDocument[];
warning?: string;
@@ -2561,6 +2564,7 @@ export type SearchResponse =
| ErrorResponse
| {
success: true;
+ agent_hints?: string[];
warning?: string;
data: Document[];
creditsUsed: number;
@@ -2568,6 +2572,7 @@ export type SearchResponse =
}
| {
success: true;
+ agent_hints?: string[];
warning?: string;
data: import("../../lib/entities").SearchV2Response;
creditsUsed: number;
@@ -2575,6 +2580,7 @@ export type SearchResponse =
}
| {
success: true;
+ agent_hints?: string[];
warning?: string;
data: import("../../lib/entities").SearchV2Response;
scrapeIds: {
diff --git a/apps/api/src/lib/agent-hints.test.ts b/apps/api/src/lib/agent-hints.test.ts
new file mode 100644
index 000000000..bc5718993
--- /dev/null
+++ b/apps/api/src/lib/agent-hints.test.ts
@@ -0,0 +1,229 @@
+import { buildAgentHints, type AgentHintContext } from "./agent-hints";
+
+const jobId = "0199412e-7590-7000-8000-000000000001";
+const fullTool = {
+ provider: "zillow",
+ capability: "properties/property",
+ options: [],
+ response: { fields: [] },
+};
+const call = {
+ provider: "firecrawl",
+ capability: "find-tools",
+ options: { providers: ["zillow"] },
+};
+const catalogue = (data: unknown) => ({
+ success: true,
+ data: {
+ alexandria: [{ provider: "firecrawl", capability: "find-tools", data }],
+ },
+});
+const hints = (overrides: Partial<AgentHintContext>) =>
+ buildAgentHints({
+ endpoint: "search",
+ response: { success: true, data: {} },
+ ...overrides,
+ });
+
+describe("deterministic agent hints", () => {
+ it("keeps empty search feedback actionable and does not assume a positive rating", () => {
+ const result = hints({ feedbackJobId: jobId });
+ expect(result).toHaveLength(1);
+ expect(result[0]).toContain(`"jobId":"${jobId}"`);
+ expect(result[0]).toContain('"endpoint":"search"');
+ expect(result[0]).toContain("good, partial, or bad");
+ expect(result[0]).toContain("valuableSources");
+ expect(result[0]).toContain("missingContent");
+ expect(result[0]).not.toContain('"rating":"good"');
+ });
+
+ it("never labels tool count as relevance or expands full definitions again", () => {
+ const result = hints({
+ response: { success: true, data: { tools: [fullTool] } },
+ });
+ expect(result.join(" ")).toContain("matching your task");
+ expect(result.join(" ")).not.toMatch(
+ /relevant|rental|expand|next request/i,
+ );
+ });
+
+ it("checks missing full content per result and does not scrape everything", () => {
+ expect(
+ hints({
+ response: {
+ success: true,
+ data: { web: [{ url: "https://example.com", markdown: "full" }] },
+ },
+ }),
+ ).toEqual([]);
+ const result = hints({
+ response: {
+ success: true,
+ data: {
+ web: [
+ { url: "https://example.com", markdown: "full" },
+ { url: "https://example.org", description: "excerpt" },
+ ],
+ },
+ },
+ });
+ expect(result.join(" ")).toContain("POST /v2/scrape");
+ expect(result.join(" ").toLowerCase()).toContain("if you need");
+ });
+
+ it("selects only one cross-endpoint hint when both tools and excerpts exist", () => {
+ const result = hints({
+ response: {
+ success: true,
+ data: { tools: [fullTool], web: [{ url: "https://example.com" }] },
+ },
+ feedbackJobId: jobId,
+ });
+ expect(result).toHaveLength(2);
+ expect(result.join(" ")).not.toContain('"url"');
+ });
+
+ it("distinguishes summary expansion from catalogue paging within the three-hint cap", () => {
+ const result = hints({
+ endpoint: "scrape",
+ response: catalogue({ items: [{ next: call }], next: call }),
+ feedbackJobId: jobId,
+ });
+ expect(result.length).toBeLessThanOrEqual(3);
+ expect(result.join(" ")).toContain("full input and output definitions");
+ expect(result.join(" ")).toContain("item's next");
+ expect(result.join(" ")).not.toContain("More tools");
+ });
+
+ it("accepts a continuation with defaulted options", () => {
+ const result = hints({
+ endpoint: "scrape",
+ response: catalogue({
+ level: "tools",
+ items: [],
+ total: 12,
+ next: { provider: "firecrawl", capability: "find-tools" },
+ }),
+ });
+ expect(result.join(" ")).toContain("More tools");
+ expect(result.join(" ")).not.toContain("POST /v2/search");
+ });
+
+ it("offers web search for this empty lookup only when it has no continuation", () => {
+ expect(
+ hints({
+ endpoint: "scrape",
+ response: catalogue({ items: [], next: null }),
+ }).join(" "),
+ ).toContain("This catalogue lookup");
+ expect(
+ hints({
+ endpoint: "scrape",
+ response: catalogue({ items: [], next: call }),
+ }).join(" "),
+ ).not.toContain("POST /v2/search");
+ });
+
+ it("uses explicit page status instead of API 404s such as cache misses", () => {
+ const result = hints({
+ endpoint: "scrape",
+ response: { success: true, data: { metadata: { statusCode: 404 } } },
+ });
+ expect(result.join(" ")).toContain("POST /v2/search");
+ for (const code of [403, 429, 500]) {
+ expect(
+ hints({
+ endpoint: "scrape",
+ response: { success: true, data: { metadata: { statusCode: code } } },
+ }),
+ ).toEqual([]);
+ }
+ expect(
+ hints({
+ endpoint: "scrape",
+ response: {
+ success: false,
+ code: "SCRAPE_NO_CACHED_DATA",
+ error: "Not cached",
+ },
+ }),
+ ).toEqual([]);
+ });
+
+ it("prioritizes missing-page recovery over domain tool promotion", () => {
+ const result = hints({
+ endpoint: "scrape",
+ response: {
+ success: true,
+ data: { tools: [fullTool], metadata: { statusCode: 410 } },
+ },
+ });
+ expect(result.join(" ")).toContain("POST /v2/search");
+ expect(result.join(" ")).not.toContain("Alexandria tool definitions");
+ });
+
+ it("prioritizes a typed find-tools query correction over promotion and paging", () => {
+ const result = hints({
+ endpoint: "scrape",
+ request: { alexandria: { ...call, options: { query: "rentals" } } },
+ response: {
+ success: true,
+ data: {
+ alexandria: [
+ { ...call, error: { code: "invalid_option", message: "invalid" } },
+ ],
+ },
+ },
+ });
+ expect(result).toHaveLength(1);
+ expect(result[0]).toContain("does not accept query");
+ expect(result[0]).toContain('"query":"rentals"');
+ });
+
+ it("preserves a top-level typed rejection while supplying the query correction", () => {
+ const result = hints({
+ endpoint: "scrape",
+ request: { alexandria: { ...call, options: { query: "rentals" } } },
+ response: {
+ success: false,
+ code: "invalid_option",
+ error: "Find Tools does not take query",
+ },
+ });
+ expect(result).toHaveLength(1);
+ expect(result[0]).toContain("does not accept query");
+ expect(result[0]).not.toContain("/v2/feedback");
+ });
+
+ it("does not turn provider-result errors into a success workflow", () => {
+ expect(
+ hints({
+ endpoint: "scrape",
+ response: {
+ success: true,
+ data: {
+ alexandria: [{ error: { code: "unknown", message: "failed" } }],
+ },
+ },
+ }),
+ ).toEqual([]);
+ });
+
+ it("does not suggest feedback for failed searches even if identity is supplied", () => {
+ expect(
+ hints({
+ response: { success: false, error: "failed" },
+ feedbackJobId: jobId,
+ }),
+ ).toEqual([]);
+ });
+
+ it.each(["scrape", "parse", "map"] as const)(
+ "uses %s feedback identity and accepted substantive note",
+ endpoint => {
+ const result = hints({ endpoint, feedbackJobId: jobId });
+ expect(result.join(" ")).toContain(`"endpoint":"${endpoint}"`);
+ expect(result.join(" ")).toContain("note");
+ },
+ );
+});
diff --git a/apps/api/src/lib/agent-hints.ts b/apps/api/src/lib/agent-hints.ts
new file mode 100644
index 000000000..9f108f46e
--- /dev/null
+++ b/apps/api/src/lib/agent-hints.ts
@@ -0,0 +1,170 @@
+/** Response-only heuristics: no inference, I/O, or task/session state. */
+export type AgentHintEndpoint = "search" | "scrape" | "parse" | "map";
+export interface AgentHintContext {
+ endpoint: AgentHintEndpoint;
+ request?: unknown;
+ response: unknown;
+ /** Set only by a controller that created a feedback-supported job. */
+ feedbackJobId?: string;
+ searchFeedbackMaxAgeSec?: number;
+}
+
+type ObjectValue = Record<string, unknown>;
+function object(value: unknown): ObjectValue {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? (value as ObjectValue)
+ : {};
+}
+function array(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
+}
+function isCall(value: unknown): boolean {
+ const call = object(value);
+ return (
+ typeof call.provider === "string" &&
+ typeof call.capability === "string" &&
+ (call.options === undefined ||
+ (call.options !== null &&
+ typeof call.options === "object" &&
+ !Array.isArray(call.options)))
+ );
+}
+function fullDefinition(value: unknown): boolean {
+ const tool = object(value);
+ return Array.isArray(tool.options) && !!(tool.response || tool.returns);
+}
+
+const inspectTools =
+ 'Alexandria tool definitions are included. Inspect those matching your task, including required inputs and supported operations; execute a selected tool with POST /v2/scrape and {"alexandria":{"provider":"<tool provider>","capability":"<tool capability>","options":{"<input name>":"<value from your task>"}}}. Replace placeholders using its definition; do not assume a domain match supports your task.';
+const expandTool =
+ 'These are tool summaries. For a tool matching your task, send POST /v2/scrape with {"alexandria": <that item\'s next object>} to obtain its full input and output definitions before execution.';
+const pageTools =
+ 'More tools are available in this catalogue lookup. If the items shown do not cover your task, send POST /v2/scrape with {"alexandria": <this catalogue page\'s next object>}. This fetches another catalogue page, not provider records.';
+const searchWeb =
+ 'This catalogue lookup returned no tools and no next page. If it does not cover your task, use POST /v2/search with {"query":"<remaining research need>","sources":["web"]}; this does not imply that every Alexandria provider was searched.';
+
+function feedbackHint(context: AgentHintContext): string | undefined {
+ if (!context.feedbackJobId || object(context.response).success !== true)
+ return;
+ const identity = JSON.stringify({
+ endpoint: context.endpoint,
+ jobId: context.feedbackJobId,
+ });
+ const prefix = `After evaluating this ${context.endpoint} result, submit feedback once via POST /v2/feedback. Use ${identity}, add rating chosen honestly from good, partial, or bad, and add evidence. `;
+ if (context.endpoint === "search") {
+ const window =
+ context.searchFeedbackMaxAgeSec && context.searchFeedbackMaxAgeSec > 0
+ ? ` Submit within ${context.searchFeedbackMaxAgeSec} seconds of this search.`
+ : "";
+ return (
+ prefix +
+ `For good, include valuableSources:[{url,reason}]; for partial, include valuableSources or missingContent:[{topic,description}]; for bad, include missingContent or querySuggestions. Report useful sources as well as missing, stale, or irrelevant information; do not rate success from the HTTP status alone. Add metadata:{"assessmentSource":"agent"} for an agent assessment.` +
+ window
+ );
+ }
+ return (
+ prefix +
+ 'Include note with what was useful and what was missing or incorrect. An optional metadata:{"assessmentSource":"agent"} identifies an agent assessment. Do not submit again for a retry of this same job.'
+ );
+}
+
+export function buildAgentHints(context: AgentHintContext): string[] {
+ const response = object(context.response);
+ const data = object(response.data);
+ const request = object(context.request);
+ const providerResults = array(data.alexandria);
+ let crossEndpoint: string | undefined;
+ let resultStep: string | undefined;
+
+ // A typed upstream rejection must not be disguised as a successful workflow.
+ const providerError = providerResults
+ .map(object)
+ .find(result => result.error);
+ const typedError = providerError
+ ? object(providerError.error)
+ : response.success === false
+ ? object(typeof response.error === "object" ? response.error : response)
+ : undefined;
+ if (typedError) {
+ const calls = Array.isArray(request.alexandria)
+ ? request.alexandria
+ : [request.alexandria];
+ const invalidQuery = calls
+ .map(object)
+ .find(
+ call =>
+ call.provider === "firecrawl" &&
+ call.capability === "find-tools" &&
+ typeof object(call.options).query === "string",
+ );
+ if (typedError.code === "invalid_option" && invalidQuery) {
+ const query = String(object(invalidQuery.options).query).slice(0, 500);
+ resultStep = `Find Tools does not accept query. For free-text discovery use POST /v2/search with ${JSON.stringify({ query, sources: ["alexandria"] })}. For provider filters, use the accepted options listed in the error before retrying.`;
+ }
+ } else if (response.success === true) {
+ const tools = array(data.tools);
+ const catalogues = providerResults
+ .map(object)
+ .filter(
+ result =>
+ result.provider === "firecrawl" && result.capability === "find-tools",
+ )
+ .map(result => object(result.data));
+ const catalogueItems = catalogues.flatMap(catalogue =>
+ array(catalogue.items),
+ );
+ const summaries = [...tools, ...catalogueItems].some(
+ tool => !fullDefinition(tool) && isCall(object(tool).next),
+ );
+ if (summaries) resultStep = expandTool;
+ else if (catalogues.some(catalogue => isCall(catalogue.next)))
+ resultStep = pageTools;
+
+ const pageStatus = object(data.metadata).statusCode;
+ if (
+ context.endpoint === "scrape" &&
+ (pageStatus === 404 || pageStatus === 410)
+ ) {
+ crossEndpoint =
+ 'The source page returned 404 or 410. If you need its current location or an alternative, use POST /v2/search with {"query":"<page name or subject>","sources":["web"]}. Use the page identity from your task; this is not a transient-error retry.';
+ resultStep = undefined;
+ } else if ([...tools, ...catalogueItems].some(fullDefinition)) {
+ crossEndpoint = inspectTools;
+ } else if (
+ catalogues.length > 0 &&
+ catalogues.every(
+ catalogue =>
+ Array.isArray(catalogue.items) &&
+ catalogue.items.length === 0 &&
+ !catalogue.next,
+ )
+ ) {
+ crossEndpoint = searchWeb;
+ } else if (context.endpoint === "search") {
+ const web = Array.isArray(response.data)
+ ? response.data
+ : array(data.web);
+ if (
+ web.some(value => {
+ const item = object(value);
+ return (
+ typeof item.url === "string" &&
+ !item.markdown &&
+ !item.html &&
+ !item.rawHtml
+ );
+ })
+ ) {
+ crossEndpoint =
+ 'Some web results have no full page content. If you need more than an excerpt, use POST /v2/scrape with {"url":"<selected result URL>","formats":["markdown"]}. Retrieve only needed pages; do not re-scrape results that already contain the required content.';
+ }
+ }
+ }
+
+ // Separate slots keep feedback present while bounding promotions and next steps.
+ const feedback = feedbackHint(context);
+ return [resultStep, crossEndpoint, feedback]
+ .filter((hint): hint is string => !!hint)
+ .filter((hint, index, hints) => hints.indexOf(hint) === index)
+ .slice(0, 3);
+}
diff --git a/apps/api/src/middlewares/__tests__/agent-hints.test.ts b/apps/api/src/middlewares/__tests__/agent-hints.test.ts
new file mode 100644
index 000000000..fa5b660be
--- /dev/null
+++ b/apps/api/src/middlewares/__tests__/agent-hints.test.ts
@@ -0,0 +1,96 @@
+import express from "express";
+import request from "supertest";
+import { config } from "../../config";
+import { agentHintsMiddleware, setAgentHintFeedback } from "../agent-hints";
+
+vi.mock("../../config", () => ({ config: { USE_DB_AUTHENTICATION: true } }));
+const jobId = "0199412e-7590-7000-8000-000000000001";
+function appFor(
+ {
+ endpoint = "search",
+ body = { success: true, data: {} },
+ status = 200,
+ feedback = true,
+ zdr = false,
+ preview = false,
+ optOut = false,
+ } = {} as any,
+) {
+ const app = express();
+ app.use(express.json());
+ app.post("/", agentHintsMiddleware(endpoint), (req, res) => {
+ Object.assign(req, {
+ auth: { team_id: preview ? "preview_keyless_x" : "team" },
+ acuc: { flags: { searchFeedbackOptOut: optOut } },
+ });
+ if (feedback) setAgentHintFeedback(res, jobId, zdr);
+ res.status(status).json(body);
+ });
+ return app;
+}
+
+describe("agent hint response middleware", () => {
+ it("adds top-level metadata without changing data or warning", async () => {
+ const body = { success: true, data: { web: [] }, warning: "existing" };
+ const response = await request(appFor({ body })).post("/").send({});
+ expect(response.statusCode).toBe(200);
+ expect(response.body).toMatchObject(body);
+ expect(response.body.agent_hints).toHaveLength(1);
+ });
+
+ it("opt-out header preserves the original envelope", async () => {
+ const body = {
+ success: true,
+ data: { tools: [{ options: [], response: {} }] },
+ };
+ const response = await request(appFor({ body }))
+ .post("/")
+ .set("X-Firecrawl-Agent-Hints", "false")
+ .send({});
+ expect(response.body).toEqual(body);
+ });
+
+ it.each([
+ { preview: true },
+ { optOut: true },
+ { zdr: true },
+ { feedback: false },
+ ])("does not invent accepted feedback for %j", async settings => {
+ const response = await request(appFor(settings)).post("/").send({});
+ expect(response.body).not.toHaveProperty("agent_hints");
+ });
+
+ it("omits feedback when database authentication is unavailable", async () => {
+ config.USE_DB_AUTHENTICATION = false;
+ try {
+ const response = await request(appFor()).post("/").send({});
+ expect(response.body).not.toHaveProperty("agent_hints");
+ } finally {
+ config.USE_DB_AUTHENTICATION = true;
+ }
+ });
+
+ it("preserves failure status, code, and details without bogus feedback", async () => {
+ const body = {
+ success: false,
+ error: "Bad URL",
+ code: "BAD_REQUEST",
+ details: [{ field: "url" }],
+ };
+ const response = await request(appFor({ body, status: 400 }))
+ .post("/")
+ .send({});
+ expect(response.statusCode).toBe(400);
+ expect(response.body).toEqual(body);
+ });
+
+ it("does not attach feedback to an unpersisted Alexandria scrape id", async () => {
+ const body = { success: true, scrape_id: jobId, data: { alexandria: [] } };
+ const response = await request(
+ appFor({ endpoint: "scrape", body, feedback: false }),
+ )
+ .post("/")
+ .send({ alexandria: [] });
+ expect(response.body).toEqual(body);
+ });
+});
diff --git a/apps/api/src/middlewares/agent-hints.ts b/apps/api/src/middlewares/agent-hints.ts
new file mode 100644
index 000000000..c6c5a72d7
--- /dev/null
+++ b/apps/api/src/middlewares/agent-hints.ts
@@ -0,0 +1,52 @@
+import type { RequestHandler, Response } from "express";
+import { config } from "../config";
+import { buildAgentHints, type AgentHintEndpoint } from "../lib/agent-hints";
+import type { RequestWithAuth } from "../controllers/v2/types";
+
+/** Controllers opt in only after producing a feedback-supported job. */
+export function setAgentHintFeedback(
+ res: Response,
+ jobId: string,
+ zeroDataRetention: boolean = false,
+): void {
+ res.locals ??= {};
+ res.locals.agentHintFeedback = { jobId, zeroDataRetention };
+}
+
+/** Only registered on business POST routes, never feedback or polling routes. */
+export function agentHintsMiddleware(
+ endpoint: AgentHintEndpoint,
+): RequestHandler {
+ return (req, res, next) => {
+ if (req.get("X-Firecrawl-Agent-Hints")?.trim().toLowerCase() === "false")
+ return next();
+ const json = res.json;
+ res.json = function (body) {
+ if (!body || typeof body !== "object" || Array.isArray(body))
+ return json.call(this, body);
+ const authReq = req as RequestWithAuth<any, any, any>;
+ const teamId = authReq.auth?.team_id;
+ const feedback = res.locals.agentHintFeedback;
+ const canSubmitFeedback =
+ config.USE_DB_AUTHENTICATION === true &&
+ typeof teamId === "string" &&
+ teamId !== "preview" &&
+ !teamId.startsWith("preview_") &&
+ authReq.acuc?.flags?.searchFeedbackOptOut !== true &&
+ feedback &&
+ !feedback.zeroDataRetention;
+ const hints = buildAgentHints({
+ endpoint,
+ request: req.body,
+ response: body,
+ feedbackJobId: canSubmitFeedback ? feedback.jobId : undefined,
+ searchFeedbackMaxAgeSec: config.SEARCH_FEEDBACK_MAX_AGE_SEC,
+ });
+ return json.call(
+ this,
+ hints.length > 0 ? { ...body, agent_hints: hints } : body,
+ );
+ };
+ next();
+ };
+}
diff --git a/apps/api/src/routes/v2.ts b/apps/api/src/routes/v2.ts
index 309d15ba0..d25751954 100644
--- a/apps/api/src/routes/v2.ts
+++ b/apps/api/src/routes/v2.ts
@@ -1,3 +1,4 @@
+import { agentHintsMiddleware } from "../middlewares/agent-hints";
import express from "express";
import multer from "multer";
import { config } from "../config";
@@ -189,6 +190,7 @@ registerMcpActionLogReadRoute(
v2Router.post(
"/search",
+ agentHintsMiddleware("search"),
researchCategoryNoticeMiddleware,
authMiddleware(RateLimiterMode.Search, { allowKeyless: true }),
countryCheck,
@@ -226,6 +228,7 @@ v2Router.put(
v2Router.post(
"/parse",
+ agentHintsMiddleware("parse"),
authMiddleware(RateLimiterMode.Scrape, { allowKeyless: true }),
countryCheck,
checkCreditsMiddleware(1),
@@ -235,6 +238,7 @@ v2Router.post(
v2Router.post(
"/scrape",
+ agentHintsMiddleware("scrape"),
authMiddleware(RateLimiterMode.Scrape, { allowKeyless: true }),
countryCheck,
checkCreditsMiddleware(1),
@@ -274,6 +278,7 @@ v2Router.post(
v2Router.post(
"/map",
+ agentHintsMiddleware("map"),
authMiddleware(RateLimiterMode.Map),
checkCreditsMiddleware(1),
blocklistMiddleware,
diff --git a/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-hints.test.ts b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-hints.test.ts
new file mode 100644
index 000000000..15e6c2b63
--- /dev/null
+++ b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/agent-hints.test.ts
@@ -0,0 +1,155 @@
+import { describe, expect, it, jest } from "@jest/globals";
+import { search } from "../../../v2/methods/search";
+import { scrape } from "../../../v2/methods/scrape";
+import { parse } from "../../../v2/methods/parse";
+import { map } from "../../../v2/methods/map";
+import { findTools, scrapeAlexandria } from "../../../v2/methods/tools";
+import {
+ normalizeAxiosError,
+ throwForBadResponse,
+} from "../../../v2/utils/errorHandler";
+
+const hints = [
+ "Inspect the returned definitions before choosing a tool.",
+ "Evaluate this result before submitting feedback.",
+];
+function httpFor(body: object) {
+ return {
+ post: jest.fn<any>().mockResolvedValue({ status: 200, data: body }),
+ postMultipart: jest
+ .fn<any>()
+ .mockResolvedValue({ status: 200, data: body }),
+ } as any;
+}
+
+describe("agent hints survive SDK response unwrapping", () => {
+ it("preserves hints for empty searches without adding them to records", async () => {
+ const result = await search(
+ httpFor({ success: true, data: { web: [] }, agent_hints: hints }),
+ { query: "test" },
+ );
+ expect(result.web).toEqual([]);
+ expect(result.agent_hints).toEqual(hints);
+ expect(JSON.parse(JSON.stringify(result)).agent_hints).toEqual(hints);
+ });
+
+ it("keeps existing search output unchanged when hints are absent", async () => {
+ const result = await search(httpFor({ success: true, data: { web: [] } }), {
+ query: "test",
+ });
+ expect(Object.keys(result)).toEqual(["web"]);
+ });
+
+ it.each(["scrape", "parse"])(
+ "keeps %s hints separate from document content",
+ async (method) => {
+ const http = httpFor({
+ success: true,
+ data: { markdown: "# Page" },
+ agent_hints: hints,
+ });
+ const result =
+ method === "scrape"
+ ? await scrape(http, "https://example.com")
+ : await parse(http, { filename: "page.txt", data: "Page" });
+ expect(result.markdown).toBe("# Page");
+ expect(result.agent_hints).toEqual(hints);
+ },
+ );
+
+ it("preserves map metadata alongside normalized links", async () => {
+ const result = await map(
+ httpFor({
+ success: true,
+ id: "map-id",
+ links: ["https://example.com"],
+ agent_hints: hints,
+ }),
+ "https://example.com",
+ );
+ expect(result).toEqual({
+ id: "map-id",
+ links: [{ url: "https://example.com" }],
+ agent_hints: hints,
+ });
+ });
+
+ it("preserves hints for Alexandria and its Find Tools convenience method", async () => {
+ const body = {
+ success: true,
+ scrape_id: "scrape-id",
+ agent_hints: hints,
+ data: {
+ creditsCost: 0,
+ alexandria: [{ data: { level: "tools", total: 0, items: [] } }],
+ },
+ };
+ const result = await scrapeAlexandria(httpFor(body), [
+ { provider: "firecrawl", capability: "find-tools" },
+ ]);
+ expect(result.agent_hints).toEqual(hints);
+ expect((await findTools(httpFor(body))).agent_hints).toEqual(hints);
+ });
+
+ it("keeps hints when Find Tools returns a nested validation error", async () => {
+ const http = httpFor({
+ success: true,
+ agent_hints: hints,
+ data: {
+ creditsCost: 0,
+ alexandria: [
+ {
+ error: {
+ message: "Invalid options",
+ status: 400,
+ code: "invalid_option",
+ },
+ },
+ ],
+ },
+ });
+ await expect(findTools(http)).rejects.toMatchObject({
+ code: "invalid_option",
+ agent_hints: hints,
+ });
+ });
+
+ it.each([null, "unexpected", [123]])(
+ "ignores malformed optional hints: %j",
+ async (value) => {
+ const result = await search(
+ httpFor({ success: true, data: {}, agent_hints: value }),
+ { query: "test" },
+ );
+ expect(result).not.toHaveProperty("agent_hints");
+ },
+ );
+
+ it("preserves hints on HTTP and Axios errors without changing their status", () => {
+ const response = {
+ status: 400,
+ data: {
+ success: false,
+ code: "INVALID",
+ error: "Invalid request",
+ agent_hints: hints,
+ },
+ } as any;
+ for (const raise of [
+ () => throwForBadResponse(response, "search"),
+ () =>
+ normalizeAxiosError({ response, isAxiosError: true } as any, "search"),
+ ]) {
+ try {
+ raise();
+ throw new Error("Expected SDK error");
+ } catch (error) {
+ expect(error).toMatchObject({
+ status: 400,
+ code: "INVALID",
+ agent_hints: hints,
+ });
+ }
+ }
+ });
+});
diff --git a/apps/js-sdk/firecrawl/src/v2/methods/map.ts b/apps/js-sdk/firecrawl/src/v2/methods/map.ts
index 2bc493e2d..a2816d70f 100644
--- a/apps/js-sdk/firecrawl/src/v2/methods/map.ts
+++ b/apps/js-sdk/firecrawl/src/v2/methods/map.ts
@@ -1,5 +1,6 @@
import { type MapData, type MapOptions, type SearchResultWeb } from "../types";
import { HttpClient } from "../utils/httpClient";
+import { agentHintMetadata } from "../utils/agentHints";
import {
throwForBadResponse,
normalizeAxiosError,
@@ -65,7 +66,7 @@ export async function map(
description: (item as any).description,
});
}
- return { id: res.data.id, links };
+ return { id: res.data.id, links, ...agentHintMetadata(res.data) };
} catch (err: any) {
if (err?.isAxiosError) return normalizeAxiosError(err, "map");
throw err;
diff --git a/apps/js-sdk/firecrawl/src/v2/methods/parse.ts b/apps/js-sdk/firecrawl/src/v2/methods/parse.ts
index 2de04ab1d..d85f90cc8 100644
--- a/apps/js-sdk/firecrawl/src/v2/methods/parse.ts
+++ b/apps/js-sdk/firecrawl/src/v2/methods/parse.ts
@@ -1,5 +1,6 @@
import { type Document, type ParseFile, type ParseOptions } from "../types";
import { HttpClient } from "../utils/httpClient";
+import { agentHintMetadata } from "../utils/agentHints";
import { ensureValidParseOptions } from "../utils/validation";
import {
throwForBadResponse,
@@ -88,7 +89,7 @@ export async function parse(
if (res.status !== 200 || !res.data?.success) {
throwForBadResponse(res, "parse");
}
- return (res.data.data || {}) as Document;
+ return { ...res.data.data, ...agentHintMetadata(res.data) };
} catch (err: any) {
if (err?.isAxiosError) return normalizeAxiosError(err, "parse");
throw err;
diff --git a/apps/js-sdk/firecrawl/src/v2/methods/scrape.ts b/apps/js-sdk/firecrawl/src/v2/methods/scrape.ts
index 02243ba54..9d1369b80 100644
--- a/apps/js-sdk/firecrawl/src/v2/methods/scrape.ts
+++ b/apps/js-sdk/firecrawl/src/v2/methods/scrape.ts
@@ -6,6 +6,7 @@ import {
type ScrapeOptions,
} from "../types";
import { HttpClient } from "../utils/httpClient";
+import { agentHintMetadata } from "../utils/agentHints";
import { ensureValidScrapeOptions } from "../utils/validation";
import {
throwForBadResponse,
@@ -131,7 +132,7 @@ export async function scrape(
if (res.status !== 200 || !res.data?.success) {
throwForBadResponse(res, "scrape");
}
- return (res.data.data || {}) as Document;
+ return { ...res.data.data, ...agentHintMetadata(res.data) };
} catch (err: any) {
const delayMs = autoResume !== false ? processingContinuesDelayMs(err) : undefined;
if (
diff --git a/apps/js-sdk/firecrawl/src/v2/methods/search.ts b/apps/js-sdk/firecrawl/src/v2/methods/search.ts
index 495e9d95e..08509ca2e 100644
--- a/apps/js-sdk/firecrawl/src/v2/methods/search.ts
+++ b/apps/js-sdk/firecrawl/src/v2/methods/search.ts
@@ -8,6 +8,7 @@ import {
type SearchResultImages,
} from "../types";
import { HttpClient } from "../utils/httpClient";
+import { agentHintMetadata } from "../utils/agentHints";
import { ensureValidScrapeOptions } from "../utils/validation";
import {
throwForBadResponse,
@@ -101,7 +102,7 @@ export async function search(
throwForBadResponse(res, "search");
}
const data = (res.data.data || {}) as Record<string, any>;
- const out: SearchData = {};
+ const out: SearchData = { ...agentHintMetadata(res.data) };
if (res.data.warning) out.warning = res.data.warning;
if (data.web) out.web = transformArray<SearchResultWeb>(data.web);
if (data.news) out.news = transformArray<SearchResultNews>(data.news);
diff --git a/apps/js-sdk/firecrawl/src/v2/methods/tools.ts b/apps/js-sdk/firecrawl/src/v2/methods/tools.ts
index 1ec3c0517..e3190fb6d 100644
--- a/apps/js-sdk/firecrawl/src/v2/methods/tools.ts
+++ b/apps/js-sdk/firecrawl/src/v2/methods/tools.ts
@@ -8,6 +8,7 @@ import type {
} from "../types";
import { SdkError } from "../types";
import { HttpClient } from "../utils/httpClient";
+import { agentHintMetadata } from "../utils/agentHints";
import {
normalizeAxiosError,
throwForBadResponse,
@@ -102,6 +103,7 @@ export async function scrapeAlexandria(
requestId,
alexandria: data.alexandria,
creditsCost: data.creditsCost,
+ ...agentHintMetadata(res.data),
};
} catch (err: any) {
try {
@@ -132,6 +134,7 @@ export async function findTools(
throw Object.assign(
new SdkError(item.error.message, item.error.status, item.error.code),
{ requestId: result.requestId },
+ agentHintMetadata(result),
);
- return item.data as FindToolsData;
+ return { ...(item.data as FindToolsData), ...agentHintMetadata(result) };
}
diff --git a/apps/js-sdk/firecrawl/src/v2/types.ts b/apps/js-sdk/firecrawl/src/v2/types.ts
index 3a34094e8..eb0312c6e 100644
--- a/apps/js-sdk/firecrawl/src/v2/types.ts
+++ b/apps/js-sdk/firecrawl/src/v2/types.ts
@@ -678,6 +678,8 @@ export interface DocumentMetadata {
}
export interface Document {
+ /** API guidance, separate from extracted page content. */
+ agent_hints?: string[];
markdown?: string;
html?: string;
rawHtml?: string;
@@ -820,6 +822,7 @@ export interface SearchResultImages {
}
export interface SearchData {
+ agent_hints?: string[];
warning?: string;
web?: Array<SearchResultWeb | Document>;
news?: Array<SearchResultNews | Document>;
@@ -882,6 +885,7 @@ export interface FindToolsOptions {
}
export interface FindToolsData {
+ agent_hints?: string[];
level: "providers" | "groups" | "tools";
items: Array<{
id: string;
@@ -932,6 +936,7 @@ export type AlexandriaScrapeResult =
};
export interface AlexandriaScrapeData {
+ agent_hints?: string[];
scrapeId: string;
requestId: string;
alexandria: AlexandriaScrapeResult[];
@@ -1086,6 +1091,7 @@ export interface BatchScrapeJob {
}
export interface MapData {
+ agent_hints?: string[];
id?: string;
links: SearchResultWeb[];
}
@@ -1876,6 +1882,7 @@ export function parseRequiresAction(value: unknown): RequiresAction | undefined
}
export class SdkError extends Error {
+ declare agent_hints?: string[];
requestId?: string;
status?: number;
code?: string;
diff --git a/apps/js-sdk/firecrawl/src/v2/utils/agentHints.ts b/apps/js-sdk/firecrawl/src/v2/utils/agentHints.ts
new file mode 100644
index 000000000..f0b973496
--- /dev/null
+++ b/apps/js-sdk/firecrawl/src/v2/utils/agentHints.ts
@@ -0,0 +1,7 @@
+/** Keep response guidance as metadata when convenience methods unwrap data. */
+export function agentHintMetadata(body: unknown): { agent_hints?: string[] } {
+ const hints = (body as { agent_hints?: unknown } | null)?.agent_hints;
+ return Array.isArray(hints) && hints.every((hint) => typeof hint === "string")
+ ? { agent_hints: [...hints] }
+ : {};
+}
diff --git a/apps/js-sdk/firecrawl/src/v2/utils/errorHandler.ts b/apps/js-sdk/firecrawl/src/v2/utils/errorHandler.ts
index 1da04eb71..e14dd5ace 100644
--- a/apps/js-sdk/firecrawl/src/v2/utils/errorHandler.ts
+++ b/apps/js-sdk/firecrawl/src/v2/utils/errorHandler.ts
@@ -1,11 +1,12 @@
import { type AxiosError, type AxiosResponse } from "axios";
import { SdkError, JobTimeoutError, parseRequiresAction } from "../types";
+import { agentHintMetadata } from "./agentHints";
export function throwForBadResponse(resp: AxiosResponse, action: string): never {
const status = resp.status;
const body = resp.data || {};
const msg = body?.error || body?.message || `Request failed (${status}) while trying to ${action}`;
- throw new SdkError(
+ throw Object.assign(new SdkError(
msg,
status,
body?.code,
@@ -13,7 +14,7 @@ export function throwForBadResponse(resp: AxiosResponse, action: string): never
undefined,
body?.chargeId,
parseRequiresAction(body?.requiresAction),
- );
+ ), agentHintMetadata(body));
}
export function normalizeAxiosError(err: AxiosError, action: string): never {
@@ -21,7 +22,7 @@ export function normalizeAxiosError(err: AxiosError, action: string): never {
const body: any = err.response?.data;
const message = body?.error || err.message || `Request failed${status ? ` (${status})` : ""} while trying to ${action}`;
const code = (body?.code as string) || err.code;
- throw new SdkError(
+ throw Object.assign(new SdkError(
message,
status,
code,
@@ -29,7 +30,7 @@ export function normalizeAxiosError(err: AxiosError, action: string): never {
undefined,
body?.chargeId,
parseRequiresAction(body?.requiresAction),
- );
+ ), agentHintMetadata(body));
}
export function isRetryableError(err: any): boolean {
@@ -64,4 +65,3 @@ export function isRetryableError(err: any): boolean {
// Default: retry on unknown errors (safer than not retrying)
return true;
}
-
diff --git a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent_hints.py b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent_hints.py
new file mode 100644
index 000000000..3de51ce71
--- /dev/null
+++ b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_agent_hints.py
@@ -0,0 +1,110 @@
+"""Envelope hints remain visible after sync/async SDK convenience methods."""
+from unittest.mock import AsyncMock, Mock
+from types import SimpleNamespace
+
+import pytest
+
+from firecrawl.v2.types import SearchRequest
+from firecrawl.v2.methods.search import search
+from firecrawl.v2.methods.scrape import scrape, _parse_scrape_alexandria_response
+from firecrawl.v2.methods.parse import parse
+from firecrawl.v2.methods.map import map as map_urls
+from firecrawl.v2.methods.aio.search import search as async_search
+from firecrawl.v2.methods.aio.scrape import scrape as async_scrape
+from firecrawl.v2.methods.aio.parse import parse as async_parse
+from firecrawl.v2.methods.aio.map import map as async_map
+from firecrawl.v2.utils.error_handler import FirecrawlError, handle_response_error
+from firecrawl.v2.client import FirecrawlClient
+from firecrawl.v2.client_async import AsyncFirecrawlClient
+
+
+HINTS = ["Inspect tool definitions before choosing a tool.", "Evaluate the result before submitting feedback."]
+
+
+def response(body, status=200):
+ result = Mock(status_code=status, ok=status < 400)
+ result.json.return_value = body
+ return result
+
+
+def body():
+ return {"success": True, "data": {"markdown": "# Page", "web": []}, "links": [], "agent_hints": HINTS}
+
+
[email protected]("operation", ["search", "scrape", "parse", "map"])
+def test_sync_hints_survive_unwrapping(operation):
+ client = Mock()
+ client.post.return_value = client.post_multipart.return_value = response(body())
+ calls = {
+ "search": lambda: search(client, SearchRequest(query="test")),
+ "scrape": lambda: scrape(client, "https://example.com"),
+ "parse": lambda: parse(client, b"Page", filename="page.txt"),
+ "map": lambda: map_urls(client, "https://example.com"),
+ }
+ result = calls[operation]()
+ assert result.agent_hints == HINTS
+ assert result.model_dump(exclude_none=True)["agent_hints"] == HINTS
+ if operation in ("scrape", "parse"):
+ assert result.markdown == "# Page"
+
+
[email protected]("operation", ["search", "scrape", "parse", "map"])
+async def test_async_hints_survive_unwrapping(operation):
+ client = Mock()
+ client.post = AsyncMock(return_value=response(body()))
+ client.post_multipart = AsyncMock(return_value=response(body()))
+ calls = {
+ "search": lambda: async_search(client, SearchRequest(query="test")),
+ "scrape": lambda: async_scrape(client, "https://example.com"),
+ "parse": lambda: async_parse(client, b"Page", filename="page.txt"),
+ "map": lambda: async_map(client, "https://example.com"),
+ }
+ result = await calls[operation]()
+ assert result.agent_hints == HINTS
+
+
+def test_alexandria_preserves_outer_hints():
+ result = _parse_scrape_alexandria_response({"success": True, "agent_hints": HINTS, "data": {"alexandria": [], "creditsCost": 0}}, "request-id")
+ assert result.agent_hints == HINTS
+ assert result.request_id == "request-id"
+
+
[email protected]("failed", [False, True])
+async def test_find_tools_convenience_methods_preserve_hints(failed):
+ error = SimpleNamespace(message="Invalid options", status=400, code="invalid_option", charge_id=None) if failed else None
+ result = SimpleNamespace(
+ alexandria=[SimpleNamespace(error=error, data={"level": "tools", "items": [], "total": 0})],
+ request_id="request-id", agent_hints=HINTS,
+ )
+ sync_client = FirecrawlClient(api_key="test")
+ async_client = AsyncFirecrawlClient(api_key="test")
+ sync_client.scrape_alexandria = Mock(return_value=result)
+ async_client.scrape_alexandria = AsyncMock(return_value=result)
+ if failed:
+ with pytest.raises(FirecrawlError) as sync_error:
+ sync_client.find_tools()
+ with pytest.raises(FirecrawlError) as async_error:
+ await async_client.find_tools()
+ assert sync_error.value.agent_hints == async_error.value.agent_hints == HINTS
+ else:
+ assert sync_client.find_tools().agent_hints == HINTS
+ assert (await async_client.find_tools()).agent_hints == HINTS
+
+
[email protected]("value", [None, "unexpected", [123]])
+def test_malformed_hints_do_not_break_search(value):
+ client = Mock()
+ client.post.return_value = response({"success": True, "data": {}, "agent_hints": value})
+ result = search(client, SearchRequest(query="test"))
+ assert result.agent_hints is None
+ assert "agent_hints" not in result.model_dump(exclude_none=True)
+
+
+def test_error_keeps_status_and_hints():
+ with pytest.raises(FirecrawlError) as raised:
+ handle_response_error(response({"success": False, "error": "Invalid request", "code": "INVALID", "agent_hints": HINTS}, 400), "search")
+ assert raised.value.status_code == 400
+ assert raised.value.code == "INVALID"
+ assert raised.value.agent_hints == HINTS
diff --git a/apps/python-sdk/firecrawl/v2/client.py b/apps/python-sdk/firecrawl/v2/client.py
index b95f844e7..171ac11ef 100644
--- a/apps/python-sdk/firecrawl/v2/client.py
+++ b/apps/python-sdk/firecrawl/v2/client.py
@@ -295,8 +295,9 @@ class FirecrawlClient:
request_id=result.request_id,
code=item.error.code,
charge_id=item.error.charge_id,
+ agent_hints=result.agent_hints,
)
- return FindToolsData(**item.data)
+ return FindToolsData(**{**item.data, "agent_hints": result.agent_hints})
# Research paper index (/v2/search/research)
@doc(CLIENT_SEARCH_PAPERS_DOC)
diff --git a/apps/python-sdk/firecrawl/v2/client_async.py b/apps/python-sdk/firecrawl/v2/client_async.py
index 0b745e087..9cdf5bf06 100644
--- a/apps/python-sdk/firecrawl/v2/client_async.py
+++ b/apps/python-sdk/firecrawl/v2/client_async.py
@@ -166,8 +166,9 @@ class AsyncFirecrawlClient:
request_id=result.request_id,
code=item.error.code,
charge_id=item.error.charge_id,
+ agent_hints=result.agent_hints,
)
- return FindToolsData(**item.data)
+ return FindToolsData(**{**item.data, "agent_hints": result.agent_hints})
# Research paper index (/v2/search/research)
@doc(ASYNC_CLIENT_SEARCH_PAPERS_DOC)
diff --git a/apps/python-sdk/firecrawl/v2/methods/aio/map.py b/apps/python-sdk/firecrawl/v2/methods/aio/map.py
index 09eff4be8..ba47cf078 100644
--- a/apps/python-sdk/firecrawl/v2/methods/aio/map.py
+++ b/apps/python-sdk/firecrawl/v2/methods/aio/map.py
@@ -1,5 +1,6 @@
from typing import Optional, Dict, Any
from ...types import MapOptions, MapData, LinkResult
+from ...utils.agent_hints import agent_hint_metadata
from ...utils.http_client_async import AsyncHttpClient
from ...utils.error_handler import handle_response_error
@@ -45,7 +46,7 @@ async def map(client: AsyncHttpClient, url: str, options: Optional[MapOptions] =
handle_response_error(response, "map")
body = response.json()
if not body.get("success"):
- raise Exception(body.get("error", "Unknown error occurred"))
+ handle_response_error(response, "map")
# data = body.get("data", {})
@@ -69,4 +70,4 @@ async def map(client: AsyncHttpClient, url: str, options: Optional[MapOptions] =
elif isinstance(item, str):
result_links.append(LinkResult(url=item))
- return MapData(links=result_links)
+ return MapData(links=result_links, **agent_hint_metadata(body))
diff --git a/apps/python-sdk/firecrawl/v2/methods/aio/parse.py b/apps/python-sdk/firecrawl/v2/methods/aio/parse.py
index 1dc6b010f..9a599b6e8 100644
--- a/apps/python-sdk/firecrawl/v2/methods/aio/parse.py
+++ b/apps/python-sdk/firecrawl/v2/methods/aio/parse.py
@@ -4,6 +4,7 @@ import json
from typing import Optional, Dict, Any, Tuple
from ...types import Document, ParseOptions
+from ...utils.agent_hints import agent_hint_metadata
from ...utils.normalize import normalize_document_input
from ...utils.error_handler import handle_response_error
from ...utils.http_client_async import AsyncHttpClient
@@ -56,8 +57,8 @@ async def parse(
body = response.json()
if not body.get("success"):
- raise Exception(body.get("error", "Unknown error occurred"))
+ handle_response_error(response, "parse")
document_data = body.get("data", {})
- normalized = normalize_document_input(document_data)
+ normalized = {**normalize_document_input(document_data), **agent_hint_metadata(body)}
return Document(**normalized)
diff --git a/apps/python-sdk/firecrawl/v2/methods/aio/scrape.py b/apps/python-sdk/firecrawl/v2/methods/aio/scrape.py
index eed1cab9e..3b8808bd5 100644
--- a/apps/python-sdk/firecrawl/v2/methods/aio/scrape.py
+++ b/apps/python-sdk/firecrawl/v2/methods/aio/scrape.py
@@ -9,6 +9,7 @@ from ...types import (
AlexandriaScrapeData,
)
from ..scrape import _alexandria_request_id, _prepare_scrape_alexandria_request, _parse_scrape_alexandria_response
+from ...utils.agent_hints import agent_hint_metadata
from ...utils.normalize import normalize_document_input
from ...utils.error_handler import FirecrawlError, handle_response_error
from ...utils.validation import prepare_scrape_options, validate_scrape_options
@@ -52,9 +53,9 @@ async def scrape(
handle_response_error(response, "scrape")
body = response.json()
if not body.get("success"):
- raise Exception(body.get("error", "Unknown error occurred"))
+ handle_response_error(response, "scrape")
document_data = body.get("data", {})
- normalized = normalize_document_input(document_data)
+ normalized = {**normalize_document_input(document_data), **agent_hint_metadata(body)}
return Document(**normalized)
diff --git a/apps/python-sdk/firecrawl/v2/methods/aio/search.py b/apps/python-sdk/firecrawl/v2/methods/aio/search.py
index 31058af55..a45aa96b0 100644
--- a/apps/python-sdk/firecrawl/v2/methods/aio/search.py
+++ b/apps/python-sdk/firecrawl/v2/methods/aio/search.py
@@ -8,6 +8,7 @@ from ...types import (
SearchResultNews,
SearchResultImages,
)
+from ...utils.agent_hints import agent_hint_metadata
from ...utils.http_client_async import AsyncHttpClient
from ...utils.error_handler import handle_response_error
from ...utils.normalize import normalize_document_input
@@ -41,7 +42,7 @@ async def search(
if not response_data.get("success"):
handle_response_error(response, "search")
data = response_data.get("data", {}) or {}
- out = SearchData(warning=response_data.get("warning"))
+ out = SearchData(warning=response_data.get("warning"), **agent_hint_metadata(response_data))
if "web" in data:
out.web = _transform_array(data["web"], SearchResultWeb)
if "news" in data:
diff --git a/apps/python-sdk/firecrawl/v2/methods/map.py b/apps/python-sdk/firecrawl/v2/methods/map.py
index 7ebff6414..782d9a0cb 100644
--- a/apps/python-sdk/firecrawl/v2/methods/map.py
+++ b/apps/python-sdk/firecrawl/v2/methods/map.py
@@ -4,6 +4,7 @@ Mapping functionality for Firecrawl v2 API.
from typing import Optional, Dict, Any
from ..types import MapOptions, MapData, LinkResult
+from ..utils.agent_hints import agent_hint_metadata
from ..utils import HttpClient, handle_response_error
@@ -57,7 +58,7 @@ def map(client: HttpClient, url: str, options: Optional[MapOptions] = None) -> M
body = response.json()
if not body.get("success"):
- raise Exception(body.get("error", "Unknown error occurred"))
+ handle_response_error(response, "map")
# shouldnt return inside data?
# data = body.get("data", {})
@@ -87,4 +88,4 @@ def map(client: HttpClient, url: str, options: Optional[MapOptions] = None) -> M
elif isinstance(item, str):
result_links.append(LinkResult(url=item))
- return MapData(links=result_links)
+ return MapData(links=result_links, **agent_hint_metadata(body))
diff --git a/apps/python-sdk/firecrawl/v2/methods/parse.py b/apps/python-sdk/firecrawl/v2/methods/parse.py
index f40188d0e..22e43fbaa 100644
--- a/apps/python-sdk/firecrawl/v2/methods/parse.py
+++ b/apps/python-sdk/firecrawl/v2/methods/parse.py
@@ -8,6 +8,7 @@ from pathlib import Path
from typing import Optional, Dict, Any, BinaryIO, Union, Tuple
from ..types import Document, ParseOptions
+from ..utils.agent_hints import agent_hint_metadata
from ..utils.normalize import normalize_document_input
from ..utils import HttpClient, handle_response_error, prepare_scrape_options, validate_scrape_options
from ..utils.get_version import get_version
@@ -157,8 +158,8 @@ def parse(
body = response.json()
if not body.get("success"):
- raise Exception(body.get("error", "Unknown error occurred"))
+ handle_response_error(response, "parse")
document_data = body.get("data", {})
- normalized = normalize_document_input(document_data)
+ normalized = {**normalize_document_input(document_data), **agent_hint_metadata(body)}
return Document(**normalized)
diff --git a/apps/python-sdk/firecrawl/v2/methods/scrape.py b/apps/python-sdk/firecrawl/v2/methods/scrape.py
index 47f50d3a9..be245ae79 100644
--- a/apps/python-sdk/firecrawl/v2/methods/scrape.py
+++ b/apps/python-sdk/firecrawl/v2/methods/scrape.py
@@ -15,6 +15,7 @@ from ..types import (
AlexandriaScrapeData,
AlexandriaScrapeResult,
)
+from ..utils.agent_hints import agent_hint_metadata
from ..utils.normalize import normalize_document_input
from ..utils import FirecrawlError, HttpClient, handle_response_error, prepare_scrape_options, validate_scrape_options
from ..utils.auto_resume import ResumeTracker
@@ -86,10 +87,10 @@ def scrape(
body = response.json()
if not body.get("success"):
- raise Exception(body.get("error", "Unknown error occurred"))
+ handle_response_error(response, "scrape")
document_data = body.get("data", {})
- normalized = normalize_document_input(document_data)
+ normalized = {**normalize_document_input(document_data), **agent_hint_metadata(body)}
return Document(**normalized)
@@ -142,6 +143,7 @@ def _parse_scrape_alexandria_response(body: Dict[str, Any], request_id: str) ->
alexandria=results,
credits_cost=data["creditsCost"],
request_id=request_id,
+ **agent_hint_metadata(body),
)
diff --git a/apps/python-sdk/firecrawl/v2/methods/search.py b/apps/python-sdk/firecrawl/v2/methods/search.py
index 9887dc928..b46709688 100644
--- a/apps/python-sdk/firecrawl/v2/methods/search.py
+++ b/apps/python-sdk/firecrawl/v2/methods/search.py
@@ -4,6 +4,7 @@ Search functionality for Firecrawl v2 API.
from typing import Dict, Any, Union, List, TypeVar, Type
from ..types import SearchRequest, SearchData, Document, SearchResultWeb, SearchResultNews, SearchResultImages, DiscoveredTool
+from ..utils.agent_hints import agent_hint_metadata
from ..utils.normalize import normalize_document_input, _map_search_result_keys
from ..utils import HttpClient, handle_response_error, validate_scrape_options, prepare_scrape_options
@@ -35,7 +36,7 @@ def search(
if not response_data.get("success"):
handle_response_error(response, "search")
data = response_data.get("data", {}) or {}
- out = SearchData(warning=response_data.get("warning"))
+ out = SearchData(warning=response_data.get("warning"), **agent_hint_metadata(response_data))
if "web" in data:
out.web = _transform_array(data["web"], SearchResultWeb)
if "news" in data:
diff --git a/apps/python-sdk/firecrawl/v2/types.py b/apps/python-sdk/firecrawl/v2/types.py
index 8c29260fe..eaa601a5f 100644
--- a/apps/python-sdk/firecrawl/v2/types.py
+++ b/apps/python-sdk/firecrawl/v2/types.py
@@ -68,6 +68,7 @@ class BaseResponse(BaseModel, Generic[T]):
"""Base response structure for all API responses."""
success: bool
+ agent_hints: Optional[List[str]] = None
data: Optional[T] = None
error: Optional[str] = None
warning: Optional[str] = None
@@ -497,6 +498,7 @@ class PdfPage(BaseModel):
class Document(BaseModel):
"""A scraped document."""
+ agent_hints: Optional[List[str]] = None
markdown: Optional[str] = None
html: Optional[str] = None
raw_html: Optional[str] = None
@@ -1090,6 +1092,7 @@ class DiscoveredTool(ExchangeSearchResult):
class FindToolsData(BaseModel):
+ agent_hints: Optional[List[str]] = None
level: Literal["providers", "groups", "tools"]
items: List[Dict[str, Any]]
total: int
@@ -1130,6 +1133,7 @@ class AlexandriaScrapeResult(BaseModel):
class AlexandriaScrapeData(BaseModel):
+ agent_hints: Optional[List[str]] = None
model_config = {"extra": "allow", "populate_by_name": True}
scrape_id: Optional[str] = None
@@ -1255,6 +1259,7 @@ class MapRequest(BaseModel):
class MapData(BaseModel):
"""Map results data."""
+ agent_hints: Optional[List[str]] = None
links: List["SearchResult"]
@@ -2358,6 +2363,7 @@ SearchResult = LinkResult
class SearchData(BaseModel):
"""Search results grouped by source type."""
+ agent_hints: Optional[List[str]] = None
warning: Optional[str] = None
web: Optional[List[Union[SearchResultWeb, Document]]] = None
news: Optional[List[Union[SearchResultNews, Document]]] = None
diff --git a/apps/python-sdk/firecrawl/v2/utils/agent_hints.py b/apps/python-sdk/firecrawl/v2/utils/agent_hints.py
new file mode 100644
index 000000000..1144dee2c
--- /dev/null
+++ b/apps/python-sdk/firecrawl/v2/utils/agent_hints.py
@@ -0,0 +1,9 @@
+"""Preserve response guidance separately from extracted document content."""
+from typing import Any, Dict, List
+
+
+def agent_hint_metadata(body: Any) -> Dict[str, List[str]]:
+ hints = body.get("agent_hints") if isinstance(body, dict) else None
+ if isinstance(hints, list) and all(isinstance(hint, str) for hint in hints):
+ return {"agent_hints": list(hints)}
+ return {}
diff --git a/apps/python-sdk/firecrawl/v2/utils/error_handler.py b/apps/python-sdk/firecrawl/v2/utils/error_handler.py
index 75f7f93c9..fa90e20ca 100644
--- a/apps/python-sdk/firecrawl/v2/utils/error_handler.py
+++ b/apps/python-sdk/firecrawl/v2/utils/error_handler.py
@@ -3,7 +3,8 @@ Error handling utilities for v2 API.
"""
import requests
-from typing import Dict, Any, Optional
+from typing import Dict, Any, Optional, List
+from .agent_hints import agent_hint_metadata
PROVIDER_TERMS_REQUIRED_CODE = "THIRD_PARTY_DATA_TERMS_REQUIRED"
@@ -11,7 +12,7 @@ PROVIDER_TERMS_REQUIRED_CODE = "THIRD_PARTY_DATA_TERMS_REQUIRED"
class FirecrawlError(Exception):
"""Base exception for Firecrawl API errors."""
- def __init__(self, message: str, status_code: Optional[int] = None, response: Optional[requests.Response] = None, *, request_id: Optional[str] = None, code: Optional[str] = None, charge_id: Optional[str] = None, requires_action: Optional["RequiresAction"] = None):
+ def __init__(self, message: str, status_code: Optional[int] = None, response: Optional[requests.Response] = None, *, request_id: Optional[str] = None, code: Optional[str] = None, charge_id: Optional[str] = None, requires_action: Optional["RequiresAction"] = None, agent_hints: Optional[List[str]] = None):
super().__init__(message)
self.status_code = status_code
self.response = response
@@ -23,6 +24,7 @@ class FirecrawlError(Exception):
self.code = code
self.charge_id = charge_id
self.requires_action = requires_action
+ self.agent_hints = agent_hints
class RequiresAction:
@@ -99,8 +101,10 @@ def handle_response_error(response: requests.Response, action: str) -> None:
code = None
charge_id = None
requires_action = None
+ hints = {}
try:
response_json = response.json()
+ hints = agent_hint_metadata(response_json)
error_message = response_json.get('error', 'No error message provided.')
error_details = response_json.get('details', 'No additional error details provided.')
# Exchange-mediated scrape errors: { success: false, error, code?, chargeId?, requiresAction? }
@@ -124,27 +128,27 @@ def handle_response_error(response: requests.Response, action: str) -> None:
# Create appropriate error message
if response.status_code == 400:
message = f"Bad Request: Failed to {action}. {error_message} - {error_details}"
- raise BadRequestError(message, response.status_code, response, code=code, charge_id=charge_id)
+ raise BadRequestError(message, response.status_code, response, code=code, charge_id=charge_id, **hints)
elif response.status_code == 401:
message = f"Unauthorized: Failed to {action}. {error_message} - {error_details}"
- raise UnauthorizedError(message, response.status_code, response, code=code, charge_id=charge_id)
+ raise UnauthorizedError(message, response.status_code, response, code=code, charge_id=charge_id, **hints)
elif response.status_code == 402:
message = f"Payment Required: Failed to {action}. {error_message} - {error_details}"
- raise PaymentRequiredError(message, response.status_code, response, code=code, charge_id=charge_id)
+ raise PaymentRequiredError(message, response.status_code, response, code=code, charge_id=charge_id, **hints)
elif response.status_code == 403 and code == PROVIDER_TERMS_REQUIRED_CODE:
- raise ProviderTermsRequiredError(error_message, response.status_code, response, code=code, charge_id=charge_id, requires_action=requires_action)
+ raise ProviderTermsRequiredError(error_message, response.status_code, response, code=code, charge_id=charge_id, requires_action=requires_action, **hints)
elif response.status_code == 403:
message = f"Website Not Supported: Failed to {action}. {error_message} - {error_details}"
- raise WebsiteNotSupportedError(message, response.status_code, response, code=code, charge_id=charge_id)
+ raise WebsiteNotSupportedError(message, response.status_code, response, code=code, charge_id=charge_id, **hints)
elif response.status_code == 408:
message = f"Request Timeout: Failed to {action} as the request timed out. {error_message} - {error_details}"
- raise RequestTimeoutError(message, response.status_code, response, code=code, charge_id=charge_id)
+ raise RequestTimeoutError(message, response.status_code, response, code=code, charge_id=charge_id, **hints)
elif response.status_code == 429:
message = f"Rate Limit Exceeded: Failed to {action}. {error_message} - {error_details}"
- raise RateLimitError(message, response.status_code, response, code=code, charge_id=charge_id)
+ raise RateLimitError(message, response.status_code, response, code=code, charge_id=charge_id, **hints)
elif response.status_code == 500:
message = f"Internal Server Error: Failed to {action}. {error_message} - {error_details}"
- raise InternalServerError(message, response.status_code, response, code=code, charge_id=charge_id)
+ raise InternalServerError(message, response.status_code, response, code=code, charge_id=charge_id, **hints)
else:
message = f"Unexpected error during {action}: Status code {response.status_code}. {error_message} - {error_details}"
- raise FirecrawlError(message, response.status_code, response, code=code, charge_id=charge_id)
+ raise FirecrawlError(message, response.status_code, response, code=code, charge_id=charge_id, **hints)