The Open Framework for Building Agents
fix(eve): recover when OpenAI-compatible hosts reject web search (#4585)
Ben Pankowcf724862100c
diff --git a/.changeset/web-search-compat-recovery.md b/.changeset/web-search-compat-recovery.mdnew file mode 100644index 000000000..ee349820f--- /dev/null+++ b/.changeset/web-search-compat-recovery.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Agents whose OpenAI model is served by an endpoint without OpenAI web search, such as Amazon Bedrock through `createOpenAI({ baseURL })` or AI Gateway, now retry the step without `web_search` instead of failing every turn.diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.mdindex 401f08a98..7ee01d8ba 100644--- a/docs/concepts/built-in-tools.md+++ b/docs/concepts/built-in-tools.md@@ -240,6 +240,23 @@ export default webSearch({ provider: "native", fallback: "exa" });The `provider` setting applies only to AI Gateway models. Direct OpenAI, Anthropic, and Gemini 3 and later models always use their native search; other direct models omit `web_search`.+eve identifies a direct model's vendor by its AI SDK provider name, so a `createOpenAI()` model pointed at an OpenAI-compatible endpoint, such as Amazon Bedrock's, gets OpenAI web search. When the endpoint rejects it, eve retries the step without `web_search`, so each step makes one rejected call first. To skip it, give the provider its own name:++```ts title="agent/agent.ts"+import { createOpenAI } from "@ai-sdk/openai";+import { defineAgent } from "eve";++const mantle = createOpenAI({+ name: "mantle",+ baseURL: "https://bedrock-mantle.us-east-1.api.aws/openai/v1",+ apiKey: process.env.BEDROCK_API_KEY,+});++export default defineAgent({ model: mantle("openai.gpt-5.6-sol") });+```++The agent then gets no `web_search`, the same as other direct models without native search.+Replace provider-managed search with an authored implementation:```ts title="agent/tools/web_search.ts"diff --git a/packages/eve/src/harness/model-call/errors.test.ts b/packages/eve/src/harness/model-call/errors.test.tsindex b30dba629..adfc7a3c3 100644--- a/packages/eve/src/harness/model-call/errors.test.ts+++ b/packages/eve/src/harness/model-call/errors.test.ts@@ -610,6 +610,69 @@ describe("extractUnsupportedProviderToolTypes", () => {expect(extractUnsupportedProviderToolTypes(error)).toEqual([]);});+ it("returns the include value an OpenAI-compatible endpoint rejected", () => {+ // Bedrock Mantle's response when the request carries OpenAI web search.+ const body = {+ error: {+ code: "invalid_value",+ message:+ "Invalid value: 'web_search_call.action.sources'. Supported values are: 'reasoning.encrypted_content'.",+ param: "include",+ type: "invalid_request_error",+ },+ };+ const error = Object.assign(new Error(body.error.message), {+ data: body,+ name: "AI_APICallError",+ responseBody: JSON.stringify(body),+ statusCode: 400,+ });++ expect(extractUnsupportedProviderToolTypes(error)).toEqual(["web_search_call.action.sources"]);+ });++ it("returns only the rejected value, not the supported values listed after it", () => {+ const upstream = Object.assign(new Error("Bad Request"), {+ responseBody: JSON.stringify({+ error: {+ message:+ "Invalid value: 'file_search_call.results'. Supported values are: 'web_search_call.action.sources'.",+ param: "include",+ },+ }),+ statusCode: 400,+ });++ expect(extractUnsupportedProviderToolTypes(upstream)).toEqual(["file_search_call.results"]);+ });++ it("returns OpenAI's web search type when AI Gateway routed it to a host without web search", () => {+ // AI Gateway's response for OpenAI web search routed to Bedrock.+ const body = {+ error: {+ message: "web search is not supported for this request",+ param: {+ message: "web search is not supported for this request",+ name: "AI_APICallError",+ statusCode: 400,+ },+ type: "AI_APICallError",+ },+ };+ const upstream = Object.assign(new Error(body.error.message), {+ data: body,+ name: "AI_APICallError",+ responseBody: JSON.stringify(body),+ statusCode: 400,+ });+ const error = Object.assign(new Error(body.error.message, { cause: upstream }), {+ name: "GatewayInternalServerError",+ statusCode: 400,+ });++ expect(extractUnsupportedProviderToolTypes(error)).toEqual(["web_search"]);+ });+it("returns empty for plain Error and null/undefined inputs", () => {expect(extractUnsupportedProviderToolTypes(new Error("mystery"))).toEqual([]);expect(extractUnsupportedProviderToolTypes(null)).toEqual([]);diff --git a/packages/eve/src/harness/model-call/errors.ts b/packages/eve/src/harness/model-call/errors.tsindex 2a06a03f8..e7ec62fa5 100644--- a/packages/eve/src/harness/model-call/errors.ts+++ b/packages/eve/src/harness/model-call/errors.ts@@ -10,18 +10,22 @@ const GATEWAY_MODEL_REQUEST_REJECTED_MESSAGE ="AI Gateway rejected the model request before the agent produced a response.";/**- * Anchored regex for the upstream "unsupported tool" rejection message- * that AI Gateway returns when a fallback provider cannot serve a- * provider-specific tool (e.g. Bedrock rejecting `web_search_20250305`).- *- * The gateway reports a single rejecting host as `tool type 'X' is not- * supported`. When every host fails, it surfaces each host's raw error, and- * Bedrock's reads `Input tag 'X' found using 'type' does not match`. Both- * alternatives are anchored on their literal phrasing to avoid sweeping in- * unrelated "not supported" errors.+ * Upstream rejections of a provider tool the host cannot serve, each anchored on its literal+ * phrasing so unrelated "not supported" errors don't drop a tool. Each yields the upstream+ * identifier it names: the tool type, or a request value only that tool adds.*/-const UNSUPPORTED_TOOL_TYPE_REGEX =- /tool type ['"]([\w.-]+)['"] is not supported|Input tag ['"]([\w.-]+)['"] found using ['"]type['"] does not match/i;+const UNSUPPORTED_PROVIDER_TOOL_MATCHERS: readonly ((text: string) => string | undefined)[] = [+ // AI Gateway reporting the one host that rejected the tool.+ (text) => /tool type ['"]([\w.-]+)['"] is not supported/i.exec(text)?.[1],+ // Bedrock's raw error, which AI Gateway surfaces when every host failed.+ (text) => /Input tag ['"]([\w.-]+)['"] found using ['"]type['"] does not match/i.exec(text)?.[1],+ // OpenAI-compatible Responses endpoints (Bedrock Mantle) rejecting the `include` value the+ // OpenAI web search tool adds. The first quoted value is the rejected one; any after it are+ // the endpoint's supported values.+ (text) => /Invalid value: ['"]([\w.-]+)['"]/i.exec(text)?.[1],+ // AI Gateway routing OpenAI web search to a host without it (Bedrock).+ (text) => (/web search is not supported for this request/i.test(text) ? "web_search" : undefined),+];/*** The most informative human-readable rejection a model-call error@@ -95,13 +99,12 @@ function isTransientHttpStatus(status: number | undefined): boolean {}/**- * Returns the distinct upstream tool types referenced by any- * "tool type 'X' is not supported" rejection in an AI Gateway error's- * provider attempt list.+ * Returns the distinct upstream identifiers named by any unsupported provider tool rejection+ * (see {@link UNSUPPORTED_PROVIDER_TOOL_MATCHERS}) in a model-call error.*- * Walks the cause chain to find the gateway error and inspects both the- * structured `data` field and the raw `responseBody` JSON. Returns an- * empty array for errors that are not of this shape.+ * Walks the cause chain and inspects both the structured `data` field and+ * the raw `responseBody` JSON. Returns an empty array for errors that are+ * not of this shape.** Used by the harness recovery path to identify which framework tools* to drop before retrying the failing step. Detection is by string@@ -124,8 +127,7 @@ export function extractUnsupportedProviderToolTypes(error: unknown): readonly st// includes a large request snapshot. Fall back to a raw string// scan so we still surface the tool name when the regex match// lies before the truncation boundary.- const type = matchUnsupportedToolType(responseBody);- if (type !== undefined) found.add(type);+ collectUnsupportedToolTypes(responseBody, found);}}}@@ -133,17 +135,18 @@ export function extractUnsupportedProviderToolTypes(error: unknown): readonly streturn [...found];}-function matchUnsupportedToolType(text: string): string | undefined {- const match = UNSUPPORTED_TOOL_TYPE_REGEX.exec(text);- return match?.[1] ?? match?.[2];+function collectUnsupportedToolTypes(text: string, out: Set<string>): void {+ for (const match of UNSUPPORTED_PROVIDER_TOOL_MATCHERS) {+ const type = match(text);+ if (type !== undefined) out.add(type);+ }}function collectUnsupportedToolTypesFromValue(value: unknown, out: Set<string>): void {if (value === null || value === undefined) return;if (typeof value === "string") {- const type = matchUnsupportedToolType(value);- if (type !== undefined) out.add(type);+ collectUnsupportedToolTypes(value, out);return;}diff --git a/packages/eve/src/harness/model-call/recovery.ts b/packages/eve/src/harness/model-call/recovery.tsindex 571d08058..d4c898c26 100644--- a/packages/eve/src/harness/model-call/recovery.ts+++ b/packages/eve/src/harness/model-call/recovery.ts@@ -22,9 +22,10 @@ type RecoveryCall = (options: {* Recovers a failed model call, each recovery at most once and within the current step, so the* reissue suppresses a second `step.started`:*- * 1. AI Gateway rejected a provider-specific tool a fallback provider can't serve ("tool type 'X'- * is not supported"): the call is reissued without it, and a system note tells the model which- * capability went away. Only known provider tools are dropped, never an authored one.+ * 1. The host rejected a provider-specific tool it can't serve (an AI Gateway fallback provider,+ * or an OpenAI-compatible endpoint without OpenAI web search): the call is reissued without+ * it, and a system note tells the model which capability went away. Only known provider tools+ * are dropped, never an authored one.* 2. The response was empty (see {@link EmptyModelResponseError}), including the first* recovery's: the call is reissued with {@link EMPTY_RESPONSE_NUDGE}, repeating what the first* recovery removed.diff --git a/packages/eve/src/harness/provider-tools.test.ts b/packages/eve/src/harness/provider-tools.test.tsindex c84ebc912..08eb99a46 100644--- a/packages/eve/src/harness/provider-tools.test.ts+++ b/packages/eve/src/harness/provider-tools.test.ts@@ -179,6 +179,13 @@ describe("resolveFrameworkToolFromUpstreamType", () => {expect(resolveFrameworkToolFromUpstreamType("web_search_20250305")).toBe("web_search");});+ it("maps OpenAI web search's tool type and include value back to web_search", () => {+ expect(resolveFrameworkToolFromUpstreamType("web_search")).toBe("web_search");+ expect(resolveFrameworkToolFromUpstreamType("web_search_call.action.sources")).toBe(+ "web_search",+ );+ });+it("returns null for unknown upstream tool types", () => {expect(resolveFrameworkToolFromUpstreamType("computer_20251022")).toBeNull();expect(resolveFrameworkToolFromUpstreamType("some.future.tool")).toBeNull();diff --git a/packages/eve/src/harness/provider-tools.ts b/packages/eve/src/harness/provider-tools.tsindex bcf9e151d..c2cdc1b0a 100644--- a/packages/eve/src/harness/provider-tools.ts+++ b/packages/eve/src/harness/provider-tools.ts@@ -18,13 +18,13 @@ import type { WebSearchSelection } from "#shared/web-search.js";type WebSearchBackend = "anthropic" | "exa" | "google" | "openai" | "parallel" | "browserbase";/**- * Maps an upstream provider tool type (the literal `type` string the AI SDK- * sends to the provider) back to the framework tool name that injected it.+ * Maps an upstream identifier back to the framework tool name that injected it: a provider tool+ * type (the literal `type` string the AI SDK sends to the provider), or a request value the AI SDK+ * adds only for that tool.*- * Used when the AI Gateway routes a request to a fallback provider that- * does not support a provider-specific tool — the upstream error references- * the provider-specific type (e.g. `web_search_20250305`), but the harness- * needs to drop the framework tool by its public name (`web_search`).+ * Used when a host does not support a provider-specific tool — the upstream error references+ * the provider-specific identifier (e.g. `web_search_20250305`), but the harness needs to drop+ * the framework tool by its public name (`web_search`).** Adding a new provider tool requires adding the corresponding mapping* entry here alongside its {@link resolveWebSearchProviderTool} switch@@ -35,6 +35,10 @@ const UPSTREAM_TOOL_TYPE_TO_FRAMEWORK_NAME: Readonly<Record<string, string>> = {// Anthropic backends reject this type because they only host the// older Claude Messages surface.web_search_20250305: WEB_SEARCH_TOOL_NAME,+ // OpenAI's web search tool, which OpenAI-compatible hosts such as Bedrock may not serve.+ web_search: WEB_SEARCH_TOOL_NAME,+ // The `include` value `@ai-sdk/openai` adds only alongside OpenAI web search.+ "web_search_call.action.sources": WEB_SEARCH_TOOL_NAME,};/**@@ -42,7 +46,7 @@ const UPSTREAM_TOOL_TYPE_TO_FRAMEWORK_NAME: Readonly<Record<string, string>> = {* `type`, or `null` when the type is not one we know how to remove.** Used by the harness recovery path to decide which tools to drop when a- * gateway fallback provider rejects a tool. Unknown types fall through to+ * host rejects a tool. Unknown types fall through to* the existing terminal/recoverable handling.*/export function resolveFrameworkToolFromUpstreamType(type: string): string | null {diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 0e38ea1c2..d8b2b8c46 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -5140,6 +5140,71 @@ describe("createToolLoopHarness", () => {);});+ it("retries without web search when an OpenAI-compatible endpoint rejects its include value", async () => {+ // An OpenAI-compatible endpoint (Bedrock Mantle) that rejects every request carrying+ // OpenAI web search.+ const body = {+ error: {+ message:+ "Invalid value: 'web_search_call.action.sources'. Supported values are: 'reasoning.encrypted_content'.",+ param: "include",+ },+ };+ const rejection = Object.assign(new Error(body.error.message), {+ data: body,+ isRetryable: false,+ name: "AI_APICallError",+ responseBody: JSON.stringify(body),+ statusCode: 400,+ });+ const successResult = {+ finishReason: "stop",+ response: { messages: [{ content: "ok", role: "assistant" }] },+ text: "ok",+ toolCalls: [],+ toolResults: [],+ };+ vi.mocked(ToolLoopAgent).mockImplementation(function (+ this: Record<string, unknown>,+ settings: MockAgentSettings & { tools: Record<string, unknown> },+ ) {+ const { tools } = settings;+ this.stream = vi.fn().mockImplementation(async () => {+ if (tools.web_search !== undefined) throw rejection;+ void Promise.resolve().then(() => settings.onStepEnd?.(successResult));+ return createMockStreamResult(successResult);+ });+ return this as unknown as ToolLoopAgent;+ } as unknown as MockAgentConstructor);++ const model = { modelId: "gpt-5.6-sol", provider: "openai.responses" } as LanguageModel;+ const session = createTestSession({+ agent: {+ modelReference: { id: "gpt-5.6-sol" },+ system: "You are a test assistant.",+ tools: [{ description: "Web search.", name: "web_search", inputSchema: null }],+ },+ });+ const runStep = createToolLoopHarness({+ handleEvent: createEventCollector().emit,+ resolveModel: vi.fn().mockResolvedValue(model),+ tools: new Map([+ [+ "web_search",+ { description: "Web search.", inputSchema: jsonSchema({}), name: "web_search" },+ ],+ ]),+ });++ const result = await runStep(session, { message: "Hi" });++ expect(result.next).toBeNull();+ const toolsPerCall = vi+ .mocked(ToolLoopAgent)+ .mock.calls.map(([settings]) => Object.keys(settings.tools as object));+ expect(toolsPerCall).toEqual([["web_search"], []]);+ });+it("falls through to terminal cascade when recovery retry also fails", async () => {const logs = captureLogRecords();// Both attempts fail with the same unsupported-tool error. The