Google search tool for LangChain

To give a LangChain agent Google search, wrap a BestSERP call in a function decorated with @tool from langchain_core.tools. The function POSTs the query to /search and returns compact results (title, link, snippet) that the model reads and cites. Bind the tool to any chat model that supports tool calling.

Last updated:

Key takeaways

  • No SDK to install: a tool function around one HTTP call is enough.
  • Send the key in the X-API-KEY header, never in a URL or in browser code.
  • 202 means the search is still running: poll GET /requests/{requestId}.
  • 60 searches per minute per account by default; 429 and 503 are not charged.

Step by step

  1. Install

    pip install langchain-core requests
  2. Define the tool

    The docstring becomes the tool description the model sees, so keep it precise.

    tools.py
    import os
    
    import requests
    from langchain_core.tools import tool
    
    API = "https://api.bestserp.com"
    HEADERS = {"X-API-KEY": os.environ["BESTSERP_API_KEY"]}
    
    
    @tool
    def google_search(query: str, country: str = "us") -> list[dict]:
        """Search Google and return the top results with title, link and snippet.
        Use it for current facts, prices, news or anything not in your training data."""
        r = requests.post(f"{API}/search", headers=HEADERS,
                          json={"q": query, "gl": country, "hl": "en", "timeout": 120}, timeout=130)
        r.raise_for_status()
        data = r.json()
        return [{"title": i.get("title"), "link": i.get("link"), "snippet": i.get("snippet")}
                for i in data.get("organic", [])[:8]]
    
    
    if __name__ == "__main__":
        print(google_search.invoke({"query": "latest LangChain release"}))
  3. Bind it to a model

    With any LangChain chat model that supports tool calling: model.bind_tools([google_search]). When the model asks for the tool, run it and pass the results back, or use a prebuilt agent that does this loop for you.

  4. Keep answers grounded

    Ask the model to cite the links it used. Limit how many searches one conversation may run to control cost (1 credit each).

Status codes to handle

What the search endpoints answer, and whether the request costs credits.
StatusCodeMeaningCredits
202-Not finished within timeout (or async: true). Poll pollUrl.Reserved
400invalid_requestMalformed body or a parameter out of range.No
400unknown_parameterA field the API does not know (typo?).No
400unsupported_parameterA known field that this endpoint does not support yet (e.g. location).No
401missing_api_key / invalid_api_keyNo key, or the key is wrong or revoked.No
402insufficient_creditsYour balance is too low for this request.No
403account_suspendedThe account is suspended.No
404not_foundUnknown requestId, or it belongs to another account.-
429rate_limitedToo many requests this minute. See Retry-After.No
502search_failedThe search could not be completed (blocked or timed out).Refunded
503busyNo capacity right now. Retry after Retry-After seconds.Refunded

Frequently asked questions

Is there a ready-made LangChain integration package?
Not from us. The tool on this page is the whole integration: about 15 lines with requests.
Why return only title, link and snippet?
They are what the model needs to answer and cite, and they keep the context short. Add fields such as date for news if your use needs them.
Can the tool search news instead?
Yes: post to /news and read the news array. Each article has title, link, source and date.
What happens if a search takes long?
With timeout 120 the API waits up to two minutes before answering 202. For an agent, treat 202 as a failure or poll /requests/{requestId}.

Start with 3,000 free searches

No credit card. Sign in with Google, create a key, send your first request.