LangChain 6 min read

LangChain Serper Alternative: A Tested SearchCans Tool

Build and test a typed LangChain search tool with SearchCans data.organic parsing, clear failure states and an offline fixture using the actual framework.

(Updated: ) • 1,123 words

Quick answer

A LangChain Serper alternative needs a tool contract and a provider adapter, not just a new provider name. Keep the input schema and search-result meaning explicit, check the SearchCans business envelope, and test the tool with a saved response before attaching a model.

This page owns the Python tool adapter. It does not rank providers by speed or price. Use the Serper comparison for product fit and the source-context contract when retrieved references become LLM evidence.

Define what the tool does and does not return

Contract part Implementation here
Input Nonempty query; client-side result limit from 1 to 10
Search operation Google search with country us and language en
Envelope HTTP errors fail; business code must be integer 0; results come from data.organic
Output JSON string with source URLs, titles and snippets
Evidence boundary Search references are not source-page content; unresolved intermediary URLs are rejected

The result cap is enforced after the search response. It is not an undocumented API parameter and does not reduce the charge by returning fewer items. An empty organic array is a valid empty search; a missing or malformed array is a failed contract.

Run the real tool against an offline fixture

The example was invoked with Python 3.12.14, langchain-core==1.7.3 and pydantic==2.14.2 in the local validation environment on November 1, 2026. Those are tested versions, not a compatibility claim for all framework releases. Install the pinned packages in an isolated environment. No model is needed for tool.invoke.

import json
import os
from urllib.parse import urlsplit
from urllib.request import Request, urlopen
from langchain_core.tools import StructuredTool
from pydantic import BaseModel, Field, StrictInt, StrictStr


class SearchInput(BaseModel):
    query: StrictStr
    limit: StrictInt = Field(default=3, ge=1, le=10)


def source_url(value):
    if not isinstance(value, str) or any(c.isspace() for c in value):
        raise ValueError("Expected an absolute source URL")
    try:
        parsed = urlsplit(value)
        host, port = parsed.hostname, parsed.port
    except ValueError as exc:
        raise ValueError("Malformed URL") from exc
    if (parsed.scheme not in ("http", "https") or not host
            or parsed.username is not None or parsed.password is not None):
        raise ValueError("Expected a publisher URL without credentials")
    host = host.lower()
    google = host == "google.com" or host.endswith(".google.com")
    if host in ("share.google", "search.app") or (google and
            parsed.path.rstrip("/") in ("/url", "/goto")):
        raise ValueError("Resolve the intermediary before using it as evidence")
    return value


def parse_search(payload, limit):
    if type(limit) is not int or not 1 <= limit <= 10:
        raise ValueError("limit must be an integer from 1 to 10")
    if (not isinstance(payload, dict) or type(payload.get("code")) is not int
            or payload["code"] != 0):
        raise ValueError("SearchCans business error or invalid envelope")
    data = payload.get("data")
    if not isinstance(data, dict) or not isinstance(data.get("organic"), list):
        raise ValueError("Expected data.organic")
    results = []
    for row in data["organic"][:limit]:
        if not isinstance(row, dict):
            raise ValueError("Invalid organic row")
        link = source_url(row.get("link"))
        if any(not isinstance(row.get(k, ""), str) for k in ("title", "snippet")):
            raise ValueError("Invalid title or snippet")
        results.append({"url": link, "title": row.get("title", ""),
                        "snippet": row.get("snippet", ""),
                        "evidence_kind": "search_result_not_source_page"})
    return json.dumps({"results": results}, ensure_ascii=False)


def post_search(query):
    req = Request("https://www.searchcans.com/api/v1/search",
                  data=json.dumps({"t": "google", "s": query,
                                   "country": "us", "language": "en",
                                   "d": 30000}).encode(),
                  headers={"Authorization": "Bearer " + os.environ["SEARCHCANS_API_KEY"],
                           "Content-Type": "application/json"}, method="POST")
    with urlopen(req, timeout=40) as response:
        return json.load(response)


def make_search_tool(transport=post_search):
    def search(query: str, limit: int = 3) -> str:
        """Find web result references; this tool does not read source pages."""
        if not isinstance(query, str) or not query.strip():
            raise ValueError("query must be nonempty")
        # Validate before making a charged request. This is a client-side cap.
        if type(limit) is not int or not 1 <= limit <= 10:
            raise ValueError("Invalid limit")
        return parse_search(transport(query), limit)
    return StructuredTool.from_function(search, name="searchcans_web_search",
                                        args_schema=SearchInput)


if __name__ == "__main__":
    # Offline fixture exercises the real LangChain tool, without an LLM or API call.
    fixture = {"code": 0, "data": {"organic": [
        {"link": "https://example.com/source", "title": "Synthetic source",
         "snippet": "A fixture, not a live observation."}]}}
    tool = make_search_tool(lambda query: fixture)
    print(tool.invoke({"query": "example", "limit": 1}))

The default script prints one synthetic result without an API call. To make a real search, create make_search_tool() without the fixture transport, set your own SEARCHCANS_API_KEY privately, and invoke the same schema. The default transport sends a paid request according to current product terms. Do not put a key in source code or logs.

Test the boundary before attaching an agent

  • Invoke the actual StructuredTool with a valid fixture and confirm the returned URL and evidence-kind marker.
  • Reject a business error, a data array in place of an object, missing organic, an invalid link and a malformed result row.
  • Pass a valid empty organic array and keep it distinct from an error.
  • Test strict input validation before transport invocation, including a boolean or string supplied as the result limit. The explicit Pydantic schema prevents those values being silently coerced.
  • Reject unresolved Google intermediary URLs before treating a result as publisher evidence. Resolving one requires a separate verified step.

Add reading as a separate controlled task

A title and snippet can help choose a source, but they do not establish the contents of that page. A separate Reader operation can retrieve selected URLs. Verify readable content and final source identity, retain the collection time, and label page text as untrusted data. Tool output can contain misleading or adversarial instructions; a JSON wrapper is not a complete prompt-injection defense.

Use the current SearchCans search contract and Reader reference. LangChain’s official tools guide describes typed tool inputs and descriptions. This adapter avoids depending on a particular Serper wrapper’s undocumented behavior. It does not claim that every existing agent can switch providers without testing.

Tags:

LangChain SERP API AI Agents Python LLM
SearchCans Team

SearchCans Team

SERP API & Reader API Experts

The SearchCans engineering team builds high-performance search APIs serving developers worldwide. We share practical tutorials, best practices, and insights on SERP data, web scraping, RAG pipelines, and AI integration.

Ready to build with SearchCans?

Test SERP API and Reader API with 100 free credits. No credit card required.