~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix: preserve provider usage-limit guidance through research failures (#8195)
LearningCircuitd3cbf0328145
diff --git a/changelog.d/+provider-payment-required-guidance.bugfix.md b/changelog.d/+provider-payment-required-guidance.bugfix.mdnew file mode 100644index 0000000000..24f177c742--- /dev/null+++ b/changelog.d/+provider-payment-required-guidance.bugfix.md@@ -0,0 +1 @@+Show specific guidance for provider payment or usage-limit refusals while keeping provider response details out of saved error reports.diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.pyindex fb97112cd2..5f2fe84b68 100644--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py@@ -28,6 +28,11 @@ from loguru import loggerfrom ...citation_handler import CitationHandlerfrom ...exceptions import ResearchTerminatedException+from ...error_handling.openai_compat_errors import (+ ProviderUsageLimitError,+ is_openai_payment_required,+)+from ...security.secure_logging import log_exception_typefrom ...security.egress import EngineClassification, classify_enginefrom ...security import (redact_url_for_log,@@ -3496,6 +3501,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):# delegate via __getattr__ unstripped; stream() passes chunks on# unstripped; `|` raises TypeError, no __or__), but none are on this# create_agent path — see config/llm_config.py.+ usage_limit_failure = Falsetry:agent = create_agent(model=self.model,@@ -3509,14 +3515,24 @@ class LangGraphAgentStrategy(BaseSearchStrategy):)],)+ except PolicyDeniedError:+ raiseexcept Exception as exc:- logger.exception("Failed to create LangGraph agent")- return self._error_result(- sanitize_error_for_agent(- f"Failed to create agent (model may not "- f"support tool calling): {exc}"+ if is_openai_payment_required(exc):+ usage_limit_failure = True+ log_exception_type("LangGraph agent creation refused", exc)+ else:+ logger.exception("Failed to create LangGraph agent")+ return self._error_result(+ sanitize_error_for_agent(+ f"Failed to create agent (model may not "+ f"support tool calling): {exc}"+ ))- )+ # Leave the handler before raising: the SDK response must not become+ # a chained exception when the worker records this authored failure.+ if usage_limit_failure:+ raise ProviderUsageLimitError()# Stream agent executioneffective_max = max(MIN_ITERATIONS, self.max_iterations)@@ -3524,6 +3540,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):iteration = 0final_content = ""agent_messages: list = []+ usage_limit_failure = Falsetry:for chunk in agent.stream(@@ -3677,10 +3694,22 @@ class LangGraphAgentStrategy(BaseSearchStrategy):"status": "tools_exhausted",},)+ except PolicyDeniedError:+ raiseexcept Exception as exc:- logger.exception("LangGraph agent error")+ usage_limited = is_openai_payment_required(exc)+ if usage_limited:+ log_exception_type("LangGraph agent request refused", exc)+ else:+ logger.exception("LangGraph agent error")if not final_content and not self.collector.results:- return self._error_result(self._format_agent_error(exc))+ if usage_limited:+ usage_limit_failure = True+ else:+ return self._error_result(self._format_agent_error(exc))++ if usage_limit_failure:+ raise ProviderUsageLimitError()if not final_content:if self.collector.results:diff --git a/src/local_deep_research/error_handling/error_messages.py b/src/local_deep_research/error_handling/error_messages.pyindex 20842794d3..4b40c2a3b9 100644--- a/src/local_deep_research/error_handling/error_messages.py+++ b/src/local_deep_research/error_handling/error_messages.py@@ -18,6 +18,10 @@ TYPED_RESEARCH_ERROR_MESSAGES = {"openai_bad_request": "The LLM endpoint rejected the request.","openai_unknown": "The configured LLM provider returned an error.","openai_rate_limit": "The LLM provider rate-limited the request.",+ "openai_payment_required": (+ "The LLM provider cannot process this request within its current "+ "billing or usage limits."+ ),}_SAFE_WORKER_MESSAGES = frozenset(TYPED_RESEARCH_ERROR_MESSAGES.values()) | {diff --git a/src/local_deep_research/error_handling/error_reporter.py b/src/local_deep_research/error_handling/error_reporter.pyindex 9a6373d322..bd1f1e1f5e 100644--- a/src/local_deep_research/error_handling/error_reporter.py+++ b/src/local_deep_research/error_handling/error_reporter.py@@ -64,6 +64,8 @@ class ErrorReporter:r"Error type: openai_model_not_found",r"Error type: openai_bad_request",r"Error type: openai_unknown",+ r"Error type: openai_payment_required",+ r"billing or usage limits",],ErrorCategory.RATE_LIMIT_ERROR: [r"429.*resource.*exhausted",diff --git a/src/local_deep_research/error_handling/openai_compat_errors.py b/src/local_deep_research/error_handling/openai_compat_errors.pyindex 32d81d58e4..b7bacef6be 100644--- a/src/local_deep_research/error_handling/openai_compat_errors.py+++ b/src/local_deep_research/error_handling/openai_compat_errors.py@@ -8,9 +8,9 @@ produces a message that includes that context, while preserving the existing``Error type: <code>`` token convention used downstream in research_service.pyand ErrorReporter.-The helper deliberately does NOT introduce a new exception class -- the rest of-the pipeline is string-based today and tokens are how Sites B and C-communicate.+ProviderUsageLimitError carries authored guidance across strategy boundaries+that otherwise return error text. Other SDK failures retain the existing+error-token convention between Sites B and C."""from __future__ import annotations@@ -22,6 +22,7 @@ import openaifrom ..security.log_sanitizer import sanitize_error_messagefrom ..security.url_redaction import redact_url_credentials+from .error_messages import TYPED_RESEARCH_ERROR_MESSAGES# openai 3.x makes its requests through httpx2, so its transport errors are# httpx2 classes and are unrelated to the httpx ones imported above. openai 2.x@@ -43,9 +44,26 @@ _READ_TIMEOUTS = tuple(m.ReadTimeout for m in _TRANSPORT_MODULES)_strip_credentials = redact_url_credentials+class ProviderUsageLimitError(RuntimeError):+ """An authored failure signal without a provider response payload."""++ def __init__(self) -> None:+ super().__init__(+ TYPED_RESEARCH_ERROR_MESSAGES["openai_payment_required"]+ )++def _is_dispatchable(exc: BaseException) -> bool:"""Return True when :func:`_dispatch` has a branch for ``exc``."""- return isinstance(exc, (openai.APIError, *_CONNECT_ERRORS, *_READ_TIMEOUTS))+ return isinstance(+ exc,+ (+ ProviderUsageLimitError,+ openai.APIError,+ *_CONNECT_ERRORS,+ *_READ_TIMEOUTS,+ ),+ )def _walk_cause(exc: BaseException) -> BaseException:@@ -73,6 +91,27 @@ def _walk_cause(exc: BaseException) -> BaseException:return deepest+def is_openai_payment_required(exc: BaseException) -> bool:+ """Recognize typed usage refusals without reclassifying policy failures."""+ from ..security.egress.policy import PolicyDeniedError++ seen: set[int] = set()+ current: BaseException | None = exc+ while current is not None and id(current) not in seen:+ seen.add(id(current))+ if not isinstance(current, Exception) or isinstance(+ current, PolicyDeniedError+ ):+ return False+ if _is_dispatchable(current):+ return isinstance(current, ProviderUsageLimitError) or (+ isinstance(current, openai.APIStatusError)+ and current.status_code == 402+ )+ current = current.__cause__ or current.__context__+ return False++# The setting name is the label the UI actually renders (see# ``defaults/default_settings.json``), not a Settings -> ... path, so a user# can search for it. The connect bound is stated separately because@@ -167,6 +206,15 @@ def _dispatch("limiting in Settings.",)+ # Payment/usage limits (402). Use the SDK status, not provider prose,+ # which can mention unrelated failures or contain private response data.+ if is_openai_payment_required(root):+ return (+ "openai_payment_required",+ f"{provider} at {base_url} cannot process model '{model}' "+ "within its current billing or usage limits.",+ )+# Bad request (400)if _is("BadRequestError"):return (@@ -191,7 +239,7 @@ def _dispatch(def is_openai_compat_runtime_error(exc: BaseException) -> bool:"""Return True iff ``exc`` (or any exception in its cause chain) is an- ``openai.*`` or transport runtime error we can rewrite.+ ``openai.*`` error, transport failure, or authored usage refusal we can rewrite.Used at Site B in research_service.py to decide whether to call:func:`friendly_openai_compatible_error` instead of the existingdiff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex f8bc497e5d..686b303d05 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -30,6 +30,7 @@ from ...error_handling.error_messages import TYPED_RESEARCH_ERROR_MESSAGESfrom ...error_handling.openai_compat_errors import (friendly_openai_compatible_error,is_openai_compat_runtime_error,+ is_openai_payment_required,)from ...error_handling.report_generator import ErrorReportGeneratorfrom ...llm.providers.base import normalize_provider@@ -3051,6 +3052,13 @@ def run_research_process(research_id, query, mode, **kwargs):error_context = {"solution": "Set Egress Scope to 'Unprotected' to override, or use local inference / non-sensitive sources."}+ elif is_openai_payment_required(e):+ user_friendly_error = TYPED_RESEARCH_ERROR_MESSAGES[+ "openai_payment_required"+ ]+ error_context = {+ "solution": "Review the configured provider's billing and usage limits, or retry if the provider reports a temporary limit."+ }elif "Error type: ollama_unavailable" in user_friendly_error:user_friendly_error = "Ollama AI service is unavailable. Please check that Ollama is running properly on your system."error_context = {diff --git a/tests/error_handling/test_openai_payment_required.py b/tests/error_handling/test_openai_payment_required.pynew file mode 100644index 0000000000..0965b4a7c2--- /dev/null+++ b/tests/error_handling/test_openai_payment_required.py@@ -0,0 +1,165 @@+"""Typed provider-limit handling through the real SDK response boundary."""++import json+from pathlib import Path+import shutil+import subprocess++import openai+import pytest++from local_deep_research.error_handling.error_messages import (+ TYPED_RESEARCH_ERROR_MESSAGES,+)+from local_deep_research.error_handling.error_reporter import (+ ErrorCategory,+ ErrorReporter,+)+from local_deep_research.error_handling.openai_compat_errors import (+ ProviderUsageLimitError,+ _TRANSPORT_MODULES,+ friendly_openai_compatible_error,+ is_openai_payment_required,+)+from local_deep_research.error_handling.report_generator import (+ ErrorReportGenerator,+)+++ ("status", "expected"),+ [+ (402, "openai_payment_required"),+ (400, "openai_bad_request"),+ (403, "openai_permission_denied"),+ (429, "openai_rate_limit"),+ (500, "openai_unknown"),+ ],+)[email protected]("wrapped", [False, True], ids=["direct", "wrapped"])+def test_sdk_status_selects_only_the_matching_error_kind(+ status, expected, wrapped+):+ # OpenAI 2.x and 3.x use different HTTP client classes. Exercise whichever+ # transport the installed SDK actually accepts, replacing only HTTP I/O.+ transport_module = next(+ module+ for module in _TRANSPORT_MODULES+ if issubclass(openai.DefaultHttpxClient, module.Client)+ )+ calls = []++ def respond(request):+ calls.append(request.method)+ return transport_module.Response(+ status,+ json={"error": {"message": "synthetic payment-required detail"}},+ )++ with openai.OpenAI(+ api_key="synthetic-test-key",+ base_url="https://provider.invalid/v1",+ max_retries=0,+ http_client=transport_module.Client(+ transport=transport_module.MockTransport(respond)+ ),+ ) as client:+ with pytest.raises(openai.APIStatusError) as raised:+ client.chat.completions.create(+ model="synthetic-model",+ messages=[{"role": "user", "content": "synthetic input"}],+ )+ assert calls == ["POST"]+ error = raised.value+ if wrapped:+ error = RuntimeError("synthetic wrapper")+ error.__cause__ = raised.value+ message = friendly_openai_compatible_error(+ error,+ provider="synthetic-provider",+ base_url="https://provider.invalid/v1",+ model="synthetic-model",+ )+ assert f"Error type: {expected}" in message+ assert "synthetic-provider" in message+ assert "https://provider.invalid/v1" in message+ assert "synthetic-model" in message+ assert is_openai_payment_required(error) is (status == 402)+ if status != 402:+ assert "openai_payment_required" not in message+++def test_payment_guidance_survives_report_rendering_without_provider_detail():+ message = TYPED_RESEARCH_ERROR_MESSAGES["openai_payment_required"]+ assert (+ ErrorReporter().categorize_error(message) == ErrorCategory.MODEL_ERROR+ )+ report = ErrorReportGenerator().generate_error_report(+ "Research failed: " + message, query="synthetic query"+ )+ assert message in report+ assert "LLM Service Error" in report+++def test_message_text_does_not_change_an_unrelated_exception_kind():+ error = RuntimeError("synthetic error 402: payment required")+ message = friendly_openai_compatible_error(+ error, provider="openai_endpoint", base_url=None, model=None+ )+ assert "Error type: openai_unknown" in message+ assert "openai_payment_required" not in message+ assert not is_openai_payment_required(error)++[email protected]("wrapped", [False, True])+def test_authored_agent_signal_retains_the_specific_category(wrapped):+ error = ProviderUsageLimitError()+ if wrapped:+ wrapper = RuntimeError("synthetic wrapper")+ wrapper.__cause__ = error+ error = wrapper+ assert is_openai_payment_required(error)+ message = friendly_openai_compatible_error(+ error, provider="synthetic-provider", base_url=None, model=None+ )+ assert "Error type: openai_payment_required" in message+++def test_an_exception_cycle_without_a_typed_refusal_is_not_a_usage_limit():+ error = RuntimeError("synthetic wrapper")+ error.__cause__ = error+ assert not is_openai_payment_required(error)+++ shutil.which("node") is None, reason="Node.js not installed"+)+def test_authored_report_matches_the_browser_failure_contract():+ node = shutil.which("node")+ assert node is not None+ message = TYPED_RESEARCH_ERROR_MESSAGES["openai_payment_required"]+ report = ErrorReportGenerator().generate_error_report(+ "Research failed: " + message, query="synthetic query"+ )+ helper = (+ Path(__file__).resolve().parents[1] / "puppeteer/research_failure.js"+ )+ script = (+ "const {isProviderUsageLimitReport} = require(process.argv[1]);"+ "const [report, error] = JSON.parse("+ "require('node:fs').readFileSync(0, 'utf8'));"+ "process.stdout.write(JSON.stringify("+ "isProviderUsageLimitReport(report, error)));"+ )+ result = subprocess.run(+ [node, "-e", script, str(helper)],+ # The helper matches the heading and authored message. Removing the+ # Markdown heading prefix lets the real producer drive that contract.+ input=json.dumps([report.removeprefix("# "), message]),+ text=True,+ capture_output=True,+ check=True,+ timeout=10,+ env={},+ )+ assert json.loads(result.stdout) is Truediff --git a/tests/puppeteer/research_failure.js b/tests/puppeteer/research_failure.jsnew file mode 100644index 0000000000..b9f332888e--- /dev/null+++ b/tests/puppeteer/research_failure.js@@ -0,0 +1,12 @@+// Require the server's authored error category and the actual failure report.+// Report text alone does not establish why the run failed.+const PAYMENT_REQUIRED_MESSAGE = 'The LLM provider cannot process this request within its current billing or usage limits.';++function isProviderUsageLimitReport(content, errorMessage) {+ return typeof content === 'string' &&+ errorMessage === PAYMENT_REQUIRED_MESSAGE &&+ /^\s*(?:\u26a0\ufe0f?\s*)?Research Failed(?:\s|$)/u.test(content) &&+ content.includes(PAYMENT_REQUIRED_MESSAGE);+}++module.exports = { isProviderUsageLimitReport };diff --git a/tests/puppeteer/test_deep_functionality.js b/tests/puppeteer/test_deep_functionality.jsindex 51f3219dba..fb509e4d2d 100644--- a/tests/puppeteer/test_deep_functionality.js+++ b/tests/puppeteer/test_deep_functionality.js@@ -12,6 +12,7 @@const puppeteer = require('puppeteer');const { expect } = require('chai');+const { isProviderUsageLimitReport } = require('./research_failure');// Import shared helpersconst {@@ -470,8 +471,8 @@ describe('Deep Functionality Tests', function() {}}- // Poll the API to confirm database status is truly "completed"- // This bridges the gap between UI rendering and database commit timing+ // Confirm a terminal database state after the UI transition.+ // The output check below validates the reason for a failed run.if (completed) {const apiMaxWait = 30000;const apiStart = Date.now();@@ -488,9 +489,9 @@ describe('Deep Functionality Tests', function() {}}, BASE_URL, researchId);- if (statusRes === 'completed') {+ if (statusRes === 'completed' || statusRes === 'failed') {apiCompleted = true;- console.log(' API confirmed research completed');+ console.log(` API confirmed terminal research status: ${statusRes}`);} else {console.log(` Waiting for API status (currently: ${statusRes})`);await delay(2000);@@ -498,7 +499,7 @@ describe('Deep Functionality Tests', function() {}if (!apiCompleted) {- throw new Error('API did not confirm completion within 30s timeout');+ throw new Error('API did not confirm a terminal state within 30s timeout');}}@@ -519,7 +520,7 @@ describe('Deep Functionality Tests', function() {}});- it('should export and display research output', async () => {+ it('should export and display research output', async function() {if (!researchId) {console.log(' Skipping - no research ID from previous test');return;@@ -581,6 +582,19 @@ describe('Deep Functionality Tests', function() {resultContent.includes('Connection refused') ||resultContent.includes('Connection Issue') ||resultContent.includes('Agent error:');+ let serverErrorMessage = null;+ if (hasResearchError) {+ serverErrorMessage = await page.evaluate(async (id) => {+ const response = await fetch(`/api/research/${encodeURIComponent(id)}/status`, {+ signal: window.AbortSignal.timeout(5000),+ credentials: 'same-origin'+ });+ if (!response.ok) return null;+ const data = await response.json();+ return data.metadata?.error ?? null;+ }, researchId).catch(() => null);+ }+ const isProviderUsageLimit = isProviderUsageLimitReport(resultContent, serverErrorMessage);if (hasResearchError) {console.log(' ❌ Research failed with error');@@ -588,7 +602,7 @@ describe('Deep Functionality Tests', function() {const errorMatch = resultContent.match(/Error.*?(?=\n\n|\n#|$)/s);if (errorMatch) console.log(' Error:', errorMatch[0]);- if (isSearchEngineError || isTransientLlmError || isConnectionError) {+ if (isSearchEngineError || isTransientLlmError || isConnectionError || isProviderUsageLimit) {researchErroredOnEnvironment = true;// (used by the export-markdown test below to skip)// Known CI limitation — either search engines aren't fully configured@@ -602,6 +616,8 @@ describe('Deep Functionality Tests', function() {console.log(' ⚠️ Search engine configuration issue (known CI limitation)');} else if (isConnectionError) {console.log(' ⚠️ No upstream LLM/search endpoint reachable (env limitation)');+ } else if (isProviderUsageLimit) {+ console.log(' ⚠️ Upstream provider usage limit prevents a report (env limitation)');} else {console.log(' ⚠️ Transient upstream LLM provider error (known CI limitation)');}@@ -665,7 +681,7 @@ describe('Deep Functionality Tests', function() {// anything about export functionality.if (researchErroredOnEnvironment) {console.log(' ⚠️ Skipping export-markdown test — research did not produce a report');- return;+ this.skip();}const exportBtn = await page.$('#export-markdown-btn');if (exportBtn) {@@ -775,7 +791,7 @@ describe('Deep Functionality Tests', function() {expect(resultContent).to.not.be.null;});- it('should verify research contains sources', async () => {+ it('should verify research contains sources', async function() {if (!researchId) {console.log(' Skipping - no research ID');return;@@ -785,6 +801,7 @@ describe('Deep Functionality Tests', function() {const sourcesResponse = await page.evaluate(async (baseUrl, id) => {try {const res = await fetch(`${baseUrl}/api/research/${id}`);+ if (!res.ok) return { error: 'Research details request failed' };return await res.json();} catch (e) {return { error: e.message };@@ -793,11 +810,17 @@ describe('Deep Functionality Tests', function() {console.log(' Research details:', JSON.stringify(sourcesResponse, null, 2).substring(0, 1000));- // Verify research completed successfully- if (sourcesResponse.status) {- expect(sourcesResponse.status, 'Research status should be completed').to.equal('completed');+ if (sourcesResponse.status === 'failed') {+ const content = await page.$eval('#results-content', el => el.textContent).catch(() => null);+ if (isProviderUsageLimitReport(content, sourcesResponse.metadata?.error)) {+ console.log(' Upstream provider usage limit prevents source verification');+ this.skip();+ }}+ // Verify research completed successfully+ expect(sourcesResponse.status, 'Research status should be completed').to.equal('completed');+// Check for sources in the response or pageconst pageContent = await page.$eval('body', el => el.textContent);const hasSources = pageContent.includes('Source') ||diff --git a/tests/puppeteer/toolchain/research_failure.test.js b/tests/puppeteer/toolchain/research_failure.test.jsnew file mode 100644index 0000000000..be25311adf--- /dev/null+++ b/tests/puppeteer/toolchain/research_failure.test.js@@ -0,0 +1,33 @@+const assert = require('node:assert/strict');+const { test: nodeTest } = require('node:test');+const { isProviderUsageLimitReport } = require('../research_failure');++const message = 'The LLM provider cannot process this request within its current billing or usage limits.';++nodeTest('recognizes authored provider-limit guidance on the results page', () => {+ assert.equal(isProviderUsageLimitReport(`\n⚠️ Research Failed\nError Type: LLM Service Error\nWhat happened: ${message}`, message), true);+});++nodeTest('keeps unrelated failures and provider prose as failures', () => {+ for (const report of [+ '⚠️ Research Failed\nUnexpected Error',+ '⚠️ Research Failed\nProvider error 402: payment required',+ `Research Failedness\n${message}`,+ '⚠️ Research Failed\nPlease review billing or usage limits.',+ ]) {+ assert.equal(isProviderUsageLimitReport(report, message), false);+ }+});++nodeTest('does not skip healthy output or missing results', () => {+ for (const report of [message, `Synthetic report\n${message}`, '', null, undefined]) {+ assert.equal(isProviderUsageLimitReport(report, message), false);+ }+});++nodeTest('requires confirmation from the server error metadata', () => {+ const report = `⚠️ Research Failed\nWhat happened: ${message}`;+ for (const serverMessage of [null, undefined, '', 'Unrelated failure', `${message} Additional detail`]) {+ assert.equal(isProviderUsageLimitReport(report, serverMessage), false);+ }+});diff --git a/tests/strategies/test_provider_usage_limits.py b/tests/strategies/test_provider_usage_limits.pynew file mode 100644index 0000000000..75e9602aca--- /dev/null+++ b/tests/strategies/test_provider_usage_limits.py@@ -0,0 +1,253 @@+"""Provider refusals must survive real agent execution and retain controls."""++import json+from contextlib import contextmanager+from unittest.mock import MagicMock, patch++import openai+import pytest+from langchain_core.tools import tool+from langchain_openai import ChatOpenAI++from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (+ LangGraphAgentStrategy,+)+from local_deep_research.config.llm_config import ProcessingLLMWrapper+from local_deep_research.error_handling.error_messages import (+ TYPED_RESEARCH_ERROR_MESSAGES,+)+from local_deep_research.error_handling.openai_compat_errors import (+ ProviderUsageLimitError,+ _TRANSPORT_MODULES,+ is_openai_payment_required,+)+from local_deep_research.exceptions import ResearchTerminatedException+from local_deep_research.security.egress.policy import (+ Decision,+ PolicyDeniedError,+)+++DETAIL = "synthetic-provider-response-detail"+ANSWER = "A synthetic research answer."+++def _response(content=ANSWER, tool_calls=None):+ message = {"role": "assistant", "content": content}+ if tool_calls:+ message["tool_calls"] = tool_calls+ return {+ "id": "synthetic-completion",+ "object": "chat.completion",+ "created": 0,+ "model": "synthetic-model",+ "choices": [+ {+ "index": 0,+ "message": message,+ "finish_reason": "tool_calls" if tool_calls else "stop",+ }+ ],+ "usage": {+ "prompt_tokens": 1,+ "completion_tokens": 1,+ "total_tokens": 2,+ },+ }+++@contextmanager+def _sdk_model(responses):+ """Keep the SDK, wrapper and agent real; replace only outbound HTTP."""+ transport = next(+ module+ for module in _TRANSPORT_MODULES+ if issubclass(openai.DefaultHttpxClient, module.Client)+ )+ calls = []+ remaining = iter(responses)++ def respond(request):+ calls.append(json.loads(request.content))+ status, body = next(remaining)+ return transport.Response(status, json=body)++ with transport.Client(+ transport=transport.MockTransport(respond)+ ) as http_client:+ model = ChatOpenAI(+ api_key="synthetic-test-key",+ base_url="https://provider.invalid/v1",+ model="synthetic-model",+ max_retries=0,+ http_client=http_client,+ )+ yield ProcessingLLMWrapper(model, owns_llm=False), calls+++def _strategy(model):+ return LangGraphAgentStrategy(+ model=model,+ search=MagicMock(),+ all_links_of_system=[],+ settings_snapshot={"search.tool": {"value": "mock"}},+ )+++@tool+def synthetic_search(query: str) -> str:+ """Return an offline synthetic observation."""+ return "A synthetic observation."++[email protected]("status", [200, 400, 402])+def test_real_sdk_agent_preserves_healthy_and_unrelated_results(status):+ body = _response() if status == 200 else {"error": {"message": DETAIL}}+ with _sdk_model([(status, body)]) as (model, calls):+ strategy = _strategy(model)+ with patch.object(+ strategy, "_build_tools", return_value=[synthetic_search]+ ):+ if status == 402:+ with pytest.raises(ProviderUsageLimitError) as raised:+ strategy.analyze_topic("synthetic query")+ error = raised.value+ assert (+ str(error)+ == TYPED_RESEARCH_ERROR_MESSAGES["openai_payment_required"]+ )+ assert error.__cause__ is None+ assert error.__context__ is None+ assert DETAIL not in str(error)+ else:+ result = strategy.analyze_topic("synthetic query")+ if status == 200:+ assert result.get("error") is None+ assert ANSWER in result["formatted_findings"]+ else:+ assert result["error"]+ assert "billing or usage limits" not in result["error"]+ assert len(calls) == 1+ assert calls[0]["tools"][0]["function"]["name"] == "synthetic_search"+++def test_next_invocation_recovers_after_a_usage_refusal():+ responses = [+ (402, {"error": {"message": DETAIL}}),+ (200, _response()),+ ]+ with _sdk_model(responses) as (model, calls):+ strategy = _strategy(model)+ with patch.object(+ strategy, "_build_tools", return_value=[synthetic_search]+ ):+ with pytest.raises(ProviderUsageLimitError):+ strategy.analyze_topic("synthetic query")+ result = strategy.analyze_topic("synthetic recovery query")+ assert len(calls) == 2+ assert result.get("error") is None+ assert ANSWER in result["formatted_findings"]+++def test_real_tool_results_survive_a_later_usage_refusal():+ # The real agent calls the tool, then encounters 402. Both fallback+ # synthesis and citation processing still use the actual model wrapper.+ first = _response(+ content=None,+ tool_calls=[+ {+ "id": "synthetic-call",+ "type": "function",+ "function": {+ "name": "synthetic_search",+ "arguments": json.dumps({"query": "synthetic query"}),+ },+ }+ ],+ )+ responses = [+ (200, first),+ (402, {"error": {"message": DETAIL}}),+ (200, _response("A synthetic retained answer [1].")),+ (200, _response("A synthetic retained answer [1].")),+ ]+ with _sdk_model(responses) as (model, calls):+ strategy = _strategy(model)+ tool_calls = []++ @tool("synthetic_search")+ def collect(query: str) -> str:+ """Record an offline synthetic source."""+ tool_calls.append(query)+ strategy.collector.add_results(+ [+ {+ "title": "Synthetic source",+ "link": "https://source.invalid/document",+ "snippet": "Synthetic source evidence.",+ }+ ]+ )+ return "[1] Synthetic source evidence."++ with patch.object(strategy, "_build_tools", return_value=[collect]):+ result = strategy.analyze_topic("synthetic query")+ assert tool_calls == ["synthetic query"]+ assert len(calls) == 4+ assert result.get("error") is None+ assert "synthetic retained answer" in result["formatted_findings"]+ assert "https://source.invalid/document" in result["formatted_findings"]+ assert DETAIL not in result["formatted_findings"]+++def test_agent_creation_refusal_uses_a_payload_free_signal():+ with _sdk_model([(402, {"error": {"message": DETAIL}})]) as (model, calls):+ with pytest.raises(openai.APIStatusError) as sdk_error:+ model.invoke("synthetic query")+ strategy = _strategy(model)+ with (+ patch.object(+ strategy, "_build_tools", return_value=[synthetic_search]+ ),+ patch("langchain.agents.create_agent", side_effect=sdk_error.value),+ pytest.raises(ProviderUsageLimitError) as raised,+ ):+ strategy.analyze_topic("synthetic query")+ assert len(calls) == 1+ assert raised.value.__cause__ is None+ assert raised.value.__context__ is None+ assert DETAIL not in str(raised.value)++[email protected]("boundary", ["creation", "stream"])[email protected]("control", ["policy", "cancellation"])+def test_agent_failures_never_convert_policy_or_cancellation(boundary, control):+ with _sdk_model([(402, {"error": {"message": DETAIL}})]) as (model, calls):+ with pytest.raises(openai.APIStatusError) as sdk_error:+ model.invoke("synthetic query")+ error = (+ PolicyDeniedError(+ Decision(allowed=False, reason="synthetic denial")+ )+ if control == "policy"+ else ResearchTerminatedException("synthetic cancellation")+ )+ error.__cause__ = sdk_error.value+ assert not is_openai_payment_required(error)+ agent = MagicMock()+ agent.stream.side_effect = error+ strategy = _strategy(model)+ with (+ patch.object(+ strategy, "_build_tools", return_value=[synthetic_search]+ ),+ patch(+ "langchain.agents.create_agent",+ side_effect=error if boundary == "creation" else None,+ return_value=agent,+ ),+ pytest.raises(type(error)) as raised,+ ):+ strategy.analyze_topic("synthetic query")+ assert raised.value is error+ assert len(calls) == 1diff --git a/tests/web/services/test_research_error_report_guidance.py b/tests/web/services/test_research_error_report_guidance.pyindex 9efa82f102..c14b99d940 100644--- a/tests/web/services/test_research_error_report_guidance.py+++ b/tests/web/services/test_research_error_report_guidance.py@@ -4,13 +4,21 @@ from contextlib import ExitStack, contextmanagerfrom unittest.mock import MagicMock, patchimport pytest+import httpx+import openaifrom fastapi import FastAPIfrom fastapi.testclient import TestClientfrom local_deep_research.database.models import ResearchHistory+from local_deep_research.error_handling.error_messages import (+ TYPED_RESEARCH_ERROR_MESSAGES,+)from local_deep_research.error_handling.report_generator import (ErrorReportGenerator,)+from local_deep_research.error_handling.openai_compat_errors import (+ ProviderUsageLimitError,+)from local_deep_research.storage.database import DatabaseReportStoragefrom local_deep_research.web.dependencies.auth import require_authfrom local_deep_research.web.routers.research import router@@ -23,6 +31,30 @@ from tests.web.services.helpers import ()+def _payment_refusal(marker):+ response = httpx.Response(+ 402,+ request=httpx.Request("POST", "https://provider.invalid/v1"),+ )+ return openai.APIStatusError(marker, response=response, body=None)+++def _request_refusal(marker):+ response = httpx.Response(+ 400,+ request=httpx.Request("POST", "https://provider.invalid/v1"),+ )+ return openai.BadRequestError(+ "Error type: openai_payment_required " + marker,+ response=response,+ body=None,+ )+++def _agent_usage_refusal(marker):+ return ProviderUsageLimitError()++@pytest.mark.parametrize("target, raw_error, expected_hint",[@@ -50,6 +82,27 @@ from tests.web.services.helpers import (("get_llm", "Error type: openai_bad_request", "rejected the request"),("get_llm", "Error type: openai_unknown", "returned an error"),("get_llm", "Error type: openai_rate_limit", "rate-limited"),+ (+ "get_llm",+ _payment_refusal,+ "billing or usage limits",+ ),+ (+ "analyze_topic",+ _payment_refusal,+ "billing or usage limits",+ ),+ (+ "analyze_topic",+ _agent_usage_refusal,+ "billing or usage limits",+ ),+ ("analyze_topic", _request_refusal, "rejected the request"),+ (+ "get_llm",+ "Error type: openai_payment_required",+ None,+ ),("get_llm", "model path does not exist", "LLM configuration"),("get_search", "api_key not configured", "search engine configuration"),],@@ -61,9 +114,19 @@ def test_worker_persists_specific_safe_error_report(patches = _base_run_patches()patches[f"{MODULE}.get_llm"] = MagicMock(return_value=MagicMock())patches[f"{MODULE}.get_search"] = MagicMock(return_value=MagicMock())- patches[f"{MODULE}.{target}"] = MagicMock(- side_effect=RuntimeError(f"{raw_error} {marker}")+ error = (+ raw_error(marker)+ if callable(raw_error)+ else RuntimeError(f"{raw_error} {marker}"))+ if target == "analyze_topic":+ system = MagicMock()+ system.analyze_topic.side_effect = error+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(+ return_value=system+ )+ else:+ patches[f"{MODULE}.{target}"] = MagicMock(side_effect=error)# Keep the real renderer in the real worker path. Earlier tests mocked# this boundary and only checked the safe message before it was rendered.patches[f"{MODULE}.ErrorReportGenerator"] = ErrorReportGenerator@@ -94,6 +157,8 @@ def test_worker_persists_specific_safe_error_report(},)+ if target == "analyze_topic":+ system.analyze_topic.assert_called_once_with("research query")report_db.expire_all()row = report_db.get(ResearchHistory, "report-errors")report = row.report_content@@ -102,7 +167,10 @@ def test_worker_persists_specific_safe_error_report(for line in report.splitlines()if line.startswith("**What happened:**"))- assert expected_hint.lower() in message.lower()+ if expected_hint is None:+ assert "unexpected error" in message.lower()+ else:+ assert expected_hint.lower() in message.lower()assert marker not in report# Apply the worker's queued failure metadata, then read it through HTTP.@@ -129,8 +197,22 @@ def test_worker_persists_specific_safe_error_report(TestClient(app) as client,):response = client.get("/api/research/report-errors/status")+ details = client.get("/api/research/report-errors")assert response.status_code == 200, response.text+ assert details.status_code == 200metadata = response.json()["metadata"]- assert expected_hint.lower() in metadata["error"].lower()- assert expected_hint.lower() in metadata["error_info"]["message"].lower()+ assert details.json()["metadata"]["error"] == metadata["error"]+ assert marker not in details.text+ payment_message = TYPED_RESEARCH_ERROR_MESSAGES["openai_payment_required"]+ assert (metadata["error"] == payment_message) is (+ raw_error in (_payment_refusal, _agent_usage_refusal)+ )+ if expected_hint is None:+ assert metadata["error_info"]["type"] == "unknown"+ assert "openai_payment_required" not in response.text+ else:+ assert expected_hint.lower() in metadata["error"].lower()+ assert (+ expected_hint.lower() in metadata["error_info"]["message"].lower()+ )assert marker not in response.text