LLMs 是强大的 AI 工具,可以像人类一样解释和生成文本。它们用途广泛,可以撰写内容、翻译语言、总结和回答问题,而无需为每个任务进行专门的训练。
除了文本生成,许多模型还支持:
工具调用 -
调用外部工具(如数据库查询或 API 调用)并在其响应中使用结果。
结构化输出 -
模型的响应被约束为遵循定义的格式。
多模态 -
处理和返回文本以外的数据,如图像、音频和视频。
推理 -
模型执行多步推理以得出结论。
模型是智能体 的推理引擎。它们驱动智能体的决策过程,决定调用哪些工具、如何解释结果以及何时提供最终答案。
您选择的模型的质量和能力直接影响智能体的基线可靠性和性能。不同的模型擅长不同的任务——有些更擅长遵循复杂的指令,有些更擅长结构化推理,有些则支持更大的上下文窗口以处理更多信息。
LangChain 的标准模型接口让您能够访问许多不同的提供商集成,这使得轻松试验和切换模型以找到最适合您用例的模型变得容易。
有关特定提供商的集成信息和功能,请参阅提供商的聊天模型页面 。
基本用法
模型可以通过两种方式使用:
与智能体一起使用 - 在创建智能体 时可以动态指定模型。
独立使用 - 可以直接调用模型(在智能体循环之外),用于文本生成、分类或提取等任务,而无需智能体框架。
相同的模型接口在两种上下文中都有效,这为您提供了灵活性,可以从简单开始,并根据需要扩展到更复杂的基于智能体的工作流。
初始化模型
在 LangChain 中开始使用独立模型的最简单方法是使用 init_chat_model 从您选择的聊天模型提供商初始化一个模型(示例如下):
OpenAI
Anthropic
Azure
Google Gemini
AWS Bedrock
HuggingFace
OpenRouter
👉 阅读 OpenAI 聊天模型集成文档 pip install -U "langchain[openai]"
init_chat_model
Model Class
import os
from langchain . chat_models import init_chat_model
os . environ [ " OPENAI_API_KEY " ] = "sk-..."
model = init_chat_model ( "gpt-5.2" )
👉 阅读 Anthropic 聊天模型集成文档 pip install -U "langchain[anthropic]"
init_chat_model
Model Class
import os
from langchain . chat_models import init_chat_model
os . environ [ " ANTHROPIC_API_KEY " ] = "sk-..."
model = init_chat_model ( "claude-sonnet-4-6" )
👉 阅读 Azure 聊天模型集成文档 pip install -U "langchain[openai]"
init_chat_model
Model Class
import os
from langchain . chat_models import init_chat_model
os . environ [ " AZURE_OPENAI_API_KEY " ] = "..."
os . environ [ " AZURE_OPENAI_ENDPOINT " ] = "..."
os . environ [ " OPENAI_API_VERSION " ] = "2025-03-01-preview"
model = init_chat_model (
"azure_openai:gpt-5.2" ,
azure_deployment = os . environ [ " AZURE_OPENAI_DEPLOYMENT_NAME " ],
)
👉 阅读 Google GenAI 聊天模型集成文档 pip install -U "langchain[google-genai]"
init_chat_model
Model Class
import os
from langchain . chat_models import init_chat_model
os . environ [ " GOOGLE_API_KEY " ] = "..."
model = init_chat_model ( "google_genai:gemini-2.5-flash-lite" )
👉 阅读 AWS Bedrock 聊天模型集成文档 pip install -U "langchain[aws]"
init_chat_model
Model Class
from langchain . chat_models import init_chat_model
# 按照此处步骤配置您的凭据:
# https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
model = init_chat_model (
"anthropic.claude-3-5-sonnet-20240620-v1:0" ,
model_provider = "bedrock_converse" ,
)
👉 阅读 HuggingFace 聊天模型集成文档 pip install -U "langchain[huggingface]"
init_chat_model
Model Class
import os
from langchain . chat_models import init_chat_model
os . environ [ " HUGGINGFACEHUB_API_TOKEN " ] = "hf_..."
model = init_chat_model (
"microsoft/Phi-3-mini-4k-instruct" ,
model_provider = "huggingface" ,
temperature = 0.7 ,
max_tokens = 1024 ,
)
👉 阅读 OpenRouter 聊天模型集成文档 pip install -U "langchain-openrouter"
init_chat_model
Model Class
import os
from langchain . chat_models import init_chat_model
os . environ [ " OPENROUTER_API_KEY " ] = "sk-..."
model = init_chat_model (
"auto" ,
model_provider = "openrouter" ,
)
python response = model.invoke("为什么鹦鹉会说话?")
有关更多详细信息,包括如何传递模型参数 的信息,请参阅 init_chat_model 。
支持的提供商和模型
LangChain 通过专用的集成包支持所有主要的模型提供商。每个提供商包都实现了相同的标准接口,因此您可以在不重写应用程序逻辑的情况下交换提供商。新的模型名称可以立即使用——无需更新 LangChain——因为提供商包会将模型名称直接传递给提供商的 API。
浏览支持的提供商完整列表 ,或参阅提供商和模型 以了解提供商、包和模型名称在 LangChain 中如何协同工作的概念概述。
关键方法
调用 (Invoke) 模型将消息作为输入,并在生成完整响应后输出消息。
流式处理 (Stream) 调用模型,但实时流式传输生成的输出。
批处理 (Batch) 向模型批量发送多个请求以实现更高效的处理。
除了聊天模型,LangChain
还提供对其他相邻技术的支持,例如嵌入模型和向量存储。有关详细信息,请参阅集成页面 。
聊天模型接受可用于配置其行为的参数。支持的完整参数集因模型和提供商而异,但标准参数包括:
您希望与提供商一起使用的特定模型的名称或标识符。您也可以使用 ’
:’ 格式在单个参数中同时指定模型及其提供商,例如 ‘openai:o1’。
用于向模型提供商进行身份验证所需的密钥。这通常在您注册访问模型时颁发。通常通过设置 环境变量 来访问。
控制模型输出的随机性。数字越高,响应越有创意;数字越低,响应越确定。
在取消请求之前等待模型响应的最长时间(以秒为单位)。
如果请求因网络超时或速率限制等问题失败,系统将尝试重新发送请求的最大次数。重试使用带有抖动的指数退避。网络错误、速率限制
(429) 和服务器错误 (5xx) 会自动重试。客户端错误(如 401(未授权)或
404)不会重试。对于不可靠网络上的长时间运行的智能体 任务,建议将此值增加到
10-15。
使用 init_chat_model ,将这些参数作为内联**kwargs 传递:
model = init_chat_model (
"claude-sonnet-4-6" ,
# 传递给模型的 Kwargs:
temperature = 0.7 ,
timeout = 30 ,
max_tokens = 1000 ,
max_retries = 6 , # 默认值;对于不可靠网络请增加
)
每个聊天模型集成可能有额外的参数用于控制特定于提供商的功能。 例如,ChatOpenAI 有 use_responses_api 来决定是使用 OpenAI Responses API 还是 Completions API。 要查找给定聊天模型支持的所有参数,请访问聊天模型集成 页面。
必须调用聊天模型才能生成输出。有三种主要的调用方法,每种方法适用于不同的用例。
调用 (Invoke)
调用模型最直接的方法是使用 invoke() 传递单个消息或消息列表。
response = model . invoke ( "为什么鹦鹉有彩色的羽毛?" )
print ( response )
可以向聊天模型提供消息列表以表示对话历史。每条消息都有一个角色,模型使用该角色来指示对话中谁发送了消息。
有关角色、类型和内容的更多详细信息,请参阅消息 指南。
conversation = [
{ "role" : "system" , "content" : "您是一个将英语翻译成法语的有用助手。" },
{ "role" : "user" , "content" : "翻译:我喜欢编程。" },
{ "role" : "assistant" , "content" : "J'adore la programmation." },
{ "role" : "user" , "content" : "翻译:我喜欢构建应用程序。" }
]
response = model . invoke ( conversation )
print ( response ) # AIMessage("J'adore créer des applications.")
from langchain . messages import HumanMessage , AIMessage , SystemMessage
conversation = [
SystemMessage ( "您是一个将英语翻译成法语的有用助手。" ),
HumanMessage ( "翻译:我喜欢编程。" ),
AIMessage ( "J'adore la programmation." ),
HumanMessage ( "翻译:我喜欢构建应用程序。" )
]
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 ( "为什么鹦鹉有彩色的羽毛?" ):
print ( chunk . text , end = "|" , flush = True )
与 invoke() 在模型完成生成完整响应后返回单个 AIMessage 不同,stream() 返回多个 AIMessageChunk 对象,每个对象包含部分输出文本。重要的是,流中的每个块都设计为通过求和收集到完整消息中:
full = None # None | AIMessageChunk
for chunk in model . stream ( "天空是什么颜色?" ):
full = chunk if full is None else full + chunk
print ( full . text )
# 天空
# 天空是
# 天空通常是
# 天空通常是蓝色
# ...
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 "输入: { event [ ' data ' ][ 'input' ] } " )
elif event [ " event " ] == "on_chat_model_stream" :
print ( f "令牌: { event [ ' data ' ][ 'chunk' ]. text } " )
elif event [ " event " ] == "on_chat_model_end" :
print ( f "完整消息: { event [ ' data ' ][ 'output' ]. text } " )
else :
pass
输入: Hello
令牌: Hi
令牌: there
令牌: !
令牌: How
令牌: can
令牌: I
...
完整消息: Hi there! How can I help today?
LangChain 通过在某些情况下自动启用流式处理模式来简化从聊天模型的流式处理,即使您没有显式调用流式处理方法。当您使用非流式调用方法但仍希望流式传输整个应用程序(包括来自聊天模型的中间结果)时,这尤其有用。 在 LangGraph 智能体 中,例如,您可以在节点内调用 model.invoke(),但如果在流式处理模式下运行,LangChain 会自动委托给流式处理。 工作原理 当您 invoke() 一个聊天模型时,如果 LangChain 检测到您正在尝试流式传输整个应用程序,它会自动切换到内部流式处理模式。调用的结果对于使用 invoke 的代码来说是相同的;但是,当聊天模型被流式处理时,LangChain 会负责在 LangChain 的回调系统中调用 on_llm_new_token 事件。 回调事件允许 LangGraph stream() 和 astream_events() 实时显示聊天模型的输出。
批处理 (Batch)
将独立请求的集合批量发送到模型可以显著提高性能并降低成本,因为处理可以并行完成:
responses = model . batch ([
"为什么鹦鹉有彩色的羽毛?" ,
"飞机如何飞行?" ,
"什么是量子计算?"
])
for response in responses :
print ( response )
默认情况下,batch() 仅返回整个批处理的最终输出。如果您希望在每个输入完成生成时接收其输出,可以使用 batch_as_completed() 流式传输结果:
for response in model . batch_as_completed ([
"为什么鹦鹉有彩色的羽毛?" ,
"飞机如何飞行?" ,
"什么是量子计算?"
]):
print ( response )
有关批处理的更多详细信息,请参阅参考 。
工具调用
模型可以请求调用执行任务的工具,例如从数据库获取数据、搜索网络或运行代码。工具是以下内容的配对:
一个模式,包括工具的名称、描述和/或参数定义(通常是 JSON 模式)
一个函数或协程 来执行。
您可能会听到“函数调用”这个术语。我们将其与“工具调用”互换使用。
以下是用户和模型之间的基本工具调用流程:
要使您定义的工具可供模型使用,必须使用 bind_tools 将它们绑定。在后续调用中,模型可以根据需要选择调用任何绑定的工具。
一些模型提供商提供内置工具 ,可以通过模型或调用参数启用(例如 ChatOpenAI , ChatAnthropic )。有关详细信息,请检查相应的提供商参考 。
有关创建工具的详细信息和其他选项,请参阅工具指南 。
from langchain . tools import tool
@tool
def get_weather ( location : str ) -> str :
"""获取某个位置的天气。"""
return f "It's sunny in { location } ."
model_with_tools = model . bind_tools ([ get_weather ])
response = model_with_tools . invoke ( "波士顿的天气怎么样?" )
for tool_call in response . tool_calls :
# 查看模型进行的工具调用
print ( f "工具: { tool_call [ ' name ' ] } " )
print ( f "参数: { tool_call [ ' args ' ] } " )
当绑定用户定义的工具时,模型的响应包含一个执行工具的请求 。当在智能体 之外单独使用模型时,由您来执行请求的工具并将结果返回给模型以供后续推理使用。当使用智能体 时,智能体循环将为您处理工具执行循环。
下面,我们展示了一些使用工具调用的常见方法。
当模型返回工具调用时,您需要执行工具并将结果传回模型。这会创建一个对话循环,模型可以使用工具结果来生成其最终响应。LangChain 包括处理此编排的智能体 抽象。 以下是如何执行此操作的简单示例: # 将(可能多个)工具绑定到模型
model_with_tools = model . bind_tools ([ get_weather ])
# 步骤 1:模型生成工具调用
messages = [{ "role" : "user" , "content" : "波士顿的天气怎么样?" }]
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,该 ID 与原始工具调用匹配,帮助模型将结果与请求关联起来。
结构化输出
可以请求模型以匹配给定模式的格式提供其响应。这对于确保输出易于解析并在后续处理中使用非常有用。LangChain 支持多种模式类型和强制结构化输出的方法。
Pydantic
TypedDict
JSON 模式
Pydantic 模型 提供了最丰富的功能集,包括字段验证、描述和嵌套结构。from pydantic import BaseModel , Field
class Movie ( BaseModel ):
"""一部包含详细信息的电影。"""
title : str = Field ( description = "电影标题" )
year : int = Field ( description = "电影发行年份" )
director : str = Field ( description = "电影导演" )
rating : float = Field ( description = "电影评分(满分10分)" )
model_with_structure = model . with_structured_output ( Movie )
response = model_with_structure . invoke ( "提供电影《盗梦空间》的详细信息" )
print ( response ) # Movie(title="Inception", year=2010, director="Christopher Nolan", rating=8.8)
Python 的 TypedDict 提供了比 Pydantic 模型更简单的替代方案,当您不需要运行时验证时非常理想。 from typing_extensions import TypedDict , Annotated
class MovieDict ( TypedDict ):
"""一部包含详细信息的电影。"""
title : Annotated [ str , ... , " 电影标题 " ]
year : Annotated [ int , ... , " 电影发行年份 " ]
director : Annotated [ str , ... , " 电影导演 " ]
rating : Annotated [ float , ... , " 电影评分(满分10分) " ]
model_with_structure = model . with_structured_output ( MovieDict )
response = model_with_structure . invoke ( "提供电影《盗梦空间》的详细信息" )
print ( response ) # {'title': 'Inception', 'year': 2010, 'director': 'Christopher Nolan', 'rating': 8.8}
提供 JSON 模式 以获得最大控制和互操作性。 import json
json_schema = {
"title" : "Movie" ,
"description" : "一部包含详细信息的电影" ,
"type" : "object" ,
"properties" : {
"title" : {
"type" : "string" ,
"description" : "电影标题"
},
"year" : {
"type" : "integer" ,
"description" : "电影发行年份"
},
"director" : {
"type" : "string" ,
"description" : "电影导演"
},
"rating" : {
"type" : "number" ,
"description" : "电影评分(满分10分)"
}
},
"required" : [ "title" , "year" , "director" , "rating" ]
}
model_with_structure = model . with_structured_output (
json_schema ,
method = "json_schema" ,
)
response = model_with_structure . invoke ( "提供电影《盗梦空间》的详细信息" )
print ( response ) # {'title': 'Inception', 'year': 2010, ...}
结构化输出的关键注意事项
方法参数 :一些提供商支持不同的结构化输出方法:
'json_schema':使用提供商提供的专用结构化输出功能。
'function_calling':通过强制遵循给定模式的工具调用 来派生结构化输出。
'json_mode':某些提供商提供的 'json_schema' 的前身。生成有效的 JSON,但模式必须在提示中描述。
包含原始消息 :设置 include_raw=True 以获取解析后的输出和原始 AI 消息。
验证 :Pydantic 模型提供自动验证。TypedDict 和 JSON 模式需要手动验证。
有关支持的方法和配置选项,请参阅您的提供商集成页面 。
返回原始 AIMessage 对象以及解析后的表示形式可能很有用,以便访问响应元数据,例如令牌计数 。为此,在调用 with_structured_output 时设置 include_raw=True : from pydantic import BaseModel , Field
class Movie ( BaseModel ):
"""一部包含详细信息的电影。"""
title : str = Field ( description = "电影标题" )
year : int = Field ( description = "电影发行年份" )
director : str = Field ( description = "电影导演" )
rating : float = Field ( description = "电影评分(满分10分)" )
model_with_structure = model . with_structured_output ( Movie , include_raw = True )
response = model_with_structure . invoke ( "提供电影《盗梦空间》的详细信息" )
response
# {
# "raw": AIMessage(...),
# "parsed": Movie(title=..., year=..., ...),
# "parsing_error": None,
# }
模式可以嵌套: Pydantic BaseModel
TypedDict
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 = "预算(百万美元)" )
model_with_structure = model . with_structured_output ( MovieDetails )
高级主题
模型配置文件
LangChain 聊天模型可以通过 profile 属性公开支持的功能和能力的字典:
model . profile
# {
# "max_input_tokens": 400000,
# "image_inputs": True,
# "reasoning_output": True,
# "tool_calling": True,
# ...
# }
有关字段的完整列表,请参阅 API 参考 。
大部分模型配置文件数据由 models.dev 项目提供,这是一个提供模型能力数据的开源计划。这些数据通过额外的字段进行了增强,以便与 LangChain 一起使用。这些增强功能会随着上游项目的演变而保持一致。
模型配置文件数据允许应用程序动态地处理模型能力。例如:
摘要中间件 可以根据模型的上下文窗口大小触发摘要。
create_agent 中的结构化输出 策略可以自动推断(例如,通过检查对原生结构化输出功能的支持)。
模型输入可以根据支持的模态 和最大输入令牌数进行限制。
Deep Agents CLI 过滤交互式模型切换器 以显示其配置文件报告支持 tool_calling 和文本 I/O 的模型,并在选择器详细视图中显示上下文窗口大小和能力标志。
模型配置文件是测试版功能。配置文件的格式可能会发生变化。
多模态
某些模型可以处理和返回非文本数据,如图像、音频和视频。您可以通过提供内容块 将非文本数据传递给模型。
所有具有底层多模态功能的 LangChain 聊天模型都支持:
跨提供商标准格式的数据(请参阅我们的消息指南 )
OpenAI 聊天补全 格式
特定于该提供商的任何原生格式(例如,Anthropic 模型接受 Anthropic 原生格式)
有关详细信息,请参阅消息指南的多模态部分 。
某些模型
可以在其响应中返回多模态数据。如果调用这样做,生成的
AIMessage
将包含具有多模态类型的内容块。
response = model . invoke ( "创建一张猫的图片" )
print ( response . content_blocks )
# [
# {"type": "text", "text": "这是一张猫的图片"},
# {"type": "image", "base64": "...", "mime_type": "image/jpeg"},
# ]
有关特定提供商的详细信息,请参阅集成页面 。
许多模型能够执行多步推理以得出结论。这涉及将复杂问题分解为更小、更易管理的步骤。
如果底层模型支持, 您可以显示此推理过程以更好地了解模型如何得出最终答案。
for chunk in model . stream ( "为什么鹦鹉有彩色的羽毛?" ):
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 是在本地运行聊天和嵌入模型的最简单方法之一。
提示缓存
许多提供商提供提示缓存功能,以减少重复处理相同令牌时的延迟和成本。这些功能可以是隐式 或显式 的:
隐式提示缓存 :如果请求命中缓存,提供商将自动传递成本节省。示例:OpenAI 和 Gemini 。
显式缓存 :提供商允许您手动指示缓存点以获得更大的控制或保证成本节省。示例:
提示缓存通常仅在超过最小输入令牌阈值时才启用。有关详细信息,请参阅提供商页面 。
缓存使用情况将反映在模型响应的使用元数据 中。
服务器端工具使用
一些提供商支持服务器端工具调用 循环:模型可以与网络搜索、代码解释器和其他工具交互,并在单个对话回合中分析结果。
如果模型在服务器端调用工具,响应消息的内容将包含表示工具调用和结果的内容。访问响应的内容块 将返回服务器端工具调用和结果,格式与提供商无关:
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 ( "今天有什么积极的新闻故事吗?" )
print ( response . content_blocks )
[
{
"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 。此限制器是线程安全的,可以由同一进程中的多个线程共享。 from langchain_core . rate_limiters import InMemoryRateLimiter
rate_limiter = InMemoryRateLimiter (
requests_per_second = 0.1 , # 每 10 秒 1 个请求
check_every_n_seconds = 0.1 , # 每 100 毫秒检查一次是否允许发出请求
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 AI , vLLM )。您可以使用 init_chat_model 与这些提供商一起使用,通过指定适当的 base_url 参数: 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 ( "为什么鹦鹉会说话?" )
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 }
}
}
from langchain . chat_models import init_chat_model
from langchain_core . callbacks import get_usage_metadata_callback
model_1 = init_chat_model ( model = "gpt-4.1-mini" )
model_2 = init_chat_model ( model = "claude-haiku-4-5-20251001" )
with get_usage_metadata_callback () as cb :
model_1 . invoke ( "Hello" )
model_2 . invoke ( "Hello" )
print ( cb . 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 字典传递其他配置。这提供了对执行行为、回调和元数据跟踪的运行时控制。
常见的配置选项包括:
response = model . invoke (
"讲个笑话" ,
config = {
"run_name" : "joke_generation" , # 此运行的自定义名称
"tags" : [ "humor" , "demo" ], # 用于分类的标签
"metadata" : { "user_id" : "123" }, # 自定义元数据
"callbacks" : [ my_callback_handler ], # 回调处理程序
}
)
这些配置值在以下情况下特别有用:
使用 LangSmith 跟踪进行调试
实现自定义日志记录或监控
在生产中控制资源使用
跟踪复杂管道中的调用
由所有子调用继承的标签,用于在调试工具中进行过滤和组织。
用于跟踪附加上下文的自定义键值对,由所有子调用继承。
可配置模型
您还可以通过指定 configurable_fields 创建运行时可配置的模型。如果您未指定模型值,则 'model' 和 'model_provider' 将默认可配置。
from langchain . chat_models import init_chat_model
configurable_model = init_chat_model ( temperature = 0 )
configurable_model . invoke (
"你叫什么名字" ,
config = { "configurable" : { "model" : "gpt-5-nano" }}, # 使用 GPT-5-Nano 运行
)
configurable_model . invoke (
"你叫什么名字" ,
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 ( "你叫什么名字" )
first_model . invoke (
"你叫什么名字" ,
config = {
"configurable" : {
"first_model" : "claude-sonnet-4-6" ,
"first_temperature" : 0.5 ,
"first_max_tokens" : 100 ,
}
},
)
有关 configurable_fields 和 config_prefix 的更多详细信息,请参阅 init_chat_model 参考。