08F.5 Chat Models, Messages and Content Blocks
Every LangChain and LangGraph program, from a three-line script to a multi-agent system, rests on one object: the chat model. It takes a list of messages, calls a provider, and hands back an AIMessage. Lessons 03.1 to 03.11 taught you what happens on the wire for each provider and had you build your own thin client. This lesson teaches the same layer as LangChain 1.x packages it: how to create a model (init_chat_model and the provider classes), the message types and the standard content blocks that normalize every provider's reply into one shape, the call methods (invoke, stream, batch and their async twins), multimodal input, reasoning output, usage metadata, rate limiters, caching, retries and fallbacks, a first look at with_structured_output, and, just as important, what does not port between providers. Everything that can run without a key is run for you, with real output.
What you'll learn
- What a LangChain chat model is (
BaseChatModel, aRunnablefrom messages toAIMessage), and how it differs from the legacy text-in, text-out LLM classes - Two ways to build one:
init_chat_model("provider:model")and the provider classes (ChatOpenAI,ChatAnthropic,ChatGoogleGenerativeAI,ChatOpenRouter,ChatOllama, and others), including how the provider string is resolved and the traps in that resolution - The standard parameters (
model,api_key,temperature,max_tokens,timeout,max_retries,rate_limiter,profile) and the defaults that actually apply, which differ from what some docs pages say - The message types (
SystemMessage,HumanMessage,AIMessage,ToolMessage,RemoveMessage), the dict and tuple shorthand,AIMessage's attributes, and message utilities (trim_messages,convert_to_openai_messages, serialization) - Standard content blocks:
contentversuscontent_blocksversus.text, the block reference (text, reasoning, refusal, images, files, tool calls, server tool calls,non_standard), how Anthropic and OpenAI replies are normalized, andoutput_version invoke,stream,batch,batch_as_completed,ainvoke,astream,abatch,astream_events,RunnableConfig, and the streaming-tool-call change inlangchain-core1.7- Multimodal input in the standard format (URL, base64, provider file id) and multimodal output
- Reasoning output (
reasoning_effort, Anthropicthinking, and for the optional providers Geminithinking_leveland Ollamareasoning) and reading reasoning blocks - Usage metadata (
UsageMetadata, cache and reasoning token details,get_usage_metadata_callback) - Tool calling at the model level (
bind_tools,tool_choice, the manual loop) andwith_structured_outputbasics - Reliability on the model object:
max_retries,with_retry,with_fallbacks,InMemoryRateLimiter, the LangChain cache, provider prompt caching, and the standard exception hierarchy - Model profiles, configurable models, and the full list of provider-agnostic caveats
- How to test model-calling code with fake chat models, no key required, and how to read pre-1.0 tutorials
What you don't need
- API keys for most of the lesson. Provider-calling samples are written against the official documentation and the package source and are labelled illustrative. Every sample that uses a fake model, plain message objects or local utilities was actually run, and its output is real.
- Prior LangChain knowledge. Lesson 08F.4 gave you the package map; this lesson starts at the first model call.
- The agent loop. You built it by hand in 08A.2.
create_agent(which automates it) is lesson 08F.8; here you only see the model-level pieces it is made of.
Setup
Everything here needs Python 3.11 or newer: langchain 1.5 and langchain-core 1.8 dropped Python 3.10 (the install page still says 3.10; the package metadata that uv and pip enforce says 3.11). New to uv? The first uv add fails outside a project, so create one first (or follow 03.1):
uv init chat-models --bare --python 3.13 && cd chat-models # first time only
uv add langchain langchain-openai langchain-anthropic langchain-google-genai python-dotenv
# or: pip install langchain langchain-openai langchain-anthropic langchain-google-genai python-dotenvProvider packages are separate installs (langchain-openai and friends); you can also use extras such as uv add "langchain[openai]". The Gemini package (langchain-google-genai) is optional. OpenRouter (optional) needs uv add langchain-openrouter, and a local Ollama model (optional) needs uv add langchain-ollama. No == pins are needed: the lockfile uv writes pins whatever it resolves.
Versions (current at time of writing, verified 14 November 2026 against PyPI and the unpacked packages, and re-verified for the reliability, reasoning and API-selection details on 15 November 2026): langchain 1.5.0, langchain-core 1.8.0, langchain-openai 1.8.0, langchain-anthropic 1.7.10, langchain-google-genai 4.5.0, langchain-ollama 1.1.0 (these resolved the Google SDK google-genai to 3.3.0, which matters for 11.2). These packages release several times a week. Check what you have with uv pip list | grep -i langchain, and read the changelog when something behaves differently from this lesson.
The .env file is the one used across Modules 03 and 08A. LangChain's provider classes read the standard variable names from the environment, so load the file once at the top of your script:
# .env (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=... # optional
OPENROUTER_API_KEY=... # optional gatewayfrom dotenv import load_dotenv
load_dotenv() # puts the keys into os.environ; the provider classes read them from thereChatGoogleGenerativeAI checks GOOGLE_API_KEY first and GEMINI_API_KEY second (verified in the 4.5.0 source), so the .env above works unchanged. Never write a key into source code.
Free practice path. Most of this lesson runs without any key, using LangChain's fake chat models (Part 13) and by building and inspecting message objects. The samples marked Output: below were run during writing with uv run --no-project --with langchain python <file>.py (a scratch environment, no project needed) and the output is real. Building a model object does not send a request to the provider (the profile and defaults samples in 2.3 and 2.6 build objects with placeholder key values and call nothing), so model profiles can be inspected with any non-empty value in the key variable; only invoke, stream and batch need a real key. For a free local model, lesson 03.1, Part 12 covers the Ollama stand-in, and ChatOllama (2.2) is the LangChain class for it.
What you must be able to do after this lesson#
- Create a chat model with init_chat_model and with a provider class
- Build a conversation from message types and read an AIMessage
- Call a model with invoke, stream and batch
- Read usage metadata and estimate cost
- Bind tools to a model and run the manual tool loop
- Put a provider-neutral model module together
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
"Just use init_chat_model so we can swap providers." |
Part 2 and the provider-agnostic caveats |
| "It returned a list instead of a string." | 4.1 Three views of one reply |
| "Where did the thinking go?" | Part 7 and 4.3 |
"Is the name field safe to rely on?" |
3.3 ToolMessage, RemoveMessage and the name field |
"batch didn't use the batch API." |
5.4 batch |
| "We pay for retries twice." | 11.1 Four layers of retry |
"The Claude call 400s when we add temperature." |
2.3 Standard parameters |
"gemini-... went to Vertex AI, not the Gemini API." |
2.1 init_chat_model |
| "How do we test this without a key?" | Part 13 |
"This tutorial uses llm.predict and from langchain.llms import OpenAI." |
Part 14 |
"Does with_structured_output use function calling or JSON schema?" |
Part 10 |
| "How many tokens did that ticket cost?" | Part 8 |
| "The answer just stops mid-sentence." | 5.8 response_metadata and truncation |
| "Will this prompt fit before I send it?" | 8.5 Counting tokens before you call |
Part 1: Where the chat model sits#
1.1 One interface over many providers#
A LangChain chat model is an instance of a class that inherits from BaseChatModel (in langchain-core). Every provider integration is one such class, and the naming convention makes them easy to spot: they all start with Chat (ChatOpenAI, ChatAnthropic, ChatGoogleGenerativeAI, ChatOllama, ChatOpenRouter, ChatBedrockConverse). The base class gives all of them the same methods, the same input types, the same output type and the same extras (rate limiting, caching, retries, fallbacks, callbacks), so code written against BaseChatModel does not care which one it holds.
flowchart TD
app["Your code<br/>model.invoke(messages)"] --> base["BaseChatModel (langchain-core)<br/>Runnable: invoke, stream, batch, async"]
base --> cls["Provider class<br/>ChatOpenAI, ChatAnthropic, ChatGoogleGenerativeAI, ..."]
init["init_chat_model('provider:model')"] -.->|"picks and builds"| cls
cls --> sdk["Provider SDK<br/>openai, anthropic, google-genai"]
sdk --> api["Provider HTTP API"]
api --> sdk
sdk --> cls
cls -->|"normalizes into"| ai["AIMessage<br/>content, content_blocks, tool_calls,<br/>usage_metadata, response_metadata"]
ai --> appThree facts to hold on to, because the rest of the lesson hangs from them:
- A chat model is a
Runnable.invoke,stream,batchand their async versions areRunnablemethods, which is why a model can later be piped into prompts and parsers (08F.7) and dropped into graph nodes (08F.10) without adapters. - The provider SDK is still underneath.
ChatOpenAIuses theopenaipackage,ChatAnthropictheanthropicpackage,ChatGoogleGenerativeAIGoogle'sgoogle-genaipackage (sincelangchain-google-genai4.0). Everything you learned about the wire in Module 03 (status codes, rate limits, streaming events, token accounting) still applies; LangChain translates in both directions. invokereturns anAIMessage, always. Since v1 the declared return type isAIMessage, not the looserBaseMessage. If you ever get a bare string back, you are holding a legacy text LLM, not a chat model (Part 14).
1.2 What LangChain's model layer adds, and what it does not#
It is worth being honest about the trade, because 08F.1 already gave you the general costs of frameworks, and 03.11 built a provider-agnostic client by hand.
| LangChain gives you | What it does not do for you |
|---|---|
One call signature (invoke, stream, batch) across providers |
Make providers behave identically: sampling parameters, reasoning controls, caching and structured output differ (Part 12) |
One output type with normalized content_blocks, tool_calls and usage_metadata |
Remove provider-specific content: the native blocks are still in content unless you opt in to output_version="v1" (4.4) |
| Built-in retries, fallbacks, rate limiter, cache, callbacks and tracing hooks | Choose sensible limits: the defaults differ per provider package and you must set them deliberately (2.3) |
A standard exception hierarchy (ModelRateLimitError, ...) |
Replace 03.8: you still decide what to retry and what never to retry |
Model profiles (capability metadata) and init_chat_model for run-time selection |
Guarantee a model supports a feature: profile data is beta metadata, not a contract |
| Fake chat models for key-free tests | Make a pre-bound or scripted model behave exactly like a real provider |
1.3 When to use the LangChain model layer, and when to skip it#
| Situation | Better choice |
|---|---|
You are building with create_agent, LangGraph, LangChain retrievers or LangSmith tracing |
The LangChain model layer: everything in that ecosystem expects BaseChatModel |
| One provider, one model, a single call in a script | The provider SDK directly (Module 03); there is nothing to abstract |
| You need a provider feature LangChain does not expose yet (a brand new beta flag, a raw request body) | The provider SDK, or LangChain's escape hatches (12.4) for one-off cases |
| Many providers and routing across hundreds of models | A gateway such as OpenRouter or LiteLLM, reached through ChatOpenRouter, ChatLiteLLM or ChatOpenAI(base_url=...) (2.2); Module 11A covers gateways |
| You already own a provider-agnostic client | Keep it, and wrap it as a BaseChatModel only if you need the LangChain ecosystem on top |
Part 2: Creating a model#
2.1 init_chat_model#
init_chat_model is a factory function. You give it a model name (optionally prefixed with a provider) and it imports the right provider class, builds it and returns it.
from langchain.chat_models import init_chat_modelThe signature, verified in the 1.5.0 source, is:
def init_chat_model(
model: str | None = None,
*,
model_provider: str | None = None,
configurable_fields: Literal["any"] | list[str] | tuple[str, ...] | None = None,
config_prefix: str | None = None,
**kwargs: Any,
) -> BaseChatModel | _ConfigurableModelEverything in **kwargs is passed to the provider class constructor, so temperature, max_tokens, timeout, max_retries, base_url, rate_limiter, profile, output_version, use_responses_api and reasoning_effort all work, as long as the underlying class accepts them.
The three forms of the model argument
import os
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
load_dotenv()
# 1. Prefixed "provider:model" (preferred: explicit and unambiguous)
openai_model = init_chat_model("openai:gpt-6-luna")
claude = init_chat_model("anthropic:claude-haiku-5-5")
gemini = init_chat_model("google_genai:gemini-3.8-flash") # optional provider; note the UNDERSCORE
router = init_chat_model("openrouter:openai/gpt-6-luna") # optional gateway; needs the langchain-openrouter package
# 2. Bare name, provider inferred from the name (best effort; avoid in production code)
also_claude = init_chat_model("claude-haiku-5-5")
# 3. Explicit provider keyword (needed for ids that cannot be inferred)
bedrock = init_chat_model("us.anthropic.claude-sonnet-4-6", model_provider="bedrock_converse")
open_weights = init_chat_model("microsoft/Phi-3-mini-4k-instruct", model_provider="huggingface")
reply = claude.invoke("Explain what a purchase order is in one sentence.")
print(reply.text)This sample is illustrative: it needs OPENAI_API_KEY and ANTHROPIC_API_KEY, plus (optional) GEMINI_API_KEY (or GOOGLE_API_KEY) and OPENROUTER_API_KEY, for the lines that are actually invoked, plus the matching provider packages. Model ids are volatile; the ids above come from the course model table (02.9), and the Bedrock and Hugging Face ids are only examples of the shape each provider expects. Check each provider's models page for the current ids.
A purchase order is a document a buyer sends to a seller to formally request goods or services at agreed prices and quantities.How the provider is resolved (_parse_model in the source):
- If you pass
model_provider=, that wins. - Otherwise, if
modelcontains a colon and the text before the first colon is a key of the built-in provider registry, that prefix is the provider and the rest is the model name. - Otherwise LangChain tries to infer the provider from the start of the model name.
- If nothing matches you get a
ValueError; if the integration package is missing you get anImportErrortelling you which package to install.
The provider is then normalized (- to _, lower case) only after it has been found. That order is the source of a real trap, covered below.
The built-in provider registry (keys accepted before the colon). The registry docstring says it is "not exhaustive": a provider outside it must be imported and instantiated directly.
| Key | Class and package | Notes |
|---|---|---|
openai |
ChatOpenAI in langchain-openai |
OpenAI Chat Completions or Responses API |
anthropic |
ChatAnthropic in langchain-anthropic |
Anthropic Messages API |
google_genai |
ChatGoogleGenerativeAI in langchain-google-genai |
Gemini API and (via env switch) Vertex AI |
openrouter |
ChatOpenRouter in langchain-openrouter |
OpenRouter's catalogue; separate install |
azure_openai |
AzureChatOpenAI in langchain-openai |
Azure deployments |
bedrock_converse, bedrock, anthropic_bedrock |
classes in langchain-aws |
AWS Bedrock |
google_vertexai |
ChatVertexAI in langchain-google-vertexai |
Vertex AI (a different package from google_genai) |
ollama |
ChatOllama in langchain-ollama |
local models; falls back to langchain-community (sunset) if langchain-ollama is missing |
huggingface |
ChatHuggingFace (built with from_model_id) in langchain-huggingface |
Hugging Face models |
litellm |
LiteLLM wrapper | via langchain-litellm |
mistralai, cohere, groq, fireworks, together, deepseek, xai, perplexity, nvidia, ibm, meta, upstage, baseten, azure_ai, langsmith, google_anthropic_vertex, bedrock_mantle_anthropic, bedrock_mantle_openai |
the matching partner packages | see the integrations index |
Bare-name inference (best effort; the docstring says "prefer the prefixed form"):
| Name starts with | Resolved provider |
|---|---|
gpt-, o1, o3, chatgpt, text-davinci |
openai |
claude |
anthropic |
gemini |
google_vertexai (with a DeprecationWarning that the default will change to google_genai) |
command |
cohere |
mistral, mixtral |
mistralai |
deepseek, grok, sonar, solar |
deepseek, xai, perplexity, upstage |
amazon., anthropic., meta. |
bedrock |
accounts/fireworks |
fireworks |
from langchain.chat_models import init_chat_model
from langchain_core.language_models import FakeListChatModel
attempts = [
"google-genai:gemini-3.8-flash", # hyphen: not a registry key
"mystery-model", # no prefix and no inferable family
"openai:gpt-6-luna", # valid form; raises ImportError only if langchain-openai is missing
]
for name in attempts:
try:
init_chat_model(name)
except Exception as exc:
print(f"{name!r}\n {type(exc).__name__}: {str(exc).splitlines()[0][:150]}")
try:
init_chat_model(FakeListChatModel(responses=["x"])) # already a model object
except TypeError as exc:
print("TypeError:", str(exc)[:110])'google-genai:gemini-3.8-flash'
ValueError: Unable to infer model provider for model='google-genai:gemini-3.8-flash'. Please specify 'model_provider' directly.
'mystery-model'
ValueError: Unable to infer model provider for model='mystery-model'. Please specify 'model_provider' directly.
'openai:gpt-6-luna'
ImportError: Initializing ChatOpenAI requires the langchain-openai package. Please install it with `pip install langchain-openai`
TypeError: `model` must be a string (e.g., 'openai:gpt-5.5'), got FakeListChatModel. If you've already constructed a chatThe third attempt shows the other failure: a valid string, but the provider package is not installed. Install the integration (uv add langchain-openai, or the extra langchain[openai]).
Extras install. Besides the provider packages, langchain has optional extras named after providers: openai, anthropic, google-genai, google-vertexai, aws, azure-ai, huggingface, ollama, mistralai, groq, fireworks, xai, deepseek, together, perplexity and a few more (not every provider has one: Cohere, for instance, is installed as langchain-cohere). Each extra pulls in the matching langchain-<provider> package, so uv add "langchain[anthropic]" equals uv add langchain langchain-anthropic. Check the current list on the PyPI page rather than trusting a table in a lesson.
2.2 Provider classes, and where each one lives#
You can always skip init_chat_model and import the class. Do this when you need a provider-only argument, or when you want the import to fail loudly at the top of the file if the package is missing.
| Provider (course order) | Install | Class | Environment variable | Notes |
|---|---|---|---|---|
| OpenAI | langchain-openai |
ChatOpenAI |
OPENAI_API_KEY |
Chat Completions by default, Responses API on request or when needed (2.7) |
| Anthropic | langchain-anthropic |
ChatAnthropic |
ANTHROPIC_API_KEY |
Messages API; thinking, effort, cache controls |
| Google Gemini | langchain-google-genai |
ChatGoogleGenerativeAI |
GOOGLE_API_KEY, then GEMINI_API_KEY |
v4 is built on Google's consolidated google-genai SDK |
| OpenRouter | langchain-openrouter |
ChatOpenRouter |
OPENROUTER_API_KEY |
model slugs like openai/gpt-6-luna; also model="auto" in the docs; the package is 0.x and flagged Beta on PyPI as of November 2026 (see below) |
| Ollama (local) | langchain-ollama |
ChatOllama |
none | ollama pull <model> first; base_url for a remote Ollama |
| Azure OpenAI | langchain-openai |
AzureChatOpenAI |
AZURE_OPENAI_API_KEY, AZURE_OPENAI_ENDPOINT, OPENAI_API_VERSION |
azure_deployment= selects the deployment |
| AWS Bedrock | langchain-aws |
ChatBedrockConverse, ChatBedrock |
AWS credentials | model ids such as us.anthropic... need model_provider |
| Hugging Face | langchain-huggingface |
ChatHuggingFace |
HUGGINGFACEHUB_API_TOKEN |
wraps a HuggingFaceEndpoint or local pipeline |
from dotenv import load_dotenv
from langchain_anthropic import ChatAnthropic
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_openai import ChatOpenAI
load_dotenv()
openai_model = ChatOpenAI(model="gpt-6-luna", max_retries=2, timeout=30)
claude = ChatAnthropic(model="claude-haiku-5-5", max_tokens=1024, max_retries=2, timeout=30)
gemini = ChatGoogleGenerativeAI(model="gemini-3.8-flash", max_retries=2, timeout=30)
for model in (openai_model, claude, gemini):
print(type(model).__name__, "->", model.invoke("Name one French cheese.").text)This sample is illustrative: it needs real keys for all three providers and the three packages. Remove the lines for providers you do not have.
ChatOpenAI -> Brie.
ChatAnthropic -> Camembert.
ChatGoogleGenerativeAI -> Roquefort.OpenAI-compatible endpoints. Many servers (vLLM, Together, a local gateway) speak the OpenAI wire format. ChatOpenAI(base_url=..., api_key=..., model=...) targets them. The base URL is resolved in this order: an explicit base_url or openai_api_base argument, then the OPENAI_API_BASE variable (read by LangChain), then OPENAI_BASE_URL (read by the openai SDK). The base URL also decides one default: LangChain turns stream_usage on only when you left the endpoint and the HTTP client alone (details in 8.3).
2.3 Standard parameters, and the defaults that actually apply#
LangChain documents six constructor arguments that mean the same thing everywhere:
| Parameter | Meaning | Notes |
|---|---|---|
model |
the model id (required); "provider:model" accepted by init_chat_model |
volatile; keep in config |
api_key |
credential | normally left out and read from the environment |
temperature |
randomness | do not pass it by default (see below) |
max_tokens |
output token cap | OpenAI's class converts it to max_completion_tokens internally |
timeout |
seconds per request | set it; the SDK defaults are long (03.8 Part 6) |
max_retries |
client-side retries for 429, 5xx and network errors | see the next subsection |
Providers add their own: use_responses_api, stream_usage, reasoning_effort, verbosity, service_tier and prompt_cache_options on ChatOpenAI; thinking and effort on ChatAnthropic; thinking_budget, thinking_level and cached_content on ChatGoogleGenerativeAI; num_ctx, format, keep_alive, reasoning on ChatOllama. Read each provider's page under integrations/chat for the full list.
Sampling parameters. As the course has said since 02.5 Part 6, most current frontier models reject or ignore temperature and top_p. LangChain passes them through unchanged, so the provider's 400 comes straight back. The Anthropic integration page is explicit: setting temperature, top_p or top_k to a non-default value on the newest Claude models returns a 400 (the message is that the parameter "is deprecated for this model"), and the parameters are still accepted on a list of older models. The practical rule is the one from Module 03: do not add temperature out of habit, especially in code that may be pointed at a newer model later. The samples in this lesson leave it out.
Where the defaults really come from. The models page says max_retries "defaults to 6" with exponential backoff and jitter. The source disagrees, and a package-by-package reading (confirmed by constructing the objects, no network involved) shows the default depends on the class:
from langchain_anthropic import ChatAnthropic
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_openai import ChatOpenAI
openai_model = ChatOpenAI(model="gpt-6-luna")
claude = ChatAnthropic(model="claude-haiku-5-5")
gemini = ChatGoogleGenerativeAI(model="gemini-3.8-flash")
print("max_retries openai:", openai_model.max_retries, "| anthropic:", claude.max_retries, "| google:", gemini.max_retries)
print("anthropic max_tokens default:", claude.max_tokens)
print("openai stream_usage:", openai_model.stream_usage, "| use_responses_api:", openai_model.use_responses_api)Output (real; values read from the installed packages, with placeholder keys set in the shell only so the objects could be constructed):
max_retries openai: None | anthropic: 2 | google: 6
anthropic max_tokens default: 128000
openai stream_usage: True | use_responses_api: None| Class | max_retries default (as of the versions above) |
What it means |
|---|---|---|
ChatOpenAI |
None |
the openai SDK's own default applies (2 in the SDK version checked) |
ChatAnthropic |
2 |
explicit in the class |
ChatGoogleGenerativeAI |
6 |
the docs' number is true here |
ChatOllama |
no max_retries field found in the source |
local calls; handle failures yourself (and see the warning below: the other standard names are ignored too) |
Set max_retries and timeout explicitly everywhere. Then your behaviour no longer depends on which package version you happen to have. 03.8 Part 5 explains why you want exactly one layer retrying; Part 11 below shows the LangChain layers.
Other behaviour worth knowing:
- Client errors (401, 404) are not retried; network errors, 429 and 5xx are.
ChatAnthropic.max_tokensis no longer the old fixed 1024. Since v1 the default comes from the model profile'smax_output_tokens(128000 for the Claude Haiku 5.5 profile in the output above). That is a ceiling, not a sensible default for a chatbot: setmax_tokensto what your task needs, because a rambling reply that runs to a six-figure token cap is a cost and latency incident.- Watch out (optional provider, only if you use Ollama):
ChatOllamasilently ignoresmax_tokens,timeoutandmax_retries. Its model config isextra="ignore"and it has no such fields, soinit_chat_model("ollama:demo", max_tokens=10, timeout=3, max_retries=0)builds without complaint and sends no output cap and no timeout (checked on 15 November 2026 by building the object and reading the request options, nothing sent). Use the native names:num_predictfor the output cap andclient_kwargs={"timeout": 3}for thehttpxtimeout. The same trap applies to any provider class that ignores unknown arguments, so print the request options (or read the class fields) the first time you use a new integration. ChatOpenAI.stream_usageis switched on for you only when you leave the endpoint and the HTTP client at their defaults, which is what makes token usage appear while streaming (8.3). The printedTrueabove is that default case.- Docs advice for long-running agents on unreliable networks: raise
max_retries(10 to 15) and use a checkpointer (08F.11) so a crash resumes instead of restarting.
2.4 Model ids, aliases and how to look them up#
Model ids are the most volatile string in any LLM program. The docs print ids that look like placeholders (gpt-6.1-sol, gemini-4-hydrogen), older tutorials print retired ids, and the ids a provider accepts change monthly. Rules that hold up:
- Never hard-code an id in a lesson, a library or a shared module. Read it from configuration (
MODEL=anthropic:claude-haiku-5-5in.env), so a model upgrade is a config change plus an eval run (Module 10A). - Prefer pinned versions over moving aliases for anything evaluated or audited.
- Look the id up where it is authoritative: the provider's models page, or
GET /modelson the provider's API. LangChain does not validate ids at construction (an unknown id fails on the first call with a 404, which LangChain surfaces asModelNotFoundError, 11.6). - Log the resolved model name.
response.response_metadatanormally carries the model the provider says answered; keep it with the usage numbers (8.4).
2.5 Configurable models: choose the model at run time#
If you call init_chat_model without a model (or with configurable_fields), you get a configurable model: a lightweight wrapper that builds the real model when invoked, using values from the call's config["configurable"].
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
load_dotenv()
# 1. No model given: model and model_provider are configurable by default.
configurable = init_chat_model(max_tokens=500)
cheap = configurable.invoke(
"Summarise: invoice INV-2231 is overdue by 14 days.",
config={"configurable": {"model": "openai:gpt-6-luna"}},
)
strong = configurable.invoke(
"Summarise: invoice INV-2231 is overdue by 14 days.",
config={"configurable": {"model": "anthropic:claude-sonnet-5-5"}},
)
# 2. A default model, with an explicit allow-list of configurable fields and a prefix.
triage = init_chat_model(
"anthropic:claude-haiku-5-5",
max_tokens=500,
configurable_fields=("model", "model_provider", "max_tokens"),
config_prefix="triage",
)
override = triage.invoke(
"Is this ticket billing or technical? Ticket: 'I was charged twice.'",
config={"configurable": {"triage_model": "openai:gpt-6-luna", "triage_max_tokens": 200}},
)
print(cheap.text, strong.text, override.text, sep="\n")This sample is illustrative: it needs OpenAI and Anthropic keys and packages. The point is the shape: with config_prefix="triage", the configurable keys become triage_model, triage_max_tokens and so on, so two configurable models in one graph can be steered independently.
Invoice INV-2231 is 14 days overdue.
Invoice INV-2231 is two weeks past its due date and needs follow-up.
Billing.Things to know:
bind_toolsandwith_structured_outputwork declaratively on a configurable model: call them on the wrapper, and they are applied to whichever real model is built later.- A configurable model with no default model fails confusingly if you forget to choose one. In
langchain1.5.0,init_chat_model(temperature=0).invoke("hi")with noconfigurableentry raisedTypeError: _init_chat_model_helper() missing 1 required positional argument: 'model'when tried during writing. That error means "you did not passmodelin the config". - Security.
configurable_fields="any"lets the caller change anything, includingapi_keyandbase_url. If any part ofconfigcan come from untrusted input (a request body, a tenant setting), enumerate the fields explicitly, and map user choices to an allow-list of model names in your own code. A user who can setbase_urlcan send your key to their server. - For per-request model choice inside an agent, the recommended mechanism is middleware (
@wrap_model_callwithrequest.override(model=...), 08F.8), not a configurable model.
flowchart TD
start["Which model do I build?"] --> q1{"Fixed model, known provider?"}
q1 -->|"yes, and I need provider-only options"| cls["Provider class directly<br/>ChatAnthropic(thinking=...)"]
q1 -->|"yes, portable options only"| init["init_chat_model('provider:model', ...)"]
q1 -->|"no, chosen at run time"| q2{"Who chooses?"}
q2 -->|"my code or my config"| cfg["init_chat_model(configurable_fields=[...])<br/>or middleware per request"]
q2 -->|"untrusted user input"| safe["Allow-list of model names in YOUR code,<br/>never configurable_fields='any'"]
q1 -->|"provider not in the registry"| direct["Import its class directly"]2.6 Model profiles: what the model can do, as data#
Chat models expose a profile: a dictionary of capabilities and limits (beta, since langchain 1.1). The data comes from the models.dev project plus per-package augmentations that ship inside the provider package, so reading it needs no network call.
from langchain.chat_models import init_chat_model
# Profile data ships inside the provider package, so reading it needs no request to the provider.
# The key variables must be set (any non-empty value is enough for this inspection) so the objects can be built.
for spec in ["openai:gpt-6-luna", "anthropic:claude-haiku-5-5", "google_genai:gemini-3.8-flash"]:
model = init_chat_model(spec)
p = model.profile or {}
print(spec)
print(" max_input_tokens :", p.get("max_input_tokens"))
print(" max_output_tokens:", p.get("max_output_tokens"))
print(" image_inputs :", p.get("image_inputs"), "| pdf_inputs:", p.get("pdf_inputs"), "| audio_inputs:", p.get("audio_inputs"))
print(" reasoning_output :", p.get("reasoning_output"), "| effort levels:", p.get("reasoning_effort_levels"))
print(" structured_output:", p.get("structured_output"), "| tool_calling:", p.get("tool_calling"))Output (real, run on 14 November 2026 with the package versions in the Versions line; the placeholder values were set only in the shell command so the objects could be constructed, and nothing was sent anywhere):
openai:gpt-6-luna
max_input_tokens : 1050000
max_output_tokens: 128000
image_inputs : True | pdf_inputs: True | audio_inputs: False
reasoning_output : True | effort levels: ['none', 'low', 'medium', 'high', 'xhigh', 'max']
structured_output: True | tool_calling: True
anthropic:claude-haiku-5-5
max_input_tokens : 1000000
max_output_tokens: 128000
image_inputs : True | pdf_inputs: True | audio_inputs: False
reasoning_output : True | effort levels: None
structured_output: False | tool_calling: True
google_genai:gemini-3.8-flash
max_input_tokens : 1048576
max_output_tokens: 65536
image_inputs : True | pdf_inputs: True | audio_inputs: True
reasoning_output : True | effort levels: None
structured_output: True | tool_calling: TrueHow to use profiles, and how not to:
- Typical fields:
max_input_tokens,max_output_tokens,text_inputs,image_inputs,audio_inputs,pdf_inputs,video_inputs,reasoning_output,tool_calling,structured_output,tool_choice,reasoning_effort_levels,reasoning_effort_default. The full list is in the API reference forModelProfile(langchain_core.language_models.ModelProfile). SummarizationMiddlewarereadsmax_input_tokensto decide when to summarize, andcreate_agentreads capabilities to choose a structured-output strategy (08F.8).- A profile is metadata about the model, not a guarantee about the integration. In the output above the Claude Haiku 5.5 profile says
structured_output: False, yetChatAnthropic.with_structured_outputworks through tool calling (Part 10). Treat aFalseas "not advertised natively", test the behaviour, and do not gate code on a single flag. - Override stale data when a model is new or the dataset is wrong:
init_chat_model("...", profile={...}), ormodel.model_copy(update={"profile": {...}}). Thelangchain-model-profilestool (langchain-profiles refresh --provider <name> --data-dir <dir>) regenerates the data. model.profilecan beNonefor a model the dataset does not know (a brand new or private id), so code that reads it must handle that (model.profile or {}, as above).
2.7 ChatOpenAI: Chat Completions or the Responses API#
Module 03 treats the OpenAI Responses API as primary and Chat Completions as the ecosystem's common dialect. ChatOpenAI supports both:
- The default is "decide per request". The field
use_responses_apiisNone(seen in the output above), which means "Chat Completions unless the request needs Responses". The class switches to the Responses API when you setuse_responses_api=True,reasoning,include,truncation,context_managementoruse_previous_response_id, when you pass a Responses-only call argument (textorprevious_response_id), when you pass a provider built-in tool dict (such as web search), when the model is on a short list of Responses-only ids (and any id containingcodex), or, forgpt-6*models inlangchain-openai1.8.0, as soon as you pass any tools at all, including a plain function tool. use_responses_api=Trueforces the Responses API anduse_responses_api=Falseforces Chat Completions. ANoneprinted in the field is not the effective choice: the sameChatOpenAI(model="gpt-6-luna")object printedNoneand still used Chat Completions for a plain call and Responses once tools were bound (checked on 15 November 2026 by asking the class which API a payload would use, with no request sent;gpt-5.5stayed on Chat Completions with the same tools).- Find out which API a call used by looking at the reply: Responses replies carry a list in
reply.content(items) and Responses-only keys inresponse_metadata(such asstatus), while Chat Completions replies carry a string andfinish_reason. When the choice matters to you (logging, caching, tests), setuse_responses_apiexplicitly. - Since v1, Responses API output items are stored in
message.contentby default (reasoning items, tool-call items and so on), which is whycontentis a list on those replies.output_version="v0"restores the old layout (items inadditional_kwargs) for code written before v1; see 4.4. - With the Responses API you can also keep conversation state on the provider (
use_previous_response_id). Doing so changes who owns history, which 03.2 and 08B.2 discuss; with LangChain's checkpointers (08F.11) you normally keep history on your side.
Part 3: Messages#
03.2 taught the three layers of a conversation request (instructions, turns, parts) and the shape rules each provider enforces. LangChain's messages are the same idea in Python objects, with one shared vocabulary across providers.
3.1 Roles, classes and the input shorthands#
Import the message classes from langchain.messages (the langchain package re-exports them from langchain-core):
from langchain.messages import (
AIMessage, AIMessageChunk, HumanMessage, SystemMessage, ToolMessage, RemoveMessage, trim_messages,
)| Role | Class | .type |
What it carries |
|---|---|---|---|
| system | SystemMessage |
system |
instructions for the whole conversation; where it goes on the wire differs per provider (03.2 Part 2) |
| user | HumanMessage |
human |
what the user said; can contain images, files and audio |
| assistant | AIMessage |
ai |
a model reply (or one you insert by hand) |
| tool | ToolMessage |
tool |
the result of one tool call, matched by tool_call_id |
| (none) | RemoveMessage |
remove |
a delete instruction for a message id, used by graph reducers and middleware |
invoke accepts four equivalent input forms. You can mix styles in a project, but be consistent inside one function:
| Form | Example | Notes |
|---|---|---|
| a string | model.invoke("Hello") |
becomes one HumanMessage |
| a list of message objects | [SystemMessage(...), HumanMessage(...)] |
the typed, IDE-friendly form |
| a list of OpenAI-style dicts | {"role": "user", "content": "..."} with roles system, user, assistant, tool |
handy for data that already has this shape |
| a list of tuples | ("human", "..."), ("system", "...") |
shorthand that also works in prompt templates |
from langchain.messages import AIMessage, HumanMessage, SystemMessage
from langchain_core.language_models import FakeListChatModel
model = FakeListChatModel(responses=["Refunds are processed within 5 business days."])
# Four ways to say the same thing. All of them reach the model as
# [SystemMessage, HumanMessage]. (The fake model ignores the content; real
# models see all four forms identically.)
as_objects = [SystemMessage("You answer billing questions."), HumanMessage("How long do refunds take?")]
as_dicts = [
{"role": "system", "content": "You answer billing questions."},
{"role": "user", "content": "How long do refunds take?"},
]
as_tuples = [("system", "You answer billing questions."), ("human", "How long do refunds take?")]
as_string = "How long do refunds take?" # a bare string becomes one HumanMessage
for name, payload in [("objects", as_objects), ("dicts", as_dicts), ("tuples", as_tuples), ("string", as_string)]:
reply = model.invoke(payload)
print(f"{name:8} -> {type(reply).__name__}: {reply.text}")
# Messages are plain data: inspect them.
human = HumanMessage("Hi", name="alice", id="msg_1")
print(human.type, human.name, human.id)
print(isinstance(AIMessage("x").tool_calls, list), AIMessage("x").tool_calls)Output (real; the fake model returns the same canned reply whatever it is sent, which is exactly what the sample is for: all four forms are accepted and each returns an AIMessage):
objects -> AIMessage: Refunds are processed within 5 business days.
dicts -> AIMessage: Refunds are processed within 5 business days.
tuples -> AIMessage: Refunds are processed within 5 business days.
string -> AIMessage: Refunds are processed within 5 business days.
human alice msg_1
True []The roles map to each provider's roles at call time: LangChain turns a SystemMessage into whatever each provider expects (Anthropic's top-level system parameter, Gemini's system_instruction, a system-level message for OpenAI), as 03.2 described. You do not write that translation, but you still own the shape rules: for example, a tool result must follow the assistant message that requested it.
3.2 AIMessage anatomy#
AIMessage is the type you will read most. Its attributes (all verified in the sheet and source):
| Attribute | Type | Meaning |
|---|---|---|
content |
str or list |
the loosely typed payload: a string, or a list of provider-native or standard blocks |
content_blocks |
list of typed blocks | the same content parsed into LangChain's standard representation (Part 4) |
text |
str |
all text blocks joined: a property, not a method |
tool_calls |
list of ToolCall dicts |
the tool calls the model requested ([] if none), each with name, args, id, type |
invalid_tool_calls |
list | tool calls whose arguments were not valid JSON |
id |
str or None |
message id (set by LangChain or the provider) |
usage_metadata |
UsageMetadata or None |
token counts (Part 8) |
response_metadata |
dict | provider extras: finish reason, model name, request ids, logprobs when requested |
additional_kwargs |
dict | a legacy holding area for provider-specific payloads (less used since v1) |
Use response.text whenever you only want the words. response.content is a string only for plain text replies; as soon as the model reasons, calls a tool or returns citations, content is a list.
You can construct an AIMessage yourself, for example to insert a canned assistant turn into a history, to seed a few-shot example, or to build test fixtures. The sample in 3.3 below does this (the third message of history) next to a tool-call turn.
3.3 ToolMessage, RemoveMessage and the name field#
ToolMessage returns a tool's result to the model:
| Field | Required | Meaning |
|---|---|---|
content |
yes | the tool result as a string (stringify structured data yourself, or use a content-block list) |
tool_call_id |
yes | must equal the id of the AIMessage.tool_calls[i] it answers |
name |
no | the tool's name |
artifact |
no | data kept for downstream code and not sent to the model, for example the document ids behind a retrieval answer |
artifact is the clean way to keep "what the model should see" separate from "what my program needs", a problem every RAG-as-a-tool design runs into (08F.9).
from langchain.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
# A history with an inserted assistant turn (a canned reply, as if the model had said it).
history = [
SystemMessage("You are a helpful billing assistant."),
HumanMessage("Can you help me with an invoice?"),
AIMessage("Of course. What is the invoice number?"),
HumanMessage("INV-2231"),
]
print([m.type for m in history])
# A tool-call turn: the AIMessage requests the call, the ToolMessage answers it by id.
ai_message = AIMessage(
content=[],
tool_calls=[{"name": "get_weather", "args": {"location": "Pune"}, "id": "call_123"}],
)
tool_message = ToolMessage(
content="Sunny, 31 C",
tool_call_id="call_123",
artifact={"source": "weather-service", "station": "VAPO"}, # for your code; never sent to the model
)
messages = [HumanMessage("What's the weather in Pune?"), ai_message, tool_message]
print([m.type for m in messages])
print(tool_message.tool_call_id == ai_message.tool_calls[0]["id"], tool_message.artifact)Output (real). Passing messages to model.invoke(...) is what would let the model answer from the tool result:
['system', 'human', 'ai', 'human']
['human', 'ai', 'tool']
True {'source': 'weather-service', 'station': 'VAPO'}RemoveMessage(id=...) does not talk to a model. LangGraph's add_messages reducer and several middleware classes treat it as "delete the message with this id" (08F.10 and 08F.11 use it to trim history).
The name field. HumanMessage("...", name="alice") exists so multi-party chats can say who spoke. Its behaviour varies by provider: some use it for speaker identification, others ignore it. Do not build logic on it; if the model must know who is speaking, put the name in the text.
Two legacy classes still exist in langchain_core.messages (not in langchain.messages): ChatMessage (a message with an arbitrary role string) and FunctionMessage (the pre-tool-calling function result). Use them only to read old code.
3.4 Message utilities you will actually use#
All of these live in langchain_core.messages (and trim_messages is also re-exported from langchain.messages).
| Utility | Purpose |
|---|---|
trim_messages(...) |
keep a conversation inside a token budget |
convert_to_openai_messages(...) |
convert LangChain messages to the OpenAI chat format |
convert_to_messages(...) |
normalize strings, dicts and tuples into message objects |
filter_messages(...), merge_message_runs(...) |
select by type or name, or merge adjacent same-role messages |
get_buffer_string(...) |
a Human: ... / AI: ... transcript string, for logs and summarization prompts |
messages_to_dict, messages_from_dict, message_to_dict |
older serialization helpers |
dumpd, load (from langchain_core.load) |
the current serialization pair |
trim_messages has this signature (verified in the source):
trim_messages(messages, *, max_tokens: int,
token_counter, # a callable, a model, or the string "approximate"
strategy="last", # or "first"
allow_partial=False, end_on=None, start_on=None,
include_system=False, text_splitter=None)The counter can be any function that counts a list of messages, a chat model (counted with that model's own method), or the literal "approximate", which needs no model. trim_messages also works as a Runnable, so it can sit in a chain before a model.
import warnings
from langchain.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage, trim_messages
from langchain_core.messages import convert_to_openai_messages, get_buffer_string
from langchain_core.load import dumpd, load
history = [
SystemMessage("You are a support agent."),
HumanMessage("My invoice total looks wrong."),
AIMessage("Can you share the invoice number?"),
HumanMessage("It is INV-2231."),
AIMessage("Thanks, checking now."),
HumanMessage("Any update?"),
]
# Keep the system prompt plus the newest messages that fit; never start on an AI turn.
trimmed = trim_messages(
history,
max_tokens=30,
token_counter="approximate", # no model needed; a rough character-based estimate
strategy="last",
include_system=True,
start_on="human",
)
print("kept:", [(m.type, m.content) for m in trimmed])
# Convert to the OpenAI chat format (useful when handing history to a non-LangChain client).
ai = AIMessage("", tool_calls=[{"name": "lookup_invoice", "args": {"id": "INV-2231"}, "id": "call_1"}])
print(convert_to_openai_messages([HumanMessage("hi"), ai, ToolMessage("total: 120.00", tool_call_id="call_1")]))
# A transcript string for logs.
print(get_buffer_string(history[:3]))
# Serialize and restore. Only ever load data YOU wrote.
with warnings.catch_warnings():
warnings.simplefilter("ignore") # load() is beta and warns about allowed_objects
restored = load(dumpd(ai), allowed_objects="messages")
print(restored == ai)kept: [('system', 'You are a support agent.'), ('human', 'Any update?')]
[{'role': 'user', 'content': 'hi'}, {'role': 'assistant', 'tool_calls': [{'type': 'function', 'id': 'call_1', 'function': {'name': 'lookup_invoice', 'arguments': '{"id": "INV-2231"}'}}], 'content': ''}, {'role': 'tool', 'tool_call_id': 'call_1', 'content': 'total: 120.00'}]
System: You are a support agent.
Human: My invoice total looks wrong.
AI: Can you share the invoice number?
TrueNotes on what you just saw:
strategy="last"keeps the newest messages that fit;include_system=Truekeeps the system message even though it is oldest;start_on="human"stops the trimmed history from starting on anAIortoolmessage, which most providers reject. These three options together are the safe default for chat history."approximate"is a rough character-based estimate. It is good enough to stay under a window with a safety margin and wrong for billing. Exact counting is a provider endpoint (03.7 Part 2);token_counteralso accepts a chat model object, in which case that model'sget_num_tokens_from_messagesis used. What that method does differs a lot per provider (a local tokenizer for OpenAI, a network call for Anthropic and Google, and an import error for classes with no counter at all), so read 8.5 before you pass a model as the counter.- Trimming by tokens does not preserve meaning. For long-lived conversations, summarization and memory (08B.2, 08F.11,
SummarizationMiddlewarein 08F.8) are the real answers;trim_messagesis the blunt instrument. - A trimmed history that cuts between an assistant tool call and its tool result produces an invalid conversation.
start_on="human"avoids the common case; check your own histories when tools are involved.
Serialization. dumpd(message) turns a message into a JSON-compatible dict and load(...) rebuilds it, which is how histories are stored and shipped between processes.
3.5 Statelessness, again#
A chat model has no memory. The history you pass is the entire context (02.7). Appending to a list is "memory" in the simplest sense; checkpointers make it durable (08F.11), and create_agent and LangGraph manage the list for you. One rule survives every abstraction: append the whole AIMessage the model returned, not just its text, because tool calls, reasoning blocks and provider signatures live in the message and must be sent back (08A.2, 02.8).
Part 4: Content and standard content blocks#
Deep-dive
4.1 Three views of one reply: content, content_blocks and .text#
A provider reply is not always a string. It can be text, reasoning, tool calls, citations and images, in a provider-specific shape. LangChain gives you three ways to read it:
| View | Type | When to use it |
|---|---|---|
message.text |
str |
you only want the words: logging, display, simple tasks |
message.content_blocks |
list of standard typed blocks | you want to handle reasoning, tool calls, images or citations in a provider-independent way |
message.content |
str, or a list of provider-native or standard blocks |
you want the raw payload, or you are sending content back to the same provider |
content_blocks is computed lazily from content (and the message's response_metadata["model_provider"], which tells LangChain which translator to apply). It is a view, not a replacement: content is untouched. You can also build a message from standard blocks, type-safely: HumanMessage(content_blocks=[...]) still populates content correctly.
4.2 The block reference#
Each standard block is a TypedDict with a type field. The list below follows the official content-block reference and was cross-checked against the exports of langchain.messages in the 1.5.0 wheel.
| Group | Block (type) |
Key fields | Notes |
|---|---|---|---|
| Core | TextContentBlock (text) |
text, optional annotations, extras |
annotations carry citations |
| Core | ReasoningContentBlock (reasoning) |
reasoning, extras |
provider signatures go in extras |
| Core | RefusalContentBlock (refusal) |
refusal, extras |
only when the provider reports a refusal explicitly; needs langchain-core>=1.7.5; exported from langchain_core.messages, not langchain.messages |
| Multimodal | ImageContentBlock (image) |
url or base64 + mime_type, or file_id; id |
mime_type required with base64 |
| Multimodal | AudioContentBlock (audio) |
url, base64 + mime_type, or file_id |
|
| Multimodal | VideoContentBlock (video) |
url, base64 + mime_type, or file_id |
|
| Multimodal | FileContentBlock (file) |
url, base64 + mime_type (for example application/pdf), or file_id |
PDFs and other documents; OpenAI requires a filename |
| Multimodal | PlainTextContentBlock (text-plain) |
text, mime_type |
a text document, not an assistant text block |
| Tool calling | ToolCall (tool_call) |
name, args (dict), id |
a finished call |
| Tool calling | ToolCallChunk (tool_call_chunk) |
name, args (partial JSON string), id, index |
seen only while streaming |
| Tool calling | InvalidToolCall (invalid_tool_call) |
name, args, id, error |
unparseable arguments |
| Server-side tools | ServerToolCall (server_tool_call), ServerToolCallChunk, ServerToolResult (server_tool_result) |
result has tool_call_id, status (success or error), output |
tools the provider ran itself (web search, code execution); no ToolMessage is needed |
| Escape hatch | NonStandardContentBlock (non_standard) |
value |
a provider payload with no standard type |
Two properties of this scheme matter for code you write:
- Always branch on
type, never on position. A reply can carry several blocks in any order, and whenlangchain-coreadds a new standard type later, a payload that used to arrive asnon_standardstarts arriving as the new type. The official docs say the same: "branch ontypeinstead of relying on a payload stayingnon_standard." - Ignore unknown types rather than raising. New block types will appear (the refusal block is one added in 2026). A helper that skips what it does not understand survives upgrades.
4.3 How providers are normalized#
The sample below builds two AIMessage objects exactly as the integrations produce them (Anthropic's native thinking block; OpenAI Responses reasoning items with a summary list) and asks LangChain for the standard view. No provider is called: normalization is a local translation.
from langchain.messages import AIMessage
# What Anthropic returns (provider-native), as stored in message.content.
anthropic_style = AIMessage(
content=[
{"type": "thinking", "thinking": "The user wants the refund window.", "signature": "sig-abc"},
{"type": "text", "text": "Refunds take 5 business days."},
],
response_metadata={"model_provider": "anthropic"},
)
# What OpenAI's Responses API returns: reasoning items carry a list of summaries.
openai_style = AIMessage(
content=[
{"type": "reasoning", "id": "rs_1", "summary": [
{"type": "summary_text", "text": "Check the refund policy."},
{"type": "summary_text", "text": "Answer briefly."},
]},
{"type": "text", "text": "Refunds take 5 business days.", "annotations": []},
],
response_metadata={"model_provider": "openai"},
)
for label, msg in [("anthropic", anthropic_style), ("openai", openai_style)]:
print(label, "content :", [b["type"] for b in msg.content])
print(label, "standard :", msg.content_blocks)
print(label, "text :", msg.text)
print()
# A tool call shows up in content_blocks too, even though content is empty.
call = AIMessage(content="", tool_calls=[{"name": "get_order_status", "args": {"order_id": "A-1042"}, "id": "call_1"}])
print(call.content_blocks)
# Without response_metadata["model_provider"], LangChain cannot tell which dialect to translate,
# so a native Anthropic block is wrapped as non_standard instead of becoming a reasoning block.
no_provider = AIMessage(content=[{"type": "thinking", "thinking": "hmm", "signature": "sig-abc"}])
print(no_provider.content_blocks)anthropic content : ['thinking', 'text']
anthropic standard : [{'type': 'reasoning', 'reasoning': 'The user wants the refund window.', 'extras': {'signature': 'sig-abc'}}, {'type': 'text', 'text': 'Refunds take 5 business days.'}]
anthropic text : Refunds take 5 business days.
openai content : ['reasoning', 'text']
openai standard : [{'type': 'reasoning', 'id': 'rs_1', 'reasoning': 'Check the refund policy.'}, {'type': 'reasoning', 'id': 'rs_1', 'reasoning': 'Answer briefly.'}, {'type': 'text', 'text': 'Refunds take 5 business days.', 'annotations': []}]
openai text : Refunds take 5 business days.
[{'type': 'tool_call', 'id': 'call_1', 'name': 'get_order_status', 'args': {'order_id': 'A-1042'}}]
[{'type': 'non_standard', 'value': {'type': 'thinking', 'thinking': 'hmm', 'signature': 'sig-abc'}}]Read the output closely:
- Anthropic
thinkingbecamereasoning, and the provider'ssignaturemoved intoextras. The signature must go back to Anthropic unchanged if you continue the conversation, which is why you append the whole message instead of rebuilding one from text. - OpenAI
reasoningitems carry a list of summaries; each summary item became its ownreasoningblock (sameid). One provider item can therefore become several standard blocks. textis the same in both, and.textjoined only the text blocks (reasoning is excluded).- A tool call appears in
content_blocksas atool_callblock even whencontentis empty, because LangChain builds it fromtool_calls. - The last line shows the failure mode of an unknown dialect: without
model_provider, the nativethinkingblock comes back wrapped in anon_standardblock, not asreasoning.
4.4 output_version: v0 and v1#
By default, content keeps whatever the provider integration puts there (provider-native blocks), and content_blocks is the normalized view on top. If you want the standard blocks to be what is stored in content, opt in:
from langchain.chat_models import init_chat_model
model = init_chat_model("anthropic:claude-haiku-5-5", output_version="v1")
# or for the whole process: export LC_OUTPUT_VERSION=v1This line is illustrative: it needs langchain-anthropic and a key to construct and use. BaseChatModel.output_version is a string or None, read from LC_OUTPUT_VERSION when unset: 'v0' means provider format, 'v1' means standard format. Use v1 when your own code (or stored history) should be provider-independent, for instance a conversation you may continue on a different provider; keep the default when you simply pass messages back to the same provider and read content_blocks for display. For ChatOpenAI, output_version="v0" also restores the pre-v1 layout of Responses API items (2.7).
4.5 Reading replies safely: one helper for every provider#
The reference lesson's rule applies: write the extraction once, branch on type, and ignore the unknown.
from typing import Any
from langchain.messages import AIMessage
def unpack(message: AIMessage) -> dict[str, Any]:
"""Split a model reply into text, reasoning, tool calls and anything unknown.
Branches on block ``type`` (never on position) and ignores types it does not know,
so a new standard block type added by a later langchain-core cannot crash it.
"""
text_parts: list[str] = []
reasoning_parts: list[str] = []
tool_calls: list[dict[str, Any]] = []
other_types: list[str] = []
for block in message.content_blocks:
kind = block["type"]
if kind == "text":
text_parts.append(block["text"])
elif kind == "reasoning":
reasoning_parts.append(block.get("reasoning", ""))
elif kind == "tool_call":
tool_calls.append({"name": block["name"], "args": block["args"], "id": block["id"]})
else:
other_types.append(kind)
return {
"text": "".join(text_parts),
"reasoning": "\n".join(p for p in reasoning_parts if p),
"tool_calls": tool_calls,
"other_block_types": other_types,
}
reply = AIMessage(
content=[
{"type": "thinking", "thinking": "Look up the order first.", "signature": "sig"},
{"type": "text", "text": "Let me check that order."},
# ChatAnthropic keeps the native tool_use block in content AND fills .tool_calls.
{"type": "tool_use", "id": "call_7", "name": "get_order_status", "input": {"order_id": "A-1042"}},
],
tool_calls=[{"name": "get_order_status", "args": {"order_id": "A-1042"}, "id": "call_7"}],
response_metadata={"model_provider": "anthropic"},
)
print(unpack(reply)){'text': 'Let me check that order.', 'reasoning': 'Look up the order first.', 'tool_calls': [{'name': 'get_order_status', 'args': {'order_id': 'A-1042'}, 'id': 'call_7'}], 'other_block_types': []}Where the helper deliberately stops: it does not render images, citations (annotations on text blocks) or server tool blocks. Add branches for the block types your application actually shows to users, and keep the else that records the unknown type so you notice new ones in logs.
Refusals. Providers report refusals differently (Anthropic with a refusal stop reason, OpenAI structured outputs with a refusal field). When the provider reports one explicitly, LangChain emits a refusal block. It does not detect refusals the model writes as ordinary text ("I can't help with that"); those are plain text. For the safety side of refusals see 02.10 and Module 12.
Citations arrive as annotations on text blocks for providers and tools that return them (for example server-side web search). The shape of an annotation is provider-dependent; read the official messages page for the standard Citation and NonStandardAnnotation types, and see 08F.9 for citations in RAG.
Part 5: Calling a model#
All call methods are Runnable methods, so everything here also applies to prompts, parsers and graphs (08F.7). The table is the map; the subsections give the details and the traps.
| Method | Input | Output | Use it for |
|---|---|---|---|
invoke(input, config=None, *, stop=None, **kwargs) |
string, messages or PromptValue |
AIMessage |
one answer, blocking |
ainvoke(...) |
same | AIMessage |
one answer inside async code |
stream(...) |
same | iterator of AIMessageChunk |
show output as it is generated |
astream(...) |
same | async iterator of AIMessageChunk |
the same, in async code |
batch(list, config=None) / abatch |
list of inputs | list of AIMessage |
many independent prompts, client-side parallelism |
batch_as_completed(...) / abatch_as_completed |
list of inputs | yields (index, result_or_exception) |
process results as they finish |
astream_events(..., version="v2") |
same | async iterator of event dicts | fine-grained events for UIs and tracing |
stream_events(...) (sync) |
same | iterator of events | the sync counterpart |
5.1 invoke#
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
load_dotenv()
model = init_chat_model("anthropic:claude-haiku-5-5", max_tokens=400, max_retries=2, timeout=30)
reply = model.invoke(
[
("system", "You write one-sentence summaries of support tickets."),
("human", "Ticket: The export button on the invoices page does nothing in Firefox 131."),
],
config={"run_name": "summarise-ticket", "tags": ["support", "demo"], "metadata": {"ticket_id": "T-5521"}},
)
print(type(reply).__name__)
print(reply.text)
print(reply.usage_metadata)This sample is illustrative: it needs langchain-anthropic and ANTHROPIC_API_KEY.
AIMessage
The invoices page's export button is unresponsive in Firefox 131.
{'input_tokens': 38, 'output_tokens': 17, 'total_tokens': 55}invoke returns an AIMessage whatever the provider. Notes:
stop=[...]passes stop sequences; extra keyword arguments are forwarded to the provider call. For options you want on every call, prefermodel.bind(...)(5.7).- Exceptions are the provider's, wrapped into the standard hierarchy (11.6): catch
ModelRateLimitError,ModelTimeoutErrorand friends, or the SDK's own classes; both work. - With reasoning models, leave room in
max_tokens: thinking tokens count against it (02.8 Part 5). An answer cut off with an emptytextis usually amax_tokensthat the reasoning consumed. Do not guess: the reply says why it stopped, and 5.8 shows where to read it.
5.2 stream and chunk accumulation#
stream yields AIMessageChunk objects as the provider generates them. A chunk is a message fragment: chunk.text is the new text, and chunks add up with +. The final chunk reports chunk_position == "last".
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain.messages import AIMessageChunk
load_dotenv()
model = init_chat_model("openai:gpt-6-luna", max_tokens=300)
full: AIMessageChunk | None = None
for chunk in model.stream("Explain what a purchase order is in two sentences."):
print(chunk.text, end="|", flush=True) # show tokens as they arrive
full = chunk if full is None else full + chunk # accumulate into one message
print()
print(full.text)
print(full.content_blocks) # the standard view of the accumulated message
print(full.usage_metadata) # final usage, when the provider reports it while streamingThis sample is illustrative: it needs langchain-openai and OPENAI_API_KEY.
A purchase| order is| a document| a buyer sends| to a seller| ...|
A purchase order is a document a buyer sends to a seller to request goods or services. It records the quantities and agreed prices.
[{'type': 'text', 'text': 'A purchase order is a document a buyer sends to a seller to request goods or services. It records the quantities and agreed prices.'}]
{'input_tokens': 16, 'output_tokens': 31, 'total_tokens': 47}The same mechanics, runnable without a key. The first half accumulates text chunks from a fake model; the second half shows how a tool call's arguments arrive in pieces and are merged by index:
from langchain.messages import AIMessageChunk
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
model = GenericFakeChatModel(messages=iter(["Your refund was issued today."]))
# 1. Print tokens as they arrive; join chunks with + to rebuild the full message.
full: AIMessageChunk | None = None
pieces: list[str] = []
for chunk in model.stream("Where is my refund?"):
pieces.append(chunk.text)
full = chunk if full is None else full + chunk # chunks support +
print(pieces)
print(type(full).__name__, repr(full.text), "last chunk position:", full.chunk_position)
# 2. Tool-call arguments arrive as partial JSON strings and are merged by index.
first = AIMessageChunk(content="", tool_call_chunks=[
{"name": "get_order_status", "args": '{"order_', "id": "call_9", "index": 0}])
second = AIMessageChunk(content="", tool_call_chunks=[
{"name": None, "args": 'id": "A-1042"}', "id": None, "index": 0}])
merged = first + second
print(merged.tool_call_chunks)
print(merged.tool_calls)['Your', ' ', 'refund', ' ', 'was', ' ', 'issued', ' ', 'today.']
AIMessageChunk 'Your refund was issued today.' last chunk position: last
[{'name': 'get_order_status', 'args': '{"order_id": "A-1042"}', 'id': 'call_9', 'index': 0, 'type': 'tool_call_chunk'}]
[{'name': 'get_order_status', 'args': {'order_id': 'A-1042'}, 'id': 'call_9', 'type': 'tool_call'}]What to take from this:
- Chunks are real messages.
full + chunkmerges text, tool-call chunks, usage and metadata, and the result is anAIMessageChunkyou can append to history. You do not need to rebuild messages by hand (03.3 Part 5 did exactly that against raw provider events). - Tool-call arguments are partial JSON strings (
argsin atool_call_chunk) until merged.merged.tool_callsparsed them into a dict once the pieces were complete. Neverjson.loadsa single chunk'sargs. stream()falls back to one chunk when a model does not implement streaming. It does not error: you simply get the whole reply as one chunk, so the demo looks like it works but nothing is incremental. The model'sdisable_streamingfield forces this (disable_streaming="tool_calling"bypasses streaming only when tools are passed).- Auto-streaming. When you call
invokeon a model inside an agent or graph that is being streamed, LangChain switches the model to its streaming internals so token callbacks fire, even though your node calledinvoke. That is why a graph can stream tokens without every node usingstream()(08F.14). - Caching does not apply to streaming (11.4).
For a browser or a server that forwards tokens, the transport side (Server-Sent Events, backpressure, cancellation, resumable streams) is 03.3 and 08F.14.
5.3 Async: ainvoke, astream, abatch#
Use the a-prefixed methods inside async def code (FastAPI handlers, notebooks with an event loop, workers). A provider class that implements native async uses the provider's async SDK client; otherwise ainvoke runs the sync call in a thread executor. Either way it does not block your event loop.
import asyncio
from langchain_core.language_models import FakeListChatModel
async def main() -> None:
model = FakeListChatModel(responses=["alpha", "beta", "gamma", "delta"])
one = await model.ainvoke("first question")
print("ainvoke :", one.text)
# abatch runs the calls concurrently on a real model; cap it with max_concurrency.
many = await model.abatch(["q1", "q2"], config={"max_concurrency": 2})
print("abatch :", [m.text for m in many])
# astream yields AIMessageChunk objects.
text = "".join([chunk.text async for chunk in model.astream("stream me")])
print("astream :", text)
# abatch_as_completed yields (index, result) in completion order, not input order.
seen = []
async for index, result in model.abatch_as_completed(["a", "b"]):
seen.append((index, type(result).__name__))
print("as_completed:", sorted(seen))
# Fan out your own coroutines when you need per-call config or error handling.
results = await asyncio.gather(model.ainvoke("x"), model.ainvoke("y"), return_exceptions=True)
print("gather :", [type(r).__name__ for r in results])
asyncio.run(main())ainvoke : alpha
abatch : ['beta', 'gamma']
astream : delta
as_completed: [(0, 'AIMessage'), (1, 'AIMessage')]
gather : ['AIMessage', 'AIMessage']Three ways to fan out, and when to use each:
| Tool | Use it when |
|---|---|
await model.abatch(inputs, config={"max_concurrency": N}) |
many independent prompts, same settings, results in input order |
abatch_as_completed(...) |
you want to start processing each result as soon as it lands; results carry their input index |
your own asyncio.gather / semaphore (03.9 Part 4) |
per-call config, per-call timeouts, partial failure handling, or mixed models |
5.4 batch and batch_as_completed#
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
load_dotenv()
model = init_chat_model("openai:gpt-6-luna", max_tokens=100, max_retries=2, timeout=30)
tickets = [
"I was charged twice for invoice INV-2231.",
"The mobile app crashes when I open settings.",
"How do I change the email on my account?",
]
prompts = [f"Classify as billing, bug or other. One word only.\n\n{t}" for t in tickets]
# Results come back in input order. return_exceptions=True keeps one failure from losing the rest.
results = model.batch(prompts, config={"max_concurrency": 3}, return_exceptions=True)
for ticket, result in zip(tickets, results):
label = result.text.strip() if not isinstance(result, Exception) else f"ERROR {type(result).__name__}"
print(f"{label:10} <- {ticket}")
# Process as they finish (indices tell you which input each result belongs to):
for index, result in model.batch_as_completed(prompts, config={"max_concurrency": 3}):
print(index, result if isinstance(result, Exception) else result.text.strip())This sample is illustrative: it needs langchain-openai and OPENAI_API_KEY.
billing <- I was charged twice for invoice INV-2231.
bug <- The mobile app crashes when I open settings.
other <- How do I change the email on my account?
1 bug
0 billing
2 other5.5 Events: astream_events#
astream_events emits one event dict per stage (start, each streamed chunk, end) for a model, and for every nested runnable when you call it on a chain or graph. It is the primitive UIs and tracers use to show "the model is thinking, now calling a tool, now writing".
import asyncio
from langchain_core.language_models import FakeListChatModel
async def main() -> None:
model = FakeListChatModel(responses=["ok"])
async for event in model.astream_events("hello", version="v2"):
print(event["event"], "|", event["name"], "|", event.get("run_id") is not None)
asyncio.run(main())Output (real; the fake model streams its reply one character per chunk, and ok has two characters, so there are two stream events):
on_chat_model_start | FakeListChatModel | True
on_chat_model_stream | FakeListChatModel | True
on_chat_model_stream | FakeListChatModel | True
on_chat_model_end | FakeListChatModel | TrueOn a real model the events are on_chat_model_start, one on_chat_model_stream per chunk (the chunk is in event["data"]["chunk"]), then on_chat_model_end. Pass version="v2" explicitly (it is the documented default). There is also a version="v3" form, newer, which returns typed projections (.text, .reasoning, .tool_calls, .output) on a ChatModelStream or AsyncChatModelStream object. Its API surface is still evolving and is only summarized here: use v2 in production code and read 08F.14 and the current docs before adopting v3.
5.6 RunnableConfig: names, tags, metadata, callbacks#
Every call method accepts config={...}. The keys the models docs use:
| Key | Meaning | Inherited by nested calls? |
|---|---|---|
run_name |
the label this run shows in traces | no |
tags |
list of strings for filtering | yes |
metadata |
dict for context (ticket id, tenant, experiment name) | yes |
callbacks |
handlers such as UsageMetadataCallbackHandler |
yes |
max_concurrency |
cap on parallel calls in batch and parallel branches |
n/a |
recursion_limit |
cap on graph steps (08F.10) | n/a |
tags and metadata are what make traces searchable in LangSmith (11A.5) and in any tracing backend (Module 11A). Set a run_name and a ticket_id on every call you might one day have to debug.
5.7 config, bind and per-call options#
Two mechanisms look similar and are not:
model.invoke(x, config=...)sets run configuration (names, tags, callbacks, concurrency).model.bind(**kwargs)returns a new runnable with provider call arguments pre-filled. It does not change the original object.
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
load_dotenv()
model = init_chat_model("openai:gpt-6-luna", max_tokens=200)
# bind() is how provider-specific call options such as logprobs are attached (illustrative below).
model_with_logprobs = model.bind(logprobs=True)
reply = model_with_logprobs.invoke("Is a refund the same as a credit note? Answer yes or no.")
print(reply.text)
print(reply.response_metadata["logprobs"]["content"][0]["token"])This sample is illustrative: it needs langchain-openai and OPENAI_API_KEY, and the shape of logprobs depends on the provider. Logprobs themselves are explained in 02.5 Part 5; not every provider or model returns them.
No.
Nobind is also what bind_tools (Part 9), with_structured_output (Part 10) and with_retry (11.2) build on: each returns a new runnable wrapping the original.
5.8 What came back besides the text: response_metadata and truncation#
reply.response_metadata is the provider's own envelope for the answer: the resolved model name, request ids, the finish reason, safety or service-tier details, and logprobs when you asked for them. LangChain does not normalize it (unlike usage_metadata), so the keys differ per provider. The one you cannot skip is the reason the model stopped, because a reply that hit your output cap looks like a normal reply until a human reads it, and a truncated structured-output call is a classic source of mystery parse errors.
| Provider class | Where "stopped because of the output cap" shows up |
|---|---|
ChatOpenAI, Chat Completions |
response_metadata["finish_reason"] == "length" |
ChatOpenAI, Responses API |
response_metadata["status"] == "incomplete" and response_metadata["incomplete_details"]["reason"] == "max_output_tokens" (OpenAI documents both values; it can happen before any visible text exists, because reasoning counts against the cap) |
ChatAnthropic |
response_metadata["stop_reason"] == "max_tokens" |
ChatGoogleGenerativeAI |
response_metadata["finish_reason"], the name of Google's finish-reason enum, so "MAX_TOKENS" (verify the key on Google's integration page when you upgrade) |
ChatOllama |
response_metadata["done_reason"] == "length" |
A small helper turns that table into one function. The sample builds messages by hand with metadata shaped like each provider's (copied from what the integrations' source writes), so it runs without a key:
from langchain.messages import AIMessage
# Metadata shapes copied from the integrations' source: the key differs per provider.
replies = {
"openai chat completions": AIMessage("The refund policy says", response_metadata={"finish_reason": "length", "model_name": "demo"}),
"openai responses": AIMessage("", response_metadata={"status": "incomplete", "incomplete_details": {"reason": "max_output_tokens"}}),
"anthropic": AIMessage("The refund policy says", response_metadata={"stop_reason": "max_tokens", "model_name": "demo"}),
"google": AIMessage("The refund policy says", response_metadata={"finish_reason": "MAX_TOKENS"}),
"ollama": AIMessage("The refund policy says", response_metadata={"done_reason": "length"}),
"finished normally": AIMessage("Refunds take 5 days.", response_metadata={"finish_reason": "stop"}),
}
CUT_OFF = {"length", "max_tokens", "MAX_TOKENS"}
def was_truncated(reply: AIMessage) -> bool:
"""True when the provider says it stopped because the output cap was reached."""
meta = reply.response_metadata
reason = meta.get("finish_reason") or meta.get("stop_reason") or meta.get("done_reason")
if reason in CUT_OFF:
return True
details = meta.get("incomplete_details") # OpenAI Responses API
return isinstance(details, dict) and details.get("reason") == "max_output_tokens"
for name, reply in replies.items():
print(f"{name:25} truncated={was_truncated(reply)}")Output (real; the metadata is supplied by the sample, so this checks the helper's logic, not any provider):
openai chat completions truncated=True
openai responses truncated=True
anthropic truncated=True
google truncated=True
ollama truncated=True
finished normally truncated=FalseWhat to do with the answer: log it next to the usage line (8.4), retry once with a larger max_tokens (or a lower reasoning effort, Part 7) if the task allows it, and never parse a truncated reply as if it were complete. When you stream, run the same check on the accumulated message (full, 5.2) after the loop ends, and test it on your provider first: streamed metadata is assembled from many chunks and differs more between providers than invoke metadata does.
Part 6: Multimodal input and output#
Deep-dive
03.6 taught what each provider accepts, how images cost tokens, and how to preprocess. LangChain adds one standard block format for all of it.
6.1 The standard input blocks#
# text + image by URL
{"type": "image", "url": "https://example.com/receipt.jpg"}
# image from base64 (mime_type is required)
{"type": "image", "base64": "<base64 text>", "mime_type": "image/jpeg"}
# an image already uploaded through the provider's Files API
{"type": "image", "file_id": "file-abc123"}
# a PDF
{"type": "file", "url": "https://example.com/invoice.pdf"}
{"type": "file", "base64": "<base64 text>", "mime_type": "application/pdf"}
# audio and video
{"type": "audio", "base64": "<base64 text>", "mime_type": "audio/wav"}
{"type": "video", "base64": "<base64 text>", "mime_type": "video/mp4"}These are block shapes; the sample in 6.2 builds real ones. A block goes inside a message's content list next to a text block. Rules and caveats from the docs:
mime_typeis required for base64.- Chat models also accept two older dialects: OpenAI's
image_urlblocks and the provider-native format. The standard format is the portable one. - Extra keys can sit at the top level or under
"extras". - OpenAI requires a filename for PDFs. Others ignore it.
- Not all models support all file types. Check the model's profile (
image_inputs,pdf_inputs,audio_inputs,video_inputsfrom 2.6) and the provider's page, and handle the 400 when you guess wrong. - Whether a URL is fetched by the provider or must be downloaded by you differs per provider and per feature (03.6 Part 1); for private or large files use
file_idfrom the provider's Files API (03.6 Part 5) or base64.
6.2 Building media blocks from files#
This helper builds a standard block from a local file and refuses to guess a missing mime type. The sample generates a valid 2x2 PNG with the standard library so it runs anywhere with no image files:
import base64
import mimetypes
import struct
import tempfile
import zlib
from pathlib import Path
from typing import Any
from langchain.messages import HumanMessage
def file_block(path: Path) -> dict[str, Any]:
"""Build a standard content block (image or file) from a local file, with a required mime_type."""
mime, _ = mimetypes.guess_type(path.name)
if mime is None:
raise ValueError(f"cannot guess a mime type for {path.name}")
data = base64.b64encode(path.read_bytes()).decode("ascii")
kind = "image" if mime.startswith("image/") else "file"
return {"type": kind, "base64": data, "mime_type": mime}
def tiny_png(path: Path) -> None:
"""Write a valid 2x2 PNG using only the standard library (so the sample needs no image files)."""
def chunk(tag: bytes, body: bytes) -> bytes:
return struct.pack(">I", len(body)) + tag + body + struct.pack(">I", zlib.crc32(tag + body))
rows = b"".join(b"\x00" + b"\xff\x00\x00" * 2 for _ in range(2)) # filter byte + 2 red pixels
png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 2, 2, 8, 2, 0, 0, 0)) \
+ chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")
path.write_bytes(png)
with tempfile.TemporaryDirectory() as tmp:
image_path = Path(tmp) / "swatch.png"
tiny_png(image_path)
block = file_block(image_path)
message = HumanMessage(content_blocks=[
{"type": "text", "text": "What colour is this image?"},
block,
])
shown = {**block, "base64": block["base64"][:24] + "..."}
print("image block :", shown)
print("content types :", [b["type"] for b in message.content_blocks])
# The same message as a plain dict, which invoke() also accepts:
as_dict = {"role": "user", "content": [
{"type": "text", "text": "Summarise this PDF."},
{"type": "file", "url": "https://example.com/invoice.pdf"},
]}
print("dict form ok :", isinstance(as_dict["content"][1]["url"], str))image block : {'type': 'image', 'base64': 'iVBORw0KGgoAAAANSUhEUgAA...', 'mime_type': 'image/png'}
content types : ['text', 'image']
dict form ok : TrueThe call that sends it is the one-liner model.invoke([message]) against a vision-capable model:
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
load_dotenv()
model = init_chat_model("google_genai:gemini-3.8-flash", max_tokens=300)
message = HumanMessage(content_blocks=[
{"type": "text", "text": "Read the total from this receipt. Reply with the number only."},
{"type": "image", "url": "https://example.com/receipts/rcpt-1042.jpg"},
])
print(model.invoke([message]).text)This sample is illustrative: it needs langchain-google-genai, a Gemini key and a real image URL.
48.20Preprocessing (resizing, DPI, page selection, OCR fallbacks) and the cost of image tokens are unchanged by LangChain: see 03.6 Parts 3 and 6 and Module 09.
6.3 Multimodal output#
Some models return images (and, through other APIs, audio). When they do, response.content_blocks contains standard blocks such as {"type": "image", "base64": "...", "mime_type": "image/jpeg"}. The same rule applies as for text: select blocks by type, decode base64 yourself, and never assume position. Image generation as a product feature belongs to Module 09.
Part 7: Reasoning output#
Deep-dive
Current models think by default (02.8). The mechanics of reasoning tokens and effort are taught there; this part is how LangChain exposes them.
7.1 Reading reasoning#
# `response` is any AIMessage returned by a model
reasoning_texts = [b["reasoning"] for b in response.content_blocks if b["type"] == "reasoning"]That line is the whole idea: reasoning is a block of type == "reasoning" with the text under the reasoning key, whichever provider produced it (4.3). While streaming, look at chunk.content_blocks on each chunk. What you can see varies, and in every case you must ask for it: OpenAI returns summaries, not raw thinking, and only through the Responses API when you request a summary; Anthropic returns thinking text (with a signature) on supported models, but on the newest models the default is to omit the text unless you set display; Gemini returns thought summaries only when you set include_thoughts=True (02.8 Part 4). The exact switches are in the table below. A reasoning block may be empty or absent even when the model reasoned, and the tokens are billed either way (7.4).
7.2 Controlling effort: one parameter, per-provider reality#
reasoning_effort is a standard parameter you can set at construction or per call. It requires langchain-core>=1.5.2 and these provider package versions or newer: langchain-anthropic 1.5.3, langchain-openai 1.4.1, langchain-google-genai 4.3.1, langchain-aws 1.7.0, langchain-fireworks 1.5.2, langchain-xai 1.3.0. The classes the docs name are ChatOpenAI, ChatAnthropic, ChatGoogleGenerativeAI, ChatBedrockConverse, ChatFireworks and ChatXAI.
| Provider class | Standard parameter | Native alias or alternative | Accepted values | What you must set to see reasoning text |
|---|---|---|---|---|
ChatOpenAI |
reasoning_effort="low" |
the Responses API reasoning dict |
model dependent (the profile of the model above lists none, low, medium, high, xhigh, max) |
reasoning={"effort": "high", "summary": "auto"} (Responses API; summary can be auto, concise or detailed). reasoning_effort alone stays on Chat Completions, which returns no summaries |
ChatAnthropic |
reasoning_effort=... |
alias effort=...; thinking={...} for budgets and adaptive thinking |
max, xhigh, high, medium, low; support varies by model; effort wins if both are set |
thinking={"type": "adaptive", "display": "summarized"} on Opus 4.7 and later, Opus 5, Opus 5.5 and Sonnet 5 (the default display there is "omitted"); thinking={"type": "enabled", "budget_tokens": N} on older models |
ChatGoogleGenerativeAI |
reasoning_effort=... |
alias thinking_level=...; thinking_budget (older 2.5 models) |
minimal, low, medium, high |
include_thoughts=True (summaries) |
ChatOllama |
none | reasoning=True, False, a string, or None |
model dependent | reasoning=True: the thinking arrives in additional_kwargs["reasoning_content"] instead of <think> tags inside the content (None leaves any tags in the text) |
(Sources, read in the installed packages on 15 November 2026: the reasoning field docstring of ChatOpenAI, the thinking docstring of ChatAnthropic, the include_thoughts field and docstring of ChatGoogleGenerativeAI, and the reasoning docstring of ChatOllama. Recheck them on upgrade: these are the knobs that change most often.)
The levels a model supports are data: read model.profile["reasoning_effort_levels"] and model.profile["reasoning_effort_default"] (as in the profile sample, which shows OpenAI's list and None for the other two) rather than hard-coding them.
from dotenv import load_dotenv
from langchain_anthropic import ChatAnthropic
from langchain_openai import ChatOpenAI
load_dotenv()
hard_question = "A contract allows termination with 30 days' notice but a renewal clause auto-renews 60 days before the end date. Can I still exit before renewal?"
# OpenAI: the Responses API `reasoning` dict asks for effort AND a summary. (reasoning_effort="high" alone
# stays on Chat Completions and returns no reasoning text, only a reasoning token count.)
openai_model = ChatOpenAI(model="gpt-6-luna", max_tokens=4000, reasoning={"effort": "high", "summary": "auto"})
openai_reply = openai_model.invoke(hard_question)
# Anthropic: adaptive thinking, with display="summarized" because the newest models omit the text by default.
claude = ChatAnthropic(
model="claude-sonnet-5-5", max_tokens=6000, thinking={"type": "adaptive", "display": "summarized"},
)
claude_reply = claude.invoke(hard_question)
for name, reply in [("openai", openai_reply), ("anthropic", claude_reply)]:
thinking = [b["reasoning"] for b in reply.content_blocks if b["type"] == "reasoning"]
print(name, "| reasoning blocks:", len(thinking), "| answer:", reply.text[:80])
print(" usage:", reply.usage_metadata)This sample is illustrative: it needs both provider packages and keys. The thinking options follow the Anthropic integration page and the ChatAnthropic.thinking docstring: {"type": "enabled", "budget_tokens": N} is the older explicit-budget form (the model needs max_tokens above the budget; it is removed on the newest models), and {"type": "adaptive"} lets newer models decide how much to think (Opus 4.6 and later; check the page for the model you use). Setting reasoning_effort on ChatAnthropic without an explicit thinking adds {"type": "adaptive", "display": "summarized"} for you on models whose profile lists xhigh, so that route also returns summaries. Anthropic's per-task token budgets are a beta feature in langchain-anthropic 1.4.1 and later. Do not copy numbers from this sample into production: tune effort on your own data (02.8 Part 10).
openai | reasoning blocks: 1 | answer: Probably yes, if you give notice before the renewal window opens and ...
usage: {'input_tokens': 62, 'output_tokens': 740, 'total_tokens': 802, 'output_token_details': {'reasoning': 612}}
anthropic | reasoning blocks: 1 | answer: It depends on which date controls: the 60-day renewal cutoff comes before ...
usage: {'input_tokens': 71, 'output_tokens': 905, 'total_tokens': 976, 'output_token_details': {'reasoning': 520}}7.3 Reasoning in conversation history#
Reasoning blocks and their signatures are part of the conversation state. When a reasoning model uses tools, the provider needs the previous reasoning back on the next request, so append the whole AIMessage to history (3.5). LangChain keeps the signature in extras on the standard block and in the native block in content, so passing the same message back to the same provider works with no work from you.
7.4 Reasoning cost#
Reasoning tokens are billed as output tokens and show up in usage_metadata["output_token_details"]["reasoning"] when the provider reports them (Part 8). They can be a large share of the answer's cost. The decision of when reasoning is worth it is 02.8 Part 6.
Part 8: Usage metadata and cost#
Deep-dive
03.7 built cost tracking against each provider's raw usage object. LangChain normalizes the token counts into one shape, so one tracker works for every provider.
8.1 The UsageMetadata shape#
AIMessage.usage_metadata is a UsageMetadata dictionary (or None when the provider reported nothing). The meaning of each field, from the langchain-core source:
| Key | Meaning |
|---|---|
input_tokens |
count of input tokens, the sum of all input token types (cached tokens are included) |
output_tokens |
count of output tokens, the sum of all output token types (reasoning tokens are included) |
total_tokens |
input_tokens + output_tokens |
input_token_details (optional) |
a breakdown that "does not need to sum to the full input count" and "does not need to have all keys": audio, cache_creation, cache_read, and possibly provider-specific extras |
output_token_details (optional) |
a breakdown with audio, reasoning, and possibly extras |
Two consequences for any cost code you write:
- The detail keys are subsets, not additions. To price a call you subtract
cache_readandcache_creationfrominput_tokensto get the plain input, and you do not addreasoningtooutput_tokens(they are already inside it). - Every key except the three totals may be missing. A provider that does not report caching simply has no
cache_read. Use.get(...)with a default, and treatusage_metadata is Noneas "unknown", not zero.
The first rule differs from a raw Anthropic response (whose own input_tokens leaves out cache tokens, as 03.7 Part 3 explains), which is exactly why the normalized shape is useful: your tracker no longer needs a per-provider branch. It is the documented convention, so reconcile your totals with the provider's usage page before you bill anyone from them. Each provider's cache accounting is in 03.7 Parts 6 to 8.
8.2 Aggregating across calls and models#
Add up a whole request (several model calls, maybe several models) with a callback. get_usage_metadata_callback() is a context manager; UsageMetadataCallbackHandler is the same thing as a handler object you pass in config["callbacks"].
import json
from langchain.messages import AIMessage
from langchain_core.callbacks import get_usage_metadata_callback
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
def reply(text: str, in_tok: int, out_tok: int, **details) -> AIMessage:
"""Build an AIMessage that looks like a provider reply with usage attached."""
return AIMessage(
content=text,
usage_metadata={"input_tokens": in_tok, "output_tokens": out_tok, "total_tokens": in_tok + out_tok, **details},
response_metadata={"model_name": "demo-model"},
)
model = GenericFakeChatModel(messages=iter([
reply("Done.", 1200, 40, input_token_details={"cache_read": 1000}, output_token_details={"reasoning": 25}),
reply("Also done.", 1300, 55),
]))
# Aggregate across several calls (and several models) with the context-manager form.
with get_usage_metadata_callback() as cb:
first = model.invoke("ticket 1")
second = model.invoke("ticket 2")
print("one call :", first.usage_metadata)
print("aggregate:", json.dumps(cb.usage_metadata, sort_keys=True)) # keyed by response_metadata["model_name"]Output (real; the fake model returns messages whose usage numbers the sample supplies, and the aggregate is printed with sorted keys because the order of the inner dictionary can differ from run to run):
one call : {'input_tokens': 1200, 'output_tokens': 40, 'total_tokens': 1240, 'input_token_details': {'cache_read': 1000}, 'output_token_details': {'reasoning': 25}}
aggregate: {"demo-model": {"input_token_details": {"cache_read": 1000}, "input_tokens": 2500, "output_token_details": {"reasoning": 25}, "output_tokens": 95, "total_tokens": 2595}}Notice that the aggregate is keyed by model name (read from response_metadata["model_name"]), and that it merged the numeric detail fields across the two calls: cache_read and reasoning appear once because only the first call reported them. The handler form for real models:
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain_core.callbacks import UsageMetadataCallbackHandler
load_dotenv()
cheap = init_chat_model("openai:gpt-6-luna", max_tokens=300, max_retries=2, timeout=30)
strong = init_chat_model("anthropic:claude-sonnet-5-5", max_tokens=300, max_retries=2, timeout=30)
callback = UsageMetadataCallbackHandler()
config = {"callbacks": [callback]}
draft = cheap.invoke("Draft a two-line apology for a late delivery.", config=config)
final = strong.invoke(f"Polish this apology:\n\n{draft.text}", config=config)
print(callback.usage_metadata) # one entry per model name that answeredThis sample is illustrative: it needs both providers' packages and keys.
{'gpt-6-luna': {'input_tokens': 21, 'output_tokens': 38, 'total_tokens': 59},
'claude-sonnet-5-5': {'input_tokens': 62, 'output_tokens': 41, 'total_tokens': 103}}(The keys are whatever string each provider puts in response_metadata["model_name"], which is often a dated snapshot name rather than the short id you passed; the names above are simplified.)
8.3 Usage while streaming#
How and whether usage shows up in a stream depends on the provider (02.5 Part 8 and 03.3 cover the wire):
- OpenAI and Azure OpenAI chat completions need a flag to report usage while streaming:
stream_usage=True. In the 1.8.0 sourcestream_usagedefaults toNoneand is switched on automatically only when you passed none ofstream_usage,openai_proxy, your ownclientorhttp_clientobjects (sync or async), and the endpoint is the default one (the object above printedTrue). It therefore stays off whenever you passbase_url=(oropenai_api_base), passopenai_proxy, supply your own HTTP client, or set theOPENAI_BASE_URLenvironment variable, and you should assume it is off for third-party endpoints. In all those cases set it explicitly (ChatOpenAI(..., stream_usage=True)) when you need counts, and confirm the endpoint really sends usage. - Anthropic, Google and Ollama include usage in the stream.
- In all cases the accumulated message (
full + chunk, 5.2) carriesusage_metadataif the stream reported it.
8.4 Logging usage per call#
A small helper that turns one reply into one structured log line gives you cost per ticket, per tenant and per feature, which is the foundation of everything in Module 11A. Prices are inputs: take them from the provider's pricing page and keep them in configuration, as 03.7 Part 4 argues.
import json
from dataclasses import dataclass
from langchain.messages import AIMessage
@dataclass(frozen=True)
class Price:
"""USD per million tokens. Fill these from the provider's pricing page; never hard-code from memory."""
input: float
output: float
cache_read: float | None = None # None means "bill cache reads as normal input"
cache_creation: float | None = None # None means "bill cache writes as normal input"
def cost_usd(usage: dict, price: Price) -> float:
"""Cost of one reply from AIMessage.usage_metadata.
In LangChain's standard shape, input_tokens is the SUM of all input token types and
cache_read / cache_creation are parts of it; reasoning tokens are a part of output_tokens.
So the uncached share is what is left after subtracting the cache parts.
"""
details = usage.get("input_token_details", {})
cache_read = details.get("cache_read", 0)
cache_creation = details.get("cache_creation", 0)
plain_input = usage["input_tokens"] - cache_read - cache_creation
total = plain_input * price.input
total += cache_read * (price.cache_read if price.cache_read is not None else price.input)
total += cache_creation * (price.cache_creation if price.cache_creation is not None else price.input)
total += usage["output_tokens"] * price.output # reasoning tokens are already inside output_tokens
return total / 1_000_000
def usage_log_line(reply: AIMessage, price: Price, **context: str) -> str:
"""One structured log line per call: model, tokens, cache and reasoning shares, cost."""
usage = reply.usage_metadata or {}
record = {
**context,
"model": reply.response_metadata.get("model_name"),
"input_tokens": usage.get("input_tokens"),
"output_tokens": usage.get("output_tokens"),
"cache_read": usage.get("input_token_details", {}).get("cache_read", 0),
"reasoning": usage.get("output_token_details", {}).get("reasoning", 0),
"cost_usd": round(cost_usd(usage, price), 6) if usage else None,
}
return json.dumps(record)
demo_price = Price(input=1.00, output=5.00, cache_read=0.10) # made-up numbers for the demo only
reply = AIMessage(
content="Your refund was issued.",
usage_metadata={"input_tokens": 2000, "output_tokens": 300, "total_tokens": 2300,
"input_token_details": {"cache_read": 1500},
"output_token_details": {"reasoning": 200}},
response_metadata={"model_name": "demo-model"},
)
print(usage_log_line(reply, demo_price, ticket_id="T-5521"))Output (real, arithmetic on the made-up demo prices in the sample: 500 plain input tokens at 1.00, 1500 cache-read tokens at 0.10, 300 output tokens at 5.00, per million):
{"ticket_id": "T-5521", "model": "demo-model", "input_tokens": 2000, "output_tokens": 300, "cache_read": 1500, "reasoning": 200, "cost_usd": 0.00215}8.5 Counting tokens before you call#
Usage metadata tells you what a call cost after it ran. To check that a prompt will fit, or to let trim_messages cut a history to a budget, you need a count before the call. Every chat model has three methods for it (from BaseLanguageModel): get_token_ids(text), get_num_tokens(text) and get_num_tokens_from_messages(messages, tools=None). What they do depends on the class, which is the whole point of this section:
| Class | How it counts | Needs |
|---|---|---|
ChatOpenAI |
a local tiktoken encoding chosen from the model name (o200k_base for gpt-4o, gpt-4.1, gpt-5 and gpt-6 names when tiktoken does not know the id), with OpenAI's per-message overhead; tool schemas are ignored with a warning; images only if pillow (and httpx for URLs) are installed |
no key; the encoding file is fetched once and cached, so the first call may need the network |
ChatAnthropic |
Anthropic's official token-counting endpoint, and it can include system text and tool schemas | a network call and a key on every count; the endpoint has its own request-rate limits (check Anthropic's token-counting page for the current ones) |
ChatGoogleGenerativeAI |
get_num_tokens calls Google's count_tokens for the text; the messages version is the base-class loop, one request per message |
a network call and a key; tool schemas ignored |
ChatOllama, fakes and any class with no counter |
the base class falls back to a GPT-2 tokenizer from the transformers package |
transformers installed (without it you get an ImportError), and a rough count for any non-GPT-2 model |
(Read from the installed 1.8.0 / 1.7.10 / 4.5.0 / 1.1.0 sources on 15 November 2026. The Anthropic and Google rows call the provider, so no output is shown for them.)
Two things to remember. First, the count is an estimate of the input only: it does not know about reasoning tokens, tool-call overhead you add later, or provider-side prompt rewriting, so keep a margin below profile["max_input_tokens"] (2.6). Second, in the base-class loop each message is counted as its Human: ... or System: ... transcript line, so the role prefix adds a few tokens per message. You can see both effects without a key by giving a fake model a toy tokenizer (one token per word) through the custom_get_token_ids field that every chat model has, and trimming with the model as the counter:
from langchain.messages import AIMessage, HumanMessage, SystemMessage, trim_messages
from langchain_core.language_models import FakeListChatModel
# A fake model with a custom tokenizer (one token per whitespace-separated word), so no network is needed.
model = FakeListChatModel(responses=["unused"], custom_get_token_ids=lambda text: list(range(len(text.split()))))
history = [
SystemMessage("Be brief."),
HumanMessage("My invoice total looks wrong, please check it."),
AIMessage("Can you share the invoice number?"),
HumanMessage("It is INV-2231."),
]
print("get_num_tokens:", model.get_num_tokens("My invoice total looks wrong, please check it."))
print("per message :", [model.get_num_tokens_from_messages([m]) for m in history])
print("whole history :", model.get_num_tokens_from_messages(history))
kept = trim_messages(history, max_tokens=12, token_counter=model, strategy="last", include_system=True, start_on="human")
print("kept:", [(m.type, m.content) for m in kept])Output (real; the "model" is a fake with a word-count tokenizer, so the numbers show the mechanics, not any provider's counts):
get_num_tokens: 8
per message : [3, 9, 7, 4]
whole history : 23
kept: [('system', 'Be brief.'), ('human', 'It is INV-2231.')]Read it line by line: the sentence has 8 words, but the first message in the history, System: Be brief., counts 3 because of the System: prefix; the whole history is the sum of the per-message counts (3 + 9 + 7 + 4 = 23); and trim_messages used the model as its counter to keep the system message plus the newest human turn that fit in 12 tokens.
Part 9: Tool calling at the model level#
03.5 taught one tool round trip on the wire, 08A.2 the loop, and 08A.6 tool design. Lesson 08F.8 covers LangChain's @tool decorator and create_agent in full. Here is only the model-level mechanism they are both built on.
9.1 bind_tools#
model.bind_tools(tools, *, tool_choice=None, **kwargs) returns a new runnable that sends the tool schemas with every call. The original model is unchanged.
toolsis a sequence of dicts (a raw provider schema), Pydantic classes, plain callables, orBaseToolobjects (what@toolproduces).- The reply is an
AIMessagewhose.tool_callslists the requests as{"name", "args", "id", "type": "tool_call"}dictionaries (empty list when the model answered in text). tool_choice:"any"forces the model to call some tool; a tool name forces that one; leaving it out lets the model decide. Provider classes add their own arguments: for exampleChatOpenAI.bind_toolsalso takesstrict,parallel_tool_callsandresponse_format.parallel_tool_calls=False(OpenAI, Anthropic) disables parallel calls when you need strict sequencing (03.5 Part 8).- Provider built-in (server-side) tools are passed as dicts, for example
model.bind_tools([{"type": "web_search"}]). The provider runs them itself, the reply carriesserver_tool_callandserver_tool_resultblocks, and noToolMessageis needed (03.5 Part 13, 08A.8).
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain.tools import tool
load_dotenv()
@tool
def get_order_status(order_id: str) -> str:
"""Look up the shipping status of an order by its id."""
return f"Order {order_id}: shipped on 2026-11-10"
model = init_chat_model("openai:gpt-6-luna", max_tokens=300, max_retries=2, timeout=30)
with_tools = model.bind_tools([get_order_status]) # the model may call it
forced = model.bind_tools([get_order_status], tool_choice="any") # the model must call a tool
reply = with_tools.invoke("Where is order A-1042?")
print(reply.tool_calls)This sample is illustrative: it needs langchain-openai and OPENAI_API_KEY.
[{'name': 'get_order_status', 'args': {'order_id': 'A-1042'}, 'id': 'call_8fK2xQ', 'type': 'tool_call'}]9.2 The manual loop, with a scripted model#
Here is the whole round trip described in 08A.2, built from the LangChain pieces and run without a key by scripting the model's two replies. The scripted model subclasses GenericFakeChatModel to add bind_tools, because the stock fake does not implement it (Part 13).
sequenceDiagram
participant You as Your code
participant M as Chat model (tools bound)
participant T as Tool function
You->>M: invoke([System, Human])
M-->>You: AIMessage with tool_calls (id call_1)
Note over You: append the whole AIMessage
You->>T: tool.invoke(tool_call)
T-->>You: ToolMessage (tool_call_id call_1)
Note over You: append the ToolMessage
You->>M: invoke([System, Human, AI, Tool])
M-->>You: AIMessage with final textfrom typing import Any
from langchain.messages import AIMessage, HumanMessage, SystemMessage
from langchain.tools import tool
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
@tool
def get_order_status(order_id: str) -> str:
"""Look up the shipping status of an order by its id."""
return f"Order {order_id}: shipped on 2026-11-10"
class ScriptedChat(GenericFakeChatModel):
"""A fake that scripts replies and tolerates bind_tools (the stock fake does not implement it)."""
def bind_tools(self, tools, **kwargs: Any):
return self
scripted = ScriptedChat(messages=iter([
AIMessage(content="", tool_calls=[{"name": "get_order_status", "args": {"order_id": "A-1042"}, "id": "call_1"}]),
AIMessage(content="Order A-1042 shipped on 10 November."),
]))
tools = {"get_order_status": get_order_status}
model = scripted.bind_tools(list(tools.values()))
messages = [SystemMessage("You are a support agent."), HumanMessage("Where is order A-1042?")]
for _ in range(5): # a hard step budget: never loop unbounded
ai = model.invoke(messages)
messages.append(ai) # append the WHOLE AIMessage, not just its text
if not ai.tool_calls:
break
for call in ai.tool_calls:
tool_message = tools[call["name"]].invoke(call) # passing a tool-call dict returns a ToolMessage
print(type(tool_message).__name__, "|", tool_message.tool_call_id, "|", tool_message.content)
messages.append(tool_message)
print("final:", messages[-1].text)
print("roles:", [m.type for m in messages])ToolMessage | call_1 | Order A-1042: shipped on 2026-11-10
final: Order A-1042 shipped on 10 November.
roles: ['system', 'human', 'ai', 'tool', 'ai']What this shows, line by line:
tools[call["name"]].invoke(call): passing the tool-call dict (not just itsargs) to aBaseToolreturns aToolMessagewith the righttool_call_idandnamealready filled in. You do not build theToolMessageyourself.- The loop has a step budget (
range(5)). An agent loop with no limit is a production incident waiting to happen (08A.2 Part 1.4, 08A.14). - Both the
AIMessageand theToolMessageare appended. Dropping theAIMessagemakes theToolMessagean orphan and the next call fails with a 400. - What this loop leaves out, and
create_agentadds: tool errors as messages the model can recover from, parallel execution, retries, human approval, streaming, middleware, a state schema and a checkpointer (08F.8). Write the manual loop once to understand it; usecreate_agentfor real work.
9.3 Streaming tool calls and invalid calls#
- While streaming,
chunk.tool_call_chunksholds partial JSON strings (name,id,args,index). Sum the chunks and read.tool_callson the result (the second half of the 5.2 sample), and mind the iteration change inlangchain-core1.7 described there. message.invalid_tool_callslists calls whose arguments were not valid JSON (type: "invalid_tool_call"with anerror). Treat them as tool errors: return aToolMessagesaying the arguments were invalid so the model can retry, rather than crashing. Reliability patterns for this are in 08A.14.strict=Truetool schemas (OpenAI, and where supported elsewhere) make the provider enforce the schema (03.5 Part 10); support and limits vary, so check the provider page.
Part 10: with_structured_output: the basics#
03.4 is the owner of structured output theory (the ladder from "ask nicely" to constrained decoding, schema subsets, validation layers). Lesson 08F.6 owns LangChain's full treatment (strategies per provider, error handling, parsers). This part gives you the basic call and the one-screen decision table, because every model-level lesson needs it.
10.1 The basic call#
model.with_structured_output(schema) returns a new runnable that returns parsed data instead of an AIMessage. The schema can be a Pydantic class (you get an instance back), a TypedDict, or a JSON Schema dictionary (you get a dict back).
from dotenv import load_dotenv
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model
load_dotenv()
class TicketTriage(BaseModel):
"""A triaged support ticket."""
category: str = Field(description="One of: billing, bug, account, other")
urgency: int = Field(description="1 (low) to 5 (critical)", ge=1, le=5)
summary: str = Field(description="One sentence, under 20 words")
model = init_chat_model("openai:gpt-6-luna", max_tokens=400, max_retries=2, timeout=30)
triage = model.with_structured_output(TicketTriage)
ticket = "I was charged twice for INV-2231 and my card is now overdrawn. Please fix today."
result = triage.invoke(ticket)
print(type(result).__name__, result)
# include_raw=True keeps the AIMessage and reports parsing problems instead of raising.
safe = model.with_structured_output(TicketTriage, include_raw=True)
out = safe.invoke(ticket)
print(out["parsing_error"], out["raw"].usage_metadata, out["parsed"])This sample is illustrative: it needs langchain-openai and OPENAI_API_KEY.
TicketTriage category='billing' urgency=4 summary='Customer was charged twice for INV-2231 and needs a same-day refund.'
None {'input_tokens': 94, 'output_tokens': 41, 'total_tokens': 135} category='billing' urgency=4 summary='Customer was charged twice for INV-2231 and needs a same-day refund.'The signature on BaseChatModel is with_structured_output(schema, *, include_raw=False, **kwargs). Provider classes add a method argument and, for OpenAI and Anthropic, strict. With include_raw=True the result is a dict with raw (the AIMessage, so you keep usage and metadata), parsed (the object, or None) and parsing_error.
10.2 Which mechanism each provider class uses by default#
method chooses how the schema reaches the model: native structured outputs ("json_schema"), a forced tool call ("function_calling"), or JSON mode ("json_mode"). In short: ChatOpenAI, ChatGoogleGenerativeAI and ChatOllama default to "json_schema", ChatAnthropic defaults to "function_calling", and what is accepted and how each value behaves differs per class (for example, "json_mode" is not an Anthropic method). 08F.6, 9.2 owns the full table of signatures and defaults, the stale OpenAI integration page, and the Claude models that reject a forced tool choice. Pass method= explicitly so your code does not depend on a default that changes.
The mechanism changes what can go wrong. Native schema modes constrain decoding and support a limited JSON Schema subset (03.4 Part 4); a forced tool call is more permissive but is not a hard guarantee. Either way, shape validity is not truth: validate values with the layers in 03.4 Part 6.
10.3 Refusals#
When a model refuses a structured request, a parser has nothing to parse. On current packages LangChain raises ModelRefusalError (from langchain_core.exceptions import ModelRefusalError, response in raw_message) instead of a confusing parsing error, or returns it as parsing_error with include_raw=True. A refusal is not retried (the standard hierarchy marks it is_retryable = False, 11.6): log it, and surface a safe message. 08F.6, 8.5 owns the minimum package versions, which providers are detected, and what older versions do (a generic ValueError, documented for OpenAI Responses API refusals only).
10.4 Pitfalls#
- Pre-bound models and
create_agent. If you pass a model that already hadbind_toolsapplied together with aresponse_format,create_agentrejects it (08F.8). - Fake models do not support it.
GenericFakeChatModeldoes not implementbind_tools, sowith_structured_outputraises on it. Test structured-output code by faking at a different seam (return the already-parsed object from a stub function), or subclass the fake (Part 13). - Schema is documentation. Field
descriptions and the class docstring are sent to the model. Write them as instructions. - Do not catch everything. Distinguish a refusal, a parsing failure, a provider 400 for an unsupported schema feature, and a network failure; each needs a different response.
Part 11: Reliability on the model object#
Deep-dive
03.8 taught what fails, what to retry and what never to retry; 03.9 taught bounded concurrency and rate-aware throughput. LangChain puts the same tools on the model object. Your job is to know which layer does what, so that retries do not stack and limits are not applied twice.
11.1 Four layers of retry, and how to stop them stacking#
flowchart TD
call["model.invoke(...)"] --> fb{"with_fallbacks<br/>wraps the chain?"}
fb --> retry["with_retry<br/>(your attempts, your exceptions)"]
retry --> cache{"cache hit?"}
cache -->|"yes"| back["return stored AIMessage"]
cache -->|"no"| rl["rate_limiter<br/>(waits before each request)"]
rl --> prov["provider class"]
prov --> sdkr["SDK retries<br/>max_retries (429, 5xx, network)"]
sdkr --> net["HTTP request"]
net -->|"error after all attempts"| fb2["fallback model<br/>(next in the list)"]
net -->|"success"| out["AIMessage"]The title counts four places where a failed call can be repeated or redirected. Be precise about what each is: max_retries= on a provider class is the SDK client's retry setting (there is no separate "chat model retry" on top of it), and a fallback is a failover, not a retry, but it is in the list because it multiplies requests in the same way.
| Layer | Set with | Retries what | Good for |
|---|---|---|---|
| SDK client | max_retries= on the provider class |
network errors, 429, 5xx, with backoff and jitter; not 401 or 404 | the default shield against transient failures |
| Runnable | model.with_retry(...) |
any exception you name (default: all of them) | retrying beyond the SDK, or retrying error types the SDK ignores |
| Fallback | model.with_fallbacks([...]) |
switches to another runnable on an exception you name | provider outage, context overflow, cost tiers |
| Agent | ModelRetryMiddleware, ModelFallbackMiddleware |
the same ideas inside create_agent (08F.8) |
agents, which need per-step control and respect is_retryable |
11.2 with_retry and with_fallbacks#
with_retry wraps a runnable in retry logic. The signature, verified in the source:
model.with_retry(
*,
retry_if_exception_type=(Exception,), # the default retries EVERYTHING, including a 400
wait_exponential_jitter=True,
exponential_jitter_params=None,
stop_after_attempt=3,
)import importlib
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain_core.exceptions import (
ContextOverflowError, ModelAPIError, ModelConnectionError, ModelRateLimitError, ModelTimeoutError,
)
load_dotenv()
# Google and Ollama raise raw transport errors for network drops and timeouts (see the warning in 11.1), so the
# retryable set must name them too. langchain-ollama uses httpx; at the versions above google-genai raises its own
# httpx2 copy, so collect whichever of the two is installed.
transport = []
for name in ("httpx", "httpx2"):
try:
transport.append(importlib.import_module(name).TransportError) # includes timeouts
except ImportError:
pass
RETRYABLE = (ModelRateLimitError, ModelAPIError, ModelConnectionError, ModelTimeoutError, *transport)
primary = init_chat_model("anthropic:claude-haiku-5-5", max_tokens=500, max_retries=0, timeout=30) # SDK layer off
backup = init_chat_model("openai:gpt-6-luna", max_tokens=500, max_retries=0, timeout=30)
bigger_context = init_chat_model("google_genai:gemini-3.8-flash", max_tokens=500, max_retries=0, timeout=60)
def context_of(model) -> int:
return (model.profile or {}).get("max_input_tokens") or 0
# Pick an overflow fallback by its context window (the profile, 2.6), never by what you named the variable.
if context_of(bigger_context) <= context_of(primary):
raise RuntimeError("the overflow fallback must have a larger context window than the primary")
# One owner of retries (with_retry), a fallback for outages, a second fallback only for overflow.
resilient = (
primary.with_retry(retry_if_exception_type=RETRYABLE, stop_after_attempt=3)
.with_fallbacks([backup.with_retry(retry_if_exception_type=RETRYABLE, stop_after_attempt=2)],
exceptions_to_handle=RETRYABLE)
.with_fallbacks([bigger_context], exceptions_to_handle=(ContextOverflowError,))
)
print(resilient.invoke("Summarise: the supplier delivered 40 units instead of 400.").text)This sample is illustrative: it needs three providers' packages and keys (use the ones you have). It shows the structure: classify exceptions (including the transport errors some integrations leave unclassified), retry the transient ones, fall back on outage, and fall back to a larger context only on overflow.
The supplier shipped 40 units instead of the 400 ordered, a tenfold shortfall.Why the transport errors are in that tuple. This sample proves it without contacting any provider: it points three models at a port where nothing listens and counts how many attempts with_retry(stop_after_attempt=3) makes, first with only the standard Model... family and then with the transport errors added.
import importlib
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.exceptions import ModelAPIError, ModelConnectionError, ModelRateLimitError, ModelTimeoutError
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_ollama import ChatOllama
from langchain_openai import ChatOpenAI
STANDARD = (ModelRateLimitError, ModelAPIError, ModelConnectionError, ModelTimeoutError)
# Transport errors that are NOT ModelError subclasses. httpx is what langchain-ollama uses; at the versions
# above, google-genai raises its own httpx2 copy, so collect whichever of the two is installed.
transport = []
for name in ("httpx", "httpx2"):
try:
transport.append(importlib.import_module(name).TransportError)
except ImportError:
pass
NETWORK = tuple(transport)
class CountAttempts(BaseCallbackHandler):
attempts = 0
def on_chat_model_start(self, *args, **kwargs):
self.attempts += 1
dead = "http://127.0.0.1:1" # nothing listens here: a connection failure, no provider is contacted
models = {
"openai": ChatOpenAI(model="gpt-6-luna", base_url=dead, max_retries=0, timeout=3),
"google": ChatGoogleGenerativeAI(model="gemini-3.8-flash", base_url=dead, max_retries=0, timeout=3),
"ollama": ChatOllama(model="demo", base_url=dead),
}
for label, retry_on in [("standard only", STANDARD), ("standard + transport", STANDARD + NETWORK)]:
for name, model in models.items():
counter = CountAttempts()
chain = model.with_retry(retry_if_exception_type=retry_on, stop_after_attempt=3, wait_exponential_jitter=False)
try:
chain.invoke("hi", config={"callbacks": [counter]})
except Exception as exc:
print(f"{label:21} {name:7} attempts={counter.attempts} raised {type(exc).__name__}")Output (real, run on 15 November 2026 with the package versions in the Versions line; placeholder values were set for OPENAI_API_KEY and GOOGLE_API_KEY in the shell only so the objects could be built, and the only address contacted was 127.0.0.1:1):
standard only openai attempts=3 raised OpenAIConnectionError
standard only google attempts=1 raised ConnectError
standard only ollama attempts=1 raised ConnectError
standard + transport openai attempts=3 raised OpenAIConnectionError
standard + transport google attempts=3 raised ConnectError
standard + transport ollama attempts=3 raised ConnectErrorWith the standard family only, OpenAI's connection failure is retried three times and Google's and Ollama's are not retried at all. Adding the transport errors fixes the two that were missed. Two options on top of that:
with_retry(retry_if_exception_type=...)also accepts a callable (verified signature: a tuple of exception types or a function from exception tobool), which lets you honour each error's own flag:lambda exc: exc.is_retryable if isinstance(exc, ModelError) else isinstance(exc, NETWORK)(withModelErrorimported fromlangchain_core.exceptions).with_fallbacks(exceptions_to_handle=...)accepts only a tuple of types, so keepRETRYABLEfor it.- Or skip the
with_retrydesign for these two providers: keep the SDK layer on for Google (max_retries=2; in a check against the dead port above,max_retries=3made the failure take seconds of backoff instead of milliseconds, so the SDK layer does retry a connection failure) and usewith_fallbacksonly for outages you have verified raise a class you list.ChatOllamahas no retry setting at all, so for Ollama the transport-error tuple is the only retry you get. Whatever you choose, test it once with a dead port, as above.
with_fallbacks(fallbacks, *, exceptions_to_handle=(Exception,), exception_key=None) tries the primary, and on an exception it handles it tries each fallback in order. Design rules:
- Fallback to what? A model that is a genuine substitute: same capabilities needed by this call (vision, tools, structured output, context length). A "cheaper" fallback can silently lower quality; log every fallback event so you notice.
- Bind tools and structured output on each model first, then add fallbacks last. A fallback model that lacks the same tools or schema fails differently from the primary. For agents, use
ModelFallbackMiddlewareinstead (08F.8). - Restrict
exceptions_to_handle. Falling back on a 400 for a malformed request just repeats the bug against another provider. Falling back on a refusal sends a request the first provider declined to a second one that may comply: decide that deliberately (Module 12). - Failover across providers changes behaviour (tone, tool-call habits, reasoning blocks). See Part 12.
- Pick the overflow fallback by comparing
model.profile["max_input_tokens"], not by name. A fallback called "bigger context" that is really the same window fixes nothing; the startup check in the sample above fails loudly instead. (A profile can beNoneor stale for a new id, so override it when you know better, 2.6.)
11.3 Rate limiters#
An InMemoryRateLimiter is a token bucket that spaces out your requests. It prevents you from hitting the provider's 429 in the first place, which is cheaper than retrying after it (03.9 Part 5, 03.8 Part 9).
from langchain.rate_limiters import InMemoryRateLimiter
limiter = InMemoryRateLimiter(
requests_per_second=0.5, # one request every 2 seconds on average
check_every_n_seconds=0.1, # how often a blocked caller re-checks for a free token
max_bucket_size=1, # burst allowance: 1 means no bursts
)
# Pass it to any chat model: init_chat_model("...", rate_limiter=limiter) or ChatX(..., rate_limiter=limiter)Verified constructor: InMemoryRateLimiter(*, requests_per_second=1, check_every_n_seconds=0.1, max_bucket_size=1) (the import from langchain.rate_limiters re-exports langchain_core.rate_limiters). It is a BaseRateLimiter subclass, so you can write your own (for example one backed by Redis for several processes). The parts that matter:
- It is in-process and thread-safe only. Ten worker processes with
requests_per_second=5each make 50 requests per second. For a fleet you need a shared limiter (a gateway, or a customBaseRateLimiter). - It limits request count, not request size. Providers also limit tokens per minute; one huge prompt can exhaust a tokens-per-minute budget while the request limiter is happy. Budget tokens separately (03.9 Part 5).
- One limiter object per limit. Share the same object between models that share a provider key and quota; give different providers different limiters.
- A cache hit does not consume a token. The source comments that cache lookups are deliberately not rate limited. A streamed call does consume one.
- It blocks the caller.
invokewaits for a token (aacquirein async); that is the point, but it means a stalled limiter looks like a hung program. Settimeoutand log waits for diagnosis.
11.4 The LangChain cache#
BaseChatModel has a cache field: True uses the global cache, False disables caching, None (the default) uses the global cache if one is set, and a BaseCache instance uses that specific cache. cache=True is stricter than the default: with no global cache configured it raises a ValueError ("Asked to cache, but no cache found at langchain.cache") instead of silently skipping, so either call set_llm_cache(...) first or pass a BaseCache instance to the model.
from langchain_core.caches import InMemoryCache
from langchain_core.globals import set_llm_cache
set_llm_cache(InMemoryCache()) # process-wide, in memory, lost on exit
# or per model: init_chat_model("...", cache=InMemoryCache())The cache key is the prompt together with a string describing the model and its settings, so changing the model, max_tokens or any bound option misses the cache. Caching is not supported for streaming methods: stream() always calls the model (shown in the next section).
Where a LangChain-level cache fits, and where it does not:
| Use it for | Do not use it for |
|---|---|
| tests and notebooks (identical prompts repeat, and you want determinism) | production answers where freshness matters |
| deterministic extraction on repeated documents | anything personalized (the prompt differs, so it rarely hits, and a hit can leak one user's answer to another if your key omits the user) |
| evaluation runs that repeat the same prompts | streaming UIs (never hit) |
InMemoryCache(*, maxsize=None) lives in process memory, has no size limit unless you set maxsize, and is not shared across processes; durable and shared caches come from separate integrations, so check the docs for the current ones. Cache strategy for production (semantic caching, response caching, invalidation) is Module 11A; provider prompt caching is a different thing, below.
11.5 Seeing it work, with no key#
This sample runs a rate limiter, the cache, retries and fallbacks against fake models that fail on purpose (a FlakyModel that raises a connection error for its first calls):
import time
from langchain.rate_limiters import InMemoryRateLimiter
from langchain_core.caches import InMemoryCache
from langchain_core.language_models import FakeListChatModel
# --- rate limiter: a token bucket shared by every call on this model object ---
limiter = InMemoryRateLimiter(requests_per_second=5, check_every_n_seconds=0.01, max_bucket_size=1)
limited = FakeListChatModel(responses=["ok"], rate_limiter=limiter)
start = time.perf_counter()
for _ in range(6):
limited.invoke("ping")
elapsed = time.perf_counter() - start
print("6 calls at 5 requests/second took at least 1 second:", elapsed >= 1.0)
# --- cache: same input, same model settings -> the stored answer, no second call ---
cached = FakeListChatModel(responses=["first", "second", "third"], cache=InMemoryCache())
print([cached.invoke("same prompt").text for _ in range(3)])
print(cached.invoke("a different prompt").text)
# Streaming bypasses the cache: each stream() consumed a fresh response.
cached_stream = FakeListChatModel(responses=["a", "b"], cache=InMemoryCache())
print("".join(c.text for c in cached_stream.stream("p")), "".join(c.text for c in cached_stream.stream("p")))
# --- retries and fallbacks on a model that fails on purpose ---
class FlakyModel(FakeListChatModel):
calls: int = 0
fail_times: int = 2
def _generate(self, *args, **kwargs):
self.calls += 1
if self.calls <= self.fail_times:
raise ConnectionError("simulated network drop")
return super()._generate(*args, **kwargs)
flaky = FlakyModel(responses=["ok after retries"])
retrying = flaky.with_retry(stop_after_attempt=3, wait_exponential_jitter=False)
print(retrying.invoke("hi").text, "| attempts:", flaky.calls)
always_down = FlakyModel(responses=["never"], fail_times=99)
backup = FakeListChatModel(responses=["answer from the backup model"])
print(always_down.with_fallbacks([backup]).invoke("hi").text)
try:
FlakyModel(responses=["x"], fail_times=99).with_retry(stop_after_attempt=2, wait_exponential_jitter=False).invoke("hi")
except ConnectionError as exc:
print("retries exhausted, original error re-raised:", exc)6 calls at 5 requests/second took at least 1 second: True
['first', 'first', 'first']
second
a b
ok after retries | attempts: 3
answer from the backup model
retries exhausted, original error re-raised: simulated network dropRead the output as a checklist of the behaviours described above:
- Rate limiter: six calls at five per second cannot finish in under a second.
- Cache: the same prompt returned
firstthree times even though the fake had three different replies queued: the second and third calls never reached the model. A different prompt reached it and gotsecond. - Streaming bypasses the cache: the two
stream()calls on the same prompt consumed two different replies (athenb). - Retry: two failures and a success, three attempts in total, and the answer arrived.
- Fallback: the primary was always down, the backup answered.
- Exhausted retries re-raise the original exception, not a wrapper, so your
exceptclauses still work.
11.6 The standard exception hierarchy#
Provider errors arrive as LangChain model exceptions (langchain_core.exceptions). Each integration raises a subclass that inherits from both the LangChain exception and the provider SDK's own exception (for example OpenAIRateLimitError(openai.RateLimitError, ModelRateLimitError)), so existing except openai.RateLimitError code keeps working and provider-agnostic code can catch the LangChain class. (This was verified in the langchain-openai and langchain-anthropic sources. The base-class docstring says every integration does the same, but it is not true yet: langchain-google-genai 4.5.0 maps HTTP errors but not connection errors or timeouts, and langchain-ollama 1.1.0 maps none, as the warning and the dead-port run in 11.1 and 11.2 show. Before you depend on the hierarchy for a provider, provoke an error and check the class you get.)
| Exception | Condition | is_retryable |
|---|---|---|
ModelAuthenticationError |
bad or missing credentials (HTTP 401) | False |
ModelPermissionDeniedError |
credentials lack permission (403) | False |
ModelInvalidRequestError |
the provider rejected the request (400) | False |
ModelNotFoundError |
the model id does not exist (404) | False |
ContextOverflowError |
input exceeds the model's context window | False |
ModelRefusalError |
the model declined (raised where the content is needed, such as with_structured_output) |
False |
ModelRateLimitError |
rate limit exceeded (429) | True |
ModelAPIError |
provider-side failure (5xx) | True |
ModelConnectionError |
could not reach the provider | True |
ModelTimeoutError |
the request timed out | True |
All inherit from ModelError, which defines the is_retryable class attribute; retry middleware reads it. The base class docstring notes that most are keyed to the HTTP status they surface with, and that a refusal is a successful response, which is why a plain invoke returns a refusal as ordinary content and only the paths that need the withheld content raise.
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain_core.exceptions import ContextOverflowError, ModelAuthenticationError, ModelTimeoutError
load_dotenv()
model = init_chat_model("openai:gpt-6-luna", max_tokens=200, timeout=0.0001, max_retries=0) # a timeout that cannot be met
try:
model.invoke("Hello")
except ModelTimeoutError:
print("caught: timeout, retryable")
except ModelAuthenticationError:
print("caught: bad key, fix configuration, do not retry")
except ContextOverflowError:
print("caught: prompt too long, trim or summarize, do not retry unchanged")This sample is illustrative: it needs langchain-openai and a key. The absurd timeout is the docs' own trick for provoking a timeout on purpose.
caught: timeout, retryable11.7 Provider prompt caching, from the LangChain side#
Prompt caching (02.7, 03.7 Parts 6 to 8) is the provider reusing the computed prefix of a prompt. It is not the LangChain cache of 11.4, and the two are independent. From LangChain you meet it at three levels:
| Level | What it looks like |
|---|---|
| Implicit (OpenAI, Gemini) | nothing to do: keep stable content at the front of the prompt and the provider caches automatically above a minimum token threshold |
| Explicit provider controls | OpenAI cache options on ChatOpenAI (the models page names prompt_cache_key; the class also has a prompt_cache_options field, so read the OpenAI integration page for current options), Anthropic cache_control markers on content blocks, Gemini's explicit context caching (cached_content), Bedrock cachePoint |
| Middleware | AnthropicPromptCachingMiddleware (from langchain_anthropic.middleware) and BedrockPromptCachingMiddleware add the markers for you inside create_agent (08F.8) |
The Anthropic marker is the one most learners need first. You put cache_control on the content block that ends the stable prefix (here a long system policy), then call twice with the same prefix:
from dotenv import load_dotenv
from langchain.messages import HumanMessage, SystemMessage
from langchain_anthropic import ChatAnthropic
load_dotenv()
LONG_POLICY = "Refund policy, section by section... " * 400 # stand-in for a long, stable policy document
model = ChatAnthropic(model="claude-haiku-5-5", max_tokens=200, max_retries=2, timeout=30)
system = SystemMessage(content=[
{"type": "text", "text": LONG_POLICY, "cache_control": {"type": "ephemeral"}}, # the cache breakpoint
])
for question in ["How long do refunds take?", "Can I refund a gift card?"]:
reply = model.invoke([system, HumanMessage(question)])
print(reply.usage_metadata["input_token_details"])This sample is illustrative: it needs langchain-anthropic and ANTHROPIC_API_KEY. The block shape (cache_control with type ephemeral on a system text block) and the habit of reading input_token_details follow the Anthropic integration page; check the page for options such as a one-hour lifetime (ttl) and for the top-level cache_control argument added in langchain-anthropic 1.4.0, which asks for a breakpoint automatically. The default lifetime is five minutes.
{'cache_read': 0, 'cache_creation': 0, 'ephemeral_5m_input_tokens': 1569, 'ephemeral_1h_input_tokens': 0}
{'cache_read': 1569, 'cache_creation': 0, 'ephemeral_5m_input_tokens': 0, 'ephemeral_1h_input_tokens': 0}Read it as the integration page's own example does: the first call writes the prefix (the write is reported under Anthropic's ephemeral_5m_input_tokens extra, so a missing cache_creation does not mean no write), the second reads it (cache_read equals the prefix size). If the second line shows cache_read of zero, the prefix is below the model's minimum cacheable length, changed between calls, or the five minutes passed.
Caching usually has a minimum input token threshold below which nothing is cached. Check it worked in usage_metadata["input_token_details"]: a non-zero cache_read on the second identical-prefix call means a hit, and cache_creation shows the write. A cache that never reports a read is not saving you anything, whatever the code claims (03.7 Part 10).
11.8 Timeouts and long-running calls#
Set timeout on every model (03.8 Part 6); the SDK defaults are generous, and a hung request holds a worker. For agents that run for minutes on unreliable networks, the docs advise raising max_retries (10 to 15) and using a checkpointer (08F.11), so that a crash or a long outage resumes from the last saved step instead of repeating paid work. Streaming (5.2) is also a reliability tool for long answers: it keeps the connection alive and gives the user progress.
Part 12: What does not port between providers#
Reference
The promise of init_chat_model is "swap the string, keep the code". It is true for plain text in, plain text out. Everything else has an asterisk. This is the part to read before you promise anyone provider independence.
12.1 The comparison table#
Facts verified on 14 November 2026 from the package sources and the integration pages, with the rows marked (15 Nov) re-checked on 15 November 2026 (re-check all of them when you upgrade):
| Aspect | OpenAI (ChatOpenAI) |
Anthropic (ChatAnthropic) |
Google (ChatGoogleGenerativeAI) |
Ollama (ChatOllama) |
|---|---|---|---|---|
| Package | langchain-openai |
langchain-anthropic |
langchain-google-genai (google_vertexai is a different package) |
langchain-ollama |
| Key | OPENAI_API_KEY |
ANTHROPIC_API_KEY |
GOOGLE_API_KEY, then GEMINI_API_KEY |
none |
| API surface | Chat Completions, or Responses (automatic when needed or use_responses_api) |
Messages API | Gemini API | Ollama local API |
| Effective API for one call (15 Nov) | decided per request: Responses for reasoning, include, built-in tools and Responses-only ids, and for any tools on gpt-6* models (the use_responses_api field still prints None) |
always Messages | always Gemini API | always Ollama API |
max_retries default |
None (SDK default applies) |
2 |
6 |
no field |
| Reasoning controls | reasoning_effort, Responses reasoning dict |
thinking={...}, effort |
thinking_level, thinking_budget (2.5) |
reasoning flag |
| To see reasoning text (15 Nov) | reasoning={"effort": ..., "summary": "auto"} |
thinking={"type": "adaptive", "display": "summarized"} on the newest models |
include_thoughts=True |
reasoning=True |
with_structured_output default |
json_schema |
function_calling |
json_schema |
json_schema |
temperature, top_p, top_k |
accepted | non-default values rejected (400) on the newest models | accepted | accepted |
| Usage while streaming | needs stream_usage (automatic only with the default endpoint and HTTP client) |
included | included | included |
| Standard exceptions (15 Nov) | full: 400, 401, 403, 404, 429, 5xx, connection, timeout, overflow | full, plus 529 overloaded | HTTP errors and overflow; no connection or timeout class | none |
| Finish-reason key (5.8) | finish_reason (Chat Completions) or status and incomplete_details (Responses) |
stop_reason |
finish_reason (enum name) |
done_reason |
| Token counting (8.5) | local tiktoken |
Anthropic's count endpoint (network) | Google's count endpoint (network) | GPT-2 fallback, needs transformers |
| Prompt caching | implicit plus cache options | cache_control blocks or middleware |
implicit plus explicit context caching | none |
| Custom endpoint | base_url (official spec only) |
base_url |
proxy and endpoint settings | base_url |
12.2 The things that do not port#
| Thing | What breaks | What to do |
|---|---|---|
| Sampling parameters | temperature, top_p, top_k are rejected by the newest Claude models and ignored or rejected by other frontier models (02.5 Part 6) |
do not set them by default; make them opt-in per model in config |
| Reasoning controls | one reasoning_effort name, but different levels, defaults and visible output per provider |
read model.profile, test per provider, handle empty reasoning blocks |
| Reasoning state in history | signatures and encrypted items from one provider are meaningless to another | store with output_version="v1", drop reasoning when switching (7.3) |
| Structured output | different default mechanism, different schema subsets, different refusal behaviour | pass method= explicitly; see 08F.6 |
| System message position | some providers allow mid-conversation system messages, others do not (the profile has mid_conversation_system_messages) |
keep one system message first |
The name field on messages |
used by some providers, ignored by others | put names in the text |
| Tool-call details | parallel calls, tool_choice values, strict schemas, id formats, how a provider treats a tool with no arguments |
keep tools simple, test each provider, keep parallel_tool_calls explicit |
| Server-side tools | web search and code execution are provider-specific dict tools | isolate behind your own function, per provider |
| Multimodal support | image-only, PDF, audio and video support and limits differ; some need file ids, some accept URLs | check profile flags, handle 400s |
| Prompt caching | different mechanisms and thresholds | measure cache_read per provider |
| Usage accounting | the normalized shape is a convention; adapters can have gaps (streaming usage, missing details) | reconcile against provider dashboards |
| Token counting and context limits | different tokenizers: the same text costs different token counts | count with the provider's counter (03.7 Part 2) |
| Refusals | explicit blocks for some, plain text for others | treat both; see 4.5 |
| Rate limits and error messages | different quotas, headers and wording | the standard exceptions help, but quotas are yours to manage |
| Behaviour | tone, verbosity, instruction following, tool-use habits differ even with identical prompts | an eval set per provider (Module 10A) before any switch |
12.3 Gateways, routers and compatible endpoints#
| Route | Class and install | Use when | Watch out for |
|---|---|---|---|
| OpenRouter | ChatOpenRouter in langchain-openrouter (0.x, Beta on PyPI as of November 2026); init_chat_model("openrouter:vendor/model") |
one key for many models, fast experiments, fallbacks across vendors | the router adds its own latency, fees and data-handling terms (02.9); the package is young, so pin it, and ChatOpenAI(base_url="https://openrouter.ai/api/v1") is the stable fallback for plain chat |
| LiteLLM | ChatLiteLLM, ChatLiteLLMRouter in langchain-litellm (Beta classifier at the time of writing); registry key litellm |
a self-hosted gateway with budgets and routing | another moving part in the request path; see Module 11A |
| OpenAI-compatible server (vLLM, Together, your gateway) | ChatOpenAI(base_url=..., api_key=..., model=...) or init_chat_model(model=..., model_provider="openai", base_url=...) |
self-hosted or third-party OpenAI-format endpoints | extensions to the response are not parsed (2.2); stream_usage is off whenever you pass base_url, a proxy or your own HTTP client, or set OPENAI_BASE_URL (8.3) |
| Local (Ollama) | ChatOllama |
development, privacy, offline | model quality and tool-calling support depend on the local model; set num_ctx |
openai_proxy exists on ChatOpenAI for an HTTP proxy (support varies); for corporate proxies, also check the provider SDK's own proxy settings.
12.4 Escape hatches#
When the common interface does not expose something you need:
- Provider class arguments. Constructors take the provider-only options (
thinking,use_responses_api,cached_content,num_ctx). Pass them throughinit_chat_model(**kwargs)or build the class directly. model.bind(**kwargs)attaches extra call arguments to a copy of the model (5.7).- Block
extras. Standard blocks accept provider-specific keys at the top level or under"extras", and tools can carry provider-specific parameters through anextrasattribute (added inlangchain1.2.0). non_standardblocks carry payloads with no standard type, so nothing is lost even when LangChain cannot classify it (4.2).- Drop to the SDK for the rare call that needs an unreleased flag. A single direct SDK call next to LangChain calls is fine; keep it behind one small function.
12.5 A decision table for provider independence#
| If your situation is... | Then |
|---|---|
| one provider, forever | use that provider's class, enjoy its full feature set, skip the portability work |
| two providers for resilience | keep one primary, test the second with your eval set, wire with_fallbacks, log every failover |
| many providers behind an internal platform | a gateway (12.3) plus contract tests; do not rely on prompts behaving the same |
| a product feature that depends on one provider's unique capability | isolate it behind your own function with a documented fallback behaviour |
Part 13: Testing without a key: fake chat models#
Deep-dive
03.10 argued that no unit test should call a real model, and 08F.1 Part 5.2 listed each framework's fake. LangChain's fakes live in langchain-core, need no key and make no network call, which is why this lesson's samples can run for real.
13.1 The fakes#
Class (import from langchain_core.language_models unless noted) |
Behaviour | Use it for |
|---|---|---|
FakeListChatModel(responses=[...]) |
returns the strings in order and cycles when exhausted | simple tests with canned text |
GenericFakeChatModel(messages=iter([...])) (from langchain_core.language_models.fake_chat_models) |
returns one item per call from an iterator of AIMessage or str; raises StopIteration when it runs out |
scripted multi-turn tests, including tool-call messages |
FakeMessagesListChatModel(responses=[...]) |
returns messages from a list | tests that need full AIMessage objects |
ParrotFakeChatModel |
echoes the last message | checking what your code sent |
FakeListLLM, FakeStreamingListLLM |
the legacy text-LLM fakes | only for legacy code |
Behaviours worth knowing, each confirmed by running the samples in this lesson:
GenericFakeChatModelconsumes its iterator. One reply per call, in order, and aStopIterationwhen the script is exhausted. Create the iterator inside each test (a function-scoped fixture), never at module level, or tests will interfere with each other.FakeListChatModelcycles, so a test that makes more calls than you scripted keeps passing with repeated answers. PreferGenericFakeChatModelwhen the exact number of calls matters, because an overrun fails loudly.- Streaming works. The
GenericFakeChatModeldocstring says streaming "is not implemented yet", but the source implements_streamby chunking the invoke result (as the 5.2 sample shows). GenericFakeChatModeldoes not implementbind_tools.with_structured_outputandcreate_agentneed it. The documented fix is to subclass it withdef bind_tools(self, tools, **kwargs): return self, as the 9.2 sample does.- Fakes do not exercise provider behaviour. They cannot tell you whether your tool schema is acceptable to a provider, how reasoning blocks look, or how rate limits feel. They test your code.
13.2 Unit tests for model-calling code#
Design the function under test to receive the model (dependency injection, 03.10 Part 6), then hand it a fake. The sample defines a small classifier and four tests, runs them, and prints the results:
"""Key-free unit tests for model-calling code, written as plain functions pytest would collect."""
from typing import Any
from langchain.messages import AIMessage, HumanMessage
from langchain_core.language_models import BaseChatModel, FakeListChatModel
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
def classify_ticket(model: BaseChatModel, text: str) -> str:
"""The code under test: ask a model for a one-word label and normalise it."""
reply = model.invoke([("system", "Reply with one word: billing, bug or other."), ("human", text)])
label = reply.text.strip().lower().rstrip(".")
return label if label in {"billing", "bug", "other"} else "other"
def test_returns_known_label() -> None:
model = FakeListChatModel(responses=["Billing."])
assert classify_ticket(model, "I was charged twice") == "billing"
def test_unknown_label_falls_back_to_other() -> None:
model = FakeListChatModel(responses=["spam"])
assert classify_ticket(model, "buy now") == "other"
def test_one_scripted_reply_per_call() -> None:
model = GenericFakeChatModel(messages=iter(["bug", AIMessage("billing")])) # fresh iterator per test
assert [classify_ticket(model, "x"), classify_ticket(model, "y")] == ["bug", "billing"]
def test_exhausted_script_fails_loudly() -> None:
model = GenericFakeChatModel(messages=iter(["bug"]))
classify_ticket(model, "x")
try:
classify_ticket(model, "y")
except StopIteration:
return
raise AssertionError("expected the script to run out")
tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
for t in tests:
t()
print("PASS", t.__name__)PASS test_exhausted_script_fails_loudly
PASS test_one_scripted_reply_per_call
PASS test_returns_known_label
PASS test_unknown_label_falls_back_to_otherWith pytest the same tests are collected automatically and the model comes from a fixture. This illustrative fragment shows the fixture pattern (it needs pytest, installed with uv add --dev pytest):
import pytest
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
@pytest.fixture
def scripted_model():
# function scope (the default): a fresh iterator for every test
return GenericFakeChatModel(messages=iter(["billing", "bug"]))
def test_two_calls(scripted_model):
assert scripted_model.invoke("a").text == "billing"
assert scripted_model.invoke("b").text == "bug"The fragment is illustrative only because it needs pytest, which this lesson did not install.
What to test with fakes:
- Prompt construction: which messages did your code send (use
ParrotFakeChatModel, or a fake subclass that records its input). - Parsing and normalization of replies, including odd shapes: reasoning blocks, empty text, tool-call-only replies,
usage_metadata=None. Theunpackhelper in 4.5 is a good target. - Error handling: a fake that raises (as
FlakyModeldoes in 11.5) tests your retry and fallback wiring without waiting for real failures. - Loop budgets and stopping conditions in agent code.
What fakes cannot test, you cover with a small suite of real-provider smoke tests, marked and excluded from the default run (03.10 Part 12), plus evaluation datasets (Module 10A, 11A.5).
Part 14: Legacy, and how to read old tutorials#
Reference
Most LangChain content on the internet predates v1.0 (October 2025). It teaches APIs that no longer exist at those paths. Use this table to translate; every row says what replaced it, and the sample below proves which ones fail today.
| In an old tutorial | What happens in langchain 1.x |
Write this instead |
|---|---|---|
from langchain.chat_models import ChatOpenAI |
ImportError |
from langchain_openai import ChatOpenAI, or init_chat_model("openai:...") |
from langchain.llms import OpenAI |
ModuleNotFoundError |
a chat model class; the legacy text-completion classes are not what you want |
from langchain_community.chat_models import ChatOpenAI |
the community copies are legacy | the partner package (langchain-openai, langchain-anthropic, ...) |
from langchain.schema import HumanMessage |
ModuleNotFoundError (the old module moved to langchain-classic) |
from langchain.messages import HumanMessage |
llm.predict("text"), llm.predict_messages([...]) |
the methods are gone | model.invoke(...) and .text |
llm("text"), chat(messages) (calling the object) |
gone | model.invoke(...) |
llm.generate([...]) returning an LLMResult |
still present, rarely needed | invoke, batch |
response.text() |
works with a deprecation warning, removed in langchain-core 2.0 |
response.text |
| a string returned from the call | you used a legacy text LLM class (BaseLLM) |
a chat model class (names start with Chat), which returns AIMessage |
AIMessage(example=...) |
removed in v1 | drop the argument |
ChatAnthropic relying on max_tokens defaulting to 1024 |
the default is model-dependent now | set max_tokens explicitly |
Responses API items found in additional_kwargs |
now in content by default |
output_version="v0" restores the old layout |
import warnings
from langchain.messages import AIMessage
from langchain_core.language_models import FakeListChatModel
# 1. Pre-1.0 import paths, as old tutorials write them.
for statement in [
"from langchain.chat_models import ChatOpenAI",
"from langchain.llms import OpenAI",
"from langchain.schema import HumanMessage",
]:
try:
exec(statement)
print("works :", statement)
except (ImportError, ModuleNotFoundError) as exc:
print("fails :", statement, "->", type(exc).__name__)
# 2. Pre-1.0 call styles on a chat model object.
model = FakeListChatModel(responses=["ok"])
for method in ["predict", "predict_messages", "__call__", "invoke", "generate"]:
print(f"{method:17}", "present" if hasattr(model, method) else "gone")
# 3. The old .text() method form still returns the text, but warns.
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
value = AIMessage("hello").text()
print("text() returned", repr(value), "| warning:", type(caught[0].message).__name__)fails : from langchain.chat_models import ChatOpenAI -> ImportError
fails : from langchain.llms import OpenAI -> ModuleNotFoundError
fails : from langchain.schema import HumanMessage -> ModuleNotFoundError
predict gone
predict_messages gone
__call__ gone
invoke present
generate present
text() returned 'hello' | warning: LangChainDeprecationWarningRules for reading old material safely:
- Check the date and the imports first.
langchain.llms,langchain.schema,LLMChain,AgentExecutor,initialize_agentandConversationBufferMemoryall mark pre-1.0 code (the agent and chain replacements are in 08F.6, 08F.7, 08F.8 and 08F.15). - Translate the concept, not the code. The idea (messages in, message out) is unchanged; the spelling is.
- Old code can still run. Legacy chains,
AgentExecutor, memory classes and the old retrievers moved to thelangchain-classicpackage, and deprecated features keep working through the whole 1.x series. That is a migration bridge, not a recommendation: new code uses the current APIs. - Beware the two functions named
create_react_agent. One is the old text-ReAct factory used withAgentExecutor(now inlangchain-classic); the other islanggraph.prebuilt.create_react_agent, deprecated in favour oflangchain.agents.create_agent(08F.8).
Part 15: Putting it together: one provider-neutral model module#
Here is the shape of a model module you can reuse across a project. It reads the model id and limits from configuration, applies one retry policy, a rate limiter and an optional fallback, extracts the text safely, and logs usage per call. The code uses only what this lesson verified; the model ids come from the environment, never from the source.
Put this in llm.py:
import importlib
import logging
import os
import time
from typing import Any
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain.messages import AIMessage
from langchain.rate_limiters import InMemoryRateLimiter
from langchain_core.exceptions import (
ContextOverflowError, ModelAPIError, ModelConnectionError, ModelRateLimitError, ModelTimeoutError,
)
from langchain_core.language_models import BaseChatModel
load_dotenv()
log = logging.getLogger("llm")
# Google and Ollama raise raw transport errors (not ModelError) for network drops and timeouts, so name them too
# (11.1). langchain-ollama uses httpx; google-genai raises its own httpx2 copy at the versions in the Versions line.
_TRANSPORT = []
for _name in ("httpx", "httpx2"):
try:
_TRANSPORT.append(importlib.import_module(_name).TransportError)
except ImportError:
pass
RETRYABLE = (ModelRateLimitError, ModelAPIError, ModelConnectionError, ModelTimeoutError, *_TRANSPORT)
# One limiter per provider quota, shared by every model object built here.
_LIMITER = InMemoryRateLimiter(requests_per_second=float(os.getenv("LLM_RPS", "2")), max_bucket_size=2)
def build_model(spec_env: str = "LLM_MODEL", fallback_env: str = "LLM_FALLBACK_MODEL") -> Any:
"""Build the primary model (and an optional fallback) from environment variables.
LLM_MODEL=anthropic:claude-haiku-5-5 LLM_FALLBACK_MODEL=openai:gpt-6-luna
"""
def make(spec: str) -> BaseChatModel:
return init_chat_model(
spec,
max_tokens=int(os.getenv("LLM_MAX_TOKENS", "800")),
timeout=float(os.getenv("LLM_TIMEOUT", "30")),
max_retries=0, # the SDK layer is off: with_retry below owns the policy (ChatOllama ignores this)
rate_limiter=_LIMITER,
)
primary = make(os.environ[spec_env]).with_retry(retry_if_exception_type=RETRYABLE, stop_after_attempt=3)
fallback_spec = os.getenv(fallback_env)
if not fallback_spec:
return primary
backup = make(fallback_spec).with_retry(retry_if_exception_type=RETRYABLE, stop_after_attempt=2)
# Fall back only on outage-type errors and on context overflow, never on 400 or refusals. Caveat: the overflow
# case only helps if the backup has the larger window, so choose it by profile["max_input_tokens"] (11.2).
return primary.with_fallbacks([backup], exceptions_to_handle=RETRYABLE + (ContextOverflowError,))
def text_of(message: AIMessage) -> str:
"""Join the text blocks; ignore reasoning, tool calls and any block type we do not know."""
return "".join(b["text"] for b in message.content_blocks if b["type"] == "text")
def ask(model: Any, messages: list, **context: str) -> str:
"""One call with a usage log line. `context` (ticket_id, tenant, ...) goes to traces and logs."""
started = time.perf_counter()
reply: AIMessage = model.invoke(messages, config={"tags": ["llm.ask"], "metadata": dict(context)})
usage = reply.usage_metadata or {}
meta = reply.response_metadata
log.info(
"llm call model=%s in=%s out=%s cache_read=%s finish=%s seconds=%.2f %s",
meta.get("model_name"),
usage.get("input_tokens"),
usage.get("output_tokens"),
usage.get("input_token_details", {}).get("cache_read", 0),
meta.get("finish_reason") or meta.get("stop_reason") or meta.get("done_reason"), # the keys of 5.8
time.perf_counter() - started,
context,
)
return text_of(reply)And a caller, main.py:
import logging
from llm import ask, build_model
logging.basicConfig(level=logging.INFO)
model = build_model()
answer = ask(
model,
[("system", "You write one-sentence summaries."),
("human", "Ticket: refund for order A-1042 has not arrived after 10 days.")],
ticket_id="T-5521",
)
print(answer)This module is illustrative: it needs langchain-openai and langchain-anthropic for the example ids, valid keys, and LLM_MODEL (and optionally LLM_FALLBACK_MODEL) in .env. The pieces were each tested above against fake models or a dead local port (rate limiter, retry, fallback, transport-error retries, text extraction, usage helper).
INFO:llm:llm call model=claude-haiku-5-5 in=31 out=22 cache_read=0 finish=end_turn seconds=1.12 {'ticket_id': 'T-5521'}
Refund for order A-1042 has not arrived after 10 days and needs investigation.One portability gap the module does not hide: if LLM_MODEL points at Ollama, the max_tokens, timeout and max_retries arguments are silently ignored by ChatOllama (2.3), so a real module would branch on the provider for those three (num_predict, client_kwargs).
What it leaves out for readability (and a real service would add): per-tenant budgets and cost lines (use the 8.4 helper), prompt versioning (Module 04), caching strategy (Module 11A), input validation and injection defences (Module 12), structured output (08F.6), tools (08F.8), and tracing configuration (11A.5).
Common misconceptions#
| Misconception | Reality |
|---|---|
"init_chat_model makes my code provider-independent." |
It makes construction uniform. Sampling parameters, reasoning controls, structured-output mechanisms, caching, multimodal support and behaviour still differ (Part 12). Independence is something you test, not something you import. |
"response.content is the answer string." |
It is a string only for plain text. With reasoning, tool calls or citations it is a list. Use response.text, or branch on content_blocks types (4.1). |
"content_blocks replaces content." |
It is a lazily computed standard view on top of content. content still holds what the provider returned unless you opt in to output_version="v1" (4.4). |
"message.text() is how you get the text." |
That is the pre-1.0 method form. It warns now and is removed in langchain-core 2.0; .text is a property (3.2). |
"google-genai:gemini-... and gemini-... both reach the Gemini API." |
The hyphenated prefix fails, and the bare gemini name resolves to Vertex AI today. Use google_genai: (2.1). |
"max_retries defaults to 6 everywhere." |
It depends on the class: None (SDK default) for ChatOpenAI, 2 for ChatAnthropic, 6 for ChatGoogleGenerativeAI. Set it explicitly (2.3). |
"model.batch(...) uses the providers' cheap Batch APIs." |
It runs ordinary requests in parallel threads at full price. Use the provider Batch APIs (03.9) for discounted offline jobs (5.4). |
"with_retry retries only transient errors." |
The default retries every exception, including a 400 and a bad key. Restrict retry_if_exception_type (11.2). |
"The standard Model...Error classes cover every provider, so my retry list is complete." |
OpenAI and Anthropic map connection errors and timeouts; Google does not, and Ollama maps nothing, so a restricted with_retry or with_fallbacks silently skips their network failures (11.1, 11.2). |
"ChatOpenAI uses Chat Completions until I ask for Responses." |
The use_responses_api=None default means "decide per request": reasoning options, built-in tools, Responses-only ids and, on gpt-6* models in 1.8.0, any bound tool switch it (2.7). |
"Setting reasoning_effort (or adaptive thinking) shows me the model's reasoning." |
Each provider also needs a switch for the text: a Responses reasoning summary, display="summarized" on the newest Claude models, include_thoughts=True on Gemini. Reasoning tokens are billed either way (7.2). |
| "If the call returned, the answer is complete." | A reply cut off by max_tokens is a normal-looking reply; read the finish reason in response_metadata (5.8). |
"SDK retries plus with_retry is extra safety." |
It multiplies attempts and cost. One layer should own retries (11.1). |
| "The LangChain cache and prompt caching are the same thing." | The LangChain cache stores whole replies in your process and is skipped by streaming. Prompt caching is the provider reusing a prompt prefix and shows up in cache_read (11.4, 11.7). |
| "The rate limiter protects my token quota." | InMemoryRateLimiter counts requests, not tokens, and only inside one process (11.3). |
| "A model profile says what the model definitely supports." | It is beta metadata from a dataset. The Claude Haiku 5.5 profile says structured_output: False while with_structured_output works (2.6). |
"usage_metadata always has cache and reasoning details." |
Only the three totals are guaranteed to exist when usage is present, and usage itself can be None (8.1). |
| "Streaming gives me usage and caching for free." | Usage while streaming depends on the provider and flags (stream_usage), and the LangChain cache never applies to streaming (8.3). |
| "Fake models behave like real ones." | They are great for testing your code and useless for testing provider behaviour; FakeListChatModel cycles, GenericFakeChatModel has no bind_tools, and some fakes ignore max_concurrency (Part 13). |
"Any tutorial that says LangChain is current." |
Pre-1.0 imports such as langchain.llms and langchain.schema fail today (Part 14). |
Key takeaways#
- A chat model is a
Runnablefrom messages toAIMessage. Every provider class (ChatOpenAI,ChatAnthropic,ChatGoogleGenerativeAI,ChatOpenRouter,ChatOllama, ...) inheritsBaseChatModel, so the sameinvoke,stream,batchand async methods, rate limiter, cache and retry wrappers work everywhere. - Create models with
init_chat_model("provider:model"), using the registry key before the colon (google_genai, with an underscore). Bare-name inference is best effort and sendsgemini...to Vertex AI. Use the provider class when you need provider-only arguments. - Set
max_retries,timeoutandmax_tokensexplicitly. Themax_retriesdefault differs by package (None, 2, 6) and a Claudemax_tokensdefault is a large ceiling, not a sensible limit. Do not addtemperatureout of habit: the newest Claude models reject it. - Messages are data. Append the whole
AIMessage(it carries tool calls, reasoning blocks and signatures), matchToolMessage.tool_call_idto the call id, useartifactfor what only your code needs, and treattrim_messagesas a blunt budget tool. - Read replies with
.textorcontent_blocks, and branch ontype. Standard blocks (text,reasoning,tool_call,image,file,refusal,server_tool_call,non_standard, ...) normalize provider dialects, and new types will appear, so ignore what you do not know. batchis client-side parallelism, not a provider Batch API. Chunks add with+. Streamed tool-call arguments are partial JSON until merged, and thelangchain-core1.7 change affects code that readstool_callsmid-stream.- Usage is normalized:
input_tokensincludes cached tokens,output_tokensincludes reasoning, detail keys are optional subsets. Log it per call and reconcile with the provider dashboard. - Reliability has four layers (SDK retries,
with_retry,with_fallbacks, agent middleware). Let one own retries, restrict retried exceptions to the retryable family plus the transport errors that Google and Ollama raise unclassified, rate-limit requests (and budget tokens separately), and know that the LangChain cache and prompt caching are different things. - Read why the model stopped.
response_metadatacarries a provider-specific finish reason (length,max_tokens,MAX_TOKENS,incomplete); a truncated reply is the commonest silent failure. Count tokens before the call with the model's own method, and remember that for Claude and Gemini that is a network request. - Know which OpenAI API you are on and how to see reasoning. The
use_responses_api=Nonedefault is decided per request (any tool ongpt-6*models in 1.8.0 switches it), and each provider needs an explicit switch to return reasoning text. with_structured_outputdefaults differ:json_schemafor OpenAI, Google and Ollama,function_callingfor Anthropic (as of the checked versions). Passmethod=explicitly and handleModelRefusalError; the full treatment is 08F.6.- Test with fakes:
FakeListChatModel,GenericFakeChatModel(addbind_toolsby subclassing), and a flaky subclass for retry wiring. Keep a small real-provider smoke suite for what fakes cannot test. - Provider independence is a test result. Keep an evaluation set, run it per provider, and isolate the unique features behind your own functions.
- Old tutorials use paths that no longer exist (
langchain.llms,langchain.schema,predict,llm(...)). Translate the concept and import from the partner packages andlangchain.messages.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Chat model | An object (a BaseChatModel subclass, such as ChatOpenAI) that takes messages and returns an AIMessage through the Runnable interface |
BaseChatModel |
The langchain-core base class that gives every provider class invoke, stream, batch, async methods, rate_limiter, cache and disable_streaming |
init_chat_model |
A factory in langchain.chat_models that builds a chat model from "provider:model", model_provider= or an inferred name |
| Provider registry | The built-in map of provider keys (openai, anthropic, google_genai, ...) to integration classes that init_chat_model consults; not exhaustive |
| Configurable model | An init_chat_model result whose model and settings are chosen per call through config["configurable"], controlled by configurable_fields and config_prefix |
| Model profile | Beta capability and limit metadata on model.profile (context size, modalities, reasoning effort levels), shipped with the provider package |
AIMessage / HumanMessage / SystemMessage / ToolMessage |
LangChain's message classes for assistant, user, system and tool-result turns |
RemoveMessage |
A message that tells a reducer or middleware to delete the message with a given id |
tool_call_id |
The id on a ToolMessage that must match the id of the tool call it answers |
artifact (on ToolMessage) |
Data attached to a tool result for downstream code and not sent to the model |
content / content_blocks / .text |
The raw payload, the standard typed view of it, and the joined text of an AIMessage |
| Standard content block | A typed dictionary (text, reasoning, tool_call, image, file, refusal, ...) that normalizes provider-specific content |
non_standard block |
The escape-hatch block that wraps a provider payload with no standard type |
output_version |
"v0" (provider format) or "v1" (standard blocks stored in content); set on the model or with LC_OUTPUT_VERSION |
AIMessageChunk |
A streamed fragment of an AIMessage; chunks combine with + and the last has chunk_position == "last" |
batch / batch_as_completed |
Client-side parallel calls over a list of inputs, in input order or in completion order with the index |
astream_events |
An async event stream (version="v2") reporting start, stream and end events for a model or a whole chain |
RunnableConfig |
The per-call configuration dict (run_name, tags, metadata, callbacks, max_concurrency, recursion_limit) |
bind |
Returns a copy of a runnable with extra call arguments pre-filled, without changing the original |
reasoning_effort |
The standard parameter for how much a reasoning model thinks, with provider aliases effort and thinking_level |
UsageMetadata |
The normalized token-usage dictionary on an AIMessage (input_tokens, output_tokens, total_tokens, optional detail breakdowns) |
get_usage_metadata_callback |
A context manager that aggregates usage_metadata across calls and models, keyed by model name |
bind_tools |
Returns a model runnable that sends tool schemas with each call; replies list requests in .tool_calls |
| Server-side tool call | A tool the provider executes itself, reported as server_tool_call and server_tool_result blocks |
with_structured_output |
Returns a runnable that yields parsed data (Pydantic object, TypedDict or dict) instead of an AIMessage; takes method and include_raw |
ModelRefusalError |
The exception raised in place of a parsing error when a model refuses a structured request |
with_retry / with_fallbacks |
Runnable wrappers that retry on chosen exceptions and fall back to other runnables |
InMemoryRateLimiter |
An in-process, thread-safe token-bucket limiter on request count, passed as rate_limiter= |
| LangChain cache | The reply cache (cache= or set_llm_cache) keyed by prompt and model settings; not used for streaming; unrelated to provider prompt caching |
| Standard model exceptions | The langchain_core.exceptions family (ModelRateLimitError, ModelTimeoutError, ContextOverflowError, ...) with an is_retryable flag |
response_metadata |
The provider's own envelope on an AIMessage (model name, ids, finish reason); keys differ per provider, so read it for diagnostics such as truncation, not for business logic |
| Finish reason | The provider's statement of why generation stopped (finish_reason, stop_reason, done_reason, or status with incomplete_details); length, max_tokens and MAX_TOKENS mean the output cap was hit |
get_num_tokens_from_messages |
A chat model method that counts input tokens before a call; local for OpenAI, a network call for Anthropic and Google, a GPT-2 fallback (needs transformers) elsewhere |
GenericFakeChatModel / FakeListChatModel |
Key-free fake chat models for tests; one scripted reply per call, or canned replies that cycle |
All terms are also collected in the glossary.
Exercises#
- Four input forms: adapt the 3.1 sample so each of the four forms is sent to a recording fake (subclass
FakeListChatModeland override_generateto store themessagesit receives), then print what the model received for each form. Which forms produce identical messages? Which one cannot carry a system message? As a second route, printconvert_to_messages(payload)for each form and compare. - Reply unpacker: extend the
unpackhelper from 4.5 to handleimageblocks (collectmime_type) andrefusalblocks (collect the text), then write four tests with fake messages: text only, reasoning plus text, tool call only, and a made-up block type"hologram". The unknown type must land inother_block_types, not crash. - Trim without breaking tools: build a 12-message history that includes an assistant tool call and its
ToolMessagein the middle. Trim it withtrim_messages(..., strategy="last", start_on="human", include_system=True)at severalmax_tokensvalues usingtoken_counter="approximate". Can you find a budget where the result starts with an orphanedToolMessage? Write a validator that checks everyToolMessagehas a matching earliertool_callsid. - Retry arithmetic: a service sets
ChatOpenAI(max_retries=2)and wraps it inwith_retry(stop_after_attempt=4)andwith_fallbacks([backup])where the backup has the same settings. When both providers are down, how many HTTP requests does oneinvokemake? Redesign the settings so the worst case is at most 6 requests and the exceptions retried are only the transient ones. - Flaky wiring test: using the
FlakyModelpattern from 11.5, write tests proving that (a) aModelRateLimitErroris retried, (b) aModelInvalidRequestErroris not retried when you pass the restrictedretry_if_exception_type, and (c) the fallback is used when the primary raisesModelAPIErrorbut not when it raisesModelAuthenticationError. (Construct the exceptions with a message string.) - Cost helper audit: feed the
cost_usdhelper from 8.4 a reply whoseusage_metadatahas noinput_token_details, one whose details sum to more thaninput_tokens, andusage_metadata=None. Decide what each case should do in production (raise, log and skip, estimate) and change the helper accordingly. - Provider swap experiment (needs two keys): write 10 realistic prompts for one task of yours (for example ticket triage). Run them through
build_model()from Part 15 against two providers withLLM_MODELchanged. Diff the outputs, token counts and cost. List three differences you did not expect, and decide whether they would break your product. - Configurable allow-list: implement a function
pick_model(user_tier: str)that returns the right model for"free"and"pro"usinginit_chat_modelwithconfigurable_fields=("model",)and an allow-list dictionary in your code. Show that a request body trying to setmodelto an arbitrary string, orbase_url, cannot change the model. - Truncation guard: extend
was_truncatedfrom 5.8 into aguarded_invoke(model, messages)that retries once withmax_tokensdoubled (usemodel.bind(max_tokens=...)or build a second model) when the first reply was cut off, and raises a clear error if the second one is cut off too. Test it with a scripted fake that returns a truncatedAIMessagefirst (metadata{"finish_reason": "length"}) and a complete one second. - Dead-port audit: reproduce the 11.2 dead-port run for
ChatOllamaandChatOpenAI, then addwith_fallbacks([backup], exceptions_to_handle=STANDARD)with a fake backup. Which primary triggers the fallback and which does not? Fix it, and write down which exception classes you checked for each provider you actually use.
Answers
- Do not use
ParrotFakeChatModelfor this: it echoes only the last message, so every form prints just the human text and the system message is never visible. A recording fake shows everything:class Recorder(FakeListChatModel)with aseen: list = []field anddef _generate(self, messages, *args, **kwargs): self.seen.append(messages); return super()._generate(messages, *args, **kwargs). Run against the four forms it records[('system', ...), ('human', ...)]for the objects, dicts and tuples forms (identical afterconvert_to_messages, which returnsTruewhen you compare them) and[('human', ...)]for the plain string, which is a singleHumanMessageand cannot carry a system message (use the list forms when you need one). Differences between forms are cosmetic: all reach the model as typed messages. - Add branches
elif kind == "image": images.append(block.get("mime_type"))andelif kind == "refusal": refusals.append(block.get("refusal", ""))and return those lists. For thehologramtest buildAIMessage(content=[{"type": "hologram"}], response_metadata={"model_provider": "anthropic"}); an unknown native block arrives asnon_standard, so assert"non_standard" in result["other_block_types"]. The robustness lesson is the same either way: never raise on an unknowntype. - With a tight budget and
strategy="last", a cut can land between the assistant message and its tool result.start_on="human"prevents the result from starting with a tool message in the usual case, so you may need an unusual history (for example consecutive tool messages) orstart_on=Noneto see the failure. The validator: walk the list keeping a set of seentool_callsids fromAIMessages and fail on anyToolMessagewhosetool_call_idis not in the set. max_retries=2means up to 3 requests per attempt, 4 attempts gives 12 requests on the primary, and the backup (same settings, if it is also wrapped) adds up to 12 more, so 24 in the worst case. A bounded design:max_retries=0on both classes,with_retry(retry_if_exception_type=RETRYABLE, stop_after_attempt=3)on the primary andstop_after_attempt=3on the backup gives at most 6 requests, and only transient errors are retried.- Subclass the fake so
_generateraises the chosen exception for the first N calls, as in 11.5. (a) WithRETRYABLEandstop_after_attempt=3, twoModelRateLimitErrors then success givescalls == 3. (b) AModelInvalidRequestErroris not inRETRYABLE, socalls == 1and the error propagates. (c)with_fallbacks([backup], exceptions_to_handle=RETRYABLE)returns the backup's answer forModelAPIErrorand re-raisesModelAuthenticationError. - Reasonable policies: missing details are fine (treat as zero); details larger than
input_tokensis an adapter bug, so raise or log an error and record the cost as unknown rather than negative;usage_metadata=Noneshould log the call as "usage unknown" and never count as free. Whatever you choose, make cost dashboards show the unknown count. - Common surprises: different token counts for the same text, different verbosity, different handling of the system message, a refusal on one provider only, and different caching behaviour. The point is that the answer comes from your own data, not from the abstraction.
- Build the model once with
configurable_fields=("model",), and keepALLOWED = {"free": "openai:gpt-6-luna", "pro": "anthropic:claude-sonnet-5-5"}. Look up the model fromuser_tierin your code and pass only that value inconfig["configurable"]. A field not inconfigurable_fields(such asbase_url) is not configurable, and request-supplied model names never reachconfigbecause only your dictionary's values do. - Wrap the call:
reply = model.invoke(messages); ifwas_truncated(reply), callmodel.bind(max_tokens=2 * current).invoke(messages)once (keep the current cap in a variable so the doubling is explicit) and check again, raisingRuntimeError("answer truncated twice")if it is still cut off. In the test, the scripted fake's second reply carries{"finish_reason": "stop"}, so the helper returns it and the fake has been called exactly twice. Remember to log both attempts' usage, because the first, wasted attempt is still billed. ChatOpenAIraisesOpenAIConnectionError, aModelConnectionError, so the standard tuple triggers the fallback.ChatOllamaraises a plainhttpx.ConnectError, which is in neither the standard tuple norModelError, so the fallback is skipped and the exception propagates. The fix isexceptions_to_handle=STANDARD + (httpx.TransportError,)(or theNETWORKtuple of 11.2 when Google is involved). Record your findings per provider; the point of the exercise is the habit of provoking each error once.
Check yourself#
- What is a
BaseChatModel, and what doesinvokereturn?Thelangchain-corebase class of every chat model integration (Chat...classes). It is aRunnabletaking a string, messages or aPromptValue, andinvokereturns anAIMessage. - Why should you write
google_genai:gemini-...rather thangemini-...orgoogle-genai:gemini-...?The registry key isgoogle_genaiwith an underscore; the hyphenated prefix is not recognized and raises "Unable to infer model provider", and a baregemininame resolves to Vertex AI today (with a deprecation warning). - Name four things the provider string and
init_chat_modeldo not guarantee when you swap providers.Any four of: sampling parameters accepted, reasoning controls and levels, structured-output mechanism and schema limits, caching, multimodal support, tool-calling details,namefield behaviour, usage reporting while streaming, refusals, behaviour and tone. - What is the difference between
message.content,message.content_blocksandmessage.text?contentis the raw payload (string or list of blocks);content_blocksis the lazily computed standard typed view;textis the joined text of the text blocks, as a property. - Why must you append the whole
AIMessageto history after a tool call or a reasoning reply?Tool calls, reasoning blocks and provider signatures live in the message; dropping them leaves orphanToolMessages and breaks reasoning continuity, producing 400s or worse answers. - What is
ToolMessage.artifactfor?It carries data for your own code (for example the source documents behind a retrieval answer) that must not be sent to the model. - What does
batchdo, and what does it not do?It runs ordinary requests in parallel (client-side, threads, optionally capped bymax_concurrency) and returns them in order; it is not the discounted asynchronous provider Batch APIs. - Why is the
langchain-core1.7 tool-call-streaming change a risk for some code?Fromlangchain-core1.6.13, iteratingtool_callson a streamed message yields only the new part of each call's arguments, so code that expected the arguments so far gets fragments; accumulate chunks and read the merged message instead. - In
usage_metadata, iscache_readadded toinput_tokensor part of it? Andreasoningversusoutput_tokens?Both are parts of the totals:cache_readandcache_creationare subsets ofinput_tokens, andreasoningis a subset ofoutput_tokens. Do not add them again. - What is wrong with
model.with_retry(stop_after_attempt=3)on a model that also hasmax_retries=2?Layers multiply (up to 3 x 3 = 9 requests), andwith_retry's default retries every exception, including 400 and 401. Keep one retry owner and restrict the retried exceptions (and check that the provider's network errors are in the list, 11.1). - What does
InMemoryRateLimiterlimit and what does it not, and why doesstream()never hit the LangChain cache?It limits the request rate (a token bucket) within one process and one object; it does not limit request size or tokens per minute, and does not coordinate across processes. Separately, caching "is not currently supported for streaming methods";stream()always calls the model, while a cache hit applies toinvokeandbatch. - Which exception tells you retrying is pointless because the prompt is too long, which tells you the key is wrong, and which connection failures are not mapped to the standard hierarchy (so a restricted
with_retrymisses them)?ContextOverflowError(not retryable) andModelAuthenticationError(not retryable). Google and Ollama network drops and timeouts arrive as the transport library's own exceptions (httpxerrors, or anhttpx2copy for Google), notModelConnectionErrororModelTimeoutError, so a tuple limited to theModel...family does not match them: addhttpx.TransportError(andhttpx2.TransportErrorwhen present) to the retry and fallback tuples, or keep the SDK retry layer on where it exists. - Why does
GenericFakeChatModelneed a subclass before you can usebind_toolswith it?The stock fake does not implementbind_tools; the documented workaround is a subclass whosebind_toolsreturnsself. - A tutorial does
from langchain.llms import OpenAIandllm.predict("hi"). What happens today, and what do you write instead?langchain.llmsdoes not exist inlangchain1.x (ModuleNotFoundError) andpredictis gone. Use a chat model (from langchain_openai import ChatOpenAIorinit_chat_model("openai:...")) andmodel.invoke("hi").text. - Where do you read that a reply was cut off by
max_tokens, and why is a missing reasoning block not proof that the model did not reason?Inresponse_metadata:finish_reason == "length"(OpenAI Chat Completions),status == "incomplete"withincomplete_details["reason"] == "max_output_tokens"(OpenAI Responses),stop_reason == "max_tokens"(Anthropic),finish_reason == "MAX_TOKENS"(Google),done_reason == "length"(Ollama). Reasoning text is only returned when you request it (a Responsesreasoningsummary,display="summarized"on the newest Claude models,include_thoughts=Trueon Gemini), while the reasoning tokens are billed and counted inoutput_token_details["reasoning"]regardless.
Further resources#
Official documentation (verified 14 November 2026). The official docs are more complete than this lesson on integrations (every provider has its own page with parameters, caveats and examples), so read the page for each provider you use:
- Models: the page this lesson follows (parameters, invocation, structured output, profiles, reasoning, rate limiting, caching, configurable models)
- Messages: message types, standard content blocks, the block reference, serialization
- Providers and models (concepts): note the hyphenated
google-genai:prefix there fails per 2.1 - Chat integrations index and the provider pages for OpenAI, Anthropic, Google Generative AI, Ollama and Bedrock
- Structured output (the subject of 08F.6)
- Unit testing: fake chat models and in-memory checkpointers
- Changelog: read it before upgrading; this area moves weekly
- API reference:
init_chat_model,BaseChatModel,AIMessage - Source:
langchain-corein the langchain monorepo; when a docs page and the behaviour disagree (as withmax_retries), the source and a five-line test are the authority - Packages on PyPI:
langchain,langchain-core,langchain-openai,langchain-anthropic,langchain-google-genai - Back in the course: 03.2 Messages and conversations, 03.8 Errors and retries, 03.10 Debugging and testing, 08F.1 Agent frameworks
- The dedicated closing lesson 08F.17 maps the whole official documentation and tells you how to keep current
← 08F.4: The LangChain Ecosystem and Your Setup | Module 08F overview | 08F.6: Prompts, Output Parsers and Structured Output →