serpapi_wrapper.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from langchain import SerpAPIWrapper
  2. from pydantic import Field, BaseModel
  3. class OptimizedSerpAPIInput(BaseModel):
  4. query: str = Field(..., description="search query.")
  5. class OptimizedSerpAPIWrapper(SerpAPIWrapper):
  6. @staticmethod
  7. def _process_response(res: dict, num_results: int = 5) -> str:
  8. """Process response from SerpAPI."""
  9. if "error" in res.keys():
  10. raise ValueError(f"Got error from SerpAPI: {res['error']}")
  11. if "answer_box" in res.keys() and type(res["answer_box"]) == list:
  12. res["answer_box"] = res["answer_box"][0]
  13. if "answer_box" in res.keys() and "answer" in res["answer_box"].keys():
  14. toret = res["answer_box"]["answer"]
  15. elif "answer_box" in res.keys() and "snippet" in res["answer_box"].keys():
  16. toret = res["answer_box"]["snippet"]
  17. elif (
  18. "answer_box" in res.keys()
  19. and "snippet_highlighted_words" in res["answer_box"].keys()
  20. ):
  21. toret = res["answer_box"]["snippet_highlighted_words"][0]
  22. elif (
  23. "sports_results" in res.keys()
  24. and "game_spotlight" in res["sports_results"].keys()
  25. ):
  26. toret = res["sports_results"]["game_spotlight"]
  27. elif (
  28. "shopping_results" in res.keys()
  29. and "title" in res["shopping_results"][0].keys()
  30. ):
  31. toret = res["shopping_results"][:3]
  32. elif (
  33. "knowledge_graph" in res.keys()
  34. and "description" in res["knowledge_graph"].keys()
  35. ):
  36. toret = res["knowledge_graph"]["description"]
  37. elif 'organic_results' in res.keys() and len(res['organic_results']) > 0:
  38. toret = ""
  39. for result in res["organic_results"][:num_results]:
  40. if "link" in result:
  41. toret += "----------------\nlink: " + result["link"] + "\n"
  42. if "snippet" in result:
  43. toret += "snippet: " + result["snippet"] + "\n"
  44. else:
  45. toret = "No good search result found"
  46. return "search result:\n" + toret