LLM 是能够像人类一样理解和生成文本的强大AI工具。无需针对每种任务进行专门训练,它们就可以进行编写内容、翻译语言、总结信息、回答问题等任务,用途非常广泛。 除了文本生成外,许多模型还支持:
  • 工具调用 - 调用外部工具(如数据库查询或 API 调用)并在响应中使用结果。
  • 结构化输出 - 将模型的响应转换为遵循预定义的格式。
  • 多模态 - 处理和返回除文本以外的数据,如图像、音频和视频。
  • 推理 - 模型执行多步骤推理以得出结论。
模型是智能体的推理引擎,它们驱动智能体的决策过程,决定调用哪些工具、如何解释结果以及何时提供最终答案。 您选择的模型的质量和能力直接决定智能体可靠性和性能的基准。不同的模型擅长不同的任务 —— 有些更擅长遵循复杂指令,有些更擅长结构化推理,有些支持更大的上下文窗口以便处理更多信息。 LangChain 的标准模型接口让您可以对接不同供应商的模型,让您能够轻松尝试和切换模型,为您的用例找到最佳匹配。
有关供应商特定的集成信息和功能,请参阅供应商的聊天模型页面

基本用法

模型可以通过两种方式使用:
  1. 与智能体一起使用 - 模型可以在创建智能体时动态指定。
  2. 独立使用 - 模型可以直接调用(不在智能体循环中),用于文本生成、分类或提取等任务,无需智能体框架。
相同的模型接口在两种场景下都能工作,这让您可以从小处着手,并根据需要而扩展到更复杂的基于智能体的工作流程。

模型初始化

在 LangChain 中开始使用独立模型的最简单方法是使用 init_chat_model 方法,它可以从您选择的供应商程序包中初始化一个模型(示例如下):
👉 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.2")
response = model.invoke("Why do parrots talk?")
请参阅 init_chat_model 了解更多详情,包括如何传递模型参数

支持的供应商和模型

LangChain 通过专用集成包支持所有主要模型供应商。每个提供应商都实现相同的标准接口,因此您可以变换供应商而无需重写应用程序逻辑。无需更新LangChain,新模型名称可以立即使用 ——因为供应商包直接将模型名称传递给供应商的 API。 浏览支持的供应商完整列表,或参阅供应商和模型了解供应商、包和模型名称如何在 LangChain 中协同工作的概念概述。

关键方法

调用(Invoke)

模型将消息作为输入,并在生成完整响应后输出消息。

流式输出(Stream)

调用模型,但实时流式输出生成的内容。

批量(Batch)

以批量模式向模型发送多个请求,以提高处理效率。
除了聊天模型外,LangChain 还提供对其他相关技术的支持,例如嵌入模型和向量存储。详细信息请参阅集成页面

参数

参数可以决定聊天模型的行为,参数因模型和供应商而异,但一般都包括如下标准的几个:
model
string
required
模型的名称或标识符。您也可以使用 ’:’ 格式在单个参数中同时指定模型及其供应商,例如 ‘openai:o1’。
api_key
string
访问供应商模型进行身份验证所需的密钥,这通常在您注册访问模型时获得。通常通过设置来访问。
temperature
number
控制模型输出的随机性。较高的数字使响应更具创造性;较低的数字使响应更具确定性。
max_tokens
number
限制输出响应中的总数,有效控制输出的长度。
timeout
number
在取消请求之前等待模型响应的时间(秒)。
max_retries
number
default:"6"
如果请求因网络超时或速率限制等问题失败,系统重新发送请求的最大次数。重试会使用指数退避算法。网络错误、速率限制(429)和服务器错误(5xx)会自动重试。客户端错误(如 401(未授权)或 404 不会重试。对于在不可靠网络上运行长时间的智能体任务,请考虑将此值增加到 10-15。
使用 init_chat_model 时,将这些参数作为内联传递:
Initialize using model parameters
model = init_chat_model(
    "claude-sonnet-4-6",
    # 传递给模型的 Kwargs:
    temperature=0.7,
    timeout=30,
    max_tokens=1000,
    max_retries=6,    # 默认值;在不可靠网络上增加
)
每个聊天模型的集成,可能存在控制供应商特定功能的附加参数。例如,ChatOpenAIuse_responses_api 来决定使用 OpenAI Responses 还是 Completions API。要查找特定聊天模型支持的所有参数,请前往聊天模型集成页面。

调用

必须调用聊天模型才能生成输出。有三种主要的调用方法,每种都适用于不同的用例。

调用(Invoke)

调用模型最直接的方法是使用 invoke() 并传入单个消息或消息序列。
Single message
response = model.invoke("Why do parrots have colorful feathers?")
print(response)
可以向聊天模型传入一个涵盖对话历史的消息序列,每条消息都有一个角色,模型用这个角色来指示是谁发送了该消息。 请参阅消息指南获取有关角色、类型和内容的更多详情。
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.")
如果本次调用返回的类型是字符串,请确保您使用的是聊天模型而不是 LLM。传统的文本补全 LLM 会直接返回字符串。LangChain 聊天模型以”Chat”为前缀,例如 ChatOpenAI(/oss/integrations/chat/openai)。

流式输出(Stream)

大多数模型可以在生成内容时能够实时地进行流式输出。通过渐进式显示输出,流式输出显著改善了用户体验,特别是对于较长的响应。 调用 stream() 返回一个,它在内容生成时返回输出块,您可以使用循环实时处理每个块:
for chunk in model.stream("Why do parrots have colorful feathers?"):
    print(chunk.text, end="|", flush=True)
invoke()(在模型完成生成完整响应后返回单个 AIMessage)不同,stream() 返回多个 AIMessageChunk 对象,每个对象都包含输出文本的一部分。重要的是,这些块最终汇总成完整消息:
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": "天空通常是蓝色的..."}]
汇总生成的消息可以像使用 invoke() 生成的消息一样处理 —— 例如,它可以聚合到消息历史中并作为对话上下文传回模型。
流式输出仅在程序中的所有步骤都知道如何处理块流时才有效。例如,如果应用程序需要在处理之前将整个输出存储在内存中,则不具备流式输出能力。
LangChain 聊天模型也可以使用 astream_events() 语义事件转换为流式输出。这简化了基于事件类型和其他元数据的过滤行为,并会在后台聚合完整消息。请参阅下面的示例。
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() 参考获取事件类型和其他详情。
在某些情况下自动启用流式输出模式,即使您没有显式调用流式方法,LangChain 可以简便的实现聊天模型流式输出的功能。当您使用非流式 invoke 方法但仍想流式输出整个应用程序(包括聊天模型的中间结果)输出时,这尤其有用。例如,在 LangGraph 智能体中,您可以在节点中调用 model.invoke(),但如果以流式模式运行,LangChain 会自动委托给流式输出。

工作原理

当您对聊天模型调用 invoke() 时,如果 LangChain 检测到您正在尝试流式输出整个应用程序,它会自动切换到内部流式输出模式。就使用 invoke 的代码而言,调用的结果将是相同的;但是,在聊天模型被流式输出时,LangChain 会负责在 LangChain 的回调系统中调用 on_llm_new_token 事件。回调事件允许 LangGraph 的 stream()astream_events() 实时显示聊天模型的输出。

批量(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)
本节介绍的聊天模型的方法 batch(),它是在客户端并行化模型调用。它与推理供应商支持的批量 API 不同,例如 OpenAIAnthropic
默认情况下,batch() 只返回整个批处理的最终响应输出。如果您想在每个输入处理完成生成响应时接收其输出,可以使用 batch_as_completed() 流式输出结果:
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,    # 限制为 5 个并行调用
    }
)
参阅 RunnableConfig 参考获取支持的完整属性列表。
有关批处理的更多详情,请参阅参考

工具调用

模型可以调用工具以便执行某些任务,例如从数据库获取数据、搜索网页或执行代码。工具由以下两部分组成:
  1. 一个模式说明(schema),包括工具名称、描述和参数定义(通常是 JSON schema)
  2. 一个用于执行的函数或
您可能听说过”function calling”这个术语,我们将其与”工具调用”互换使用。
以下是用户和模型之间的基本工具调用流程: 为了让您定义的工具可供模型使用,您必须使用 bind_tools 绑定它们。在后续调用中,模型可以选择根据需要调用任何绑定的工具。 一些模型供应商提供,可以通过模型参数或调用参数启用(例如 ChatOpenAIChatAnthropic)。请查看各自的供应商参考了解详情。
请参阅工具指南获取创建工具的详情和其他选项。
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']}")
当绑定了用户定义的工具时,如果需要调用工具,模型的响应中会包括一个执行工具请求的消息。当单独使用模型不是使用智能体时,需要您手动执行工具调用并将结果返回给模型以供后续推理使用。当使用智能体时,智能体循环会为您处理工具调用循环。 下面我们展示一些常见的工具调用方式。
当模型返回工具调用消息时,您需要执行工具并将结果传回模型。这会创建一个对话回环,在回环中模型可以使用工具返回的结果来生成最终响应。LangChain 的智能体包含处理这种编排的处理过程。下面是一个简单的示例:
Tool execution loop
# 将(可能是多个)工具绑定到模型
model_with_tools = model.bind_tools([get_weather])

# 步骤 1:模型生成工具调用
messages = [{"role": "user", "content": "What's the weather in Boston?"}]
ai_msg = model_with_tools.invoke(messages)
messages.append(ai_msg)

# 步骤 2:执行工具并收集结果
for tool_call in ai_msg.tool_calls:
    # 使用生成的参数执行工具
    tool_result = get_weather.invoke(tool_call)
    messages.append(tool_result)

# 步骤 3:将结果传回模型以获取最终响应
final_response = model_with_tools.invoke(messages)
print(final_response.text)
# "波士顿目前的天气是 72°F,晴天。"
工具返回的每个 ToolMessage 都包含一个与原始工具调用匹配的 tool_call_id,帮助模型将结果与请求关联起来。
默认情况下,模型可以自由选择使用哪个绑定的工具。但是,您可能希望强制选择某个工具,确保模型使用特定工具或给定列表中的任何工具:
model_with_tools = model.bind_tools([tool_1], tool_choice="any")
许多模型支持在适当时并行调用多个工具。这允许模型同时从不同来源收集信息。
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': '波士顿'}, 'id': 'call_1'},
#   {'name': 'get_weather', 'args': {'location': '东京'}, '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)
模型根据请求操作的独立性智能地决定何时适合并行执行。
大多数支持工具调用的模型默认启用并行工具调用。一些(包括 OpenAIAnthropic)允许您禁用此功能。为此,请设置 parallel_tool_calls=False
model.bind_tools([get_weather], parallel_tool_calls=False)
流式输出时,工具调用通过 ToolCallChunk 逐步构建。这允许您在生成时看到工具调用,而不是等待完整响应。
Streaming tool calls
for chunk in model_with_tools.stream(
    "What's the weather in Boston and Tokyo?"
):
    # 工具调用块逐步到达
    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}")

# 输出:
# 工具:get_weather
# ID:call_SvMlU1TVIZugrFLckFE2ceRE
# 参数:{"lo
# 参数:catio
# 参数:n": "B
# 参数:osto
# 参数:n"}
# 工具:get_weather
# ID:call_QMZdy6qInx13oWKE7KhuhOLR
# 参数:{"lo
# 参数:catio
# 参数:n": "T
# 参数:okyo
# 参数:"}
您可以累积块来构建完整的工具调用:
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)

结构化输出

可以请求模型以符合给定模式的格式提供响应。这对于确保输出可以轻松解析并用于后续处理非常有用。LangChain 支持多种模式类型和强制结构化输出的方法。
要了解结构化输出,请参阅结构化输出
Pydantic 模型 提供最丰富的功能集,包括字段验证、描述和嵌套结构。
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="盗梦空间", year=2010, director="克里斯托弗·诺兰", rating=8.8)
结构化输出的关键考虑因素
  • 方法参数:某些供应商支持不同的结构化输出方法:
    • 'json_schema':使用供应商提供的专用结构化输出功能。
    • 'function_calling':通过强制执行遵循给定模式的工具调用来派生结构化输出。
    • 'json_mode':某些供应商提供的 'json_schema' 的前身。生成有效的 JSON,但必须在提示词中描述模式。
  • 包含原始输出:设置 include_raw=True 以同时获取解析后的输出和原始 AI 消息。
  • 验证:Pydantic 模型提供自动验证。TypedDict 和 JSON Schema 需要手动验证。
请查看您的供应商的集成页面了解支持的方法和配置选项。
返回原始 AIMessage 对象以及解析后的表示形式可能很有用,以便访问响应元数据(如令牌使用量)。为此,在调用 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,
# }
模式可以嵌套:
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)

高级主题

模型配置

模型配置需要 langchain>=1.1
LangChain 聊天模型可以通过 profile 属性公开支持的特性和能力字典:
model.profile
# {
#   "max_input_tokens": 400000,
#   "image_inputs": True,
#   "reasoning_output": True,
#   "tool_calling": True,
#   ...
# }
请参阅 API 参考中的完整字段集。 大多数模型配置数据由 models.dev 项目提供支持,这是一个开源的模型能力数据计划。这些数据补充了与 LangChain 一起使用的附加字段。随着上游项目的发展,这些补充会保持同步。 模型配置数据允许应用程序动态处理模型能力。例如:
  1. 总结中间件 可以根据模型的上下文窗口大小触发总结。
  2. create_agent 中的结构化输出策略可以自动推断(例如,通过检查对原生结构化输出功能的支持)。
  3. 模型输入可以根据支持的模态和最大输入令牌数进行限制。
  4. Deep Agents CLI 过滤交互式模型切换器,只显示其配置报告 tool_calling 支持和文本 I/O 的模型,并在选择器详情视图中显示上下文窗口大小和功能标志。
如果配置数据缺失、过时或不正确,可以更改。选项 1(快速修复)您可以使用任何有效的配置实例化聊天模型:
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 集成包中,并与那些包一起发布。模型配置数据可以通过以下流程更新:
  1. (如需要)在 models.devGitHub 仓库 中通过拉取请求更新源数据。
  2. (如需要)在 LangChain 集成包langchain_<package>/data/profile_augmentations.toml 中通过拉取请求更新附加字段和覆盖。
  3. 使用 langchain-model-profiles CLI 工具从 models.dev 拉取最新数据,合并增强功能并更新配置数据:
pip install langchain-model-profiles
langchain-profiles refresh --provider <provider> --data-dir <data_dir>
此命令:
  • 从 models.dev 下载 <provider> 的最新数据
  • 合并来自 <data_dir>profile_augmentations.toml 的增强功能
  • 将合并后的配置写入 <data_dir> 中的 profiles.py
例如:从 LangChain monorepolibs/partners/anthropic
uv run --with langchain-model-profiles --provider anthropic --data-dir langchain_anthropic/data
模型配置是一个测试版功能。配置的格式可能会发生变化。

多模态

某些模型可以处理和返回非文本数据,如图像、音频和视频。您可以通过提供内容块将非文本数据传递给模型。
所有具有底层多模态功能的 LangChain 聊天模型都支持:
  1. 跨供应商标准格式(请参阅我们的消息指南
  2. OpenAI 聊天补全格式
  3. 该特定供应商原生的任何格式(例如,Anthropic 模型接受 Anthropic 原生格式)
请参阅消息指南的多模态部分了解详情。 可以在响应中返回多模态数据。如果被调用这样做,生成的 AIMessage 将包含具有多模态类型的内容块。
Multimodal output
response = model.invoke("Create a picture of a cat")
print(response.content_blocks)
# [
#     {"type": "text", "text": "这里是一张猫的图片"},
#     {"type": "image", "base64": "...", "mime_type": "image/jpeg"},
# ]
请参阅集成页面了解特定供应商的详情。

推理

许多模型能够执行多步骤推理来得出结论。这涉及将复杂问题分解为更小、更易管理的步骤。 **如果底层模型支持,**您可以展示这个推理过程,以更好地理解模型如何得出最终答案。
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)
根据模型的不同,有时您可以指定模型应该投入多少推理精力。同样,您可以请求模型完全关闭推理。这可能采用分类”层级”(例如 'low''high')或整数令牌预算的形式。 详情请参阅您的特定聊天模型的集成页面参考

本地模型

LangChain 支持在您自己的硬件上本地运行模型。这对于以下场景很有用:数据隐私至关重要,您想要调用自定义模型,或者您希望避免使用云模型产生的成本。 Ollama 是在本地运行聊天和嵌入模型最简单的方法之一。

提示词缓存

许多供应商提供提示词缓存功能,以减少重复处理相同令牌时的延迟和成本。这些功能可以是隐式显式的:
提示词缓存通常只在超过最小输入令牌阈值时才会触发。请参阅供应商页面了解详情。
缓存使用情况将反映在模型响应的使用量元数据中。

服务器端工具使用

某些供应商支持服务器端工具调用循环:模型可以与网络搜索、代码解释器和其他工具交互,并在单个对话回合中分析结果。 如果模型在服务器端调用工具,响应消息的内容将包括表示工具调用和结果的內容。以供应商无关的格式访问响应的内容块将返回服务器端工具调用和结果:
Invoke with server-side tool use
from langchain.chat_models import init_chat_model

model = init_chat_model("gpt-4.1-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": "..."
            }
        ]
    }
]
这代表单个对话回合;没有需要像客户端工具调用那样传入的关联 ToolMessage 对象。 请参阅您的给定供应商的集成页面了解可用工具和使用详情。

速率限制

许多聊天模型供应商对在给定时间段内可以进行的调用次数有限制。如果您达到速率限制,您通常会从供应商收到速率限制错误响应,需要等待后才能发出更多请求。 为了帮助管理速率限制,聊天模型集成接受一个 rate_limiter 参数,可以在初始化时提供该参数来控制发出请求的速率。
LangChain 附带了一个(可选的)内置 InMemoryRateLimiter。此限制器是线程安全的,可以在同一进程中的多个线程之间共享。
Define a rate limiter
from langchain_core.rate_limiters import InMemoryRateLimiter

rate_limiter = InMemoryRateLimiter(
    requests_per_second=0.1,    # 每 10 秒 1 个请求
    check_every_n_seconds=0.1,    # 每 100ms 检查是否允许发出请求
    max_bucket_size=10,    # 控制最大突发大小。
)

model = init_chat_model(
    model="gpt-5",
    model_provider="openai",
    rate_limiter=rate_limiter    
)
提供的速率限制器只能限制单位时间的请求数。如果您还需要根据请求大小进行限制,这将无济于事。

基础 URL 和代理设置

您可以为实现 OpenAI 聊天补全 API 的供应商配置自定义基础 URL。
model_provider="openai"(或直接使用 ChatOpenAI)针对官方 OpenAI API 规范。路由器和代理的供应商特定字段可能不会被提取或保留。对于 OpenRouter 和 LiteLLM,请使用专用集成:
许多模型供应商提供 OpenAI 兼容 API(例如 Together AIvLLM)。您可以通过指定适当的 base_url 参数使用 init_chat_model 与这些供应商一起使用:
model = init_chat_model(
    model="MODEL_NAME",
    model_provider="openai",
    base_url="BASE_URL",
    api_key="YOUR_API_KEY",
)
使用直接聊天模型类实例化时,参数名称可能因供应商而异。请查看各自的参考了解详情。
对于需要 HTTP 代理的部署,某些模型集成支持代理配置:
from langchain_openai import ChatOpenAI

model = ChatOpenAI(
    model="gpt-4.1",
    openai_proxy="http://proxy.example.com:8080"
)
代理支持因集成而异。请查看特定模型供应商的参考了解代理配置选项。

对数概率

某些模型可以配置为通过在初始化模型时设置 logprobs 参数来返回表示给定令牌可能性的令牌级对数概率:
model = init_chat_model(
    model="gpt-4.1",
    model_provider="openai"
).bind(logprobs=True)

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

令牌使用量

许多模型供应商将令牌使用信息作为调用响应的一部分返回。启用后,此信息将包含在相应模型生成的 AIMessage 对象上。更多详情请参阅消息指南。
某些供应商 API(特别是 OpenAI 和 Azure OpenAI 聊天补全)在流式输出场景中要求用户选择接收令牌使用数据。详情请参阅集成指南的流式输出使用量元数据部分。
您可以使用回调或上下文管理器跟踪应用程序中跨模型的聚合令牌计数,如下所示:
from langchain.chat_models import init_chat_model
from langchain_core.callbacks import UsageMetadataCallbackHandler

model_1 = init_chat_model(model="gpt-4.1-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-4.1-mini-2025-04-14': {
        '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}
    }
}

调用配置

调用模型时,您可以使用 config 参数通过 RunnableConfig 字典传递其他配置。这提供了对执行行为、回调和元数据跟踪的运行时控制。 常用配置选项包括:
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 追踪进行调试
  • 实现自定义日志记录或监控
  • 在生产环境中控制资源使用
  • 跨复杂管道追踪调用
run_name
string
在日志和追踪中标识此特定调用。不会被子调用继承。
tags
string[]
标签将被所有子调用继承,用于在调试工具中进行过滤和组织。
metadata
object
用于跟踪附加上下文的自定义键值对,会被所有子调用继承。
max_concurrency
number
使用 batch()batch_as_completed() 时控制最大并行调用数。
callbacks
array
用于在执行期间监控和响应事件的处理器。
recursion_limit
number
链的最大递归深度,防止复杂管道中的无限循环。
请参阅完整的 RunnableConfig 参考获取所有支持的属性。

可配置模型

您还可以通过指定 configurable_fields 创建一个运行时可配置的模型。如果不指定模型值,则 '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"}},    # 使用 GPT-5-Nano 运行
)
configurable_model.invoke(
    "what's your name",
    config={"configurable": {"model": "claude-sonnet-4-6"}},    # 使用 Claude 运行
)
我们可以创建一个具有默认模型值的可配置模型,指定哪些参数是可配置的,并为可配置参数添加前缀:
first_model = init_chat_model(
        model="gpt-4.1-mini",
        temperature=0,
        configurable_fields=("model", "model_provider", "temperature", "max_tokens"),
        config_prefix="first",    # 当链中有多个模型时很有用
)

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,
        }
    },
)
请参阅 init_chat_model 参考了解更多关于 configurable_fieldsconfig_prefix 的详情。
我们可以像调用常规实例化的聊天模型对象一样,对可配置模型调用声明性操作,如 bind_toolswith_structured_outputwith_configurable 等,并以相同的方式将可配置模型链接起来。
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-4.1-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'
    }
]