跳转至

模型

LangGraph 通过 LangChain 库提供对 LLM (语言模型) 的内置支持。这使得将各种 LLM 集成到你的智能代理和工作流中变得容易。

初始化模型

使用 init_chat_model 初始化模型:

聊天模型配置

查看支持的聊天模型配置方法:聊天模型选项卡

支持的模型包括:OpenAI、Anthropic、Azure、Google Gemini 和 AWS Bedrock。

使用模型提供商类初始化模型:

import { ChatOpenAI } from "@langchain/openai";

const model = new ChatOpenAI({
  model: "gpt-4o",
  temperature: 0,
});
import { ChatAnthropic } from "@langchain/anthropic";

const model = new ChatAnthropic({
  model: "claude-3-5-sonnet-20240620",
  temperature: 0,
  maxTokens: 2048,
});
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";

const model = new ChatGoogleGenerativeAI({
  model: "gemini-1.5-pro",
  temperature: 0,
});
import { ChatGroq } from "@langchain/groq";

const model = new ChatGroq({
  model: "llama-3.1-70b-versatile",
  temperature: 0,
});

直接实例化模型

如果模型提供商无法通过 init_chat_model 使用,你可以直接实例化提供商的模型类。该模型必须实现 BaseChatModel 接口并支持工具调用:

# Anthropic 已被 `init_chat_model` 支持,
# 但你也可以直接实例化它。
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(
  model="claude-3-7-sonnet-latest",
  temperature=0,
  max_tokens=2048
)

工具调用支持

如果你正在构建需要模型调用外部工具的智能代理或工作流,请确保底层语言模型支持工具调用。兼容的模型可以在 LangChain 集成目录中找到。

在智能代理中使用

使用 create_react_agent 时,你可以通过其名称字符串指定模型,这是使用 init_chat_model 初始化模型的简写。这允许你使用模型而无需直接导入或实例化它。

from langgraph.prebuilt import create_react_agent

create_react_agent(
   # highlight-next-line
   model="anthropic:claude-3-7-sonnet-latest",
   # 其他参数
)
from langchain_anthropic import ChatAnthropic
from langgraph.prebuilt import create_react_agent

model = ChatAnthropic(
    model="claude-3-7-sonnet-latest",
    temperature=0,
    max_tokens=2048
)
# 或者
# model = init_chat_model("anthropic:claude-3-7-sonnet-latest")

agent = create_react_agent(
  # highlight-next-line
  model=model,
  # 其他参数
)

使用 createReactAgent 时,你可以直接传递模型实例:

import { ChatOpenAI } from "@langchain/openai";
import { createReactAgent } from "@langchain/langgraph/prebuilt";

const model = new ChatOpenAI({
  model: "gpt-4o",
  temperature: 0,
});

const agent = createReactAgent({
  llm: model,
  tools: tools,
});

动态模型选择

将可调用函数传递给 create_react_agent 以在运行时动态选择模型。这对于你想要根据用户输入、配置设置或其他运行时条件选择模型的场景很有用。

选择器函数必须返回聊天模型。如果你使用工具,你必须在选择器函数内将工具绑定到模型。

```python from dataclasses import dataclass from typing import Literal from langchain.chat_models import init_chat_model from langchain_core.language_models import BaseChatModel from langchain_core.tools import tool from langgraph.prebuilt import create_react_agent from langgraph.prebuilt.chat_agent_executor import AgentState from langgraph.runtime import Runtime

@tool def weather() -> str: """返回当前天气状况。""" return "It's nice and sunny."

定义运行时上下文

@dataclass class CustomContext: provider: Literal["anthropic", "openai"]

初始化模型

openai_model = init_chat_model("openai:gpt-4o") anthropic_model = init_chat_model("anthropic:claude-sonnet-4-20250514")

模型选择的选择器函数

def select_model(state: AgentState, runtime: Runtime[CustomContext]) -> BaseChatModel: if runtime.context.provider == "anthropic": model = anthropic_model elif runtime.context.provider == "openai": model = openai_model else: raise ValueError(f"Unsupported provider: {runtime.context.provider}")

# 使用动态模型选择时,你必须明确绑定工具
return model.bind_tools([weather])

创建具有动态模型选择的智能代理

agent = create_react_agent(select_model, tools=[weather])

使用上下文调用以选择模型

output = agent.invoke( { "messages": [ { "role": "user", "content": "Which model is handling this?", } ] }, context=CustomContext(provider="openai"), )

print(output["messages"][-1].text())

!!! version-added "在版本 0.6.0 中添加"


## 高级模型配置

### 禁用流式传输

=== "Python"
要禁用单个 LLM 标记的流式传输,请在初始化模型时设置 `disable_streaming=True`:

=== "`init_chat_model`"

    ```python
    from langchain.chat_models import init_chat_model

    model = init_chat_model(
        "anthropic:claude-3-7-sonnet-latest",
        # highlight-next-line
        disable_streaming=True
    )
    ```

=== "`ChatModel`"

    ```python
    from langchain_anthropic import ChatAnthropic

    model = ChatAnthropic(
        model="claude-3-7-sonnet-latest",
        # highlight-next-line
        disable_streaming=True
    )
    ```

有关 `disable_streaming` 的更多信息,请参阅 [API 参考](https://python.langchain.com/api_reference/core/language_models/langchain_core.language_models.chat_models.BaseChatModel.html#langchain_core.language_models.chat_models.BaseChatModel.disable_streaming)

=== "JavaScript"
要禁用单个 LLM 标记的流式传输,请在初始化模型时设置 `streaming: false`:

```typescript
import { ChatOpenAI } from "@langchain/openai";

const model = new ChatOpenAI({
  model: "gpt-4o",
  streaming: false,
});

添加模型备用方案

你可以使用 model.with_fallbacks([...]) 添加备用方案到不同的模型或不同的 LLM 提供商:

from langchain.chat_models import init_chat_model

model_with_fallbacks = (
    init_chat_model("anthropic:claude-3-5-haiku-latest")
    # highlight-next-line
    .with_fallbacks([
        init_chat_model("openai:gpt-4.1-mini"),
    ])
)
from langchain_anthropic import ChatAnthropic
from langchain_openai import ChatOpenAI

model_with_fallbacks = (
    ChatAnthropic(model="claude-3-5-haiku-latest")
    # highlight-next-line
    .with_fallbacks([
        ChatOpenAI(model="gpt-4.1-mini"),
    ])
)

有关模型备用方案的更多信息,请参阅此指南

你可以使用 model.withFallbacks([...]) 添加备用方案到不同的模型或不同的 LLM 提供商:

import { ChatOpenAI } from "@langchain/openai";
import { ChatAnthropic } from "@langchain/anthropic";

const modelWithFallbacks = new ChatOpenAI({
  model: "gpt-4o",
}).withFallbacks([
  new ChatAnthropic({
    model: "claude-3-5-sonnet-20240620",
  }),
]);

有关模型备用方案的更多信息,请参阅此指南

使用内置的速率限制器

Langchain 包含一个内置的内存速率限制器。此速率限制器是线程安全的,可以被同一进程中的多个线程共享。

from langchain_core.rate_limiters import InMemoryRateLimiter
from langchain_anthropic import ChatAnthropic

rate_limiter = InMemoryRateLimiter(
    requests_per_second=0.1,  # <-- 超慢!我们每10秒只能发出一次请求!!
    check_every_n_seconds=0.1,  # 每100毫秒唤醒一次以检查是否允许发出请求,
    max_bucket_size=10,  # 控制最大突发大小。
)

model = ChatAnthropic(
   model_name="claude-3-opus-20240229",
   rate_limiter=rate_limiter
)

有关如何处理速率限制的更多信息,请参阅 LangChain 文档。

自带模型

如果你想要的 LLM 未被 LangChain 官方支持,请考虑以下选项:

  1. 实现自定义 LangChain 聊天模型: 创建符合 LangChain 聊天模型接口的模型。这使得与 LangGraph 的智能代理和工作流完全兼容,但需要理解 LangChain 框架。
  1. 实现自定义 LangChain 聊天模型: 创建符合 LangChain 聊天模型接口的模型。这使得与 LangGraph 的智能代理和工作流完全兼容,但需要理解 LangChain 框架。

  2. 使用自定义流式传输进行直接调用: 通过使用 StreamWriter 添加自定义流式传输逻辑直接使用你的模型。 有关指导,请参阅自定义流式传输文档。这种方法适用于不需要预构建智能代理集成的自定义工作流。

附加资源