跳转到内容

聊天模型

langchain.chat_models

在 LangChain 中使用聊天模型的入口。

参考文档

本页包含聊天模型的参考文档。关于使用聊天模型的概念指南、教程和示例,请参阅文档

init_chat_model

init_chat_model(
    model: str | None = None,
    *,
    model_provider: str | None = None,
    configurable_fields: Literal["any"] | list[str] | tuple[str, ...] | None = None,
    config_prefix: str | None = None,
    **kwargs: Any,
) -> BaseChatModel | _ConfigurableModel

使用统一的接口从任何支持的提供商初始化聊天模型。

两个主要用例

  1. 固定模型 – 事先指定模型,获取一个即用型聊天模型。
  2. 可配置模型 – 选择在运行时通过 config 指定参数(包括模型名称)。这样可以轻松地在不同模型/提供商之间切换,而无需更改代码。

注意

需要安装所选模型提供商的集成包。

请参阅下面的 model_provider 参数以了解具体的包名称(例如,pip install langchain-openai)。

有关支持的模型参数以用作 **kwargs 的信息,请参阅提供商集成的 API 参考

参数 描述

model

模型的名称或 ID,例如 'o3-mini', 'claude-sonnet-4-5-20250929'

您也可以使用 '{model_provider}:{model}' 格式在单个参数中指定模型和模型提供商,例如 'openai:o1'

类型: str | None 默认值: None

model_provider

模型提供商,如果未在模型参数中指定(见上文)。

支持的 model_provider 值及其对应的集成包如下

如果未指定,将尝试从模型名称推断 model_provider。将根据以下模型前缀推断提供商

  • gpt-... | o1... | o3... -> openai
  • claude... -> anthropic
  • amazon... -> bedrock
  • gemini... -> google_vertexai
  • command... -> cohere
  • accounts/fireworks... -> fireworks
  • mistral... -> mistralai
  • deepseek... -> deepseek
  • grok... -> xai
  • sonar... -> perplexity

类型: str | None 默认值: None

configurable_fields

哪些模型参数可在运行时配置

  • None: 无可配置字段(即固定模型)。
  • 'any': 所有字段均可配置。请参阅下面的安全说明。
  • list[str] | Tuple[str, ...]: 指定的字段可配置。

如果指定了 config_prefix,则假定字段已移除 config_prefix

如果指定了 model,则默认为 None

如果未指定 model,则默认为 ("model", "model_provider")

安全说明

设置 configurable_fields="any" 意味着像 api_keybase_url 等字段可以在运行时更改,这可能会将模型请求重定向到不同的服务/用户。

如果您接受不受信任的配置,请确保明确列出 configurable_fields=(...)

类型: Literal['any'] | list[str] | tuple[str, ...] | None 默认值: None

config_prefix

配置键的可选前缀。

当同一应用程序中有多个可配置模型时非常有用。

如果 'config_prefix' 是非空字符串,则 model 将在运行时通过 config["configurable"]["{config_prefix}_{param}"] 键进行配置。请参阅下面的示例。

如果 'config_prefix' 是空字符串,则模型将通过 config["configurable"]["{param}"] 进行配置。

类型: str | None 默认值: None

**kwargs

传递给底层聊天模型 __init__ 方法的额外特定于模型的关键字参数。常见参数包括

  • temperature: 用于控制随机性的模型温度。
  • max_tokens: 输出令牌的最大数量。
  • timeout: 等待响应的最长时间(秒)。
  • max_retries: 失败请求的最大重试次数。
  • base_url: 自定义 API 端点 URL。
  • rate_limiter: 一个 BaseRateLimiter 实例,用于控制请求速率。

有关所有可用参数,请参阅特定模型提供商的集成参考

类型: Any 默认值: {}

返回 描述
BaseChatModel | _ConfigurableModel

如果可配置性被推断为 `False`,则返回与指定的 `model_name` 和 `model_provider` 对应的 `BaseChatModel`。如果可配置,则返回一个聊天模型模拟器,它在传递配置后于运行时初始化底层模型。

引发 描述
ValueError

如果无法推断或不支持 model_provider

ImportError

如果未安装模型提供商的集成包。

初始化一个不可配置的模型
# pip install langchain langchain-openai langchain-anthropic langchain-google-vertexai

from langchain.chat_models import init_chat_model

o3_mini = init_chat_model("openai:o3-mini", temperature=0)
claude_sonnet = init_chat_model("anthropic:claude-sonnet-4-5-20250929", temperature=0)
gemini_2-5_flash = init_chat_model("google_vertexai:gemini-2.5-flash", temperature=0)

o3_mini.invoke("what's your name")
claude_sonnet.invoke("what's your name")
gemini_2-5_flash.invoke("what's your name")
无默认值的部分可配置模型
# pip install langchain langchain-openai langchain-anthropic

from langchain.chat_models import init_chat_model

# (We don't need to specify configurable=True if a model isn't specified.)
configurable_model = init_chat_model(temperature=0)

configurable_model.invoke("what's your name", config={"configurable": {"model": "gpt-4o"}})
# Use GPT-4o to generate the response

configurable_model.invoke(
    "what's your name",
    config={"configurable": {"model": "claude-sonnet-4-5-20250929"}},
)
有默认值的完全可配置模型
# pip install langchain langchain-openai langchain-anthropic

from langchain.chat_models import init_chat_model

configurable_model_with_default = init_chat_model(
    "openai:gpt-4o",
    configurable_fields="any",  # This allows us to configure other params like temperature, max_tokens, etc at runtime.
    config_prefix="foo",
    temperature=0,
)

configurable_model_with_default.invoke("what's your name")
# GPT-4o response with temperature 0 (as set in default)

configurable_model_with_default.invoke(
    "what's your name",
    config={
        "configurable": {
            "foo_model": "anthropic:claude-sonnet-4-5-20250929",
            "foo_temperature": 0.6,
        }
    },
)
# Override default to use Sonnet 4.5 with temperature 0.6 to generate response
将工具绑定到可配置模型

您可以像在普通模型上一样,在可配置模型上调用任何聊天模型的声明式方法。

# pip install langchain langchain-openai langchain-anthropic

from langchain.chat_models import init_chat_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")


configurable_model = init_chat_model(
    "gpt-4o", configurable_fields=("model", "model_provider"), temperature=0
)

configurable_model_with_tools = configurable_model.bind_tools(
    [
        GetWeather,
        GetPopulation,
    ]
)
configurable_model_with_tools.invoke(
    "Which city is hotter today and which is bigger: LA or NY?"
)
# Use GPT-4o

configurable_model_with_tools.invoke(
    "Which city is hotter today and which is bigger: LA or NY?",
    config={"configurable": {"model": "claude-sonnet-4-5-20250929"}},
)
# Use Sonnet 4.5
© . This site is unofficial and not affiliated with LangChain, Inc.