LLMs 是强大的 AI 工具,可以像人类一样理解和生成文本。它们用途广泛,可以编写内容、翻译语言、总结信息和回答问题,而无需为每项任务进行专门训练。 除了文本生成,许多模型还支持:
  • Tool calling:调用外部工具(例如数据库查询或 API 调用),并在响应中使用结果。
  • Structured output:约束模型响应遵循定义好的格式。
  • Multimodality:处理并返回文本以外的数据,例如图像、音频和视频。
  • Reasoning:模型通过多步推理得出结论。
Models 是 agents 的推理引擎。它们驱动代理的决策过程,决定调用哪些工具、如何解释结果,以及何时给出最终答案。 你选择的模型质量和能力会直接影响代理的基础可靠性和性能。不同模型擅长不同任务,有些更擅长遵循复杂指令,有些更擅长结构化推理,还有些支持更大的上下文窗口以处理更多信息。 LangChain 的标准模型接口让你能够访问许多不同的 provider integrations,从而轻松试验和切换模型,找到最适合用例的模型。 如需 provider-specific 集成信息和能力,请参阅 provider 的 chat model page
LangSmith 会追踪每次模型调用,便于你比较 providers、检查工具路由并调试故障。按照 tracing quickstart 完成设置。建议同时设置 LangSmith Engine,它会监控 traces、检测问题并提出修复建议。

Basic usage

Models 可以通过两种方式使用:
  1. 与 agents 一起使用:创建 agent 时可以动态指定 models。
  2. 独立使用:可以直接调用 models(在代理循环之外)完成文本生成、分类或提取等任务,而无需 agent framework。
同一个模型接口适用于这两种场景,因此你可以从简单场景开始,并在需要时扩展到更复杂的基于 agent 的工作流。

Initialize a model

在 LangChain 中开始使用独立模型的最简单方式,是使用 init_chat_model 从所选 chat model provider 初始化模型(示例如下):
👉 Read the OpenAI chat model integration docs
pip install -U "langchain[openai]"
import os
from langchain.chat_models import init_chat_model

os.environ["OPENAI_API_KEY"] = "sk-..."

model = init_chat_model("gpt-5.4")
response = model.invoke("Why do parrots talk?")
更多详情请参阅 init_chat_model,包括如何传递模型 parameters

Supported providers and models

LangChain 通过专用 integration packages 支持所有主要模型 providers。每个 provider package 都实现相同的标准接口,因此你可以在不重写应用逻辑的情况下切换 providers。新的模型名称可以立即使用,不需要更新 LangChain,因为 provider packages 会将模型名称直接传给 provider 的 API。 浏览 full list of supported providers,或查看 Providers and models,了解 providers、packages 和模型名称如何在 LangChain 中协同工作。

Key methods

Invoke

模型接收 messages 作为输入,并在生成完整响应后输出 messages。

Stream

调用模型,并在输出实时生成时以 stream 形式返回。

Batch

以 batch 方式向模型发送多个请求,从而更高效地处理。
除 chat models 外,LangChain 还支持其他相邻技术,例如 embedding models 和 vector stores。详情请参阅 integrations page

Parameters

Chat model 接收可用于配置其行为的参数。支持的完整参数集因模型和 provider 而异,但标准参数包括:
model
string
required
要与 provider 一起使用的具体模型名称或标识符。也可以使用 {model_provider}:{model} 格式在单个参数中同时指定模型和 provider,例如 openai:o1
api_key
string
与模型 provider 认证所需的 key。通常在注册模型访问权限时发放。通常通过设置 访问。
temperature
number
控制模型输出的随机性。数值越高,响应越有创造性;数值越低,响应越确定。
max_tokens
number
限制响应中的 总数,从而有效控制输出长度。
timeout
number
取消请求前等待模型响应的最长时间(秒)。
max_retries
number
default:"6"
如果请求因网络超时或速率限制等问题失败,系统重新发送请求的最大尝试次数。重试使用带 jitter 的指数退避。网络错误、速率限制(429)和服务器错误(5xx)会自动重试。401(unauthorized)或 404 等客户端错误不会重试。对于不可靠网络上的长时间运行 agent 任务,可以考虑将其增加到 10 到 15。
使用 init_chat_model 时,将这些参数作为内联 传入:
Initialize using model parameters
model = init_chat_model(
    "claude-sonnet-4-6",
    # Kwargs passed to the model:
    temperature=0.7,
    timeout=30,
    max_tokens=1000,
    max_retries=6,  # Default; increase for unreliable networks
)

Connection resilience

LangChain chat models 会使用指数退避自动重试失败的 API 请求。默认情况下,对于网络错误、速率限制(429)和服务器错误(5xx),模型最多重试 6 次。401(unauthorized)或 404 等客户端错误不会重试。 创建模型时可以调整 max_retriestimeout,然后将该实例传给 create_agentcreate_deep_agent,或独立调用它:
from langchain.chat_models import init_chat_model

model = init_chat_model(
    "google_genai:gemini-3.5-flash",
    max_retries=10,  # Increase for unreliable networks (default: 6)
    timeout=120,  # Seconds; increase for slow connections
)
对于不可靠网络上长时间运行的 agent graphs,可以考虑设置更高的 max_retries(例如 10 到 15),并使用 checkpointer,以便在失败后保留进度。
每个 chat model integration 都可能有额外参数,用于控制 provider-specific 功能。例如,ChatOpenAIuse_responses_api,用于指定使用 OpenAI Responses API 还是 Completions API。如需查找给定 chat model 支持的所有参数,请前往 chat model integrations 页面。

Invocation

Chat model 必须被调用才会生成输出。主要有三种调用方法,每种方法适用于不同用例。

Invoke

调用模型最直接的方式,是将单条 message 或 messages 列表传给 invoke()
Single message
response = model.invoke("Why do parrots have colorful feathers?")
print(response)
可以向 chat model 提供 messages 列表来表示对话历史。每条 message 都有一个 role,模型用它来判断对话中是谁发送了该 message。 如需了解 roles、types 和 content 的更多详情,请参阅 messages 指南。
Dictionary format
conversation = [
    {"role": "system", "content": "You are a helpful assistant that translates English to French."},
    {"role": "user", "content": "Translate: I love programming."},
    {"role": "assistant", "content": "J'adore la programmation."},
    {"role": "user", "content": "Translate: I love building applications."}
]

response = model.invoke(conversation)
print(response)  # AIMessage("J'adore créer des applications.")
Message objects
from langchain.messages import HumanMessage, AIMessage, SystemMessage

conversation = [
    SystemMessage("You are a helpful assistant that translates English to French."),
    HumanMessage("Translate: I love programming."),
    AIMessage("J'adore la programmation."),
    HumanMessage("Translate: I love building applications.")
]

response = model.invoke(conversation)
print(response)  # AIMessage("J'adore créer des applications.")
如果调用的返回类型是字符串,请确认你使用的是 chat model,而不是 LLM。旧版 text-completion LLMs 会直接返回字符串。LangChain chat models 以 “Chat” 为前缀,例如 ChatOpenAI(/oss/integrations/chat/openai)。

Stream

大多数模型都可以在生成输出内容时进行 streaming。通过逐步显示输出,streaming 可以显著改善用户体验,尤其适用于较长响应。 调用 stream() 会返回一个 ,它会在生成输出 chunks 时逐个产生。可以使用循环实时处理每个 chunk:
for chunk in model.stream("Why do parrots have colorful feathers?"):
    print(chunk.text, end="|", flush=True)
invoke() 不同,invoke() 会在模型完成完整响应生成后返回单个 AIMessage,而 stream() 会返回多个 AIMessageChunk 对象,每个对象都包含一部分输出文本。重要的是,stream 中的每个 chunk 都设计为可以通过相加聚合成完整 message:
Construct an AIMessage
full = None  # None | AIMessageChunk
for chunk in model.stream("What color is the sky?"):
    full = chunk if full is None else full + chunk
    print(full.text)

# The
# The sky
# The sky is
# The sky is typically
# The sky is typically blue
# ...

print(full.content_blocks)
# [{"type": "text", "text": "The sky is typically blue..."}]
生成的 message 可以像通过 invoke() 生成的 message 一样处理。例如,它可以聚合到 message history 中,并作为对话上下文传回模型。
只有当程序中的所有步骤都知道如何处理 chunk stream 时,streaming 才能工作。例如,不支持 streaming 的应用可能需要先将完整输出存储在内存中,然后才能处理。
LangChain chat models 也可以使用 astream_events() stream 语义事件。这会简化基于事件类型和其他 metadata 的过滤,并在后台聚合完整 message。请参阅下面的示例。
async for event in model.astream_events("Hello"):

    if event["event"] == "on_chat_model_start":
        print(f"Input: {event['data']['input']}")

    elif event["event"] == "on_chat_model_stream":
        print(f"Token: {event['data']['chunk'].text}")

    elif event["event"] == "on_chat_model_end":
        print(f"Full message: {event['data']['output'].text}")

    else:
        pass
Input: Hello
Token: Hi
Token:  there
Token: !
Token:  How
Token:  can
Token:  I
...
Full message: Hi there! How can I help today?
如需了解事件类型和其他详情,请参阅 astream_events() reference。
LangChain 会在某些情况下自动启用 streaming mode,从而简化 chat models 的 streaming,即使你没有显式调用 streaming 方法也是如此。当你使用非 streaming 的 invoke 方法,但仍希望对整个应用进行 streaming(包括 chat model 的中间结果)时,这尤其有用。例如,在 LangGraph agents 中,可以在节点内调用 model.invoke(),但如果以 streaming mode 运行,LangChain 会自动委托给 streaming。

工作原理

当你 invoke() chat model 时,如果 LangChain 检测到你正在尝试 stream 整个应用,就会自动切换到内部 streaming mode。对于使用 invoke 的代码来说,调用结果保持不变;但是在 chat model streaming 期间,LangChain 会负责在 LangChain 的 callback system 中触发 on_llm_new_token 事件。Callback events 允许 LangGraph stream()astream_events() 实时暴露 chat model 的输出。

Batch

将一组独立请求 batch 发送给模型可以显著提升性能并降低成本,因为处理可以并行完成:
Batch
responses = model.batch([
    "Why do parrots have colorful feathers?",
    "How do airplanes fly?",
    "What is quantum computing?"
])
for response in responses:
    print(response)
本节描述的是 chat model 方法 batch(),它会在客户端并行化模型调用。它与 inference providers 支持的 batch APIs 不同,例如 OpenAIAnthropic
默认情况下,batch() 只会返回整个 batch 的最终输出。如果希望在每个输入完成生成时接收对应输出,可以使用 batch_as_completed() stream 结果:
Yield batch responses upon completion
for response in model.batch_as_completed([
    "Why do parrots have colorful feathers?",
    "How do airplanes fly?",
    "What is quantum computing?"
]):
    print(response)
使用 batch_as_completed() 时,结果可能乱序到达。每个结果都包含输入索引,可用于按需匹配并重建原始顺序。
使用 batch()batch_as_completed() 处理大量输入时,你可能需要控制最大并行调用数。可以在 RunnableConfig 字典中设置 max_concurrency 属性。
Batch with max concurrency
model.batch(
    list_of_inputs,
    config={
        'max_concurrency': 5,  # Limit to 5 parallel calls
    }
)
如需查看支持属性的完整列表,请参阅 RunnableConfig reference。
如需了解 batching 的更多详情,请参阅 reference

Tool calling

Models 可以请求调用执行特定任务的 tools,例如从数据库获取数据、搜索网页或运行代码。Tools 由以下两部分组成:
  1. Schema,包括工具名称、描述和/或参数定义(通常是 JSON schema)
  2. 要执行的函数或
你可能会听到 “function calling” 这个术语。本文将它与 “tool calling” 互换使用。
下面是用户和模型之间的基本 tool calling 流程: 如需让模型能够使用你定义的 tools,必须使用 bind_tools 绑定它们。在后续调用中,模型可以按需选择调用任何已绑定 tool。 一些模型 providers 提供 ,可以通过模型或调用参数启用,例如 ChatOpenAIChatAnthropic。详情请查看对应的 provider reference
如需了解详情和创建 tools 的其他选项,请参阅 tools guide
Binding user tools
from langchain.tools import tool

@tool
def get_weather(location: str) -> str:
    """Get the weather at a location."""
    return f"It's sunny in {location}."


model_with_tools = model.bind_tools([get_weather])

response = model_with_tools.invoke("What's the weather like in Boston?")
for tool_call in response.tool_calls:
    # View tool calls made by the model
    print(f"Tool: {tool_call['name']}")
    print(f"Args: {tool_call['args']}")
绑定用户定义的 tools 后,模型响应会包含执行工具的请求。当单独使用模型而不使用 agent 时,需要由你执行请求的工具,并将结果返回给模型以供后续推理使用。使用 agent 时,agent loop 会替你处理工具执行循环。 下面展示一些使用 tool calling 的常见方式。
当模型返回 tool calls 时,需要执行 tools 并将结果传回模型。这会创建一个对话循环,模型可以使用工具结果生成最终响应。LangChain 包含 agent 抽象,可以替你处理该编排。下面是一个简单示例:
Tool execution loop
# Bind (potentially multiple) tools to the model
model_with_tools = model.bind_tools([get_weather])

# Step 1: Model generates tool calls
messages = [{"role": "user", "content": "What's the weather in Boston?"}]
ai_msg = model_with_tools.invoke(messages)
messages.append(ai_msg)

# Step 2: Execute tools and collect results
for tool_call in ai_msg.tool_calls:
    # Execute the tool with the generated arguments
    tool_result = get_weather.invoke(tool_call)
    messages.append(tool_result)

# Step 3: Pass results back to model for final response
final_response = model_with_tools.invoke(messages)
print(final_response.text)
# "The current weather in Boston is 72°F and sunny."
工具返回的每个 ToolMessage 都包含与原始 tool call 匹配的 tool_call_id,帮助模型将结果与请求关联。
默认情况下,模型可以根据用户输入自由选择使用哪个已绑定 tool。不过,你可能希望强制选择工具,确保模型使用特定工具,或使用给定列表中的任意工具:
model_with_tools = model.bind_tools([tool_1], tool_choice="any")
许多模型支持在适当时并行调用多个 tools。这使模型能够同时从不同来源收集信息。
Parallel tool calls
model_with_tools = model.bind_tools([get_weather])

response = model_with_tools.invoke(
    "What's the weather in Boston and Tokyo?"
)


# The model may generate multiple tool calls
print(response.tool_calls)
# [
#   {'name': 'get_weather', 'args': {'location': 'Boston'}, 'id': 'call_1'},
#   {'name': 'get_weather', 'args': {'location': 'Tokyo'}, 'id': 'call_2'},
# ]


# Execute all tools (can be done in parallel with async)
results = []
for tool_call in response.tool_calls:
    if tool_call['name'] == 'get_weather':
        result = get_weather.invoke(tool_call)
    ...
    results.append(result)
模型会根据请求操作之间的独立性,智能判断何时适合并行执行。
大多数支持 tool calling 的模型默认启用 parallel tool calls。有些模型(包括 OpenAIAnthropic)允许禁用此功能。为此,请设置 parallel_tool_calls=False
model.bind_tools([get_weather], parallel_tool_calls=False)
Streaming 响应时,tool calls 会通过 ToolCallChunk 逐步构建。这样可以在生成过程中查看 tool calls,而不必等待完整响应。
Streaming tool calls
for chunk in model_with_tools.stream(
    "What's the weather in Boston and Tokyo?"
):
    # Tool call chunks arrive progressively
    for tool_chunk in chunk.tool_call_chunks:
        if name := tool_chunk.get("name"):
            print(f"Tool: {name}")
        if id_ := tool_chunk.get("id"):
            print(f"ID: {id_}")
        if args := tool_chunk.get("args"):
            print(f"Args: {args}")

# Output:
# Tool: get_weather
# ID: call_SvMlU1TVIZugrFLckFE2ceRE
# Args: {"lo
# Args: catio
# Args: n": "B
# Args: osto
# Args: n"}
# Tool: get_weather
# ID: call_QMZdy6qInx13oWKE7KhuhOLR
# Args: {"lo
# Args: catio
# Args: n": "T
# Args: okyo
# Args: "}
可以累积 chunks 来构建完整 tool calls:
Accumulate tool calls
gathered = None
for chunk in model_with_tools.stream("What's the weather in Boston?"):
    gathered = chunk if gathered is None else gathered + chunk
    print(gathered.tool_calls)

Structured output

可以要求 models 以匹配给定 schema 的格式提供响应。这有助于确保输出易于解析,并可用于后续处理。LangChain 支持多种 schema 类型和强制 structured output 的方法。
如需了解 structured output,请参阅 Structured output
Pydantic models 提供最丰富的功能集,包括字段验证、描述和嵌套结构。
from pydantic import BaseModel, Field

class Movie(BaseModel):
    """A movie with details."""
    title: str = Field(description="The title of the movie")
    year: int = Field(description="The year the movie was released")
    director: str = Field(description="The director of the movie")
    rating: float = Field(description="The movie's rating out of 10")

model_with_structure = model.with_structured_output(Movie)
response = model_with_structure.invoke("Provide details about the movie Inception")
print(response)  # Movie(title="Inception", year=2010, director="Christopher Nolan", rating=8.8)
Structured output 的关键注意事项
  • Method parameter:一些 providers 支持不同的 structured output 方法:
    • 'json_schema':使用 provider 提供的专用 structured output 功能。
    • 'function_calling':通过强制执行遵循给定 schema 的 tool call 来派生 structured output。
    • 'json_mode':一些 providers 提供的 'json_schema' 前身。它会生成有效 JSON,但 schema 必须在 prompt 中描述。
  • Include raw:设置 include_raw=True,同时获取解析后的输出和原始 AI message。
  • Validation:Pydantic models 提供自动验证。TypedDict 和 JSON Schema 需要手动验证。
请查看对应 provider’s integration page,了解支持的方法和配置选项。
将原始 AIMessage 对象与解析后的表示一起返回会很有用,因为这样可以访问 token counts 等响应 metadata。为此,在调用 with_structured_output 时设置 include_raw=True
from pydantic import BaseModel, Field

class Movie(BaseModel):
    """A movie with details."""
    title: str = Field(description="The title of the movie")
    year: int = Field(description="The year the movie was released")
    director: str = Field(description="The director of the movie")
    rating: float = Field(description="The movie's rating out of 10")

model_with_structure = model.with_structured_output(Movie, include_raw=True)
response = model_with_structure.invoke("Provide details about the movie Inception")
response
# {
#     "raw": AIMessage(...),
#     "parsed": Movie(title=..., year=..., ...),
#     "parsing_error": None,
# }
Schemas 可以嵌套:
from pydantic import BaseModel, Field

class Actor(BaseModel):
    name: str
    role: str

class MovieDetails(BaseModel):
    title: str
    year: int
    cast: list[Actor]
    genres: list[str]
    budget: float | None = Field(None, description="Budget in millions USD")

model_with_structure = model.with_structured_output(MovieDetails)

Advanced topics

Model profiles

Model profiles 需要 langchain>=1.1
LangChain chat models 可以通过 profile 属性暴露支持功能和能力的字典:
model.profile
# {
#   "max_input_tokens": 400000,
#   "image_inputs": True,
#   "reasoning_output": True,
#   "tool_calling": True,
#   ...
# }
请在 API reference 中查看完整字段集。 大部分 model profile 数据由 models.dev 项目提供,这是一个提供模型能力数据的开源项目。为了在 LangChain 中使用,这些数据会通过额外字段增强。随着上游项目演进,这些增强会保持同步。 Model profile 数据允许应用围绕模型能力动态工作。例如:
  1. Summarization middleware 可以根据模型上下文窗口大小触发摘要。
  2. create_agent 中的 Structured output 策略可以自动推断,例如检查是否支持原生 structured output 功能。
  3. 可以根据支持的 modalities 和最大输入 tokens 对模型输入做 gate。
  4. Deep Agents Code 会过滤 interactive model switcher,只显示 profile 报告支持 tool_calling 和文本 I/O 的模型,并在选择器详情视图中显示上下文窗口大小和能力 flags。
如果 model profile 数据缺失、过时或不正确,可以更改它。选项 1(快速修复)可以使用任何有效 profile 实例化 chat model:
custom_profile = {
    "max_input_tokens": 100_000,
    "tool_calling": True,
    "structured_output": True,
    # ...
}
model = init_chat_model("...", profile=custom_profile)
profile 也是普通 dict,可以原地更新。如果模型实例是共享的,请考虑使用 model_copy 避免修改共享状态。
new_profile = model.profile | {"key": "value"}
model.model_copy(update={"profile": new_profile})
选项 2(修复上游数据)数据的主要来源是 models.dev 项目。这些数据会与 LangChain integration packages 中的额外字段和 overrides 合并,并随这些 packages 发布。可以通过以下流程更新 model profile 数据:
  1. (如需要)通过向 GitHub repository 提交 pull request,更新 models.dev 中的源数据。
  2. (如需要)通过向 LangChain integration package 提交 pull request,更新 langchain_<package>/data/profile_augmentations.toml 中的额外字段和 overrides。
  3. 使用 langchain-model-profiles CLI 工具从 models.dev 拉取最新数据,合并 augmentations 并更新 profile 数据:
pip install langchain-model-profiles
langchain-profiles refresh --provider <provider> --data-dir <data_dir>
该命令会:
  • 从 models.dev 下载 <provider> 的最新数据
  • 合并 <data_dir>profile_augmentations.toml 的 augmentations
  • 将合并后的 profiles 写入 <data_dir> 中的 profiles.py
例如,在 LangChain monorepo 中的 libs/partners/anthropic 运行:
uv run --with langchain-model-profiles --provider anthropic --data-dir langchain_anthropic/data
Model profiles 是 beta 功能。Profile 格式可能会变化。

Multimodal

某些模型可以处理并返回图像、音频和视频等非文本数据。可以通过提供 content blocks 将非文本数据传给模型。
所有底层具备多模态能力的 LangChain chat models 都支持:
  1. 跨 provider 标准格式的数据(参阅 our messages guide
  2. OpenAI chat completions 格式
  3. 该特定 provider 的任意 native 格式,例如 Anthropic models 接受 Anthropic native format
详情请参阅 messages 指南中的 multimodal section 可以将多模态数据作为响应的一部分返回。如果以这种方式调用,生成的 AIMessage 会包含多模态类型的 content blocks。
Multimodal output
response = model.invoke("Create a picture of a cat")
print(response.content_blocks)
# [
#     {"type": "text", "text": "Here's a picture of a cat"},
#     {"type": "image", "base64": "...", "mime_type": "image/jpeg"},
# ]
如需了解特定 providers 的详情,请参阅 integrations page

Reasoning

许多模型能够执行多步推理来得出结论。这涉及将复杂问题拆分为更小、更易处理的步骤。 如果底层模型支持, 可以暴露该推理过程,以更好地理解模型如何得出最终答案。
for chunk in model.stream("Why do parrots have colorful feathers?"):
    reasoning_steps = [r for r in chunk.content_blocks if r["type"] == "reasoning"]
    print(reasoning_steps if reasoning_steps else chunk.text)
根据模型不同,有时可以指定模型应投入到 reasoning 的 effort level。同样,也可以请求模型完全关闭 reasoning。这可能表现为分类的 reasoning “tiers”(例如 'low''high'),或整数 token budgets。 详情请参阅对应 chat model 的 integrations pagereference

Local models

LangChain 支持在自己的硬件上本地运行模型。这适用于数据隐私很关键、你想调用自定义模型,或希望避免使用云端模型产生费用的场景。 Ollama 是本地运行 chat 和 embedding models 最简单的方式之一。

Prompt caching

许多 providers 提供 prompt caching 功能,用于在重复处理相同 tokens 时降低延迟和成本。这些功能可以是隐式显式的:
Prompt caching 通常只有在超过最低输入 token 阈值后才会启用。详情请参阅 provider pages
缓存使用情况会反映在模型响应的 usage metadata 中。

Server-side tool use

一些 providers 支持 server-side tool-calling 循环:models 可以在单个对话轮次中与 web search、code interpreters 和其他 tools 交互并分析结果。 如果模型在 server-side 调用工具,响应 message 的 content 会包含表示工具调用和工具结果的内容。访问响应的 content blocks 会以 provider 无关格式返回 server-side tool calls 和结果:
Invoke with server-side tool use
from langchain.chat_models import init_chat_model

model = init_chat_model("gpt-5.4-mini")

tool = {"type": "web_search"}
model_with_tools = model.bind_tools([tool])

response = model_with_tools.invoke("What was a positive news story from today?")
print(response.content_blocks)
Result
[
    {
        "type": "server_tool_call",
        "name": "web_search",
        "args": {
            "query": "positive news stories today",
            "type": "search"
        },
        "id": "ws_abc123"
    },
    {
        "type": "server_tool_result",
        "tool_call_id": "ws_abc123",
        "status": "success"
    },
    {
        "type": "text",
        "text": "Here are some positive news stories from today...",
        "annotations": [
            {
                "end_index": 410,
                "start_index": 337,
                "title": "article title",
                "type": "citation",
                "url": "..."
            }
        ]
    }
]
这表示单个对话轮次;与 client-side tool-calling 不同,没有需要传入的关联 ToolMessage 对象。 如需了解可用 tools 和使用详情,请参阅给定 provider 的 integration page

Rate limiting

许多 chat model providers 会限制给定时间段内可进行的调用次数。如果触发 rate limit,通常会从 provider 收到 rate limit error response,并且需要等待后再发起更多请求。 为了帮助管理 rate limits,chat model integrations 接受一个 rate_limiter 参数,可以在初始化期间提供,用于控制请求速率。
LangChain 附带一个可选的内置 InMemoryRateLimiter。该 limiter 是线程安全的,可以由同一进程中的多个线程共享。
Define a rate limiter
from langchain_core.rate_limiters import InMemoryRateLimiter

rate_limiter = InMemoryRateLimiter(
    requests_per_second=0.1,  # 1 request every 10s
    check_every_n_seconds=0.1,  # Check every 100ms whether allowed to make a request
    max_bucket_size=10,  # Controls the maximum burst size.
)

model = init_chat_model(
    model="gpt-5.4",
    model_provider="openai",
    rate_limiter=rate_limiter  
)
提供的 rate limiter 只能限制单位时间内的请求数量。如果还需要根据请求大小限制,它无法提供帮助。

Base URL and proxy settings

可以为实现 OpenAI Chat Completions API 的 providers 配置自定义 base URL。
model_provider="openai"(或直接使用 ChatOpenAI)面向官方 OpenAI API 规范。来自 routers 和 proxies 的 provider-specific 字段可能不会被提取或保留。对于 OpenRouter 和 LiteLLM,优先使用专用 integrations:
许多 model providers 提供 OpenAI-compatible APIs,例如 Together AIvLLM。可以通过指定合适的 base_url 参数,将 init_chat_model 与这些 providers 一起使用:
model = init_chat_model(
    model="MODEL_NAME",
    model_provider="openai",
    base_url="BASE_URL",
    api_key="YOUR_API_KEY",
)
直接实例化 chat model class 时,参数名称可能因 provider 而异。详情请查看对应 reference
对于需要 HTTP proxies 的部署,某些 model integrations 支持 proxy 配置:
from langchain_openai import ChatOpenAI

model = ChatOpenAI(
    model="gpt-5.4",
    openai_proxy="http://proxy.example.com:8080"
)
Proxy 支持因 integration 而异。请查看具体模型 provider 的 reference,了解 proxy 配置选项。

Log probabilities

某些模型可以配置为返回 token 级别的 log probabilities,用于表示给定 token 的可能性。初始化模型时设置 logprobs 参数即可:
model = init_chat_model(
    model="gpt-5.4",
    model_provider="openai"
).bind(logprobs=True)

response = model.invoke("Why do parrots talk?")
print(response.response_metadata["logprobs"])

Token usage

许多 model providers 会将 token usage 信息作为调用响应的一部分返回。如果可用,该信息会包含在对应模型生成的 AIMessage 对象中。更多详情请参阅 messages 指南。
某些 provider APIs,尤其是 OpenAI 和 Azure OpenAI chat completions,要求用户在 streaming contexts 中显式选择接收 token usage 数据。详情请参阅 integration guide 中的 streaming usage metadata 部分。
可以使用 callback 或 context manager 在应用中跨模型追踪聚合 token 计数,如下所示:
from langchain.chat_models import init_chat_model
from langchain_core.callbacks import UsageMetadataCallbackHandler

model_1 = init_chat_model(model="gpt-5.4-mini")
model_2 = init_chat_model(model="claude-haiku-4-5-20251001")

callback = UsageMetadataCallbackHandler()
result_1 = model_1.invoke("Hello", config={"callbacks": [callback]})
result_2 = model_2.invoke("Hello", config={"callbacks": [callback]})
print(callback.usage_metadata)
{
    'gpt-5.4-mini': {
        'input_tokens': 8,
        'output_tokens': 10,
        'total_tokens': 18,
        'input_token_details': {'audio': 0, 'cache_read': 0},
        'output_token_details': {'audio': 0, 'reasoning': 0}
    },
    'claude-haiku-4-5-20251001': {
        'input_tokens': 8,
        'output_tokens': 21,
        'total_tokens': 29,
        'input_token_details': {'cache_read': 0, 'cache_creation': 0}
    }
}

Invocation config

调用模型时,可以通过 config 参数使用 RunnableConfig 字典传递额外配置。这会提供对执行行为、callbacks 和 metadata tracking 的 runtime 控制。 常见配置选项包括:
Invocation with config
response = model.invoke(
    "Tell me a joke",
    config={
        "run_name": "joke_generation",      # Custom name for this run
        "tags": ["humor", "demo"],          # Tags for categorization
        "metadata": {"user_id": "123"},     # Custom metadata
        "callbacks": [my_callback_handler], # Callback handlers
    }
)
这些配置值在以下情况尤其有用:
  • 使用 LangSmith tracing 调试
  • 实现自定义 logging 或 monitoring
  • 控制生产环境中的资源使用
  • 跨复杂 pipelines 追踪调用
run_name
string
在 logs 和 traces 中标识此特定调用。不会被 sub-calls 继承。
tags
string[]
所有 sub-calls 都会继承的标签,用于在调试工具中过滤和组织。
metadata
object
用于追踪额外上下文的自定义 key-value pairs,会被所有 sub-calls 继承。
max_concurrency
number
使用 batch()batch_as_completed() 时,控制最大并行调用数。
callbacks
array
用于在执行期间监控和响应事件的 handlers。
recursion_limit
number
Chains 的最大递归深度,用于防止复杂 pipelines 中出现无限循环。
如需查看所有支持的属性,请参阅完整 RunnableConfig reference。

Configurable models

也可以通过指定 configurable_fields 创建 runtime-configurable model。如果没有指定模型值,则默认可以配置 'model''model_provider'
from langchain.chat_models import init_chat_model

configurable_model = init_chat_model(temperature=0)

configurable_model.invoke(
    "what's your name",
    config={"configurable": {"model": "gpt-5-nano"}},  # Run with GPT-5-Nano
)
configurable_model.invoke(
    "what's your name",
    config={"configurable": {"model": "claude-sonnet-4-6"}},  # Run with Claude
)
可以创建带默认模型值的 configurable model,指定哪些参数可配置,并向 configurable params 添加前缀:
first_model = init_chat_model(
        model="gpt-5.4-mini",
        temperature=0,
        configurable_fields=("model", "model_provider", "temperature", "max_tokens"),
        config_prefix="first",  # Useful when you have a chain with multiple models
)

first_model.invoke("what's your name")
first_model.invoke(
    "what's your name",
    config={
        "configurable": {
            "first_model": "claude-sonnet-4-6",
            "first_temperature": 0.5,
            "first_max_tokens": 100,
        }
    },
)
如需了解 configurable_fieldsconfig_prefix 的更多详情,请参阅 init_chat_model reference。
可以在 configurable model 上调用 bind_toolswith_structured_outputwith_configurable 等声明式操作,并像常规实例化的 chat model 对象一样链接 configurable model。
from pydantic import BaseModel, Field


class GetWeather(BaseModel):
    """Get the current weather in a given location"""

        location: str = Field(description="The city and state, e.g. San Francisco, CA")


class GetPopulation(BaseModel):
    """Get the current population in a given location"""

        location: str = Field(description="The city and state, e.g. San Francisco, CA")


model = init_chat_model(temperature=0)
model_with_tools = model.bind_tools([GetWeather, GetPopulation])

model_with_tools.invoke(
    "what's bigger in 2024 LA or NYC", config={"configurable": {"model": "gpt-5.4-mini"}}
).tool_calls
[
    {
        'name': 'GetPopulation',
        'args': {'location': 'Los Angeles, CA'},
        'id': 'call_Ga9m8FAArIyEjItHmztPYA22',
        'type': 'tool_call'
    },
    {
        'name': 'GetPopulation',
        'args': {'location': 'New York, NY'},
        'id': 'call_jh2dEvBaAHRaw5JUDthOs7rt',
        'type': 'tool_call'
    }
]
model_with_tools.invoke(
    "what's bigger in 2024 LA or NYC",
    config={"configurable": {"model": "claude-sonnet-4-6"}},
).tool_calls
[
    {
        'name': 'GetPopulation',
        'args': {'location': 'Los Angeles, CA'},
        'id': 'toolu_01JMufPf4F4t2zLj7miFeqXp',
        'type': 'tool_call'
    },
    {
        'name': 'GetPopulation',
        'args': {'location': 'New York City, NY'},
        'id': 'toolu_01RQBHcE8kEEbYTuuS8WqY1u',
        'type': 'tool_call'
    }
]

Dynamic model selection

Dynamic models 会在 根据当前 和 context 进行选择。这支持复杂路由逻辑和成本优化。 如需使用 dynamic model,请使用 @wrap_model_call decorator 创建 middleware,以修改 request 中的模型:
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
from langchain.agents.middleware import wrap_model_call, ModelRequest, ModelResponse


basic_model = ChatOpenAI(model="gpt-5.4-mini")
advanced_model = ChatOpenAI(model="gpt-5.4")

@wrap_model_call
def dynamic_model_selection(request: ModelRequest, handler) -> ModelResponse:
    """Choose model based on conversation complexity."""
    message_count = len(request.state["messages"])

    if message_count > 10:
        # Use an advanced model for longer conversations
        model = advanced_model
    else:
        model = basic_model

    return handler(request.override(model=model))

agent = create_agent(
    model=basic_model,  # Default model
    tools=tools,
    middleware=[dynamic_model_selection]
)
使用 structured output 时,不支持 pre-bound models(已经调用过 bind_tools 的模型)。如果需要将 dynamic model selection 与 structured output 一起使用,请确保传给 middleware 的模型不是 pre-bound。
如需了解模型配置详情,请参阅 Models。如需了解 dynamic model selection 模式,请参阅 Dynamic model in middleware