Skip to content

Commit

Permalink
Fix a bug that shows "KeyError 'items'" (#1118)
Browse files Browse the repository at this point in the history
Fix KeyError 'items' when no result found.

## Problem

When no result found for a query, google search crashed with `KeyError
'items'`.

## Solution

I added a check for an empty response before accessing the 'items' key.
It will handle the case correctly.

## Other

my twitter: yakigac
(I don't mind even if you don't mention me for this PR. But just because
last time my real name was shout out :) )
  • Loading branch information
yakigac authored Feb 17, 2023
1 parent 2bee8d4 commit 1ed7083
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
2 changes: 1 addition & 1 deletion langchain/utilities/google_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def _google_search_results(self, search_term: str, **kwargs: Any) -> List[dict]:
.list(q=search_term, cx=self.google_cse_id, **kwargs)
.execute()
)
return res["items"]
return res.get("items", [])

@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
Expand Down
10 changes: 10 additions & 0 deletions tests/integration_tests/test_googlesearch_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,13 @@ def test_call() -> None:
search = GoogleSearchAPIWrapper()
output = search.run("What was Obama's first name?")
assert "Barack Hussein Obama II" in output


def test_no_result_call() -> None:
"""Test that call gives no result."""
search = GoogleSearchAPIWrapper()
output = search.run(
"NORESULTCALL_NORESULTCALL_NORESULTCALL_NORESULTCALL_NORESULTCALL_NORESULTCALL"
)
print(type(output))
assert "No good Google Search Result was found" == output

0 comments on commit 1ed7083

Please sign in to comment.