Anthropic Cookbook项目:使用Pydantic实现智能笔记工具

Anthropic Cookbook项目:使用Pydantic实现智能笔记工具

【免费下载链接】anthropic-cookbook A collection of notebooks/recipes showcasing some fun and effective ways of using Claude. 【免费下载链接】anthropic-cookbook 项目地址: https://gitcode.com/GitHub_Trending/an/anthropic-cookbook

在人工智能应用开发中,如何确保模型输出的数据格式正确且符合预期是一个常见挑战。本文将介绍如何利用Anthropic Cookbook项目中的工具使用示例,结合Pydantic数据验证库,构建一个可靠的智能笔记保存系统。

技术背景与项目概述

现代AI助手经常需要与外部工具交互完成特定任务。Anthropic Cookbook项目展示了如何让AI模型调用外部工具并处理返回结果。本教程重点介绍如何使用Pydantic来验证模型输出,确保数据格式正确。

Pydantic是一个强大的Python数据验证库,它能够:

  • 定义数据模型的结构
  • 自动验证输入数据
  • 提供类型提示和自动补全
  • 确保数据符合预期格式

环境准备与初始化

首先需要安装必要的依赖包:

%pip install anthropic pydantic 'pydantic[email]'

然后初始化Anthropic客户端和模型名称:

from anthropic import Anthropic
from pydantic import BaseModel, EmailStr, Field
from typing import Optional

client = Anthropic()
MODEL_NAME = "claude-3-opus-20240229"

数据模型设计

良好的数据模型是系统可靠性的基础。我们设计三个核心模型:

  1. 作者模型(Author):记录笔记的作者信息
  2. 笔记模型(Note):包含笔记内容和元数据
  3. 响应模型(SaveNoteResponse):工具调用的返回结果
class Author(BaseModel):
    name: str
    email: EmailStr  # 使用EmailStr确保邮箱格式正确

class Note(BaseModel):
    note: str
    author: Author
    tags: Optional[list[str]] = None
    priority: int = Field(ge=1, le=5, default=3)  # 优先级限制在1-5之间
    is_public: bool = False

class SaveNoteResponse(BaseModel):
    success: bool
    message: str

工具定义与实现

定义AI模型可以调用的"save_note"工具:

tools = [
    {
        "name": "save_note",
        "description": "A tool that saves a note with the author and metadata.",
        "input_schema": {
            "type": "object",
            "properties": {
                "note": {"type": "string", "description": "The content of the note to be saved."},
                "author": {
                    "type": "object",
                    "properties": {
                        "name": {"type": "string", "description": "The name of the author."},
                        "email": {"type": "string", "format": "email", "description": "The email address of the author."}
                    },
                    "required": ["name", "email"]
                },
                "priority": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 5,
                    "default": 3,
                    "description": "The priority level of the note (1-5)."
                },
                "is_public": {
                    "type": "boolean",
                    "default": False,
                    "description": "Indicates whether the note is publicly accessible."
                }
            },
            "required": ["note", "author"]
        }
    }
]

实现笔记保存功能(示例中为打印信息,实际可替换为数据库操作):

def save_note(note: str, author: dict, priority: int = 3, is_public: bool = False) -> None:
    print("Note saved successfully!")

工具调用处理流程

处理AI模型发起的工具调用请求:

def process_tool_call(tool_name, tool_input):
    if tool_name == "save_note":
        # 使用Pydantic模型验证输入数据
        note = Note(
            note=tool_input["note"],
            author=Author(
                name=tool_input["author"]["name"],
                email=tool_input["author"]["email"]
            ),
            priority=tool_input.get("priority", 3),
            is_public=tool_input.get("is_public", False)
        )
        save_note(note.note, note.author.model_dump(), note.priority, note.is_public)
        return SaveNoteResponse(success=True, message="Note saved successfully!")

完整交互流程实现

实现用户与AI助手的完整交互流程:

  1. 发送用户消息
  2. 接收AI响应
  3. 处理工具调用
  4. 返回工具结果
  5. 获取最终响应
def chatbot_interaction(user_message):
    # 初始化消息
    messages = [{"role": "user", "content": user_message}]
    
    # 获取AI初始响应
    message = client.messages.create(
        model=MODEL_NAME,
        max_tokens=4096,
        tools=tools,
        messages=messages
    )
    
    # 处理工具调用
    if message.stop_reason == "tool_use":
        tool_use = next(block for block in message.content if block.type == "tool_use")
        save_note_response = process_tool_call(tool_use.name, tool_use.input)
        
        # 发送工具结果给AI
        response = client.messages.create(
            model=MODEL_NAME,
            max_tokens=4096,
            messages=[
                {"role": "user", "content": user_message},
                {"role": "assistant", "content": message.content},
                {
                    "role": "user",
                    "content": [{
                        "type": "tool_result",
                        "tool_use_id": tool_use.id,
                        "content": str(save_note_response),
                    }],
                },
            ],
            tools=tools,
        )
    else:
        response = message
    
    # 提取最终响应
    final_response = next(
        (block.text for block in response.content if hasattr(block, "text")),
        None,
    )
    return final_response

实际应用示例

测试笔记保存功能:

response = chatbot_interaction("""
Can you save a private note with the following details?
Note: Remember to buy milk and eggs.
Author: John Doe (johndoe@gmail.com)
Priority: 4
""")
print(response)

输出示例:

Your private note has been saved successfully with the following details:

Note: Remember to buy milk and eggs. 
Author: John Doe (johndoe@gmail.com)
Priority: 4
Visibility: Private

Please let me know if you need anything else!

技术优势与最佳实践

  1. 数据验证:Pydantic确保所有输入数据符合预期格式
  2. 类型安全:明确的类型提示减少运行时错误
  3. 可扩展性:模型设计易于扩展新字段
  4. 错误处理:自动验证减少手动检查代码
  5. 文档友好:模型定义本身就是良好的API文档

在实际应用中,可以将笔记保存功能替换为数据库操作,并添加更复杂的业务逻辑,如权限检查、笔记分类等。

通过本教程,我们展示了如何结合Anthropic的工具使用能力和Pydantic的数据验证能力,构建可靠的人工智能应用交互流程。这种模式可以推广到各种需要AI与外部系统交互的场景中。

【免费下载链接】anthropic-cookbook A collection of notebooks/recipes showcasing some fun and effective ways of using Claude. 【免费下载链接】anthropic-cookbook 项目地址: https://gitcode.com/GitHub_Trending/an/anthropic-cookbook

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值