Skip to content

The agent engineering platform.

community: Handling missing key in Google Trends API response. (#15864)

Luke5396604ef482
diff --git a/libs/community/langchain_community/utilities/google_trends.py b/libs/community/langchain_community/utilities/google_trends.py
index f0f15000c8..59df344856 100644
--- a/libs/community/langchain_community/utilities/google_trends.py
+++ b/libs/community/langchain_community/utilities/google_trends.py
@@ -65,7 +65,12 @@ class GoogleTrendsAPIWrapper(BaseModel):
total_results = []
client = self.serp_search_engine(params)
- total_results = client.get_dict()["interest_over_time"]["timeline_data"]
+ client_dict = client.get_dict()
+ total_results = (
+ client_dict["interest_over_time"]["timeline_data"]
+ if "interest_over_time" in client_dict
+ else None
+ )
if not total_results:
return "No good Trend Result was found"
diff --git a/libs/community/tests/integration_tests/utilities/test_google_trends.py b/libs/community/tests/integration_tests/utilities/test_google_trends.py
new file mode 100644
index 0000000000..0455f16a58
--- /dev/null
+++ b/libs/community/tests/integration_tests/utilities/test_google_trends.py
@@ -0,0 +1,33 @@
+"""Unit test for Google Trends API Wrapper."""
+import os
+from unittest.mock import patch
+
+from langchain_community.utilities.google_trends import GoogleTrendsAPIWrapper
+
+
+@patch("serpapi.SerpApiClient.get_json")
+def test_unexpected_response(mocked_serpapiclient):
+ os.environ["SERPAPI_API_KEY"] = "123abcd"
+ resp = {
+ "search_metadata": {
+ "id": "659f32ec36e6a9107b46b5b4",
+ "status": "Error",
+ "json_endpoint": "https://serpapi.com/searches/.../659f32ec36e6a9107b46b5b4.json",
+ "created_at": "2024-01-11 00:14:36 UTC",
+ "processed_at": "2024-01-11 00:14:36 UTC",
+ "google_trends_url": "https://trends.google.com/trends/api/explore?tz=420&req=%7B%22comparisonItem%22%3A%5B%7B%22keyword%22%3A%22Lego+building+trends+2022%22%2C%22geo%22%3A%22%22%2C%22time%22%3A%22today+12-m%22%7D%5D%2C%22category%22%3A0%2C%22property%22%3A%22%22%2C%22userConfig%22%3A%22%7BuserType%3A+%5C%22USER_TYPE_LEGIT_USER%5C%22%7D%22%7D",
+ "prettify_html_file": "https://serpapi.com/searches/.../659f32ec36e6a9107b46b5b4.prettify",
+ "total_time_taken": 90.14,
+ },
+ "search_parameters": {
+ "engine": "google_trends",
+ "q": "Lego building trends 2022",
+ "date": "today 12-m",
+ "tz": "420",
+ "data_type": "TIMESERIES",
+ },
+ "error": "We couldn't get valid ... Please try again later.",
+ }
+ mocked_serpapiclient.return_value = resp
+ tool = GoogleTrendsAPIWrapper()
+ tool.run("does not matter")