跳到内容

模型

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

初始化模型

使用 init_chat_model 初始化模型

pip install -U "langchain[openai]"
import os
from langchain.chat_models import init_chat_model

os.environ["OPENAI_API_KEY"] = "sk-..."

llm = init_chat_model("openai:gpt-4.1")

👉 阅读 OpenAI 集成文档

pip install -U "langchain[anthropic]"
import os
from langchain.chat_models import init_chat_model

os.environ["ANTHROPIC_API_KEY"] = "sk-..."

llm = init_chat_model("anthropic:claude-3-5-sonnet-latest")

👉 阅读 Anthropic 集成文档

pip install -U "langchain[openai]"
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"

llm = init_chat_model(
    "azure_openai:gpt-4.1",
    azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],
)

👉 阅读 Azure 集成文档

pip install -U "langchain[google-genai]"
import os
from langchain.chat_models import init_chat_model

os.environ["GOOGLE_API_KEY"] = "..."

llm = init_chat_model("google_genai:gemini-2.0-flash")

👉 阅读 Google GenAI 集成文档

pip install -U "langchain[aws]"
from langchain.chat_models import init_chat_model

# Follow the steps here to configure your credentials:
# https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html

llm = init_chat_model(
    "anthropic.claude-3-5-sonnet-20240620-v1:0",
    model_provider="bedrock_converse",
)

👉 阅读 AWS Bedrock 集成文档

直接实例化模型

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

API 参考:ChatAnthropic

# Anthropic is already supported by `init_chat_model`,
# but you can also instantiate it directly.
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(
   model="anthropic:claude-3-7-sonnet-latest",
   # other parameters
)
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
)
# Alternatively
# model = init_chat_model("anthropic:claude-3-7-sonnet-latest")

agent = create_react_agent(
  model=model,
  # other parameters
)

动态模型选择

create_react_agent 传递一个可调用函数,以在运行时动态选择模型。这对于您希望根据用户输入、配置设置或其他运行时条件来选择模型的场景非常有用。

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

API 参考: init_chat_model | BaseChatModel | tool | create_react_agent | AgentState

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:
    """Returns the current weather conditions."""
    return "It's nice and sunny."


# Define the runtime context
@dataclass
class CustomContext:
    provider: Literal["anthropic", "openai"]

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


# Selector function for model choice
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}")

    # With dynamic model selection, you must bind tools explicitly
    return model.bind_tools([weather])


# Create agent with dynamic model selection
agent = create_react_agent(select_model, tools=[weather])

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

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

LangGraph v0.6 新功能

高级模型配置

禁用流式传输

要禁用单个 LLM 令牌的流式传输,请在初始化模型时设置 disable_streaming=True

from langchain.chat_models import init_chat_model

model = init_chat_model(
    "anthropic:claude-3-7-sonnet-latest",
    disable_streaming=True
)
from langchain_anthropic import ChatAnthropic

model = ChatAnthropic(
    model="claude-3-7-sonnet-latest",
    disable_streaming=True
)

有关 disable_streaming 的更多信息,请参阅 API 参考

添加模型回退

您可以使用 model.with_fallbacks([...]) 添加回退到不同的模型或不同的 LLM 提供商。

from langchain.chat_models import init_chat_model

model_with_fallbacks = (
    init_chat_model("anthropic:claude-3-5-haiku-latest")
    .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")
    .with_fallbacks([
        ChatOpenAI(model="gpt-4.1-mini"),
    ])
)

有关模型回退的更多信息,请参阅此指南

使用内置的速率限制器

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

API 参考: InMemoryRateLimiter | ChatAnthropic

from langchain_core.rate_limiters import InMemoryRateLimiter
from langchain_anthropic import ChatAnthropic

rate_limiter = InMemoryRateLimiter(
    requests_per_second=0.1,  # <-- Super slow! We can only make a request once every 10 seconds!!
    check_every_n_seconds=0.1,  # Wake up every 100 ms to check whether allowed to make a request,
    max_bucket_size=10,  # Controls the maximum burst size.
)

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

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

自带模型

如果您期望的 LLM 未被 LangChain 官方支持,请考虑以下选项:

  1. 实现自定义的 LangChain 聊天模型:创建一个符合 LangChain 聊天模型接口的模型。这可以实现与 LangGraph 的智能体和工作流的完全兼容,但需要对 LangChain 框架有所了解。

  2. 使用自定义流式传输直接调用:通过使用 StreamWriter 添加自定义流式传输逻辑来直接使用您的模型。请参阅自定义流式传输文档以获取指导。这种方法适用于不需要预构建智能体集成的自定义工作流。

更多资源