Chat Models, Messages and Content Blocks
Every provider integration is a `BaseChatModel` that takes messages and returns an `AIMessage`, so swapping providers is mostly configuration. Know how `init_chat_model` picks a provider and makes models configurable, what each message class is for, how `content` differs from the standard `content_blocks` view, where token usage lives, and how streamed chunks merge.
Key points
- 1
Chat models take a string, a list of messages (message objects,
(role, text)tuples or role/content dicts) or aPromptValue, and return anAIMessage. A bare dict is rejected. Legacy text-completion LLMs take and return strings. - 2
init_chat_model(fromlangchain.chat_models) accepts"provider:model", a bare name plusmodel_provider=, or a bare name whose prefix it can infer (claude...toanthropic,gpt-...toopenai). Precedence: explicitmodel_provider(the string is then not split), then a knownprovider:prefix, then name inference, thenValueError. - 3
Each provider class lives in its own partner package (
langchain-anthropic,langchain-openai,langchain-aws,langchain-google-genai,langchain-ollamaand so on). A missing package raisesImportErrornaming the package. - 4
Configurable models: with no
model,modelandmodel_providerare configurable by default.configurable_fields=(...)is an allowlist, andconfig_prefix="writer"makes the keyswriter_model,writer_temperatureand so on. The real model is built on each call, so errors such as a missing package surface on the firstinvoke. - 5
Message classes:
SystemMessage(instructions),HumanMessage(user input, text or multimodal blocks),AIMessage(model output, also built by hand to replay history) andToolMessage(a tool result, with a requiredtool_call_idand an optionalartifactthat is not sent to the model). In dicts,usermaps to human andassistantto AI. - 6
contentis the provider's raw payload: a string or a list of provider-shaped blocks.content_blocksis a lazily computed standard view with types such astext,reasoning,image,file,tool_call,invalid_tool_call, server-tool blocks andnon_standard..textis a property in 1.x (calling.text()still works but warns) and joins only the text parts. - 7
Standard blocks are not written into
contentunless the model hasoutput_version="v1"orLC_OUTPUT_VERSION=v1is set, which matters when non-LangChain consumers read stored messages. - 8
Multimodal input uses standard blocks:
{"type": "image", "url": ...},{"type": "image", "base64": ..., "mime_type": "image/png"},{"type": "file", ...}for PDFs, or a providerfile_id. Supported file types and sizes still vary by model. - 9
AIMessage.usage_metadatais the provider-neutral token record:input_tokens,output_tokensandtotal_tokens(all required), plus optionalinput_token_details(cache_read,cache_creation,audio) andoutput_token_details(reasoning,audio). Totals include the detail counts;response_metadataholds provider-specific extras. - 10
Adding
AIMessageChunks concatenates content, sumsusage_metadata, mergesresponse_metadataand joinstool_call_chunksbyindexinto parsedtool_calls. The result is still a chunk (usemessage_chunk_to_messagefor anAIMessage); adding a plainAIMessageraisesTypeError. - 11
Common params:
temperature(randomness; use about 0 for extraction),max_tokens(caps reply length),timeout(seconds per request),max_retries(default 6, exponential backoff with jitter, retries network errors, 429 and 5xx, not 401 or 404), plusbase_urlandrate_limiter. - 12
Model profiles (
model.profile, beta) describe capabilities and limits such asmax_input_tokens,image_inputs,pdf_inputs,tool_callingandreasoning_output, mostly from models.dev. Override withprofile=at creation ormodel_copy(update={"profile": ...}). A custom chat model must implement_generateand_llm_type;_streamand_agenerateare optional.
Common traps
Chat models are stateless: a second
invokeknows nothing about the first unless you resend the earlier turns, including the returnedAIMessage.resp.content[0]["text"]breaks when a provider returns a plain string or puts reasoning or tool-use blocks first; use.textor filtercontent_blocks.Adding
input_token_details["cache_read"]on top ofinput_tokensdouble-counts: cache reads are already inside the input total.An adapter that puts running totals on every stream chunk inflates usage, because merging sums each chunk's
usage_metadata.init_chat_model("anthropic:x", model_provider="anthropic")sends the literal idanthropic:x, since an explicit provider turns off prefix splitting.configurable_fields="any"lets runtime config changeapi_keyandbase_url; with untrusted config, list the allowed fields explicitly.Bare
gemini...names infergoogle_vertexaiwith a deprecation warning; pass the provider explicitly instead of relying on inference.Without
_stream,stream()yields the whole reply as one item, so time to first token equals total latency.
Read the source
Further reading
Suggest a resourceNo extra reading for Chat Models, Messages and Content Blocks yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Chat Models, Messages and Content Blocks
Ten questions, with the answer and explanation after each one.