You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

google.py 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import os
  18. import time
  19. from abc import ABC
  20. from serpapi import GoogleSearch
  21. from agent.tools.base import ToolParamBase, ToolMeta, ToolBase
  22. from api.utils.api_utils import timeout
  23. class GoogleParam(ToolParamBase):
  24. """
  25. Define the Google component parameters.
  26. """
  27. def __init__(self):
  28. self.meta:ToolMeta = {
  29. "name": "google_search",
  30. "description": """Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking ...""",
  31. "parameters": {
  32. "q": {
  33. "type": "string",
  34. "description": "The search keywords to execute with Google. The keywords should be the most important words/terms(includes synonyms) from the original request.",
  35. "default": "{sys.query}",
  36. "required": True
  37. },
  38. "start": {
  39. "type": "integer",
  40. "description": "Parameter defines the result offset. It skips the given number of results. It's used for pagination. (e.g., 0 (default) is the first page of results, 10 is the 2nd page of results, 20 is the 3rd page of results, etc.). Google Local Results only accepts multiples of 20(e.g. 20 for the second page results, 40 for the third page results, etc.) as the `start` value.",
  41. "default": "0",
  42. "required": False,
  43. },
  44. "num": {
  45. "type": "integer",
  46. "description": "Parameter defines the maximum number of results to return. (e.g., 10 (default) returns 10 results, 40 returns 40 results, and 100 returns 100 results). The use of num may introduce latency, and/or prevent the inclusion of specialized result types. It is better to omit this parameter unless it is strictly necessary to increase the number of results per page. Results are not guaranteed to have the number of results specified in num.",
  47. "default": "6",
  48. "required": False,
  49. }
  50. }
  51. }
  52. super().__init__()
  53. self.start = 0
  54. self.num = 6
  55. self.api_key = ""
  56. self.country = "cn"
  57. self.language = "en"
  58. def check(self):
  59. self.check_empty(self.api_key, "SerpApi API key")
  60. self.check_valid_value(self.country, "Google Country",
  61. ['af', 'al', 'dz', 'as', 'ad', 'ao', 'ai', 'aq', 'ag', 'ar', 'am', 'aw', 'au', 'at',
  62. 'az', 'bs', 'bh', 'bd', 'bb', 'by', 'be', 'bz', 'bj', 'bm', 'bt', 'bo', 'ba', 'bw',
  63. 'bv', 'br', 'io', 'bn', 'bg', 'bf', 'bi', 'kh', 'cm', 'ca', 'cv', 'ky', 'cf', 'td',
  64. 'cl', 'cn', 'cx', 'cc', 'co', 'km', 'cg', 'cd', 'ck', 'cr', 'ci', 'hr', 'cu', 'cy',
  65. 'cz', 'dk', 'dj', 'dm', 'do', 'ec', 'eg', 'sv', 'gq', 'er', 'ee', 'et', 'fk', 'fo',
  66. 'fj', 'fi', 'fr', 'gf', 'pf', 'tf', 'ga', 'gm', 'ge', 'de', 'gh', 'gi', 'gr', 'gl',
  67. 'gd', 'gp', 'gu', 'gt', 'gn', 'gw', 'gy', 'ht', 'hm', 'va', 'hn', 'hk', 'hu', 'is',
  68. 'in', 'id', 'ir', 'iq', 'ie', 'il', 'it', 'jm', 'jp', 'jo', 'kz', 'ke', 'ki', 'kp',
  69. 'kr', 'kw', 'kg', 'la', 'lv', 'lb', 'ls', 'lr', 'ly', 'li', 'lt', 'lu', 'mo', 'mk',
  70. 'mg', 'mw', 'my', 'mv', 'ml', 'mt', 'mh', 'mq', 'mr', 'mu', 'yt', 'mx', 'fm', 'md',
  71. 'mc', 'mn', 'ms', 'ma', 'mz', 'mm', 'na', 'nr', 'np', 'nl', 'an', 'nc', 'nz', 'ni',
  72. 'ne', 'ng', 'nu', 'nf', 'mp', 'no', 'om', 'pk', 'pw', 'ps', 'pa', 'pg', 'py', 'pe',
  73. 'ph', 'pn', 'pl', 'pt', 'pr', 'qa', 're', 'ro', 'ru', 'rw', 'sh', 'kn', 'lc', 'pm',
  74. 'vc', 'ws', 'sm', 'st', 'sa', 'sn', 'rs', 'sc', 'sl', 'sg', 'sk', 'si', 'sb', 'so',
  75. 'za', 'gs', 'es', 'lk', 'sd', 'sr', 'sj', 'sz', 'se', 'ch', 'sy', 'tw', 'tj', 'tz',
  76. 'th', 'tl', 'tg', 'tk', 'to', 'tt', 'tn', 'tr', 'tm', 'tc', 'tv', 'ug', 'ua', 'ae',
  77. 'uk', 'gb', 'us', 'um', 'uy', 'uz', 'vu', 've', 'vn', 'vg', 'vi', 'wf', 'eh', 'ye',
  78. 'zm', 'zw'])
  79. self.check_valid_value(self.language, "Google languages",
  80. ['af', 'ak', 'sq', 'ws', 'am', 'ar', 'hy', 'az', 'eu', 'be', 'bem', 'bn', 'bh',
  81. 'xx-bork', 'bs', 'br', 'bg', 'bt', 'km', 'ca', 'chr', 'ny', 'zh-cn', 'zh-tw', 'co',
  82. 'hr', 'cs', 'da', 'nl', 'xx-elmer', 'en', 'eo', 'et', 'ee', 'fo', 'tl', 'fi', 'fr',
  83. 'fy', 'gaa', 'gl', 'ka', 'de', 'el', 'kl', 'gn', 'gu', 'xx-hacker', 'ht', 'ha', 'haw',
  84. 'iw', 'hi', 'hu', 'is', 'ig', 'id', 'ia', 'ga', 'it', 'ja', 'jw', 'kn', 'kk', 'rw',
  85. 'rn', 'xx-klingon', 'kg', 'ko', 'kri', 'ku', 'ckb', 'ky', 'lo', 'la', 'lv', 'ln', 'lt',
  86. 'loz', 'lg', 'ach', 'mk', 'mg', 'ms', 'ml', 'mt', 'mv', 'mi', 'mr', 'mfe', 'mo', 'mn',
  87. 'sr-me', 'my', 'ne', 'pcm', 'nso', 'no', 'nn', 'oc', 'or', 'om', 'ps', 'fa',
  88. 'xx-pirate', 'pl', 'pt', 'pt-br', 'pt-pt', 'pa', 'qu', 'ro', 'rm', 'nyn', 'ru', 'gd',
  89. 'sr', 'sh', 'st', 'tn', 'crs', 'sn', 'sd', 'si', 'sk', 'sl', 'so', 'es', 'es-419', 'su',
  90. 'sw', 'sv', 'tg', 'ta', 'tt', 'te', 'th', 'ti', 'to', 'lua', 'tum', 'tr', 'tk', 'tw',
  91. 'ug', 'uk', 'ur', 'uz', 'vu', 'vi', 'cy', 'wo', 'xh', 'yi', 'yo', 'zu']
  92. )
  93. def get_input_form(self) -> dict[str, dict]:
  94. return {
  95. "q": {
  96. "name": "Query",
  97. "type": "line"
  98. },
  99. "start": {
  100. "name": "From",
  101. "type": "integer",
  102. "value": 0
  103. },
  104. "num": {
  105. "name": "Limit",
  106. "type": "integer",
  107. "value": 12
  108. }
  109. }
  110. class Google(ToolBase, ABC):
  111. component_name = "Google"
  112. @timeout(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))
  113. def _invoke(self, **kwargs):
  114. if not kwargs.get("q"):
  115. self.set_output("formalized_content", "")
  116. return ""
  117. params = {
  118. "api_key": self._param.api_key,
  119. "engine": "google",
  120. "q": kwargs["q"],
  121. "google_domain": "google.com",
  122. "gl": self._param.country,
  123. "hl": self._param.language
  124. }
  125. last_e = ""
  126. for _ in range(self._param.max_retries+1):
  127. try:
  128. search = GoogleSearch(params).get_dict()
  129. self._retrieve_chunks(search["organic_results"],
  130. get_title=lambda r: r["title"],
  131. get_url=lambda r: r["link"],
  132. get_content=lambda r: r.get("about_this_result", {}).get("source", {}).get("description", r["snippet"])
  133. )
  134. self.set_output("json", search["organic_results"])
  135. return self.output("formalized_content")
  136. except Exception as e:
  137. last_e = e
  138. logging.exception(f"Google error: {e}")
  139. time.sleep(self._param.delay_after_error)
  140. if last_e:
  141. self.set_output("_ERROR", str(last_e))
  142. return f"Google error: {last_e}"
  143. assert False, self.output()
  144. def thoughts(self) -> str:
  145. return """
  146. Keywords: {}
  147. Looking for the most relevant articles.
  148. """.format(self.get_input().get("query", "-_-!"))