AI AgentsLangChain

How do you make LangChain tools asynchronous?

Question 298 of 324 · Updated

On this page

Direct answer#

Define the tool with async def and the LangChain @tool decorator, await an asynchronous service client inside the tool, and invoke the tool using await tool.ainvoke(...) or invoke its containing agent using await agent.ainvoke(...). For older synchronous dependencies, use an appropriate thread-offloading boundary such as asyncio.to_thread for suitable blocking I/O. Limit simultaneous work, propagate deadlines, preserve cancellation, and manage clients at the application lifecycle boundary.

An async function is not automatically nonblocking. A synchronous HTTP request, database query, time.sleep or CPU-heavy loop inside async def can block the event loop. Also, asynchronous invocation does not mean all tools will execute concurrently: the model, tool-call dependencies, runtime scheduling, configuration and external service limits determine the actual execution pattern.

Source questions #14 and #17 (AI Agents #294 and #297) introduce dependency injection and tool error handling. This lesson concentrates on the asynchronous execution contract of LangChain tools, including invocation, concurrency admission, deadline and cancellation behavior, and performance verification. General Python asyncio topics, worker deployment, retry middleware and dynamic tool routing have separate lessons.

1. What asynchronous execution changes#

An async tool suspends while awaiting compatible I/O so that the event loop can make progress on other ready tasks. For example, a support agent may need to obtain inventory availability and a shipping estimate from two independent authorized services.

With sequential execution, the second read starts after the first completes. With appropriate concurrent execution, the two service waits overlap. However, if shipping requires a warehouse identifier returned by the inventory call, the calls are dependent and should not be dispatched concurrently without that prerequisite.

Execution patternAppropriate useImportant limitation
Synchronous toolSimple calculation or synchronous hostBlocking I/O occupies its executing thread
Native async toolAsync HTTP, database or other compatible I/OAwaited client must actually support nonblocking execution
Thread-offloaded sync toolLegacy blocking I/O with a suitable thread-safe clientCancellation of the await does not terminate the running thread
Process or worker executionSubstantial CPU-bound or isolated durable workSerialization, scheduling and lifecycle overhead

Concurrency is not the same as parallel CPU execution. A single Python event loop can interleave multiple I/O-bound tasks without running their Python code simultaneously on that loop. For significant CPU-bound work, select a suitable process pool, worker or native implementation rather than assume async def makes computation faster.

Loading diagram…

The diagram represents an application design, not a promise about the internal scheduler or the order of every LangChain version.

2. Define and directly invoke an async LangChain tool#

Use the same decorator and typed public arguments introduced in the earlier tool lessons. The callable should be an asynchronous function when its implementation relies on awaiting an asynchronous operation.

PYTHON
import asyncio from langchain.tools import tool @tool async def check_demo_inventory(sku: str) -> dict: """Read synthetic inventory for a product without changing stock.""" # Simulated nonblocking I/O, not an actual service. await asyncio.sleep(0.01) records = {"SKU-1": 12, "SKU-2": 0} if sku not in records: return {"status": "unavailable"} return {"status": "ok", "sku": sku, "quantity": records[sku]} async def main(): result = await check_demo_inventory.ainvoke({"sku": "SKU-1"}) print(result) if __name__ == "__main__": asyncio.run(main())

The expected logical result is a dictionary indicating 12 available units for SKU-1. This is fictional inventory. The demonstration deliberately uses asyncio.sleep rather than a real network service.

Verification note: The local environment has Python 3.13.5 but does not have langchain, langchain_core or langgraph installed. SDK examples are illustrative, unexecuted and not checked against an installed release. The standalone Python concurrency implementation in section 7 was actually executed. Check the exact framework API and provider integration before deployment.

Use ainvoke for an asynchronous-only tool. Do not assume invoke will automatically run the coroutine or create an event loop for you. Depending on the tool implementation, invoking an async-only tool synchronously may be unsupported. Some synchronous tools expose an asynchronous invocation interface that offloads execution; the exact behavior is implementation-dependent and should be verified.

In an existing asynchronous web server, notebook or worker loop, await the tool from the running event loop. Do not call asyncio.run inside an already running event loop. asyncio.run is appropriate at a standalone synchronous entry point that owns the loop lifecycle.

3. Register the tool and invoke the agent asynchronously#

A modern LangChain agent can register asynchronous tools using the ordinary tool list. Invoke the agent asynchronously when the execution path requires async model or tool operations.

PYTHON
from langchain.agents import create_agent agent = create_agent( model="openai:gpt-4o-mini", tools=[check_demo_inventory], system_prompt=( "Use the fictional inventory tool for evidence. " "Never claim a stock change occurred." ), ) async def handle(user_text: str): return await agent.ainvoke({ "messages": [{"role": "user", "content": user_text}] })

The model identifier is illustrative. This example was not executed and does not establish current model availability, tool-call support or provider behavior.

When using an asynchronous entry point, inspect the complete call chain. The model adapter, tool implementation, middleware, service clients, persistence backend and callbacks may have their own async interfaces or thread-offloading behavior. One blocking integration can undermine the responsiveness of an otherwise async application.

The agent may receive multiple tool requests in a model response. Compatible runtimes can execute independent tools concurrently, but exact scheduling and controls are version- and configuration-dependent. Do not assume that ainvoke forces simultaneous execution, that the provider supports parallel tool calling, or that tool results arrive in proposal order.

Always correlate each result with its original call identifier. If one call finishes before another, its result must not be attached to the wrong request.

Loading diagram…

This illustrates one possible scheduling pattern for independent reads. Mutating operations or dependent calls require stronger ordering and consistency controls.

4. Use asynchronous service dependencies correctly#

Prefer a long-lived, appropriately scoped asynchronous HTTP or database client managed by the host. Create clients in their supported lifecycle, use connection pooling and close owned resources only after active work has finished.

The following illustrative integration shows a tool calling a fictional typed async service through trusted runtime context. It builds on the previously taught ToolRuntime pattern rather than introducing another dependency-injection mechanism.

PYTHON
from dataclasses import dataclass from typing import Protocol from langchain.tools import tool, ToolRuntime class InventoryService(Protocol): async def quantity(self, sku: str) -> int | None: ... @dataclass(frozen=True) class InventoryContext: service: InventoryService @tool async def read_inventory( sku: str, runtime: ToolRuntime[InventoryContext] ) -> dict: """Read an authorized inventory quantity for an exact SKU.""" service = runtime.context.service quantity = await service.quantity(sku) if quantity is None: return {"status": "unavailable"} if type(quantity) is not int or quantity < 0: raise ValueError("invalid upstream quantity") return {"status": "ok", "sku": sku, "quantity": quantity}

Construct the agent with context_schema=InventoryContext and pass the trusted context on invocation. The host must supply a service that already enforces the authenticated resource scope. Never expose API keys, connection credentials or tenant identifiers as model-generated arguments merely to implement async access.

The SDK example does not instantiate a real client or implement authentication. A production client should enforce outbound destinations, connection timeouts, response size, current authorization and bounded resource use. Check that the client supports use on the relevant event loop; an async client tied to a closed loop or shared across incompatible loops can fail.

Resource lifecycle#

A typical asynchronous service owns a client for its application lifetime or a specific request scope, depending on the library. The host may use an async context manager or a finally block to guarantee cleanup. A tool consuming a shared client should not close it at the end of each call.

If a request owns a client, wait for its child tasks and streams to finish or be canceled and drained before closing the client. Otherwise one task may still attempt to use a closed connection pool.

5. Avoid blocking the event loop#

These two patterns have very different runtime behavior even though both are declared async:

PYTHON
# Incorrect: time.sleep blocks the executing event-loop thread. import time import asyncio async def blocking_example(): time.sleep(0.2) return "done" async def cooperative_example(): await asyncio.sleep(0.2) return "done"

This is an illustrative contrast, not a performance benchmark. An asynchronous HTTP client awaiting a socket behaves more like the cooperative example than the blocking one. Merely adding async def around a synchronous database driver or requests-style HTTP function does not change how that call waits.

For a legacy synchronous dependency, a suitable thread-offloading pattern is:

PYTHON
import asyncio def blocking_read(sku: str) -> dict: # Stand-in for a bounded, thread-compatible blocking I/O client. return {"sku": sku, "quantity": 12} async def read_legacy(sku: str) -> dict: return await asyncio.to_thread(blocking_read, sku)

The standalone test in section 7 confirms that asyncio.to_thread runs the tested function on a different thread. The example here uses a fictional synchronous service; it does not measure network behavior.

Thread offloading has important trade-offs:

  • The client must support access from the worker thread. Some database connections have thread affinity.
  • Thread pools have finite capacity. Large bursts of offloaded calls may queue or consume substantial resources.
  • Python cancellation of the await does not forcibly stop a running worker thread.
  • The remote operation may continue after the request has timed out.
  • A semaphore protecting only the awaiting coroutine can release a permit while the underlying thread is still running after cancellation.

For that last reason, do not treat an async semaphore around to_thread as a guaranteed bound on still-running blocking operations after timeouts. Enforce a suitably bounded executor, service-side concurrency, client timeouts and explicit tracking of worker completion where necessary. For critical work, consider a dedicated worker with durable operation tracking.

For CPU-heavy Python code, threads may not improve throughput under the ordinary GIL-enabled interpreter. Select a workload-appropriate process, native extension or worker, and evaluate the actual Python runtime rather than assume thread offloading always provides parallel computation.

6. Bound concurrency and propagate one deadline#

A model may request many independent reads. An asynchronous server may also process many concurrent agent invocations. Without a resource limit, those requests can overwhelm connection pools, upstream services or the application's memory.

An asyncio.Semaphore can limit the number of admitted operations on an event loop. Keep it at the correct sharing scope: a new semaphore inside each individual tool call does not limit concurrency across calls. A semaphore created for each request limits that request, not the entire service.

ControlWhat it limits
Per-run tool-call budgetNumber of model-generated tool operations
Shared semaphoreSimultaneous admitted operations within its owning scope
Connection poolAvailable service connections
Rate limiterRequest rate over time
Bounded queueWaiting work and memory usage
End-to-end deadlineRemaining elapsed-time budget
Distributed service quotaWork across processes or hosts

A semaphore is not a rate limiter, and a local semaphore cannot enforce a global multi-worker quota. Also, creating a million tasks that all wait for a semaphore can consume memory even if only a few enter the critical section. Limit the number of queued tasks at admission.

Use one monotonic deadline for the run or approved operation. Pass the remaining budget downstream. If a tool must wait for a concurrency permit, that waiting time counts against the budget.

Loading diagram…

This pattern applies to cooperative asynchronous reads. For thread-offloaded or external operations, returning a timeout may not mean the underlying work stopped.

Python 3.11 and later provide asyncio.timeout and asyncio.timeout_at. The latter uses the event loop's monotonic clock. asyncio.wait_for is another available mechanism, but cancellation and cleanup semantics differ; read the relevant version's documentation. A timeout is a cooperative mechanism rather than a guarantee of exact wall-clock termination, particularly if code blocks the loop or delays cancellation.

7. Tested Python implementation: bounded asynchronous reads#

This standalone example demonstrates the tool-service boundary using actual asyncio. It is independent of LangChain and does not pretend to test LangChain's scheduler.

A shared LimitedReader admits at most a configured number of cooperative asynchronous reads. Each call receives an absolute deadline that includes waiting for a permit. Expected missing-record failures become bounded observations. Unexpected exceptions and external task cancellation propagate.

PYTHON
import asyncio import threading from dataclasses import dataclass from collections.abc import Awaitable, Callable @dataclass(frozen=True) class Result: id: str status: str value: str | None = None class LimitedReader: def __init__(self, read: Callable[[str], Awaitable[str]], limit: int): if type(limit) is not int or limit < 1: raise ValueError('invalid limit') self.read = read self.slots = asyncio.Semaphore(limit) async def fetch(self, id: str, deadline: float) -> Result: try: async with asyncio.timeout_at(deadline): async with self.slots: if asyncio.get_running_loop().time() >= deadline: return Result(id, 'timeout') return Result(id, 'ok', await self.read(id)) except TimeoutError: return Result(id, 'timeout') except LookupError: return Result(id, 'unavailable') class FakeService: def __init__(self): self.active = self.peak = self.started = 0 self.entered = asyncio.Event() self.release = asyncio.Event() async def read(self, id): self.active += 1 self.started += 1 self.peak = max(self.peak, self.active) self.entered.set() try: await self.release.wait() if id == 'missing': raise LookupError('internal detail') if id == 'bug': raise RuntimeError('unexpected fault') return 'value:' + id finally: self.active -= 1 async def main(): loop = asyncio.get_running_loop() s = FakeService() r = LimitedReader(s.read, 2) tasks = [asyncio.create_task(r.fetch(str(i), loop.time()+5)) for i in range(4)] while s.started < 2: await asyncio.sleep(0) assert s.active == 2 and s.started == 2 s.release.set() results = await asyncio.gather(*tasks) assert s.peak == 2 and s.active == 0 assert [x.value for x in results] == ['value:0','value:1','value:2','value:3'] assert await r.fetch('missing',loop.time()+5) == Result('missing','unavailable') try: await r.fetch('bug',loop.time()+5) except RuntimeError: pass else: raise AssertionError('unexpected error swallowed') before = s.started assert (await r.fetch('expired',loop.time()-1)).status == 'timeout' and s.started == before s = FakeService(); r = LimitedReader(s.read,1) t = asyncio.create_task(r.fetch('held',loop.time()+5)) await s.entered.wait() assert (await r.fetch('queued',loop.time()+0.03)).status == 'timeout' and s.started == 1 t.cancel() try: await t except asyncio.CancelledError: pass else: raise AssertionError('cancel suppressed') assert s.active == 0 assert (await r.fetch('slow',loop.time()+0.03)).status == 'timeout' and s.active == 0 s.release.set() assert (await r.fetch('after',loop.time()+5)).status == 'ok' assert await asyncio.to_thread(threading.get_ident) != threading.get_ident() print('12 scenarios passed') asyncio.run(main())

Actual local execution on Python 3.13.5:

12 scenarios passed

The checks establish the following behavior. The initial concurrency case verifies admission and peak occupancy separately, and the cancellation case verifies propagation and cleanup separately.

CheckObserved result
Initial admissionExactly two reads admitted before release
Peak concurrency and cleanupPeak two, no active reads after completion
Result correspondenceFour values returned in gather input order
Expected missing-record errorControlled unavailable result
Unexpected service exceptionRuntimeError propagates
Already expired deadlineNo service call starts
Queued deadlineWaiting request times out without reaching service
External cancellationCancelledError propagates
Cancellation cleanupActive read count returns to zero
In-flight timeoutCooperative read canceled and cleaned up
Permit reuseLater request succeeds
Thread offloadWorker thread differs from event-loop thread

This is a deterministic synthetic service driven by asyncio.Event. Its short timeout tests verify control flow, not service performance. The example uses LookupError as an expected failure for teaching; real applications should catch narrow domain exception types, not broad categories that could mask programming faults. Similarly, a production service should distinguish its own upstream timeout from expiration of the application's outer deadline. The example assumes the host supplies a validated finite deadline and trusted dependency; it is not a complete request validator, distributed limiter or authorization implementation.

The wait loop in the test is a fixture synchronization mechanism. Production code should not busy-poll for service readiness. Use lifecycle events, bounded waits and structured task ownership. The reader is designed for cooperative async I/O, not for blocking workers that may continue running after cancellation.

8. Manage batches, failure propagation and cancellation#

When executing independent reads, the application can gather results or use structured concurrency. asyncio.gather returns successful results in the order of the supplied awaitables, not completion order. Its default exception behavior propagates an exception to the caller without necessarily canceling all sibling awaitables. If you own the tasks, arrange explicit cleanup and draining.

asyncio.TaskGroup provides structured ownership: on a non-cancellation failure it generally cancels remaining tasks and waits for them, then raises an exception group as applicable. This is useful for all-or-nothing batches of cooperative work. It does not roll back external side effects.

PYTHON
import asyncio async def collect_required_reads(reader, ids, deadline): async with asyncio.TaskGroup() as group: tasks = [ group.create_task(reader.fetch(id, deadline)) for id in ids ] return [task.result() for task in tasks]

This optional Python pattern is illustrative and was not separately executed. If fetch converts an expected failure into a Result with status unavailable, TaskGroup considers that task completed normally. The caller must check the returned statuses when deciding whether the entire task succeeded.

For a partial-result workflow, handle approved failure classes within individual tasks, retain verified successful results, and explicitly mark missing or timed-out evidence. Do not return an arbitrary partial observation as a complete answer. If a required dependency fails, stop rather than speculate about its result.

Cancellation should propagate to owned cooperative child tasks. Use finally blocks or context managers to release local resources. Do not swallow CancelledError simply to produce a friendly tool observation. A cancellation request from the host is different from a model-recoverable read error.

Loading diagram…

A deadline-triggered cancellation may be transformed into TimeoutError by the timeout context manager outside its block. Host cancellation normally propagates as CancelledError. Always check the external outcome for mutations: an HTTP cancellation, disconnected socket or timed-out await does not prove that the remote server canceled the request.

For a state-changing tool, reuse the authorization, idempotency and reconciliation design established in earlier lessons. Avoid concurrently performing dependent writes merely because the runtime supports parallel tool requests.

9. Practical latency and capacity example#

Assume an agent must execute three independent read operations with hypothetical service waits of 200 ms, 350 ms and 150 ms. Ignore model calls, scheduling overhead, network variation and queueing.

Scheduling approachIllustrative tool-stage time
Sequential200 + 350 + 150 = 700 ms
All three concurrentlymax(200, 350, 150) = 350 ms
Two slots, starting first two calls togethermax(200 + 150, 350) = 350 ms

The idealized sequential-to-concurrent improvement is 2 times for that particular tool stage. It is not a general 2x speedup for the entire agent. If the model spends another 900 ms generating requests and final answers, the hypothetical total changes from 1,600 ms to 1,250 ms, approximately a 22% reduction in total latency.

These numbers are constructed examples, not measured benchmarks. Actual performance depends on connection setup, queuing, service limits, task dependencies, response size, model latency and event-loop health. Excessive concurrency can increase tail latency through contention and rate limiting.

Consider a service handling 100 simultaneous agent runs with a per-run fan-out limit of four. Without a shared limit or lower-level admission control, the workload could propose up to 400 simultaneous reads. A per-process semaphore with 20 permits bounds admitted cooperative reads to 20 for its owning process, but five independently configured workers could still admit up to 100 across the service. Plan quotas and connection pools across the deployment, not only inside one agent.

10. Production verification and monitoring#

A local asyncio test is not sufficient to establish actual LangChain integration. Test the complete tool execution stack with a compatible installed version, controlled provider adapter and authorized synthetic services.

TestAcceptance condition
Async-only tool invocationainvoke returns the intended logical result
Agent async invocationTool executes and correlated observation reaches the model
Sync invocation of async-only toolBehavior matches the documented contract; no unexpected loop nesting
Multiple independent callsRuntime respects intended concurrency and correlation
Dependent callsPrerequisite evidence is available before dependent execution
Blocking client regressionEvent-loop lag stays within workload-specific limits
SaturationAdmission and queue size are bounded
Queue timeoutExpired request does not initiate an external operation
Service timeoutLocal resources are released; outcome classified truthfully
Request cancellationOwned tasks are drained and cancellation is not swallowed
Thread-offloaded timeoutRunning worker and remote outcome are tracked independently
Dependency cleanupNo client closes while owned tasks are using it
Error propagationUnexpected faults reach the appropriate host boundary
Tenant isolationConcurrent contexts never share unauthorized identities or results

For load testing, begin with deterministic service doubles that can vary delay, failure and response size. Then run approved integration tests with realistic network and connection-pool settings. Compare sequential and asynchronous implementations using the same task set, permissions, model profile, cache configuration and service behavior.

Measure p50, p95 and p99 tool-stage and end-to-end latency, queue wait, in-flight operations, connection-pool utilization, event-loop lag, timeouts, cancellation cleanup and cost per verified successful task. Track residual work that continues after a timeout. A fast HTTP response that leaves thousands of abandoned blocking operations running is not a healthy result.

Do not benchmark only successful requests; include saturation, slow upstream responses, cancellation, rate limits and partial failure. Establish release criteria before tuning. Avoid using real customer credentials or mutating external services in uncontrolled load tests.

Interview-ready answer#

I define a LangChain tool using async def and @tool, await a compatible async service client, and use await tool.ainvoke or await agent.ainvoke. I preserve the distinction between asynchronous invocation and actual parallel scheduling. For suitable legacy blocking I/O I can use asyncio.to_thread, but cancellation of the await cannot stop a running thread. I bound independent reads with shared admission limits, propagate a monotonic deadline including queue wait, preserve cancellation and unexpected errors, and close resources at their owning lifecycle boundary. I test actual tool-call correlation and SDK integration separately from deterministic asyncio tests, and measure end-to-end tail latency, saturation and verified task completion rather than assuming async is always faster.

Official documentation research leads and verification status#

Authorized offline research exception applied. These official documentation URLs are research leads and were not live-accessed. The standalone bounded-reader test actually ran on Python 3.13.5 and all 12 scenarios passed. Local inspection confirmed langchain, langchain_core and langgraph were absent; SDK examples and actual framework scheduling, provider conversion, and async integration were not executed. The optional explanatory Python snippets were not separately tested. All service data and numerical performance examples are synthetic. Mermaid diagrams use standard triple-backtick fences; rendering and public website display were not verified.

References

  1. 1.
    LangChain toolsdocs.langchain.com
  2. 2.
    LangChain agentsdocs.langchain.com
  3. 3.
    LangChain runtimedocs.langchain.com
  4. 4.
    LangChain API referencereference.langchain.com
  5. 5.
  6. 6.
  7. 7.
  8. 8.

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps

Machinoai Logo
Machinoai

Your edge in the AI era. Deep dives into machine learning concepts, paper explainers, verified industry jobs, and developer tools.

© 2026 Machinoai. All rights reserved.