AI Hints
Home›LangChain Tutorial›FAQ Bot and Async
LangChain · Lesson 81 of 120

Async Calls

Ainvoke and abatch.

⏱ 2 min read▶ Video at 1:31:44🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Most of the time, a program calling a model is just waiting for the reply. A web server handling many customers can't afford to wait for each one in turn. Async lets one program wait for many calls at once.

Async Calls
From the video: Async Calls
  • Mostly waiting
  • Many customers
  • Wait for many at once

One at a time vs all at once

Every runnable has async versions of its methods, starting with a. Here we send three questions with a invoke. First one after another, then all together, with asyncio gather. Run it. Sending them together takes about as long as the slowest single call, instead of the sum of all three.

async_calls.pypython
import asyncio, time
from langchain.chat_models import init_chat_model

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
questions = [f"Name one novel by {a}. Title only." for a in ["Austen", "Orwell", "Tolkien"]]

async def main():
    start = time.perf_counter()
    for q in questions:
        await model.ainvoke(q)
    print(f"one at a time: {time.perf_counter() - start:.1f}s")

    start = time.perf_counter()
    replies = await asyncio.gather(*(model.ainvoke(q) for q in questions))
    print(f"all at once:   {time.perf_counter() - start:.1f}s")
    print([r.text.strip() for r in replies])

asyncio.run(main())
Output
one at a time: 2.3s
all at once:   0.8s
['Pride and Prejudice', '1984', 'The Lord of the Rings']

Async methods

Each method has an async twin. A invoke for one call. A batch for a list. A stream, for streaming. And agents have them too. Use them inside async web frameworks, like Fast API, which we'll meet later.

SyncAsync
invokeainvoke
batchabatch
streamastream
agent.invokeagent.ainvoke

Summary

Async methods let one program wait for many model calls at once. Use asyncio gather, or a batch. Next, saving money by caching repeated calls.

Key takeaways
  • await ainvoke
  • asyncio.gather
  • abatch, astream
Next up: Caching Model Calls — pay once