前言
对于anthropic api的快速使用,在github上有几个example
- Customer Support Agent:由 Claude 提供支持的客户支持代理。该项目演示了如何利用 Claude 的自然语言理解和生成功能来创建可访问知识库的 AI 辅助客户支持系统。
- Financial Data Analyst :由 Claude 提供支持的金融数据分析师。该项目演示了如何利用 Claude 的交互式数据可视化功能通过聊天分析财务数据。
- Computer Use Demo: Claude 可用于控制台式计算机的环境和工具。该项目演示了如何利用新 Claude 3.5 Sonnet 模型的计算机使用功能。
其中 Computer use Demo是agent的example
链接:https://github.com/anthropics/anthropic-quickstarts/tree/main/computer-use-demo/computer_use_demo
文件介绍
打开之后可能会发现一堆报错,不慌,因为版本的问题,里面有一些python语言的不兼容,开头加上这句
from __future__ import annotations
一般agent文件目录都这么设置,朴实无华
- tools:包含base tool等一系列基础组件,接下来就是一个个tool了,最终会把tool做collection送给模型规定的格式,最终模型think后作出判断输出tool的name,collection根据name策略模式来选择对应的tool执行
- loop:agent loop的主要逻辑
- streamlit:轻量级的直接可视化工具:https://docs.streamlit.io/
除了这些,一般还会把llm单独搞个模块出来,memory等模块。
环境安装
streamlit>=1.38.0
anthropic[bedrock,vertex]>=0.39.0
jsonschema==4.22.0
boto3>=1.28.57
google-auth<3,>=2
Tool
BaseTool
from __future__ import annotationsfrom abc import ABCMeta, abstractmethod
from dataclasses import dataclass, fields, replace
from typing import Anyfrom anthropic.types.beta import BetaToolUnionParamclass BaseAnthropicTool(metaclass=ABCMeta):"""Abstract base class for Anthropic-defined tools."""@abstractmethoddef __call__(self, **kwargs) -> Any:"""Executes the tool with the given arguments."""...@abstractmethoddef to_params(self,) -> BetaToolUnionParam:raise NotImplementedError@dataclass(kw_only=True, frozen=True)
class ToolResult:"""Represents the result of a tool execution."""output: str | None = Noneerror: str | None = Nonebase64_image: str | None = Nonesystem: str | None = Nonedef __bool__(self):return any(getattr(self, field.name) for field in fields(self))def __add__(self, other: "ToolResult"):def combine_fields(field: str | None, other_field: str | None, concatenate: bool = True):if field and other_field:if concatenate:return field + other_fieldraise ValueError("Cannot combine tool results")return field or other_fieldreturn ToolResult(output=combine_fields(self.output, other.output),error=combine_fields(self.error, other.error),base64_image=combine_fields(self.base64_image, other.base64_image, False),system=combine_fields(self.system, other.system),)def replace(self, **kwargs):"""Returns a new ToolResult with the given fields replaced."""return replace(self, **kwargs)class CLIResult(ToolResult):"""A ToolResult that can be rendered as a CLI output."""class ToolFailure(ToolResult):"""A ToolResult that represents a failure."""class ToolError(Exception):"""Raised when a tool encounters an error."""def __init__(self, message):self.message = message
其他的tool都需要去实现BaseAnthropicTool,输出为定义的ToolResult结构体
Tool的基础参数格式
按照API官方文档为准,(代码里应该是有一些问题,缺少description,每个params不规范,都为自定义
https://docs.anthropic.com/zh-CN/docs/build-with-claude/tool-use/overview
{"name": "get_weather","description": "获取指定位置的当前天气","input_schema": {"type": "object","properties": {"location": {"type": "string","description": "城市和州,例如 San Francisco, CA"},"unit": {"type": "string","enum": ["celsius", "fahrenheit"],"description": "温度单位,可以是'celsius'或'fahrenheit'"}},"required": ["location"]}
}
特殊的三个Tool
文档:https://docs.anthropic.com/en/docs/agents-and-tools/computer-use
以下三个tool的参数和基础common参数不一致,是特殊的处理
- Computer tool: 截图,通过x,y坐标 挪动 鼠标, 多模态 这里面的很多操作也都是通过执行shell命令完成的
- Bash tool:shell命令的tool
- text-editor-tool
这三个tool都是模型本身训练过的,computer和text相对多模态比较难,bash可能出于安全考虑所以三个常用的tool都是训练过的,这里注意使用的时候的形态。
Collection设计
class ToolCollection:"""A collection of anthropic-defined tools."""def __init__(self, *tools: BaseAnthropicTool):self.tools = toolsself.tool_map = {tool.to_params()["name"]: tool for tool in tools}def to_params(self,) -> list[BetaToolUnionParam]:return [tool.to_params() for tool in self.tools]async def run(self, *, name: str, tool_input: dict[str, Any]) -> ToolResult:tool = self.tool_map.get(name)if not tool:return ToolFailure(error=f"Tool {name} is invalid")try:return await tool(**tool_input)except ToolError as e:return ToolFailure(error=e.message)
to_params之后得到一个对应格式tool各个参数的list,直接送入model,进行判断,模型判断得到tool name再通过run,进行解析参数,并通过name拿到对应的tool执行
可以借鉴的tool
- bash, 因为是模拟电脑运行,必不可少的就是shell
- computer:控制鼠标的一些方式,通过给予的x和y坐标