google.py
Overview
google.py is a utility component designed to perform Google searches via the SerpApi service. It provides a structured interface for querying Google's search engine, retrieving organic search results, and formatting these results for further use within the InfiniFlow system. The component encapsulates parameter validation, request execution with retry and timeout logic, and result extraction.
The file defines two main classes:
GoogleParam: Encapsulates the parameters and validation logic for the Google search tool.Google: Implements the search execution logic and result processing by interacting with the SerpApi GoogleSearch API.
This component enables the InfiniFlow agents or tools to integrate Google search capabilities seamlessly, supporting configurable search queries, result pagination, and localization options such as country and language.
Classes and Methods
Class: GoogleParam
Defines the configurable parameters for the Google search tool and validates them.
Attributes
meta(ToolMeta): Metadata describing the tool, including name, description, and input parameter schema.start(int): Result offset for pagination. Defaults to 0.num(int): Number of search results to return. Defaults to 6.api_key(str): API key for SerpApi authentication.country(str): Country code for localized search results. Defaults to"cn".language(str): Language code for search results localization. Defaults to"en".
Methods
init(self)Initializes default parameters and metadata for the Google search tool.
check(self)Validates that required parameters are provided and that
countryandlanguagevalues are within allowed sets.Raises:
Validation errors if API key is missing or if country/language codes are invalid.
get_input_form(self) -> dict[str, dict]Returns a dictionary describing the input form fields for this tool, used by UI or API consumers.
Returns:
Dictionary with keys:q: Query string input.start: Integer input for pagination offset.num: Integer input for result count limit.
Usage Example
param = GoogleParam()
param.api_key = "your_serpapi_key"
param.country = "us"
param.language = "en"
param.start = 0
param.num = 10
param.check() # Raises error if invalid
input_form = param.get_input_form()
print(input_form)
Class: Google (inherits ToolBase, ABC)
Implements the Google search tool's core functionality, including request invocation, result retrieval, and error handling.
Class Attributes
component_name(str): Identifier for the component, set to"Google".
Methods
_invoke(self, **kwargs)Executes the Google search query using SerpApi.
Parameters:
q(str): The search query keywords. Required.
Returns:
str: The formatted search content extracted from results, or an error message.
Behavior:
If
qis missing, returns empty content.Constructs parameters including API key, search engine type, country, language, and query.
Retries the search up to
max_retries + 1times on failure, with a delay between retries.On success, extracts chunks of search results:
Title from result's
title.URL from result's
link.Content from the nested "about_this_result" description or fallback snippet.
Sets output JSON and formalized content.
Logs exceptions and returns error info if all retries fail.
thoughts(self) -> strProvides a summary string describing the current query's intent.
Returns:
A string that includes the keywords being searched and a note about relevance focus.
Implementation Details
Uses
@timeoutdecorator to enforce execution time limits (default 12 seconds or environment variable overridden).Uses SerpApi's
GoogleSearchPython client to perform queries.Extracts "organic_results" from API responses.
Implements incremental retries with logging and delays (
delay_after_errorparameter).Uses helper method
_retrieve_chunks(presumed inherited fromToolBase) to parse and store result pieces.
Usage Example
google_tool = Google()
google_tool._param.api_key = "your_serpapi_key"
google_tool._param.country = "us"
google_tool._param.language = "en"
google_tool._param.max_retries = 2
google_tool._param.delay_after_error = 1
result = google_tool._invoke(q="OpenAI GPT-4 capabilities")
print(result)
Important Implementation Details and Algorithms
Parameter Validation: The
GoogleParam.checkmethod ensures the API key is present and validates that country and language codes are within predefined lists of valid ISO codes. This prevents invalid API requests and helps localize searches.Retry Logic: The
_invokemethod performs multiple retries when invoking the search API. Retries are spaced bydelay_after_errorseconds. This is important to handle transient network errors or rate limiting from SerpApi.Timeout Handling: The method is decorated with a timeout to enforce maximum execution duration, preventing hanging calls.
Result Extraction Algorithm: The method extracts search result pieces by providing three lambdas to
_retrieve_chunks:Title from the
"title"field.URL from the
"link"field.Content preferentially from
"about_this_result" → "source" → "description", falling back to"snippet"if not available.
Localization: The
gl(country) andhl(language) parameters in the SerpApi query control localization of search results.
Interaction with Other System Components
Base Classes:
GoogleParaminherits fromToolParamBaseandGoogleinherits fromToolBaseandABC, indicating that this module relies on base tool classes defined elsewhere in the system (agent.tools.base). These base classes likely provide methods such as_retrieve_chunks,set_output, andoutput.SerpApi Library: Uses the external
serpapiPython package to communicate with the Google Search API.API Utilities: Uses
timeoutdecorator fromapi.utils.api_utilsto manage execution time constraints.Environment Configuration: Reads environment variable
COMPONENT_EXEC_TIMEOUTto configure runtime timeout.Logging: Uses Python's standard logging for error reporting.
Output Setting: The tool sets outputs such as
"json","formalized_content", and"_ERROR"to communicate results or errors back to the framework.
Mermaid Diagram
The following class diagram illustrates the structure and main methods of the classes defined in google.py:
classDiagram
class GoogleParam {
+meta: ToolMeta
+start: int
+num: int
+api_key: str
+country: str
+language: str
+__init__()
+check()
+get_input_form() dict
}
class Google {
+component_name: str = "Google"
+_invoke(**kwargs) str
+thoughts() str
}
GoogleParam <|-- GoogleParamBase
Google --> ToolBase
Google --> ABC
Summary
The google.py file implements a specialized tool within the InfiniFlow system to perform Google web searches using the SerpApi service. It provides parameter encapsulation and validation (GoogleParam), search execution with retry and timeout handling (Google), and result extraction for integration with downstream components. This modular design supports flexible and localized Google search queries within larger AI agent workflows.