---------------------------------------------------------------------- This is the API documentation for the serpapi_search_tools library. ---------------------------------------------------------------------- ## Enumerations and errors Supported engines, response modes, semantic travel values, and search failures WebSearchEngine(*values) General web indexes supported by :func:`web_search`. ShoppingSearchEngine(*values) Product indexes supported by :func:`shopping_search`. SearchResultMode(*values) Control how much of a SerpApi response is returned to the agent. TravelClass(*values) Cabin class shared by flight and travel-explore tools. SerpApiSearchError A sanitized failure raised while executing a search. ## Functions Create capability-specific search tools for Python and agent SDKs web_search(*, provider: 'ProviderName | str' = 'auto', allowed_engines: 'Iterable[WebSearchEngine | str] | WebSearchEngine | str | None' = None, default_engine: 'WebSearchEngine | str | None' = None, include_examples: 'bool' = True, api_key: 'str | None' = None, client: 'SearchClient | None' = None, default_params: 'Mapping[str, Any] | None' = None, timeout: 'float | None' = None, mode: 'SearchResultMode | str' = , name: 'str' = 'web_search') -> 'Any' Create a general-web search tool. Parameters ---------- provider Agent SDK adapter name, ``"auto"``, or ``"function"`` for a callable. allowed_engines Web indexes exposed in the model-facing ``engine`` enum. default_engine Engine used when the model omits ``engine``. Defaults to Google Light when it is allowed. include_examples Add a short call example to the model-facing description. api_key, client, default_params, timeout, mode Runtime authentication, custom client, application filters, timeout, and compact or full response selection. name Tool name presented to the model. Returns ------- Any A provider-native tool whose input fields are ``query`` and ``engine``. news_search(*, provider: 'ProviderName | str' = 'auto', include_examples: 'bool' = True, api_key: 'str | None' = None, client: 'SearchClient | None' = None, default_params: 'Mapping[str, Any] | None' = None, timeout: 'float | None' = None, mode: 'SearchResultMode | str' = , name: 'str' = 'news_search') -> 'Any' Create a Google News query-mode tool for current articles and stories. Parameters ---------- provider Agent SDK adapter name, ``"auto"``, or ``"function"``. include_examples Add a short call example to the model-facing description. api_key, client, default_params, timeout, mode Runtime authentication, custom client, application filters, timeout, and compact or full response selection. name Tool name presented to the model. Returns ------- Any A provider-native tool with one required ``query`` input. maps_search(*, provider: 'ProviderName | str' = 'auto', include_examples: 'bool' = True, api_key: 'str | None' = None, client: 'SearchClient | None' = None, default_params: 'Mapping[str, Any] | None' = None, timeout: 'float | None' = None, mode: 'SearchResultMode | str' = , name: 'str' = 'maps_search') -> 'Any' Create a Google Maps search-mode tool for places and businesses. The returned tool exposes ``query`` plus optional ``location``, ``zoom``, and ``nearby`` fields. ``zoom`` is constrained to 3 through 30, and ``nearby=True`` requires ``location``. Parameters ---------- provider Agent SDK adapter name, ``"auto"``, or ``"function"``. include_examples Add a short call example to the model-facing description. api_key, client, default_params, timeout, mode Runtime authentication, custom client, application filters, timeout, and compact or full response selection. name Tool name presented to the model. Returns ------- Any A provider-native Google Maps search tool. images_search(*, provider: 'ProviderName | str' = 'auto', include_examples: 'bool' = True, api_key: 'str | None' = None, client: 'SearchClient | None' = None, default_params: 'Mapping[str, Any] | None' = None, timeout: 'float | None' = None, mode: 'SearchResultMode | str' = , name: 'str' = 'images_search') -> 'Any' Create a Google Images tool for image URLs and metadata. Parameters ---------- provider Agent SDK adapter name, ``"auto"``, or ``"function"``. include_examples Add a short call example to the model-facing description. api_key, client, default_params, timeout, mode Runtime authentication, custom client, application filters, timeout, and compact or full response selection. name Tool name presented to the model. Returns ------- Any A provider-native tool with one required ``query`` input. shopping_search(*, provider: 'ProviderName | str' = 'auto', allowed_engines: 'Iterable[ShoppingSearchEngine | str] | ShoppingSearchEngine | str | None' = None, default_engine: 'ShoppingSearchEngine | str | None' = None, include_examples: 'bool' = True, api_key: 'str | None' = None, client: 'SearchClient | None' = None, default_params: 'Mapping[str, Any] | None' = None, timeout: 'float | None' = None, mode: 'SearchResultMode | str' = , name: 'str' = 'shopping_search') -> 'Any' Create a multi-marketplace product search tool. Parameters ---------- provider Agent SDK adapter name, ``"auto"``, or ``"function"`` for a callable. allowed_engines Marketplaces exposed in the model-facing ``engine`` enum. default_engine Marketplace used when the model omits ``engine``. include_examples Add a short call example to the model-facing description. api_key, client, default_params, timeout, mode Runtime authentication, custom client, application filters, timeout, and compact or full response selection. name Tool name presented to the model. Returns ------- Any A provider-native tool whose input fields are ``query`` and ``engine``. videos_search(*, provider: 'ProviderName | str' = 'auto', include_examples: 'bool' = True, api_key: 'str | None' = None, client: 'SearchClient | None' = None, default_params: 'Mapping[str, Any] | None' = None, timeout: 'float | None' = None, mode: 'SearchResultMode | str' = , name: 'str' = 'videos_search') -> 'Any' Create a YouTube tool for videos, channels, and playlists. Parameters ---------- provider Agent SDK adapter name, ``"auto"``, or ``"function"``. include_examples Add a short call example to the model-facing description. api_key, client, default_params, timeout, mode Runtime authentication, custom client, application filters, timeout, and compact or full response selection. name Tool name presented to the model. Returns ------- Any A provider-native tool with one required ``query`` input. hotels_search(*, provider: 'ProviderName | str' = 'auto', include_examples: 'bool' = True, api_key: 'str | None' = None, client: 'SearchClient | None' = None, default_params: 'Mapping[str, Any] | None' = None, timeout: 'float | None' = None, mode: 'SearchResultMode | str' = , name: 'str' = 'hotels_search') -> 'Any' Create a Google Hotels tool with explicit stay dates. The returned tool requires ``query``, ``check_in_date``, and ``check_out_date``. It also exposes typed adult, child, and child-age fields. Parameters ---------- provider Agent SDK adapter name, ``"auto"``, or ``"function"``. include_examples Add a short call example to the model-facing description. api_key, client, default_params, timeout, mode Runtime authentication, custom client, application filters, timeout, and compact or full response selection. name Tool name presented to the model. Returns ------- Any A provider-native Google Hotels tool with a closed input schema. flights_search(*, provider: 'ProviderName | str' = 'auto', include_examples: 'bool' = True, api_key: 'str | None' = None, client: 'SearchClient | None' = None, default_params: 'Mapping[str, Any] | None' = None, timeout: 'float | None' = None, mode: 'SearchResultMode | str' = , name: 'str' = 'flights_search') -> 'Any' Create a Google Flights tool for one-way and round-trip routes. The returned tool requires departure, arrival, and outbound date fields. Adding ``return_date`` selects a round trip. Cabin class and passenger counts are semantic typed fields; no synthetic ``q`` field is exposed. Parameters ---------- provider Agent SDK adapter name, ``"auto"``, or ``"function"``. include_examples Add a short call example to the model-facing description. api_key, client, default_params, timeout, mode Runtime authentication, custom client, application filters, timeout, and compact or full response selection. name Tool name presented to the model. Returns ------- Any A provider-native Google Flights route-search tool. travel_explore_search(*, provider: 'ProviderName | str' = 'auto', include_examples: 'bool' = True, api_key: 'str | None' = None, client: 'SearchClient | None' = None, default_params: 'Mapping[str, Any] | None' = None, timeout: 'float | None' = None, mode: 'SearchResultMode | str' = , name: 'str' = 'travel_explore_search') -> 'Any' Create a Google Travel Explore destination-discovery tool. The returned tool requires only ``departure_id`` and offers optional destination, date, cabin-class, and passenger fields. It never exposes or sends a synthetic ``q`` parameter. Parameters ---------- provider Agent SDK adapter name, ``"auto"``, or ``"function"``. include_examples Add a short call example to the model-facing description. api_key, client, default_params, timeout, mode Runtime authentication, custom client, application filters, timeout, and compact or full response selection. name Tool name presented to the model. Returns ------- Any A provider-native Google Travel Explore tool. ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ## Start Here # Add live search to your Python agent `serpapi-search-tools` gives Python agents current web and specialized search through [SerpApi](https://serpapi.com). Add only the capabilities your agent needs—such as web, news, maps, shopping, hotels, or flights—and use them with your existing agent SDK or as normal Python functions. ## Supported agent SDKs The package works with OpenAI Agents SDK, Pydantic AI, LangChain, LangGraph, CrewAI, LlamaIndex, Claude Agent SDK, Microsoft Agent Framework, AutoGen, Haystack, Semantic Kernel, Agno, smolagents, and Google ADK. When one supported SDK family is installed, the package detects it automatically. See [Agent SDKs](user-guide/frameworks.html) for version details and a complete example for each SDK. You can also use every search tool without an agent SDK by choosing `provider="function"`. ## Install If your agent SDK is already installed, add the base package: ```bash pip install serpapi-search-tools ``` If you want the package to install an agent SDK too, use its extra. For OpenAI Agents SDK: ```bash pip install "serpapi-search-tools[openai-agents]" ``` Set your SerpApi key before running a search: ```bash export SERPAPI_API_KEY="your-serpapi-key" ``` ## Try it with OpenAI Agents SDK This example gives one agent both general web search and current-news search: ```python from agents import Agent, Runner from serpapi_search_tools import news_search, web_search agent = Agent( name="research-assistant", instructions="Use search when the answer needs current information.", tools=[web_search(), news_search()], ) result = Runner.run_sync( agent, "Find three recent Python packaging changes and explain why they matter.", ) print(result.final_output) ``` With only OpenAI Agents SDK installed, `web_search()` and `news_search()` are detected and created in the right format automatically. If your environment contains several supported SDKs, select one explicitly—for example, `web_search(provider="openai-agents")`. ## Choose the right search capability | Your agent needs | Start with | | --- | --- | | General websites and background research | [`web_search`](user-guide/web_search.html) | | Current reporting | [`news_search`](user-guide/news_search.html) | | Places and local businesses | [`maps_search`](user-guide/maps_search.html) | | Images and source pages | [`images_search`](user-guide/images_search.html) | | Products and marketplace listings | [`shopping_search`](user-guide/shopping_search.html) | | YouTube videos, channels, and playlists | [`videos_search`](user-guide/videos_search.html) | | Hotel availability for known dates | [`hotels_search`](user-guide/hotels_search.html) | | Flights for a known route and date | [`flights_search`](user-guide/flights_search.html) | | Destination ideas from a departure point | [`travel_explore_search`](user-guide/travel_explore_search.html) | ## Continue from here - Follow the [Quickstart](user-guide/quickstart.html) for setup, keys, a first agent, customization, and troubleshooting. - Read the [Introduction](user-guide/introduction.html) to understand what the package handles and how it fits into an agent application. - Open [Agent SDK examples](docs/sdk-examples/index.html) for copy-ready code for your framework. - Browse [Recipes](user-guide/recipes.html) for research, local discovery, shopping, and travel combinations. # Understand where the package fits `serpapi-search-tools` connects [SerpApi](https://serpapi.com) search results to Python agent SDKs. It saves you from writing a separate custom-tool wrapper for every kind of search and every SDK. ## What it adds to your agent The package gives you focused tools for general web pages, news, maps, images, shopping, videos, hotels, flights, and destination discovery. Each tool asks for the information needed for that search. For example, web search uses a query, hotel search asks for stay dates, and flight search asks for airports and an outbound date. Inputs are checked before a request is sent to SerpApi. This helps your agent correct mistakes early and avoids unnecessary failed searches. ## How the pieces work together - **SerpApi** retrieves current search results and returns structured data. - **`serpapi-search-tools`** turns each search capability into a ready-to-use Python or agent-SDK tool. - **Your agent SDK and model** decide when to call a tool and how to use the returned results in the final response. The package does not include a language model or create the agent loop. You continue to configure those through the SDK you already use. You need a [SerpApi account and API key](https://serpapi.com/users/sign_up) for live searches. Agent examples may also need a separate key for the model provider used by that example. ## One constructor for each kind of search Start with only the tools your agent needs: ```python from serpapi_search_tools import maps_search, news_search, web_search tools = [web_search(), news_search(), maps_search()] ``` Separate tools make their purpose and inputs clear. They also let you configure web, news, local, shopping, or travel searches independently as your application grows. See [Choose a search tool](search_tools.html) for all nine capabilities and their required inputs. ## Use an agent SDK or plain Python When one supported agent SDK is installed, the package detects it and returns tools that can be added to that SDK's normal tool list. If several supported SDKs are installed, pass `provider=` to choose one explicitly. For scripts, tests, or a framework that is not listed, request a callable: ```python import json from serpapi_search_tools import web_search search = web_search(provider="function") response = json.loads(search(query="Python packaging")) print(response.get("organic_results", [])) ``` Every tool returns compact JSON text by default: only its primary result families, bounded to five entries, plus useful web answer sections. Application code can opt into the untouched response with `mode=SearchResultMode.FULL`. ## Next steps - [Build your first search agent](quickstart.html) - [Choose a search tool](search_tools.html) - [Configure a search tool](configuration.html) - [Open an SDK example](../docs/sdk-examples/index.html) # Build your first search agent This quickstart uses the OpenAI Agents SDK because its tool setup is compact. The search constructors work the same way with every supported SDK: install the integration, create one or more tools, and place them in the SDK's normal tools collection. You will build an agent that can search the live web and explain why its sources matter. ## Before you begin You need: - Python 3.10 or newer; - a [SerpApi account](https://serpapi.com/users/sign_up) and API key; - an OpenAI API key for this example; - a new or existing Python environment. SerpApi performs the search. OpenAI runs the agent. The keys are separate and each service bills according to its own account. ## 1. Install the packages Choose one of these paths. If OpenAI Agents SDK is **already installed**, install only the search tools: ```bash pip install serpapi-search-tools ``` If you want this package to install a compatible OpenAI Agents SDK too, use the extra: ```bash pip install "serpapi-search-tools[openai-agents]" ``` Extras are available for every [supported agent SDK](frameworks.html). You do not need a package extra for SDKs already present in your environment. ## 2. Set the API keys On macOS or Linux: ```bash export SERPAPI_API_KEY="your-serpapi-key" export OPENAI_API_KEY="your-openai-key" ``` Set environment variables through your shell, deployment platform, or secret manager. Do not paste real keys into Python files or commit them to source control. ## 3. Create the agent Save this as `search_agent.py`: ```python import asyncio from agents import Agent, Runner from serpapi_search_tools import web_search async def main(): agent = Agent( name="research-assistant", model="gpt-5.4-mini", instructions=( "Use web search for current facts. Explain which sources support " "your answer and say when the results are inconclusive." ), tools=[web_search()], ) result = await Runner.run( agent, "Find three recent Python packaging changes and explain why they matter.", ) print(result.final_output) asyncio.run(main()) ``` Run it: ```bash python search_agent.py ``` ## What just happened? 1. `web_search()` noticed that OpenAI Agents SDK is installed and returned an OpenAI `FunctionTool`. 2. The agent decided whether it needed the tool and supplied a text query plus a supported web engine. 3. The package validated the arguments, called SerpApi, and returned the structured search response to the agent as JSON text. 4. The model used those results to write the final response. The default web engine is `google_light`, which is a good fast starting point for agent research. The model may choose another allowed web engine unless you narrow the list. ## Automatic detection and multiple SDKs Automatic detection is convenient when one supported agent SDK is installed. If your environment contains multiple supported SDKs, make the choice explicit so every machine creates the tool for the same SDK: ```python from serpapi_search_tools import web_search tool = web_search(provider="openai-agents") ``` An explicit provider is also useful in shared notebooks and deployments that install several optional extras. ## 4. Customize the first tool Application-controlled settings belong in `default_params`. This example keeps results small and asks for US English results: ```python from serpapi_search_tools import web_search tool = web_search( allowed_engines=["google_light"], default_params={"num": 5, "hl": "en", "gl": "us"}, name="current_web_research", ) ``` Replace `web_search()` in the agent's `tools` list with `tool`. The agent still chooses the query, while your application controls the engine and locale. Read [Web search](web_search.html) for all supported web engines and safe configuration patterns. ## 5. Add another capability Use a dedicated tool when the intent changes. For recent stories, add news: ```python from serpapi_search_tools import news_search, web_search tools = [web_search(), news_search()] ``` The agent can now distinguish general web research from current-news search. The same pattern works for maps, images, shopping, videos, hotels, flights, and destination exploration. See [Choose a search tool](search_tools.html). ## Common first-run problems ### No SerpApi key If the tool says to set `SERPAPI_API_KEY`, confirm the variable is available in the same terminal that runs Python. `SERPAPI_KEY` is also accepted. ### The wrong SDK was detected This usually means several supported SDKs are installed. Pass `provider="openai-agents"` or move the application into an environment with only the dependencies it needs. ### A framework dependency is missing Install the matching extra, for example: ```bash pip install "serpapi-search-tools[openai-agents]" ``` ### The search request fails Check your [SerpApi dashboard](https://serpapi.com/dashboard) for key and usage status. The package raises `SerpApiSearchError` for sanitized built-in client failures, so API keys are not included in the displayed exception. For more diagnosis paths, see [Debugging](debugging.html). ## Where to go next - [Choose a search tool](search_tools.html) - [Common configuration](configuration.html) - [OpenAI Agents SDK example](../docs/sdk-examples/openai_agents.html) - [Recipes](recipes.html) - [Runnable examples](examples.html) # Choose by what the user is trying to do Start with the smallest set of tools that covers your agent's job. Separate names and inputs make it easier for the agent to choose the right search and provide the required information. | If your agent needs to... | Use | SerpApi engine(s) | Required inputs | | --- | --- | --- | --- | | Research general websites | [`web_search`](web_search.html) | `google`, `google_light`, `bing`, `yahoo`, `duckduckgo` | `query` | | Find current reporting | [`news_search`](news_search.html) | `google_news` | `query` | | Discover places or businesses | [`maps_search`](maps_search.html) | `google_maps` | `query` | | Find image URLs and metadata | [`images_search`](images_search.html) | `google_images` | `query` | | Compare products and sellers | [`shopping_search`](shopping_search.html) | `google_shopping`, `amazon`, `walmart`, `ebay` | `query` | | Find YouTube content | [`videos_search`](videos_search.html) | `youtube` | `query` | | Search properties and rates | [`hotels_search`](hotels_search.html) | `google_hotels` | `query`, `check_in_date`, `check_out_date` | | Search a known flight route | [`flights_search`](flights_search.html) | `google_flights` | `departure_id`, `arrival_id`, `outbound_date` | | Explore possible destinations | [`travel_explore_search`](travel_explore_search.html) | `google_travel_explore` | `departure_id` | ## A simple decision rule - Start with [`web_search`](web_search.html) for broad research. - Add [`news_search`](news_search.html) when freshness and news sources matter. - Use [`maps_search`](maps_search.html), [`images_search`](images_search.html), [`shopping_search`](shopping_search.html), or [`videos_search`](videos_search.html) when the desired result is a place, image, product, or video rather than a webpage. - Use the three travel tools only when the prompt supplies or can infer their structured route, date, occupancy, or destination fields. ## Compose capabilities with a list Every constructor creates one tool ready for your selected SDK. Combine capabilities with the same list you already use for your other tools: ```python from serpapi_search_tools import maps_search, news_search, web_search tools = [web_search(), news_search(), maps_search()] ``` If only one supported agent SDK is installed, automatic detection creates the right tools for it. If several are installed, use the same explicit `provider=` on every constructor. ## Search inputs versus application settings The final column lists the information a tool needs when it runs. Your Python application separately controls settings such as engines, locale, result count, currency, API key, timeout, and tool name when it creates the tool. Open a dedicated page above for both sets of options, then read [Common configuration](configuration.html) for settings shared by all tools. # Configure a search tool Every public constructor follows the same pattern: choose the search capability, let the package detect your agent SDK, and add only the application-controlled defaults you need. ```python from serpapi_search_tools import web_search tool = web_search() ``` Start with no options. Add configuration only when you have a clear reason, such as restricting engines, fixing a locale, limiting results, setting a currency, or selecting one SDK from a multi-SDK environment. ## Three kinds of settings It helps to keep three layers separate: 1. **Model inputs** are fields the agent supplies at invocation time, such as `query`, hotel dates, or flight airports. Each dedicated tool page lists these fields. 2. **Constructor options** control how the Python tool is created, such as `provider`, `name`, `timeout`, and web-engine choices. 3. **`default_params`** are SerpApi engine parameters fixed by your application, such as language, country, currency, safe search, or result count. This separation keeps the agent's search inputs short while your application retains control of service-level settings. ## Common constructor options All nine constructors accept these options: | Option | Default | When to use it | | --- | --- | --- | | `provider` | `"auto"` | Usually omit it. Select an SDK explicitly when multiple supported SDKs are installed, or use `"function"` for a callable. | | `api_key` | `None` | Pass a SerpApi key from a secret manager instead of using an environment variable. | | `client` | `None` | Replace the built-in client for tests, caching, logging, retries, or response reduction. | | `default_params` | `None` | Set supported SerpApi options such as locale, currency, or result count in application code. | | `timeout` | `None` | Set a request timeout on the built-in SerpApi client. | | `mode` | `SearchResultMode.COMPACT` | Return focused, bounded result families for agents, or opt into the untouched response with `SearchResultMode.FULL`. | | `include_examples` | `True` | Keep or remove the short invocation hint in the tool description. | | `name` | constructor name | Give separately configured tools distinct names the model can understand. | ```python from serpapi_search_tools import news_search current_us_news = news_search( default_params={"hl": "en", "gl": "us", "num": 5}, timeout=20.0, name="current_us_news", ) ``` ## Automatic SDK detection When exactly one supported agent SDK is installed, omit `provider`: ```python from serpapi_search_tools import maps_search, web_search tools = [web_search(), maps_search()] ``` If multiple supported SDK families share an environment, automatic detection raises an error instead of silently choosing one. Make the selection explicit: ```python from serpapi_search_tools import maps_search, web_search tools = [ web_search(provider="openai-agents"), maps_search(provider="openai-agents"), ] ``` LangGraph and LangChain count as one adapter family because both use the LangChain structured-tool adapter. If no supported SDK is installed, automatic detection returns a normal Python callable. `provider="function"` requests that callable explicitly and is useful for scripts, tests, and custom integrations. ## Options that differ by tool The search inputs and useful SerpApi parameters depend on the capability: | Tool | Tool-specific configuration | | --- | --- | | [`web_search`](web_search.html) | `allowed_engines`, `default_engine`, plus per-engine web defaults | | [`news_search`](news_search.html) | Google News query-mode locale and result settings | | [`maps_search`](maps_search.html) | Typed location/zoom/nearby inputs plus Maps defaults | | [`images_search`](images_search.html) | Safe search and image filters | | [`shopping_search`](shopping_search.html) | `allowed_engines`, `default_engine`, and marketplace-specific defaults | | [`videos_search`](videos_search.html) | YouTube locale and filter token settings | | [`hotels_search`](hotels_search.html) | Typed stay/occupancy fields plus currency and property filters | | [`flights_search`](flights_search.html) | Typed route/passenger fields plus currency, airline, bag, stop, and time filters | | [`travel_explore_search`](travel_explore_search.html) | Typed destination constraints plus discovery filters | Read the dedicated page before adding engine-specific `default_params`. ## Choose compact or full results All tools default to `SearchResultMode.COMPACT`. Compact mode normally removes response metadata, parameters, pagination, filters, and other auxiliary sections. It keeps errors and at most five entries from each primary result family. If a successful response contains no recognized result family, it returns `no_results: true` plus only safe status and search-information fields instead of an ambiguous empty object. | Tool | Compact result families | | --- | --- | | `web_search` except Google Light | `answer_box`, `knowledge_graph`, `ai_overview`, `organic_results` | | `web_search` with Google Light | `answer_box`, `knowledge_graph`, `organic_results`, `related_questions`, `related_searches`, `top_stories` | | `news_search` | `news_results` | | `maps_search` | `local_results` | | `images_search` | `images_results` | | `shopping_search` | `shopping_results` for Google Shopping; `organic_results` for Amazon, Walmart, and eBay | | `videos_search` | `video_results` | | `hotels_search` | `properties` | | `flights_search` | `best_flights`, `other_flights` | | `travel_explore_search` | `destinations` | Use full mode in application code that needs an auxiliary response section: ```python from serpapi_search_tools import SearchResultMode, web_search debug_search = web_search( provider="function", mode=SearchResultMode.FULL, ) ``` `mode` is a constructor option, not a model input. An agent cannot expand its own tool response and unexpectedly consume more context. ## Restrict web and shopping engines Only `web_search` and `shopping_search` expose an `engine` choice to the model. Their constructor options define the exact enum in the generated schema: ```python from serpapi_search_tools import WebSearchEngine, web_search tool = web_search( allowed_engines=[WebSearchEngine.GOOGLE_LIGHT, WebSearchEngine.BING], default_engine=WebSearchEngine.GOOGLE_LIGHT, ) ``` `web_search` supports five general web engines and prefers `google_light`. `shopping_search` supports four commerce engines and prefers `google_shopping`. Fixed-engine tools do not show the model an engine field. ## Use `default_params` safely These values are controlled by your Python application: ```python from serpapi_search_tools import images_search safe_us_images = images_search( default_params={"safe": "active", "hl": "en", "gl": "us"}, ) ``` Typed tool fields, including their declared defaults, win over matching `default_params`, and the package always controls `engine`. The following transport parameters are reserved and rejected in `default_params`: - `api_key` - `async` - `engine` - `output` A multi-engine tool sends the same defaults to every allowed engine. Parameter names and valid values often differ, so use only shared defaults or create separate tool instances with clear names: ```python from serpapi_search_tools import web_search us_google = web_search( allowed_engines=["google_light"], default_params={"hl": "en", "gl": "us", "num": 5}, name="us_google", ) german_google = web_search( allowed_engines=["google_light"], default_params={"hl": "de", "gl": "de", "num": 5}, name="german_google", ) ``` Official engine references are linked from every dedicated tool page. ## API keys Set the key in your local shell: ```bash export SERPAPI_API_KEY="your-serpapi-key" ``` `SERPAPI_KEY` is also accepted. Generic variables such as `API_KEY` are ignored so a model-provider credential cannot be sent to SerpApi accidentally. The key is resolved when a real search runs. Creating a tool or inspecting its schema does not contact SerpApi. In production, you can pass `api_key=` using a value read from your secret manager. ## Custom clients Pass `client=` for deterministic tests, caching, logging, retries, or a company HTTP wrapper. The object needs one synchronous `search(params)` method: ```python import json from serpapi_search_tools import SearchResultMode, hotels_search class RecordingClient: def __init__(self): self.requests = [] def search(self, params): self.requests.append(params) return {"search_metadata": {"status": "Success"}, "params": params} client = RecordingClient() search = hotels_search( provider="function", client=client, mode=SearchResultMode.FULL, ) result = json.loads( search( query="hotels in Kyoto", check_in_date="2030-08-01", check_out_date="2030-08-04", ) ) print(result["params"]) ``` When a custom client is supplied, the package does not create the built-in client or read a SerpApi key. ## Use another agent SDK {#support-another-agent-sdk} Request a normal callable and wrap it with the SDK's documented custom-tool API: ```python from serpapi_search_tools import flights_search search_flights = flights_search(provider="function") tool = CustomTool( name=search_flights.__name__, description=search_flights.__doc__, function=search_flights, ) ``` The callable carries a typed Python signature. Follow your SDK's custom-tool guide and use the inputs documented on the matching search-tool page. If the SDK asks for JSON Schema, define those same fields explicitly. For complete combinations built from these options, continue with [Recipes](recipes.html) or [Runnable examples](examples.html). ## Call a tool directly ```python import json from serpapi_search_tools import web_search search = web_search(provider="function") response = json.loads(search(query="Python packaging")) ``` The returned callable has a narrow signature and returns compact JSON text. ## Add a specialized capability ```python from serpapi_search_tools import maps_search, news_search, web_search tools = [ web_search(provider="openai-agents"), news_search(provider="openai-agents"), maps_search(provider="openai-agents"), ] ``` Each constructor creates one tool for your selected SDK. Add them with the same list syntax you use for your own tools. ## Engine choices Only web and shopping expose engine selection: ```python from serpapi_search_tools import shopping_search, web_search web = web_search( provider="langchain", allowed_engines=["google_light", "bing"], default_engine="google_light", ) shopping = shopping_search( provider="langchain", allowed_engines=["google_shopping", "amazon"], ) ``` The generated schema enum contains only the allowed values. Fixed-engine tools have no `engine` field. ## Structured travel calls ```python from serpapi_search_tools import flights_search flights = flights_search(provider="function") response = flights( departure_id="LAX", arrival_id="AUS", outbound_date="2026-08-01", ) ``` The route and date are passed as clear, named fields. You do not need to build a text query for a flight search. See [Choose a search tool](search_tools.html), [Recipes](recipes.html), and [Configuration](configuration.html) next. # Start from your application's goal You rarely need every search capability. Give the agent the smallest useful set, name specialized configurations clearly, and keep policy choices such as locale, currency, safe search, and result count in `default_params`. The examples below use automatic SDK detection. They work as written when one supported agent SDK is installed. If multiple SDKs share the environment, add the same explicit `provider=` to each constructor. ## General web research Use [`web_search`](web_search.html) for public websites and background sources: ```python from serpapi_search_tools import web_search tools = [ web_search( allowed_engines=["google_light", "bing"], default_engine="google_light", default_params={"num": 5}, ) ] ``` Good first prompt: “Research three independent sources about Python package signing and summarize where they agree.” ## Current reporting Combine [`news_search`](news_search.html) with web search when the agent needs both recent coverage and durable background information: ```python from serpapi_search_tools import news_search, web_search tools = [web_search(), news_search(default_params={"hl": "en", "gl": "us"})] ``` Good first prompt: “Find today's reporting about battery recycling, then use background sources to explain the context.” ## Local discovery Use [`maps_search`](maps_search.html) for businesses and places. Location, zoom, and nearby intent are typed model inputs: ```python from serpapi_search_tools import maps_search tools = [maps_search(default_params={"hl": "en", "gl": "us"})] ``` Good first prompt: “Find three independent coffee roasters near Portland, Oregon, and compare ratings, hours, and location.” ## Image discovery Use [`images_search`](images_search.html) for image URLs and visual metadata. Safe search can be an application policy rather than a model choice: ```python from serpapi_search_tools import images_search tools = [images_search(default_params={"safe": "active"})] ``` Good first prompt: “Find visual references for compact balcony gardens and summarize recurring layout ideas.” ## Marketplace comparison Use [`shopping_search`](shopping_search.html) for product listings. Separate instances are easiest when marketplaces need different defaults: ```python from serpapi_search_tools import shopping_search tools = [ shopping_search( allowed_engines=["google_shopping"], default_params={"num": 5, "gl": "us", "hl": "en"}, name="google_products", ), shopping_search( allowed_engines=["amazon"], default_params={"num": 5}, name="amazon_products", ), ] ``` Good first prompt: “Compare noise-cancelling headphones from both marketplaces and call out price or availability differences.” ## Video discovery Use [`videos_search`](videos_search.html) for YouTube videos, channels, and playlists: ```python from serpapi_search_tools import videos_search tools = [videos_search(default_params={"hl": "en", "gl": "us"})] ``` Good first prompt: “Find a beginner pour-over coffee tutorial and explain why it is a suitable first lesson.” ## Hotel availability Use [`hotels_search`](hotels_search.html) when the destination and stay dates are known: ```python from serpapi_search_tools import hotels_search tools = [hotels_search(default_params={"currency": "USD", "gl": "us"})] ``` The prompt should include future dates and occupancy, for example: “Find hotels in Kyoto from 2030-08-01 through 2030-08-04 for two adults and one child age 8.” ## Known-route flights Use [`flights_search`](flights_search.html) when origin and destination are known: ```python from serpapi_search_tools import flights_search tools = [flights_search(default_params={"currency": "USD", "hl": "en"})] ``` Good first prompt: “Compare round-trip business-class flights from LAX to AUS, departing 2030-08-01 and returning 2030-08-04.” ## Destination ideas Use [`travel_explore_search`](travel_explore_search.html) when the departure is known but the destination is open: ```python from serpapi_search_tools import travel_explore_search tools = [travel_explore_search(default_params={"currency": "USD", "gl": "us"})] ``` Good first prompt: “Starting from JFK, suggest three destinations for a four-day trip and compare indicative fares.” ## Monitor a product launch This combination separates background pages, current reporting, and live product listings: ```python from serpapi_search_tools import news_search, shopping_search, web_search tools = [web_search(), news_search(), shopping_search()] ``` Ask the agent to use web search for official specifications, news search for recent announcements and reviews, and shopping search for current listings. This is more reliable than expecting one result type to answer every question. ## Research a move or neighborhood Use the web for city information, maps for specific places, and images for a visual sense of the area: ```python from serpapi_search_tools import images_search, maps_search, web_search tools = [web_search(), maps_search(), images_search()] ``` Good first prompt: “Research living near the Seattle Convention Center. Find grocery stores and parks, then gather visual references of the surrounding neighborhood.” ## Compare a purchase visually Combine listings, product imagery, and video demonstrations: ```python from serpapi_search_tools import images_search, shopping_search, videos_search tools = [shopping_search(), images_search(), videos_search()] ``` Good first prompt: “Compare three compact espresso machines by price, physical design, and the availability of useful setup tutorials.” ## Plan a trip from an open brief Give each stage of the planning process its own typed tool: ```python from serpapi_search_tools import ( flights_search, hotels_search, maps_search, travel_explore_search, ) tools = [ travel_explore_search(), flights_search(), hotels_search(), maps_search(), ] ``` The agent can explore destinations first, search an exact route after choosing one, find properties for explicit dates, and finally find nearby places. A good prompt includes origin, date flexibility, passenger count, budget, and travel preferences. ## Keep agent payloads manageable Every tool returns a compact response by default, keeping only a bounded number of primary results before the JSON reaches the model. Use a custom `client=` for application-specific logging or caching, and opt into `SearchResultMode.FULL` only outside model context when auxiliary sections are required. Continue with [Runnable examples](examples.html), [Common configuration](configuration.html), or [Choose a search tool](search_tools.html). # Use the agent SDK you already know Create the search capabilities you need and add them to your SDK's normal tool collection: ```python from serpapi_search_tools import hotels_search, maps_search, web_search tools = [web_search(), maps_search(), hotels_search()] ``` The package prepares the tool name, description, inputs, validation, and SerpApi request. You continue to choose the model and run the agent through your SDK as usual. ## Installation choices If your agent SDK is already installed, add only the base package: ```bash pip install serpapi-search-tools ``` If you want this package to install a compatible SDK dependency too, use its extra. For example: ```bash pip install "serpapi-search-tools[openai-agents]" ``` Replace `openai-agents` with the extra in the table below. ## Supported SDKs | SDK | Extra / explicit provider | Supported range | Complete example | | --- | --- | --- | --- | | OpenAI Agents SDK | `openai-agents` | `openai-agents >=0.18.3,<1` | [OpenAI Agents](../docs/sdk-examples/openai_agents.html) | | Pydantic AI | `pydantic-ai` | `pydantic-ai >=1.30.1,<3` | [Pydantic AI](../docs/sdk-examples/pydantic_ai.html) | | LangChain | `langchain` | `langchain >=1.3.11,<2` | [LangChain](../docs/sdk-examples/langchain.html) | | LangGraph | `langgraph` | `langgraph >=1.2.6,<2` | [LangGraph](../docs/sdk-examples/langgraph.html) | | CrewAI | `crewai` | `crewai >=1.6.1,<2` | [CrewAI](../docs/sdk-examples/crewai.html) | | LlamaIndex | `llamaindex` | core `>=0.14.22,<0.15` | [LlamaIndex](../docs/sdk-examples/llamaindex.html) | | Claude Agent SDK | `claude-agent-sdk` | `claude-agent-sdk >=0.2.108,<1` | [Claude Agent SDK](../docs/sdk-examples/claude_agent_sdk.html) | | Microsoft Agent Framework | `microsoft-agent-framework` | `agent-framework-openai >=1.10.1,<2` | [Microsoft Agent Framework](../docs/sdk-examples/microsoft_agent_framework.html) | | AutoGen | `autogen` | AgentChat `>=0.7.5,<0.8` | [AutoGen](../docs/sdk-examples/autogen.html) | | Haystack | `haystack` | `haystack-ai >=2.30.2,<4` | [Haystack](../docs/sdk-examples/haystack.html) | | Agno | `agno` | `agno >=2.6.19,<3` | [Agno](../docs/sdk-examples/agno.html) | | smolagents | `smolagents` | `smolagents >=1.26,<2` | [smolagents](../docs/sdk-examples/smolagents.html) | | Google ADK | `google-adk` | `google-adk >=2.3,<3` | [Google ADK](../docs/sdk-examples/google_adk.html) | | Semantic Kernel | `semantic-kernel` | `semantic-kernel >=1.36,<2` | [Semantic Kernel](../docs/sdk-examples/semantic_kernel.html) | You only need dependencies for the SDKs you use. The base install remains small and also supports direct Python calls. ## Automatic detection is the normal path When one supported SDK is installed, omit `provider`: ```python from serpapi_search_tools import web_search tool = web_search() ``` If multiple supported SDK families are installed, automatic detection raises an error rather than selecting by import order. Pass the table's provider value explicitly: ```python from serpapi_search_tools import web_search tool = web_search(provider="openai-agents") ``` Use the same explicit provider for every tool in one agent. LangGraph and LangChain count as one adapter family. ## No supported SDK installed Automatic detection falls back to a normal callable. You can request that form directly with `provider="function"` for scripts, tests, or an unlisted agent framework. See [Support another agent SDK](configuration.html#support-another-agent-sdk). ## Install only what your agent uses Each extra installs the packages needed to create tools for that SDK. Continue to install and configure the model integration your agent normally uses. In most applications, installing the base package plus one SDK extra keeps the environment easiest to understand and maintain. # Run an example The repository contains direct Python examples and runnable agent examples for every supported SDK. ## Start without an LLM Use the direct examples to verify credentials and request construction: ```bash uv run --isolated --no-project --with serpapi-search-tools --with python-dotenv examples/direct_search.py uv run --isolated --no-project --with serpapi-search-tools --with python-dotenv examples/direct_travel.py ``` They demonstrate general web, news, hotels, flights, and travel exploration without installing an agent framework. ## Pick a scenario | Scenario | Script | Credentials | What to look for | | --- | --- | --- | --- | | Multi-vertical research | `direct_multi_search.py` | SerpApi | Four result families reduced to short title lists | | Marketplace comparison | `direct_marketplace_comparison.py` | SerpApi | Product payloads normalized into `title`, `price`, and `link` | | Regional configuration | `direct_regioned_search.py` | SerpApi | Two named tools with separate US and German defaults | | Cached requests | `direct_cached_search.py` | SerpApi | First call is a cache miss; the identical second call is a cache hit | | Agent travel planning | `openai_agents_travel_planner.py` | SerpApi and OpenAI | Explore, round-trip flights, and hotel occupancy in one prompt | Run the direct scenarios from the project root: ```bash uv run --isolated --no-project --with serpapi-search-tools --with python-dotenv examples/direct_multi_search.py uv run --isolated --no-project --with serpapi-search-tools --with python-dotenv examples/direct_marketplace_comparison.py uv run --isolated --no-project --with serpapi-search-tools --with python-dotenv examples/direct_regioned_search.py uv run --isolated --no-project --with serpapi-search-tools --with python-dotenv examples/direct_cached_search.py ``` The direct scripts parse the compact JSON response and print bounded summaries. ## Structured travel defaults Applications can configure localization and currency when each tool is created: ```python from serpapi_search_tools import flights_search, hotels_search, travel_explore_search hotels = hotels_search( provider="function", default_params={"currency": "USD", "gl": "us"}, ) flights = flights_search( provider="function", default_params={"currency": "USD", "hl": "en"}, ) explore = travel_explore_search( provider="function", default_params={"currency": "USD", "gl": "us"}, ) ``` ## Run an agent example Set `SERPAPI_API_KEY` plus the model provider key used by the script, then run the published package with the matching optional extra from the project root: ```bash uv run --isolated --no-project --with 'serpapi-search-tools[openai-agents]' --with python-dotenv examples/openai_agents_openai.py uv run --isolated --no-project --with 'serpapi-search-tools[openai-agents]' --with python-dotenv examples/openai_agents_travel_planner.py ``` The `examples/` directory includes OpenAI Agents, Pydantic AI, LangChain, LangGraph, CrewAI, LlamaIndex, Claude Agent SDK, Microsoft Agent Framework, AutoGen, Haystack, Agno, smolagents, Google ADK, and Semantic Kernel examples. In an application with one supported SDK installed, pass a list of capability-specific tools and rely on automatic detection: ```python from serpapi_search_tools import maps_search, news_search, web_search tools = [ web_search(), news_search(), maps_search(), ] ``` Open [SDK examples](../docs/sdk-examples/index.html) for installation and complete copy-friendly code for each framework. See [Choose a search tool](search_tools.html) to choose the right constructors before assembling the list, or start from a [recipe](recipes.html). ## Useful first prompts - “Search current news for three Python packaging releases and summarize why they matter.” - “Find well-reviewed coffee shops near the Seattle Convention Center.” - “Compare one-way flights from LAX to AUS on 2030-08-01.” - “Find hotels in Kyoto from 2030-08-01 to 2030-08-04 for two adults.” Structured prompts are especially useful for a first travel run because they provide the dates and identifiers required by the tool schema. ## Search tools # Web search with `web_search` `web_search` gives an agent general webpages from Google, Google Light, Bing, Yahoo, or DuckDuckGo. It is the best default for research that does not require a specialized result type. ## When to use it Use it for background research, documentation, company websites, public facts, and cross-checking sources. Start with `google_light` when you want fast, compact organic results for an agent. Choose [`news_search`](news_search.html) for current articles, [`maps_search`](maps_search.html) for places, or [`shopping_search`](shopping_search.html) for products. Those tools return result structures designed for their verticals. ## Quick example ```python from serpapi_search_tools import web_search tool = web_search() agent_tools = [tool] ``` With one supported SDK installed, `tool` is native to that SDK. For a direct Python callable, use `web_search(provider="function")`. ## Inputs the agent can provide | Field | Type | Required | Meaning | | --- | --- | --- | --- | | `query` | string | yes | The words or question to search for | | `engine` | enum | no | One of the engines allowed by your constructor; defaults to `google_light` when allowed | The package maps the friendly `query` field to each engine's native parameter: Google, Google Light, Bing, and DuckDuckGo use `q`; Yahoo uses `p`. ## Configure the tool | Constructor option | Default | Use it for | | --- | --- | --- | | `provider` | `"auto"` | Detect the installed SDK; use `"function"` for a callable or an explicit SDK name in multi-SDK environments | | `allowed_engines` | all five engines | Restrict the enum visible to the model | | `default_engine` | `google_light` when allowed | Choose the engine used when the model omits `engine` | | `default_params` | `None` | Fix engine parameters such as locale or result count in application code | | `mode` | `compact` | Return focused web results; use `SearchResultMode.FULL` for the untouched response | | `api_key` | `None` | Override the environment-based SerpApi key | | `timeout` | `None` | Set the built-in client's request timeout | | `client` | `None` | Supply a testing, caching, logging, or custom HTTP client | | `include_examples` | `True` | Include a short invocation hint in the tool description | | `name` | `"web_search"` | Give this configured tool a distinct name | For predictable results, expose only the engines your application actually needs: ```python from serpapi_search_tools import web_search tool = web_search( allowed_engines=["google_light", "bing"], default_engine="google_light", ) ``` ## Useful SerpApi parameters `default_params` is forwarded to the selected engine and is not editable by the model. This Google Light-only tool fixes country, language, and result count: ```python from serpapi_search_tools import web_search us_web = web_search( allowed_engines=["google_light"], default_params={"gl": "us", "hl": "en", "num": 5}, name="us_web_search", ) ``` Common needs include locale, geographic targeting, pagination, safe search, and date filters. Parameter names and accepted values differ by engine. If you need engine-specific defaults, create separate tool instances instead of sending one `default_params` dictionary to several incompatible engines. ## What comes back Compact mode returns up to five `organic_results` and, when present, the `answer_box`, `knowledge_graph`, and `ai_overview`. It omits related searches, pagination, metadata, parameters, and other auxiliary sections. Treat sections as optional: a valid search may not contain every result family. Use `mode=SearchResultMode.FULL` when application code needs the untouched SerpApi response. ## Common mistakes - Adding a vertical engine such as `google_news` to `allowed_engines`. Use its dedicated constructor instead. - Applying Google-only `default_params` while Bing, Yahoo, or DuckDuckGo is still allowed. - Setting `engine` inside `default_params`. Choose available engines with `allowed_engines` and `default_engine`. - Combining incompatible location fields. The package catches common conflicts, but each engine's official reference remains the source of truth. ## Official SerpApi documentation - [Google Search API](https://serpapi.com/search-api) - [Google Light Search API](https://serpapi.com/google-light-api) - [Bing Search API](https://serpapi.com/bing-search-api) - [Yahoo Search API](https://serpapi.com/yahoo-search-api) - [DuckDuckGo Search API](https://serpapi.com/duckduckgo-search-api) See [regional tool instances](examples.html) and the [general research recipe](recipes.html) for larger examples. # News search with `news_search` `news_search` searches Google News in keyword-query mode. It gives an agent a clear way to ask for recent reporting without mixing news intent into a general web tool. ## When to use it Use it for news monitoring, recent announcements, current events, product launches, and finding reporting from several publishers. Pair it with [`web_search`](web_search.html) when the agent also needs durable background sources. Do not use it for Google News topic, publication, section, or story-token workflows. Those have a different parameter shape from keyword query mode. ## Quick example ```python from serpapi_search_tools import news_search tool = news_search() agent_tools = [tool] ``` The default `provider="auto"` creates the right tool when one supported SDK is installed in the environment. ## Inputs the agent can provide | Field | Type | Required | Meaning | | --- | --- | --- | --- | | `query` | string | yes | The event, organization, person, or topic to find in current news | The engine is fixed to `google_news`, so the model does not see an `engine` field or SerpApi's native `q` name. ## Configure the tool | Constructor option | Default | Use it for | | --- | --- | --- | | `provider` | `"auto"` | Auto-detect one installed SDK or select one explicitly | | `default_params` | `None` | Fix locale, country, or bounded result settings | | `mode` | `compact` | Return up to five news results; use `SearchResultMode.FULL` for the untouched response | | `api_key` | `None` | Override `SERPAPI_API_KEY` / `SERPAPI_KEY` | | `timeout` | `None` | Set the built-in client timeout | | `client` | `None` | Provide a custom search client | | `include_examples` | `True` | Add a short query example to the tool description | | `name` | `"news_search"` | Rename a configured news capability | ## Useful SerpApi parameters Keep locale and country decisions in the application: ```python from serpapi_search_tools import news_search us_news = news_search( default_params={"hl": "en", "gl": "us", "num": 5}, name="us_news", ) ``` Use the official reference for more Google News query parameters. Advanced token fields such as `topic_token`, `publication_token`, `section_token`, and `story_token` do not belong in this keyword-query tool. ## What comes back Compact mode returns up to five `news_results`. Items commonly include a title, source, date, snippet, thumbnail, and link. Metadata and parameters are omitted; use `mode=SearchResultMode.FULL` when application code needs them. ## Common mistakes - Using `news_search` for general websites rather than news reporting. - Passing advanced Google News token modes through `default_params`; the package rejects combinations that cannot coexist with `query`. - Assuming every article has a thumbnail or snippet. Treat optional fields as optional when normalizing results. - Asking for "latest" without giving the agent permission to call live search. ## Official SerpApi documentation - [Google News API](https://serpapi.com/google-news-api) Try the [current reporting recipe](recipes.html) or the [multi-vertical research example](examples.html). # Maps search with `maps_search` `maps_search` finds places, businesses, and local services through Google Maps. The agent can provide a search query and, when useful, a separate location, zoom level, and nearby preference. ## When to use it Use it for nearby recommendations, stores, restaurants, repair services, venues, and local discovery. Choose [`web_search`](web_search.html) when the answer is about webpages rather than physical places. This tool searches for places. It is not a place-details, reviews, directions, or photos tool; those SerpApi APIs require different identifiers and schemas. ## Quick example ```python from serpapi_search_tools import maps_search local_places = maps_search() agent_tools = [local_places] ``` An agent can then call the tool with values such as: ```json {"query": "coffee roasters", "location": "Portland, Oregon", "zoom": 12} ``` ## Inputs the agent can provide | Field | Type | Required | Default and constraints | | --- | --- | --- | --- | | `query` | string | yes | Non-empty place, category, or business query | | `location` | string | no | A geographic name such as `Austin, Texas` | | `zoom` | integer | no | `14`; must be from `3` through `30`; used when `location` is present | | `nearby` | boolean | no | `False`; `True` requires `location` | The package sends Google Maps `type="search"` and maps `zoom` to SerpApi's `z` field. ## Configure the tool | Constructor option | Default | Use it for | | --- | --- | --- | | `provider` | `"auto"` | Detect one installed SDK or choose an SDK explicitly | | `default_params` | `None` | Fix Google Maps locale or supported search filters | | `mode` | `compact` | Return up to five local results; use `SearchResultMode.FULL` for the untouched response | | `api_key` | `None` | Override environment key lookup | | `timeout` | `None` | Set the built-in client timeout | | `client` | `None` | Add deterministic tests, caching, or request logging | | `include_examples` | `True` | Add a local-search example to the description | | `name` | `"maps_search"` | Distinguish multiple configured maps tools | ## Useful SerpApi parameters The model already controls `location`, `zoom`, and `nearby` through typed fields. Use `default_params` for application policy such as locale: ```python from serpapi_search_tools import maps_search us_places = maps_search( default_params={"hl": "en", "gl": "us"}, name="us_places", ) ``` Google Maps also supports more search filters and pagination. Check the official reference before adding them; do not put place-detail identifiers in this search-mode tool. ## What comes back Compact mode returns up to five `local_results`. Place entries may include a title, address, rating, review count, category, phone, website, hours, coordinates, thumbnail, and identifiers. Availability varies by place and query. ## Common mistakes - Setting `nearby=True` without `location`. - Passing a `zoom` outside `3` through `30`. - Combining the typed `location` with `ll`, `lat`, or `lon` defaults. - Passing `place_id` or `data_cid`; this tool supports place search rather than the separate place-details API. - Expecting directions or reviews from a search-only contract. ## Official SerpApi documentation - [Google Maps API](https://serpapi.com/google-maps-api) See the [local discovery recipe](recipes.html) and [`direct_multi_search.py`](examples.html) for working usage. # Image search with `images_search` `images_search` searches Google Images for image URLs and structured metadata. It is useful when the agent needs visual references rather than ordinary web pages. ## When to use it Use it for visual research, inspiration gathering, product imagery discovery, identifying visual themes, or locating source pages for images. Choose [`web_search`](web_search.html) for text sources. This tool returns image metadata; it does not download, edit, license, or verify permission to reuse an image. ## Quick example ```python from serpapi_search_tools import images_search visual_search = images_search() agent_tools = [visual_search] ``` ## Inputs the agent can provide | Field | Type | Required | Meaning | | --- | --- | --- | --- | | `query` | string | yes | The subject, object, style, or scene to search for | The engine is fixed to `google_images`, so the agent only needs to provide the image query. ## Configure the tool | Constructor option | Default | Use it for | | --- | --- | --- | | `provider` | `"auto"` | Detect the installed agent SDK | | `default_params` | `None` | Fix safe search, locale, or other supported image filters | | `mode` | `compact` | Return up to five image results; use `SearchResultMode.FULL` for the untouched response | | `api_key` | `None` | Override environment key lookup | | `timeout` | `None` | Set the built-in client timeout | | `client` | `None` | Provide a custom client for logging, caching, or tests | | `include_examples` | `True` | Add a sample image query to the description | | `name` | `"images_search"` | Rename a specialized visual-search tool | ## Useful SerpApi parameters Safe search is a common application-controlled policy: ```python from serpapi_search_tools import images_search safe_images = images_search( default_params={"safe": "active", "hl": "en", "gl": "us"}, name="safe_image_search", ) ``` Google Images supports additional size, color, type, rights, time, and page filters. Use the official reference for accepted values. The package rejects known conflicts such as `location` with `uule`, and relative-period filters with explicit start/end dates. ## What comes back Compact mode returns up to five `images_results`. Items can include title, original image URL, thumbnail, source page, dimensions, source name, and position. Your application should not assume every result contains every optional field. ## Common mistakes - Treating a returned image URL as a reuse license. Check the source and rights. - Sending both `location` and `uule`. - Mixing relative-period and explicit date filters. - Opting into full image responses for a model when compact mode is enough. ## Official SerpApi documentation - [Google Images API](https://serpapi.com/google-images-api) See the [image discovery recipe](recipes.html) and the [Pydantic AI image example](../docs/sdk-examples/pydantic_ai.html). # Shopping search with `shopping_search` `shopping_search` gives an agent product results from Google Shopping, Amazon, Walmart, or eBay through one consistent `query` input and a constrained engine choice. ## When to use it Use it for product discovery, price comparison, merchant research, availability checks, and finding listings across marketplaces. Choose [`web_search`](web_search.html) when the goal is reviews, buying guides, or manufacturer documentation rather than product listings. This is a search-results tool. It does not complete purchases, monitor a product continuously, or fetch the separate product-detail APIs. ## Quick example ```python from serpapi_search_tools import shopping_search products = shopping_search( allowed_engines=["google_shopping", "amazon"], default_engine="google_shopping", ) agent_tools = [products] ``` ## Inputs the agent can provide | Field | Type | Required | Meaning | | --- | --- | --- | --- | | `query` | string | yes | Product, brand, model, or category to find | | `engine` | enum | no | One of the marketplaces allowed by the constructor | The package translates `query` to the marketplace's native parameter: `q` for Google Shopping, `k` for Amazon, `query` for Walmart, and `_nkw` for eBay. ## Configure the tool | Constructor option | Default | Use it for | | --- | --- | --- | | `provider` | `"auto"` | Detect one installed SDK or select one explicitly | | `allowed_engines` | all four engines | Limit the marketplaces visible to the model | | `default_engine` | `google_shopping` when allowed | Select the marketplace used when `engine` is omitted | | `default_params` | `None` | Fix result count or engine-specific marketplace filters | | `mode` | `compact` | Return up to five primary product results; use `SearchResultMode.FULL` for the untouched response | | `api_key` | `None` | Override environment key lookup | | `timeout` | `None` | Set the built-in client timeout | | `client` | `None` | Add result normalization, caching, logging, or tests | | `include_examples` | `True` | Include a product-query hint in the description | | `name` | `"shopping_search"` | Distinguish a configured marketplace capability | Use separate instances when each marketplace needs different defaults: ```python from serpapi_search_tools import shopping_search google_products = shopping_search( allowed_engines=["google_shopping"], default_params={"gl": "us", "hl": "en", "num": 5}, name="google_products", ) amazon_products = shopping_search( allowed_engines=["amazon"], default_params={"num": 5}, name="amazon_products", ) ``` ## Useful SerpApi parameters `num` is useful for bounding a first result page. Locale, sorting, category, condition, delivery, and price-filter parameters are marketplace-specific. Follow the matching official reference rather than assuming a Google Shopping parameter will work on Amazon, Walmart, or eBay. For a multi-engine tool, the same `default_params` dictionary is sent to every allowed engine. Restrict `allowed_engines` or use separate named tools before adding engine-specific values. ## What comes back Compact mode returns up to five primary product results. Google Shopping uses `shopping_results`; Amazon, Walmart, and eBay use `organic_results`. Titles, prices, links, ratings, delivery details, and seller fields also vary. Normalize only fields your application needs and keep the original engine in the normalized record. ## Common mistakes - Assuming every engine returns `shopping_results`. - Reusing marketplace-specific `default_params` across all four engines. - Combining Amazon keyword mode with `node`; the package rejects that input shape. - Expecting one price format. Some engines return strings, extracted numbers, or nested offer objects. - Sending dozens of complete product objects to a model when a bounded summary is sufficient. ## Official SerpApi documentation - [Google Shopping API](https://serpapi.com/google-shopping-api) - [Amazon Search API](https://serpapi.com/amazon-search-api) - [Walmart Search API](https://serpapi.com/walmart-search-api) - [eBay Search API](https://serpapi.com/ebay-search-api) Run the [marketplace comparison example](examples.html) to see four response shapes normalized into common title, price, and link fields. # Video search with `videos_search` `videos_search` searches YouTube for videos, channels, and playlists. It gives an agent a simple `query` field while the package sends YouTube's native `search_query` parameter. ## When to use it Use it for tutorials, demonstrations, talks, reviews, interviews, channels, and playlists. Choose [`web_search`](web_search.html) when a text source is more appropriate. This tool searches YouTube results. It does not fetch a video's transcript or the separate video-detail API. ## Quick example ```python from serpapi_search_tools import videos_search tutorial_search = videos_search() agent_tools = [tutorial_search] ``` ## Inputs the agent can provide | Field | Type | Required | Meaning | | --- | --- | --- | --- | | `query` | string | yes | The topic, tutorial, creator, or video to find | Use the consistent `query` field shown above. The package translates it to YouTube's `search_query` parameter. ## Configure the tool | Constructor option | Default | Use it for | | --- | --- | --- | | `provider` | `"auto"` | Detect one installed SDK or select one explicitly | | `default_params` | `None` | Fix locale or supported YouTube search filters | | `mode` | `compact` | Return up to five video results; use `SearchResultMode.FULL` for the untouched response | | `api_key` | `None` | Override environment key lookup | | `timeout` | `None` | Set the built-in client timeout | | `client` | `None` | Add caching, logging, tests, or response reduction | | `include_examples` | `True` | Add a sample video query to the description | | `name` | `"videos_search"` | Rename a focused video-search capability | ## Useful SerpApi parameters This example fixes language and country preferences: ```python from serpapi_search_tools import videos_search english_videos = videos_search( default_params={"hl": "en", "gl": "us"}, name="english_video_search", ) ``` YouTube search also accepts a filter token for narrowing result type, date, duration, and other search choices. Use the official reference to obtain a valid token rather than inventing filter fields. ## What comes back Compact mode returns up to five `video_results`. Entries commonly include title, link, thumbnail, channel, duration, views, and publication information. Use full mode when application code needs auxiliary channel or playlist sections. ## Common mistakes - Calling the tool with `search_query`; use `query`. - Expecting transcript text from a search response. - Treating channel and playlist entries as if they have video-only fields. - Opting into full results for a model when compact video results are enough. ## Official SerpApi documentation - [YouTube Search API](https://serpapi.com/youtube-search-api) See the [video discovery recipe](recipes.html) and the [smolagents example](../docs/sdk-examples/smolagents.html). # Hotel search with `hotels_search` `hotels_search` searches Google Hotels for a destination and stay window. It asks for check-in and check-out dates so the results can include relevant availability and prices. ## When to use it Use it when the agent needs properties, rates, availability, amenities, or hotel comparisons for a known destination and stay window. Choose [`travel_explore_search`](travel_explore_search.html) when the destination is still open, and [`maps_search`](maps_search.html) when the goal is local place discovery rather than date-specific lodging results. ## Quick example ```python from serpapi_search_tools import hotels_search hotel_tool = hotels_search( default_params={"currency": "USD", "gl": "us"}, ) agent_tools = [hotel_tool] ``` An agent invocation has a structured shape: ```json { "query": "hotels in Kyoto", "check_in_date": "2030-08-01", "check_out_date": "2030-08-04", "adults": 2, "children": 1, "children_ages": [8] } ``` ## Inputs the agent can provide | Field | Type | Required | Default and constraints | | --- | --- | --- | --- | | `query` | string | yes | Hotel name, city, region, or destination | | `check_in_date` | date string | yes | `YYYY-MM-DD` | | `check_out_date` | date string | yes | `YYYY-MM-DD`, strictly after check-in | | `adults` | integer | no | `2`; at least `1` | | `children` | integer | no | `0`; cannot be negative | | `children_ages` | list of integers | no | Exactly one age from `1` through `17` for each child | ## Configure the tool | Constructor option | Default | Use it for | | --- | --- | --- | | `provider` | `"auto"` | Detect one installed SDK or select one explicitly | | `default_params` | `None` | Fix currency, locale, country, or supported property filters | | `mode` | `compact` | Return up to five properties; use `SearchResultMode.FULL` for the untouched response | | `api_key` | `None` | Override environment key lookup | | `timeout` | `None` | Set the built-in client timeout | | `client` | `None` | Add caching, request logging, or deterministic tests | | `include_examples` | `True` | Add a stay-search hint to the model description | | `name` | `"hotels_search"` | Distinguish region- or policy-specific hotel tools | ## Useful SerpApi parameters Keep currency and locale under application control: ```python from serpapi_search_tools import hotels_search us_hotel_prices = hotels_search( default_params={"currency": "USD", "gl": "us", "hl": "en"}, name="us_hotel_prices", ) ``` Google Hotels supports additional property type, rating, hotel class, amenities, offers, and sorting filters. Check the official reference for exact names and values. Dates and occupancy should use the typed model inputs above, not duplicate values in `default_params`. ## What comes back Compact mode returns up to five `properties`. Entries may include property names, links, GPS coordinates, ratings, amenities, images, extracted prices, rate-per-night details, and nearby places. Use full mode for brands, filters, metadata, or pagination. ## Common mistakes - Omitting check-in or check-out dates. - Using a checkout date equal to or before check-in. - Providing `children=1` without one `children_ages` value. - Using a child age outside `1` through `17`. - Leaving old example dates in production code. Send real future stay dates. - Assuming a displayed rate includes every fee; inspect the returned price fields and source information. ## Official SerpApi documentation - [Google Hotels API](https://serpapi.com/google-hotels-api) See [structured travel examples](examples.html) and the [trip-planning agent recipe](recipes.html). # Flight search with `flights_search` `flights_search` searches Google Flights for a known origin, destination, and outbound date. It supports one-way and round-trip itineraries with semantic cabin and passenger fields. ## When to use it Use it when the route is known and the agent needs itineraries, prices, airlines, stops, or duration. Choose [`travel_explore_search`](travel_explore_search.html) when the destination is not decided. This tool supports one-way and round-trip searches. Multi-city itineraries are not currently supported. ## Quick example ```python from serpapi_search_tools import flights_search flight_tool = flights_search( default_params={"currency": "USD", "hl": "en"}, ) agent_tools = [flight_tool] ``` Example invocation: ```json { "departure_id": "LAX", "arrival_id": "AUS", "outbound_date": "2030-08-01", "return_date": "2030-08-04", "travel_class": "business", "adults": 1 } ``` ## Inputs the agent can provide | Field | Type | Required | Default and constraints | | --- | --- | --- | --- | | `departure_id` | string | yes | Airport code or supported SerpApi location identifier | | `arrival_id` | string | yes | Airport code or supported SerpApi location identifier | | `outbound_date` | date string | yes | `YYYY-MM-DD` | | `return_date` | date string | no | Omit for one way; otherwise not before outbound | | `travel_class` | enum | no | `economy`; also `premium_economy`, `business`, or `first` | | `adults` | integer | no | `1`; at least `1` | | `children` | integer | no | `0`; cannot be negative | | `infants_in_seat` | integer | no | `0`; cannot be negative | | `infants_on_lap` | integer | no | `0`; cannot be negative | Three-letter alphabetic airport codes are normalized to uppercase. Omitting `return_date` makes the request one way; supplying it makes the request a round trip. ## Configure the tool | Constructor option | Default | Use it for | | --- | --- | --- | | `provider` | `"auto"` | Detect one installed SDK or select one explicitly | | `default_params` | `None` | Fix currency, locale, stops, airline, bag, or time filters supported by SerpApi | | `mode` | `compact` | Return up to five best and five other itineraries; use `SearchResultMode.FULL` for the untouched response | | `api_key` | `None` | Override environment key lookup | | `timeout` | `None` | Set the built-in client timeout | | `client` | `None` | Add caching, logging, testing, or response compaction | | `include_examples` | `True` | Add a route-search hint to the description | | `name` | `"flights_search"` | Rename a configured route capability | ## Useful SerpApi parameters This tool keeps price display predictable: ```python from serpapi_search_tools import flights_search us_flights = flights_search( default_params={"currency": "USD", "hl": "en", "gl": "us"}, name="us_flights", ) ``` SerpApi also supports airline, stops, baggage, maximum price, departure time, arrival time, and other filters. The package validates common conflicts: for example, include and exclude airline lists cannot both be set, return-time filters need a round trip, and bag counts cannot exceed eligible passengers. ## What comes back Compact mode returns up to five `best_flights` and five `other_flights`. Itinerary objects can contain one or more flight legs, layovers, total duration, carbon emissions, price, airline, and booking tokens. Use full mode for price insights, airports, or metadata. ## Common mistakes - Sending a text `q`; flight tools never use one. - Omitting the route or outbound date. - Supplying a return date before outbound. - Asking for multi-city itineraries through this one-route schema. - Combining both `include_airlines` and `exclude_airlines` defaults. - Using stale dates copied from documentation. ## Official SerpApi documentation - [Google Flights API](https://serpapi.com/google-flights-api) See the [direct travel example](examples.html) and the [OpenAI Agents travel planner](../docs/sdk-examples/openai_agents.html). # Destination discovery with `travel_explore_search` `travel_explore_search` uses Google Travel Explore to find possible destinations and fares from a departure location. Only `departure_id` is required, so an agent can start broad and add region, date, cabin, or passenger constraints when the user supplies them. ## When to use it Use it for questions such as "Where can I fly from JFK for a long weekend?" or "Which European cities fit this budget?" Choose [`flights_search`](flights_search.html) once both origin and destination are known, and [`hotels_search`](hotels_search.html) after a destination and stay window are selected. ## Quick example ```python from serpapi_search_tools import travel_explore_search destination_tool = travel_explore_search( default_params={"currency": "USD", "gl": "us"}, ) agent_tools = [destination_tool] ``` Example broad invocation: ```json {"departure_id": "JFK", "adults": 1, "travel_class": "economy"} ``` ## Inputs the agent can provide | Field | Type | Required | Default and constraints | | --- | --- | --- | --- | | `departure_id` | string | yes | Departure airport or supported location identifier | | `arrival_id` | string | no | Arrival airport, city, or supported location identifier; mutually exclusive with `arrival_area_id` | | `arrival_area_id` | string | no | Google Knowledge Graph area or country identifier; mutually exclusive with `arrival_id` | | `outbound_date` | date string | no | `YYYY-MM-DD` | | `return_date` | date string | no | Requires outbound; cannot be earlier | | `travel_class` | enum | no | `economy`; also `premium_economy`, `business`, or `first` | | `adults` | integer | no | `1`; at least `1` | | `children` | integer | no | `0`; cannot be negative | | `infants_in_seat` | integer | no | `0`; cannot be negative | | `infants_on_lap` | integer | no | `0`; cannot be negative | ## Configure the tool | Constructor option | Default | Use it for | | --- | --- | --- | | `provider` | `"auto"` | Detect one installed SDK or select one explicitly | | `default_params` | `None` | Fix currency, locale, price, stops, duration, or supported interest filters | | `mode` | `compact` | Return up to five destinations; use `SearchResultMode.FULL` for the untouched response | | `api_key` | `None` | Override environment key lookup | | `timeout` | `None` | Set the built-in client timeout | | `client` | `None` | Add caching, logging, testing, or response reduction | | `include_examples` | `True` | Add a destination-discovery hint to the description | | `name` | `"travel_explore_search"` | Rename a configured discovery capability | ## Useful SerpApi parameters Currency and market are common application defaults: ```python from serpapi_search_tools import travel_explore_search us_destination_ideas = travel_explore_search( default_params={"currency": "USD", "gl": "us", "hl": "en"}, name="us_destination_ideas", ) ``` SerpApi supports more discovery constraints, including price, stops, duration, travel mode, and interest settings. Use the official reference for exact values. The package rejects `travel_mode` combined with `interest` because those modes are incompatible. ## What comes back Compact mode returns up to five `destinations`. Destination entries may include city or place names, country, airport information, flight price, duration, stops, dates, image, and location data. Use full mode for supporting sections. ## Common mistakes - Sending a text `query` or `q`; this tool starts from `departure_id`. - Supplying `return_date` without `outbound_date`. - Treating `arrival_area_id` as ordinary text; it is a Google Knowledge Graph identifier. - Combining `travel_mode` and `interest` in `default_params`. - Using Explore for a route that is already known; use `flights_search` for a tighter schema. ## Official SerpApi documentation - [Google Travel Explore API](https://serpapi.com/google-travel-explore-api) See the [destination ideas recipe](recipes.html), the [direct travel example](examples.html), and the [OpenAI Agents travel planner](../docs/sdk-examples/openai_agents.html). ## Advanced Usage # Debug search responses When an agent gives an unexpected result, call the same tool as a plain Python function first. This separates SerpApi request problems from model and SDK behavior. ## Inspect a request and response ```python import json from serpapi_search_tools import SearchResultMode, web_search search = web_search( provider="function", allowed_engines=["google_light"], default_params={"num": 3, "hl": "en", "gl": "us"}, mode=SearchResultMode.FULL, ) response = json.loads(search(query="Python packaging tutorials")) print(response.get("search_parameters")) for result in response.get("organic_results", []): print(result.get("title"), result.get("link")) ``` Plain callables and SDK tools use the same search logic. If the direct call succeeds, inspect the arguments produced by the agent next. ## Know the result section Compact mode returns these common result sections: | Tool | Common result section | | --- | --- | | `web_search` | `organic_results` | | `news_search` | `news_results` | | `maps_search` | `local_results` | | `images_search` | `images_results` | | `shopping_search` | `shopping_results` or engine-specific product results | | `videos_search` | `video_results` | | `hotels_search` | `properties` | | `flights_search` | `best_flights`, `other_flights` | | `travel_explore_search` | `destinations` | Print `response.keys()` and `response.get("error")` when the expected section is absent. To inspect `search_metadata` and `search_parameters`, create the debug callable with `mode=SearchResultMode.FULL` as shown above. ## Inspect travel request construction Travel tools do not accept a free-text `q` substitute. Their structured fields are sent directly to SerpApi: ```python from serpapi_search_tools import flights_search search = flights_search(provider="function") raw = search( departure_id="LAX", arrival_id="AUS", outbound_date="2026-08-01", return_date="2026-08-05", adults=2, ) ``` The package infers SerpApi's trip `type` from the presence of `return_date` and maps semantic cabin names such as `business` to the numeric API value. ## Common failures - **No SerpApi key:** set `SERPAPI_API_KEY`, pass `api_key=`, or verify your secret manager returned a non-empty value. - **Wrong constructor:** use `news_search`, `maps_search`, or another dedicated tool instead of passing a vertical engine to `web_search`. - **Invalid travel dates:** use `YYYY-MM-DD`; checkout must follow check-in and a return date cannot precede departure. - **Invalid child data:** `hotels_search.children_ages` must contain exactly one age from 1 through 17 for each child. - **Incompatible defaults:** remove mutually exclusive engine parameters named by the validation error. - **Direct call works but the agent fails:** compare the SDK's tool name and the arguments emitted by the agent with the fields documented for that tool. - **Direct call also fails:** keep the model out of the test until the SerpApi request and response are correct. ## Catch provider and transport failures Invalid local inputs raise `ValueError` before a SerpApi request. Failures returned by the built-in SerpApi client raise `SerpApiSearchError`: ```python from serpapi_search_tools import SerpApiSearchError, web_search search = web_search(provider="function") try: encoded = search(query="Python packaging") except ValueError as exc: print(f"Fix the tool arguments: {exc}") except SerpApiSearchError as exc: print(f"SerpApi could not complete the request: {exc}") ``` The error message replaces any API key found in the upstream request URL with `[REDACTED]`, making it safer to retain ordinary application and CI logs. Return to [Usage and composition](usage.html) after the direct call works, or open the complete example under [Choose an agent SDK](frameworks.html).