跳转到内容

聊天模型 (经典)

langchain-classic 文档

本文档涵盖 langchain-classic 包。该包将持续维护安全漏洞至 2026 年 12 月。我们鼓励用户迁移到 langchain 包以获取最新的功能和改进。查看 langchain 的文档

langchain_classic.chat_models

聊天模型 (Chat Models) 是语言模型的一种变体。

虽然聊天模型底层使用语言模型,但它们暴露的接口略有不同。它们不提供“文本输入,文本输出”的 API,而是提供一种以“聊天消息”作为输入和输出的接口。

函数 描述
init_chat_model

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

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_key`、`base_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_classic.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_classic.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_classic.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_classic.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

0.2.8 版本中的行为变更

增加了对 `configurable_fields` 和 `config_prefix` 的支持。

0.2.12 版本中的行为变更

增加了通过 langchain-ollama 包对 Ollama 的支持 (`langchain_ollama.ChatOllama`)。以前,导入的是现已弃用的 langchain-community 版本的 Ollama (`langchain_community.chat_models.ChatOllama`)。

增加了通过 Converse API 对 AWS Bedrock 模型的支持 (`model_provider="bedrock_converse"`)。

0.3.5 版本中的行为变更

脱离 Beta 测试阶段。

0.3.19 版本中的行为变更

增加了对 Deepseek、IBM、Nvidia 和 xAI 模型的支持。

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