Skip to content

fix(agent/tools): surface serpapi error responses in google search - #17062

Merged
yuzhichang merged 2 commits into
infiniflow:mainfrom
Yurii214:fix/google-serpapi-error-handling
Jul 21, 2026
Merged

yuzhichang merged 2 commits into
infiniflow:mainfrom
Yurii214:fix/google-serpapi-error-handling

Conversation

@Yurii214

Copy link
Copy Markdown
Contributor

Summary

agent/tools/google.py indexes search["organic_results"] directly after GoogleSearch(params).get_dict(). serpapi returns {"error": ...} without an organic_results key on realistic conditions — an invalid API key, an exhausted plan/quota, or a query that matched nothing. that raised KeyError('organic_results'), which the tool's retry loop then surfaced to the model as the opaque "Google error: 'organic_results'" instead of the real reason.

this guards the missing key and raises serpapi's actual error message (with a clear fallback) into the existing retry/_ERROR path, so the model sees e.g. "Google error: Invalid API key.". valid responses are unchanged.

adds test/unit_test/agent/tools/test_google_unit.py covering the error-response path (asserts the real message is surfaced, no KeyError) and the normal result path, mirroring the existing test_googlescholar.py pattern (skips when the serpapi SDK is absent).

serpapi reports an invalid api key, exhausted quota or an empty result
set through an "error" field and omits "organic_results". the google
search tool indexed search["organic_results"] directly, so those cases
raised KeyError('organic_results'), which the retry loop reported to the
model as the opaque "Google error: 'organic_results'".

guard the missing key and surface serpapi's actual message (with a clear
fallback) through the existing retry/_ERROR path instead. adds a
regression test covering the error response and the normal result path.
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Jul 17, 2026
@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 78c4dda1-077d-46b9-a363-3fe16be512d1

📥 Commits

Reviewing files that changed from the base of the PR and between c44f0ef and f0938e0.

📒 Files selected for processing (2)
  • agent/tools/google.py
  • test/unit_test/agent/tools/test_google_unit.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • agent/tools/google.py
  • test/unit_test/agent/tools/test_google_unit.py

📝 Walkthrough

Walkthrough

Changes

SerpApi response handling

Layer / File(s) Summary
Response validation and resilient result extraction
agent/tools/google.py
Google._invoke reports SerpApi errors when organic_results is missing, reuses the extracted results for chunk retrieval and JSON output, and safely handles missing title or URL fields.
Unit coverage for response paths
test/unit_test/agent/tools/test_google_unit.py
Stubbed SerpApi responses test error propagation, valid result forwarding, and rendering when optional result fields are absent.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

  • infiniflow/ragflow#17064: Adds analogous upstream search-response validation and error-message tests for the GitHub tool.

Poem

A rabbit watched search results gleam,
Missing fields no longer interrupt the stream.
Errors now hop out clear and bright,
While valid results land just right.
Tests thump paws beneath moonlight.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: surfacing SerpApi error responses in Google search.
Description check ✅ Passed The description includes the required Summary section and clearly explains the bug, fix, and test coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
agent/tools/google.py (1)

504-505: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prefer RuntimeError over base Exception.

Raising the base Exception class is generally discouraged in Python as it can be too broad to catch safely in other contexts. Consider raising a more specific exception like RuntimeError.

♻️ Proposed refactor
                 if "organic_results" not in search:
-                    raise Exception(search.get("error", "SerpApi returned no organic_results."))
+                    raise RuntimeError(search.get("error", "SerpApi returned no organic_results."))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agent/tools/google.py` around lines 504 - 505, In the organic-results
validation within the Google search flow, replace the base Exception raised when
"organic_results" is missing with RuntimeError, preserving the existing error
message and condition.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@agent/tools/google.py`:
- Around line 508-513: Update the get_content lambda passed to _retrieve_chunks
to use r.get("snippet", "") as the fallback, preventing eager evaluation from
raising KeyError when description exists without snippet. Also use safe .get()
access for title and link in the adjacent get_title and get_url lambdas.

---

Nitpick comments:
In `@agent/tools/google.py`:
- Around line 504-505: In the organic-results validation within the Google
search flow, replace the base Exception raised when "organic_results" is missing
with RuntimeError, preserving the existing error message and condition.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a25cf52f-5de8-46d8-a584-25b7f9cdc2f5

📥 Commits

Reviewing files that changed from the base of the PR and between 8ebdc02 and c44f0ef.

📒 Files selected for processing (2)
  • agent/tools/google.py
  • test/unit_test/agent/tools/test_google_unit.py

Comment thread agent/tools/google.py Resolved
@Haruko386 Haruko386 added the ci Continue Integration label Jul 20, 2026
Comment thread agent/tools/google.py Resolved
@Harry-Hz-Zhang Harry-Hz-Zhang added ci Continue Integration and removed ci Continue Integration labels Jul 20, 2026
@codecov

codecov Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (7c698f8) to head (f0938e0).
⚠️ Report is 83 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #17062      +/-   ##
==========================================
- Coverage   94.56%   90.65%   -3.91%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      650      -28     
- Misses         25       39      +14     
- Partials       14       28      +14     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

review follow-up: the get_content fallback `r["snippet"]` is evaluated
eagerly, so a result carrying a description but no snippet raised
KeyError('snippet') before the description fallback was ever used --
the same failure mode this pr set out to remove. read title, link and
snippet with .get() defaults.

also raise RuntimeError rather than the base Exception for the missing
organic_results case, and extend the test stub to apply the getters to
every result so the lambdas are actually exercised.
@Yurii214

Copy link
Copy Markdown
Contributor Author

Thanks @Hz-186 — good catch, fixed in f0938e0.

r["snippet"] was evaluated eagerly as the .get(..., default) argument, so a result carrying a description but no snippet raised KeyError('snippet') before the description fallback ever ran — the same failure mode this PR set out to remove. title, link and snippet now use .get() defaults.

Also switched the missing-organic_results raise from the base Exception to RuntimeError per the other note, and extended the test stub to apply the getters to each result so the lambdas are actually covered — including a new case for a result with a description and no snippet.

@Harry-Hz-Zhang Harry-Hz-Zhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Yurii214, LGTM ! ! !

@Harry-Hz-Zhang Harry-Hz-Zhang added lgtm This PR has been approved by a maintainer ci Continue Integration and removed ci Continue Integration labels Jul 21, 2026
@yuzhichang
yuzhichang merged commit 4f1820b into infiniflow:main Jul 21, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration lgtm This PR has been approved by a maintainer 🌈 python Pull requests that update Python code size:S This PR changes 10-29 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants