Skip to content

Anthropic 模型集成

Anthropic 是另一家提供强大语言模型的公司,其主要产品是 Claude 系列模型。本节将详细介绍如何在 LangChain 中集成 Anthropic 的 Claude 模型。

安装依赖

首先,需要安装 Anthropic 相关的依赖包:

bash
pip install langchain-anthropic

配置 API 密钥

使用 Anthropic 模型需要配置 API 密钥。可以通过以下方式设置:

  1. 环境变量:设置 ANTHROPIC_API_KEY 环境变量
  2. 直接传递:在初始化模型时直接传递 API 密钥

示例:设置环境变量

bash
# Linux/Mac
export ANTHROPIC_API_KEY="your-api-key"

# Windows
set ANTHROPIC_API_KEY=your-api-key

聊天模型

Anthropic 主要提供聊天模型,接受消息列表作为输入并生成消息作为输出。

初始化聊天模型

python
from langchain_anthropic import ChatAnthropic

# 方式 1:使用环境变量中的 API 密钥
chat_model = ChatAnthropic()

# 方式 2:直接传递 API 密钥
chat_model = ChatAnthropic(api_key="your-api-key")

# 配置模型参数
chat_model = ChatAnthropic(
    model_name="claude-3-opus-20240229",  # 模型名称
    temperature=0.7,  # 温度参数,控制输出的随机性
    max_tokens=1000,  # 最大生成 tokens 数
    top_p=1.0  # 控制生成的多样性
)

使用聊天模型

python
from langchain.schema import HumanMessage, SystemMessage, AIMessage

# 发送消息
messages = [
    SystemMessage(content="You are a helpful assistant"),
    HumanMessage(content="What is LangChain?"),
    AIMessage(content="LangChain is a framework for building LLM applications."),
    HumanMessage(content="Can you give me an example?")
]

response = chat_model(messages)
print(response.content)

# 批量生成
responses = chat_model.generate([
    [
        SystemMessage(content="You are a helpful assistant"),
        HumanMessage(content="What is LangChain?")
    ],
    [
        SystemMessage(content="You are a helpful assistant"),
        HumanMessage(content="How to use LangChain?")
    ]
])

for i, result in enumerate(responses.generations):
    print(f"Response {i+1}: {result[0].text}")

流式输出

Anthropic 模型支持流式输出,可以实时获取生成的文本。

示例:使用流式输出

python
from langchain_anthropic import ChatAnthropic
from langchain.schema import HumanMessage, SystemMessage

# 初始化聊天模型
chat_model = ChatAnthropic()

# 流式输出
messages = [
    SystemMessage(content="You are a helpful assistant"),
    HumanMessage(content="Write a short story about a robot learning to paint.")
]

for chunk in chat_model.stream(messages):
    print(chunk.content, end="", flush=True)

函数调用

Anthropic 的 Claude 3 模型支持函数调用,可以让模型根据需要调用外部函数。

示例:使用函数调用

python
from langchain_anthropic import ChatAnthropic
from langchain.schema import HumanMessage, SystemMessage, AIMessage, FunctionMessage
from langchain.tools import BaseTool
from typing import Optional, Type
from pydantic import BaseModel, Field

# 定义工具输入模式
class WeatherInput(BaseModel):
    location: str = Field(description="城市名称")

# 创建自定义工具
class WeatherTool(BaseTool):
    name = "get_weather"
    description = "获取指定城市的天气信息"
    args_schema: Type[BaseModel] = WeatherInput

    def _run(self, location: str) -> str:
        # 模拟天气 API 调用
        return f"{location} 的当前温度是 25°C,天气晴朗"

# 初始化聊天模型
chat_model = ChatAnthropic(model_name="claude-3-opus-20240229")

# 定义工具
weather_tool = WeatherTool()
tools = [weather_tool]

# 定义工具模式
工具模式 = [
    {
        "type": "function",
        "function": {
            "name": weather_tool.name,
            "description": weather_tool.description,
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市名称"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# 发送消息
messages = [
    SystemMessage(content="You are a helpful assistant. Use the get_weather tool to get weather information when needed."),
    HumanMessage(content="上海的天气怎么样?")
]

# 获取模型响应
response = chat_model(messages, tools=工具模式)
print("Model response:", response)

# 处理函数调用
if response.additional_kwargs.get("tool_calls"):
    tool_call = response.additional_kwargs["tool_calls"][0]
    location = tool_call["function"]["arguments"]
    import json
    location = json.loads(location)["location"]
    
    # 调用工具
    tool_result = weather_tool.run(location)
    print("Tool result:", tool_result)
    
    # 发送工具结果给模型
    messages.append(response)
    messages.append(FunctionMessage(content=tool_result, name=tool_call["function"]["name"]))
    
    # 获取最终响应
    final_response = chat_model(messages)
    print("Final response:", final_response.content)

比较与选择

Anthropic 的 Claude 模型与 OpenAI 的 GPT 模型各有特点:

特性Claude 模型GPT 模型
上下文窗口较大(Claude 3 支持 200K tokens)较大(GPT-4 支持 128K tokens)
推理能力强大强大
创意写作优秀优秀
代码生成良好优秀
多语言支持良好优秀
价格相对较低相对较高

在选择模型时,应根据具体需求、预算和性能要求进行综合考虑。

总结

Anthropic 的 Claude 模型是 LangChain 支持的重要模型之一,提供了强大的语言理解和生成能力。通过本文的介绍,您应该已经了解了如何在 LangChain 中使用 Anthropic 的聊天模型,以及如何使用流式输出和函数调用等高级功能。

在实际应用中,您可以根据具体需求选择合适的模型和参数,构建功能强大的 LLM 应用。