跳到主要内容

文档索引

在以下地址获取完整的文档索引:https://docs.langchain.org.cn/llms.txt

在进一步探索之前,请使用此文件发现所有可用页面。

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

基本用法

模型可以通过两种方式使用
  1. 与智能体配合 - 在创建智能体时可以动态指定模型。
  2. 独立使用 - 模型可以直接调用(在智能体循环之外),用于文本生成、分类或提取等任务,而无需智能体框架。
相同的模型接口在两种语境下均适用,这让您可以灵活地从简单开始,并根据需要扩展到更复杂的基于智能体的工作流。

初始化模型

在 LangChain 中开始使用独立模型最简单的方法是使用 init_chat_model 从您选择的聊天模型提供商处初始化一个(见下例)
👉 阅读 OpenAI 聊天模型集成文档
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 了解更多细节,包括如何传递模型参数的信息。

支持的提供商和模型

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

关键方法

调用

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

流式处理

调用模型,但在生成输出时实时流式传输。

批量处理

批量发送多个请求到模型,以进行更高效的处理。
除了聊天模型外,LangChain 还支持其他相关技术,如嵌入模型和向量库。详情请参阅集成页面

参数

聊天模型接受可用于配置其行为的参数。支持的完整参数集因模型和提供商而异,但标准参数包括:
model
字符串
必填
要与提供商配合使用的特定模型名称或标识符。您也可以使用“:”格式在单个参数中同时指定模型及其提供商,例如 ‘openai:o1’。
api_key
字符串
与模型提供商进行身份验证所需的密钥。这通常在您注册访问模型时发放。通常通过设置.
temperature
数字
控制模型输出的随机性。数值越高,响应越有创意;数值越低,响应越具确定性。
max_tokens
数字
限制响应中的总数量,从而有效控制输出的长度。
timeout
数字
在取消请求之前等待模型响应的最长时间(以秒为单位)。
max_retries
数字
默认值:"6"
如果请求由于网络超时或速率限制等问题而失败,系统尝试重新发送请求的最大次数。重试使用带抖动的指数退避。网络错误、速率限制 (429) 和服务器错误 (5xx) 会自动重试。客户端错误(如 401 未授权或 404)不会重试。对于不可靠网络上运行的耗时较长的智能体任务,请考虑将此值增加到 10–15。
使用 init_chat_model,将这些参数作为内联:
使用模型参数进行初始化
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
)
每个聊天模型集成可能都有用于控制特定提供商功能的附加参数。例如,ChatOpenAI 具有 use_responses_api 参数,用于决定是使用 OpenAI Responses API 还是 Completions API。要查找给定聊天模型支持的所有参数,请访问聊天模型集成页面。

调用

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

调用

调用模型最直接的方法是使用 invoke() 传递单条消息或消息列表。
单条消息
response = model.invoke("Why do parrots have colorful feathers?")
print(response)
可以向聊天模型提供消息列表以表示对话历史记录。每条消息都有一个角色,模型使用角色来指示对话中是谁发送了该消息。 参阅消息指南,了解有关角色、类型和内容的更多细节。
字典格式
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.")
消息对象
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() 会返回一个 ,该迭代器会在输出块产生时产出它们。您可以使用循环来实时处理每个块:
for chunk in model.stream("Why do parrots have colorful feathers?"):
    print(chunk.text, end="|", flush=True)
invoke() 在模型完成生成完整响应后返回单个 AIMessage 不同,stream() 返回多个 AIMessageChunk 对象,每个对象包含输出文本的一部分。重要的是,流中的每个块都旨在通过相加累积成一条完整的消息。
构建 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..."}]
生成的最终消息可以像使用 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() 实时呈现聊天模型的输出。

批量处理

批量处理一组独立的模型请求可以显著提高性能并降低成本,因为处理可以并行进行。
批量处理
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() 来流式传输结果。
在完成时产出批处理响应
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 属性来实现。
带最大并发限制的批量处理
model.batch(
    list_of_inputs,
    config={
        'max_concurrency': 5,  # Limit to 5 parallel calls
    }
)
参阅 RunnableConfig 参考文档以获取支持属性的完整列表。
有关批量处理的更多详情,请参阅参考文档

工具调用

模型可以请求调用执行任务的工具,例如从数据库中获取数据、搜索网页或运行代码。工具包含以下配对:
  1. 模式 (Schema),包括工具名称、描述和/或参数定义(通常是 JSON 模式)
  2. 要执行的函数或
您可能会听到“函数调用”这个词。我们将其与“工具调用”交替使用。
这是用户与模型之间基本的工具调用流程: 要使您定义的工具可供模型使用,必须使用 bind_tools 绑定它们。在随后的调用中,模型可以根据需要选择调用任何已绑定的工具。 一些模型提供商提供,可以通过模型或调用参数启用(例如 ChatOpenAIChatAnthropic)。详情请查看相应的提供商参考
参阅工具指南了解创建工具的详情和其他选项。
绑定用户工具
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 包含处理这种编排的智能体抽象。这里有一个简单的操作示例:
工具执行循环
# 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_id,帮助模型将结果与请求关联起来。
默认情况下,模型可以根据用户的输入自由选择使用哪个已绑定的工具。但是,您可能希望强制模型选择一个工具,确保模型使用特定工具或给定列表中的任何工具:
model_with_tools = model.bind_tools([tool_1], tool_choice="any")
许多模型支持在适当时并行调用多个工具。这允许模型同时从不同来源收集信息。
并行工具调用
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)
模型根据请求操作的独立性智能地确定何时适合并行执行。
大多数支持工具调用的模型默认启用并行工具调用。一些模型(包括 OpenAIAnthropic)允许您禁用此功能。为此,请设置 parallel_tool_calls=False
model.bind_tools([get_weather], parallel_tool_calls=False)
流式传输响应时,工具调用通过 ToolCallChunk 渐进式构建。这允许您在工具调用生成时查看到它们,而不是等待完整响应。
流式工具调用
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: "}
您可以累积块来构建完整的工具调用
累积工具调用
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="Inception", year=2010, director="Christopher Nolan", rating=8.8)
结构化输出的关键考虑因素
  • 方法参数:一些提供商支持不同的结构化输出方法
    • 'json_schema':使用提供商提供的专用结构化输出功能。
    • 'function_calling':通过强制执行遵循给定模式的工具调用来得出结构化输出。
    • 'json_mode':一些提供商提供的 'json_schema' 前身。生成有效的 JSON,但必须在提示词中描述模式。
  • 包含原始消息 (Include raw):设置 include_raw=True 以同时获取解析后的输出和原始 AI 消息。
  • 验证:Pydantic 模型提供自动验证。TypedDict 和 JSON 模式需要手动验证。
参阅您的提供商集成页面,了解支持的方法和配置选项。
在解析后的表示形式旁返回原始 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)

高级主题

模型配置文件

模型概况 (Model profiles) 需要 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. (如果需要)通过向其在 GitHub 上的仓库提交拉取请求,更新 models.dev 的源数据。
  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 单体仓库中,从 libs/partners/anthropic 运行。
uv run --with langchain-model-profiles --provider anthropic --data-dir langchain_anthropic/data
模型概况是一项测试版功能。概况的格式可能会发生变化。

多模态

某些模型可以处理并返回非文本数据,如图像、音频和视频。您可以通过提供内容块将非文本数据传递给模型。
所有具有底层多模态能力的 LangChain 聊天模型都支持:
  1. 跨提供商标准格式的数据(请参阅我们的消息指南
  2. OpenAI 聊天补全 (chat completions) 格式
  3. 任何特定于该提供商的原生格式(例如,Anthropic 模型接受 Anthropic 原生格式)
详情请参阅消息指南的多模态部分 可以作为其响应的一部分返回多模态数据。如果被调用执行此操作,生成的 AIMessage 将具有包含多模态类型的内容块。
多模态输出
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"},
# ]
有关特定提供商的详细信息,请参阅集成页面

推理

许多模型能够执行多步推理以得出结论。这涉及将复杂问题分解为更小、更易于管理的步骤。 如果底层模型支持,您可以呈现此推理过程,以更好地了解模型如何得出最终答案。
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 是在本地运行聊天和嵌入模型最简单的方法之一。

提示缓存

许多提供商提供提示词缓存功能,以减少重复处理相同标记时的延迟和成本。这些功能可以是隐式的或显式的:
  • 隐式提示词缓存:如果请求命中缓存,提供商将自动传递节省的成本。例如:OpenAIGemini
  • 显式缓存:提供商允许您手动指示缓存点,以获得更大的控制权或保证成本节省。示例包括:
提示词缓存通常仅在超过最小输入标记阈值时启用。详情请参阅提供商页面
缓存使用情况将反映在模型响应的使用元数据中。

服务器端工具使用

一些提供商支持服务端工具调用循环:模型可以与网页搜索、代码解释器和其他工具进行交互,并在单个对话轮次中分析结果。 如果模型在服务端调用工具,响应消息的内容将包含代表该调用和工具结果的内容。访问响应的内容块将以与提供商无关的格式返回服务端工具调用和结果:
通过服务端工具使用进行调用
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)
结果
[
    {
        "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,  # 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  
)
提供的速率限制器只能限制单位时间内的请求数量。如果您还需要根据请求的大小进行限制,它将无济于事。

基础 URL 和代理设置

您可以为实现了 OpenAI 聊天补全 API 的提供商配置自定义基础 URL。
model_provider="openai"(或直接使用 ChatOpenAI)针对官方 OpenAI API 规范。来自路由和代理的特定于提供商的字段可能无法提取或保留。对于 OpenRouter 和 LiteLLM,建议使用专用集成:
许多模型提供商提供与 OpenAI 兼容的 API(例如 Together AI, vLLM)。您可以通过指定适当的 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-5.4",
    openai_proxy="http://proxy.example.com:8080"
)
代理支持因集成而异。请查看特定模型提供商的参考文档以了解代理配置选项。

对数概率

通过在初始化模型时设置 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 用量

许多模型提供商会将标记使用信息作为调用响应的一部分返回。如果可用,此信息将包含在由相应模型生成的 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-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}
    }
}

调用配置

调用模型时,您可以使用 RunnableConfig 字典通过 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
字符串
在日志和追踪中标识此特定调用。子调用不会继承。
tags
字符串[]
所有子调用继承的标签,用于在调试工具中进行过滤和组织。
metadata
对象
用于跟踪额外上下文的自定义键值对,由所有子调用继承。
max_concurrency
数字
在使用 batch()batch_as_completed() 时控制最大并行调用数。
callbacks
array
用于在执行期间监控和响应事件的处理程序。
recursion_limit
数字
链的最大递归深度,以防止复杂流水线中的无限循环。
参阅完整的 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"}},  # Run with GPT-5-Nano
)
configurable_model.invoke(
    "what's your name",
    config={"configurable": {"model": "claude-sonnet-4-6"}},  # Run with Claude
)
我们可以创建带有默认模型值的可配置模型,指定哪些参数是可配置的,并为可配置参数添加前缀。
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,
        }
    },
)
参阅 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-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'
    }
]

© . This site is unofficial and not affiliated with LangChain, Inc.