utilities — Wrappers for SerpAPI, SQL, Wikipedia, BashProcess, etc.

Wrappers for SerpAPI, SQL, Wikipedia, BashProcess, etc.

Module langchain_classic/utilities/ — Wrappers for SerpAPI, SQL, Wikipedia, BashProcess, etc.. Part of the Cross-cutting group.

🎯 Why This Module Exists

Provider wrappers that aren't LLMs themselves but back tools and chains: SerpAPI, GoogleSearch, Bing, DuckDuckGo, Wikipedia, ArXiv, OpenWeatherMap, Wolfram Alpha, SQL databases (SQLAlchemy), BashProcess, Python REPL. Each wrapper normalises auth, rate-limit handling, and result shape so the corresponding Tool stays small.

58
Source files
0
Sub-directories
Cross-cutting
Category
Python
Language

Wrappers Tool-backing

Architecture

flowchart LR
  subgraph Core["langchain_classic/utilities/"]
    BASE["Base abstraction"]
    IMPLS["Concrete implementations"]
    BASE --> IMPLS
  end
  subgraph Up["Upstream callers"]
    U1["chains/"]
    U2["agents/"]
  end
  subgraph Down["Downstream"]
    D1["langchain_core"]
    D2["External providers"]
  end
  Up --> Core
  Core --> Down

Data Flow

sequenceDiagram
  participant Caller as Caller
  participant Utilitie as utilities
  participant Core as langchain_core
  participant Ext as External
  Caller->>Utilitie: invoke(input)
  Note over Utilitie: Validate & route
  Utilitie->>Core: delegate primitive
  Core->>Ext: provider call
  Ext-->>Core: response
  Core-->>Utilitie: typed output
  Utilitie-->>Caller: result

Design Decisions

DecisionChoice MadeAlternativesWhy This Approach
Wrapper vs ToolWrapper is the API client; Tool wraps wrapper with a name+description+schemaSingle Tool class doing bothSame wrapper sometimes backs multiple tools (search vs retrieve)
Optional depsPer-wrapper imports inside the fileAll-required dependenciesMost users need only one or two
Async wrappers where SDK supportsasyncio.to_thread fallbackSync onlyAgents often need parallel tool calls

Tools in tools/ almost always delegate to a utility wrapper here for the actual API call.

Step-by-Step Walkthrough

Follow a typical operation through the utilities/ module:

  1. Caller invokes the public surface — usually .invoke(input) on a Runnable, or a legacy __call__(inputs_dict) on a Chain subclass.
  2. Pydantic validation — every entry point is a BaseModel; constructor args, input dicts, and tool args_schema are validated before any expensive work runs. Fail-fast on type errors.
  3. CallbackManager.configure — a fresh manager is built per call, fans on_*_start events to all subscribers (LangSmith tracer, stdout handler, custom logging), and stamps a UUID4 run_id for tree reconstruction.
  4. utilities-specific logic — the module's core method runs: prompt rendering, retrieval, tool execution, memory load, document split, etc. See the deep-dive sections above.
  5. Provider call — typically a single HTTP request to OpenAI/Anthropic/etc., or a local SDK call. Retries are handled by tenacity with exponential backoff and a configurable max-attempts knob.
  6. Streaming fan-out — if the provider streams tokens, each chunk fires on_llm_new_token through the callback manager so downstream observers (UI, log, tracer) see partial output.
  7. OutputParser pass — if a parser is attached, the raw provider output is parsed into a structured Python object; OutputParserException may trigger a retry chain (RetryWithErrorOutputParser).
  8. Memory write-back — for chains/agents that have a BaseMemory attached, save_context(inputs, outputs) persists the turn before returning to the caller.
  9. on_*_end fan-out — the callback manager closes the run span; tracers serialise the Run tree and ship it to LangSmith asynchronously.
  10. Result returned — caller receives a typed object (AIMessage, dict, BaseModel, list[Document], ...) matching the module's declared output schema.

What Could Go Wrong

Failure Mode Trigger Detection Recovery
Provider 5xx / rate-limit OpenAI/Anthropic/etc. transient error HTTP status from SDK tenacity retries with exponential backoff up to max_retries; then surface to caller
Output parser failure LLM returned malformed JSON / wrong schema OutputParserException in parser RetryWithErrorOutputParser re-prompts with the parser error included; or surface
Pydantic validation Caller passes wrong-shaped dict ValidationError at __init__ / invoke Surface immediately — no fallback is correct here
Callback handler exception User-supplied tracer raises Try/except around each fan-out Logged and swallowed by default; raise_error=True to opt in to propagation
Provider auth missing OPENAI_API_KEY unset SDK AuthenticationError Surface with a helpful message; no retry (would just fail again)

Performance Profile

Hot Paths

Resource Usage

Directory Map

Source tree for utilities
utilities/
├── __init__.py
├── alpha_vantage.py
├── anthropic.py
├── apify.py
├── arcee.py
├── arxiv.py
├── asyncio.py
├── awslambda.py
├── bibtex.py
├── bing_search.py
├── brave_search.py
├── clickup.py
├── dalle_image_generator.py
├── dataforseo_api_search.py
├── duckduckgo_search.py
├── github.py
├── gitlab.py
├── golden_query.py
├── google_finance.py
├── google_jobs.py
├── google_lens.py
├── google_places_api.py
├── google_scholar.py
├── google_search.py
├── google_serper.py
├── google_trends.py
├── graphql.py
├── jira.py
├── max_compute.py
├── merriam_webster.py
├── metaphor_search.py
├── nasa.py
├── opaqueprompts.py
├── openapi.py
├── openweathermap.py
├── outline.py
├── portkey.py
├── powerbi.py
├── pubmed.py
├── python.py
├── reddit_search.py
├── redis.py
├── requests.py
├── scenexplain.py
├── searchapi.py
├── searx_search.py
├── serpapi.py
├── spark_sql.py
├── sql_database.py
├── stackexchange.py
├── steam.py
├── tavily_search.py
├── tensorflow_datasets.py
├── twilio.py
├── vertexai.py
├── wikipedia.py
├── wolfram_alpha.py
└── zapier.py