Lesson 2 of 9 · Core
Chat Models
Use chat models in LangChain: messages, init_chat_model, invoke, multi-turn chats, token usage, streaming, batching with concurrency limits and fake models.
- 7 min read
- Intermediate
- Reviewed
- Send system, human and AI messages to a chat model
- Set model parameters such as temperature and max_tokens
- Keep a multi-turn conversation by managing the message list
- Stream replies chunk by chunk and batch independent requests
- Read token usage, and test with fake models
Messages in, a message out
Chat models take a list of messages and return a message. LangChain gives each role its own class:
You can also write messages as ("system", "...") tuples or {"role": "user", "content": "..."} dictionaries; LangChain converts them. And you can pass a plain string, which becomes a single human message.
Calling a chat model
from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage, SystemMessage
model = init_chat_model("anthropic:MODEL_NAME", temperature=0.2, max_tokens=300)
messages = [
SystemMessage("You are a concise travel assistant."),
HumanMessage("Suggest one day trip from Lisbon."),
]
reply = model.invoke(messages) # an AIMessage
print(reply.content)
print(reply.usage_metadata)
# Keep the conversation going: add the reply, then the next question
messages.append(reply)
messages.append(HumanMessage("How do I get there?"))
print(model.invoke(messages).content)Sintra: palaces, gardens and forest walks, 40 minutes away by train.
{'input_tokens': 24, 'output_tokens': 19, 'total_tokens': 43}
Take the train from Rossio station; trains run about every 20 minutes.Points to notice:
- Parameters such as
temperatureandmax_tokensgo toinit_chat_modeland are passed on to the provider's model class. Others you'll often set aretimeoutandmax_retries. - The reply is an AIMessage. Its
contentis the text;usage_metadatareports the tokens used, which is how you track cost. - The model is stateless (see the Memory in AI Agents course). To continue the conversation, append the reply and the next question to the list and send the whole list again.
Streaming and batching
from langchain.chat_models import init_chat_model
model = init_chat_model("anthropic:MODEL_NAME")
# Stream: print the reply as it is generated
for chunk in model.stream("Write a haiku about Lisbon's trams."):
print(chunk.content, end="", flush=True)
print()
# Batch: several independent requests, up to 2 at a time
replies = model.batch(["Capital of Peru?", "Capital of Kenya?"], config={"max_concurrency": 2})
for r in replies:
print(r.content)Yellow trams climb through the narrow morning streets bells ring at each turn Lima. Nairobi.
streamyields the reply in small pieces as the model writes it, so users see text appear immediately instead of waiting for the whole answer.batchsends several independent requests and returns replies in the same order.max_concurrencycaps how many run at once, which keeps you inside the provider's rate limits.- Every method has an async version (
ainvoke,astream,abatch) for web servers and other async code.
How streamed chunks add up
Streamed pieces are chunks, and in LangChain chunks can be added together with + to rebuild the full message. Here's the idea in plain Python, with a tiny model that streams word by word:
# What a chat model interface does for you: messages in, a message out, streamed in chunks
# that can be added together. (A plain-Python model of how LangChain's message chunks work.)
class Chunk:
def __init__(self, content, output_tokens=0):
self.content, self.output_tokens = content, output_tokens
def __add__(self, other): # chunk + chunk = a longer chunk
return Chunk(self.content + other.content, self.output_tokens + other.output_tokens)
class TinyChatModel:
def __init__(self, scripted_reply):
self.reply = scripted_reply
def stream(self, messages):
words = self.reply.split(" ")
for i, w in enumerate(words):
yield Chunk(w + (" " if i < len(words) - 1 else ""), output_tokens=1)
def invoke(self, messages): # invoke is just "stream, then add the chunks up"
full = Chunk("")
for chunk in self.stream(messages):
full = full + chunk
return full
model = TinyChatModel("Sintra is a fairy-tale day trip forty minutes from Lisbon by train.")
messages = [("system", "You are a concise travel assistant."), ("human", "One day trip from Lisbon?")]
print("Streaming:", end=" ")
for chunk in model.stream(messages):
print(chunk.content, end="|") # | shows where each chunk ends
reply = model.invoke(messages)
print(f"\nInvoke: {reply.content}\nOutput tokens: {reply.output_tokens}")LangChain's real AIMessageChunk objects work the same way: full = chunks[0] then full += chunk for each later chunk gives you the complete message, including its token counts and any tool calls.
Fake models for testing
LangChain includes fake chat models that return scripted replies. They make tests fast, free and repeatable, and they behave like real models in chains:
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
# A fake model returns scripted replies: perfect for tests, free and instant
fake = GenericFakeChatModel(messages=iter([AIMessage("Lima.")]))
print(fake.invoke("Capital of Peru?").content)Lima.
Common mistakes
Combine streamed chunks into the final reply, as your code must when it streams a model's answer and also needs the whole text.
# Chunks as a model streams them, each with the text and the number of output tokens
chunks = [{"text": "Trams ", "tokens": 1}, {"text": "climb ", "tokens": 1},
{"text": "the hills", "tokens": 2}, {"text": " of Lisbon.", "tokens": 3}]
# Join the texts into one reply and add up the tokens, then print:
# <reply>
# <total> tokens
How do you continue a conversation with a LangChain chat model?
Summary
- Chat models take messages (system, human, AI, tool) and return an AIMessage.
- Pass parameters like
temperature,max_tokens,timeoutandmax_retriestoinit_chat_model. - Keep conversations by appending replies and new questions to the message list.
- Stream for responsiveness, batch with
max_concurrencyfor many independent requests; chunks add up to the full message. - Read
usage_metadatafor token counts, and use fake models in tests.
Next: prompt templates.
Finished reading? Tick it off to track your progress.