/ Claude  AI Agent  Anthropic  工具调用  视觉理解  大语言模型  Python  API开发 

Claude 4.5 实战指南:工具调用、视觉理解与 AI Agent 构建


封面

Claude 4.5 的能力全景:不只是聊天机器人

2025年以来,大语言模型的竞争进入白热化阶段。Anthropic 发布的 Claude 4.5 在多项基准测试中刷新了纪录,但更重要的是,它在实际工程场景中展现出了前所未有的实用性。与上一代相比,Claude 4.5 带来了三大核心升级:

  • 200K 上下文窗口:可一次性处理长达 150 万字的文档,适合代码库分析、长文档理解等场景
  • 增强型工具调用:支持并行工具调用(Parallel Tool Use),AI Agent 可同时触发多个 API
  • 原生视觉理解:直接分析图片、图表、截图,无需额外的视觉模型
  • 计算机使用(Computer Use)稳定版:可操控浏览器和桌面完成复杂任务

这些特性组合在一起,让 Claude 4.5 成为构建生产级 AI Agent 的理想基座。下面我们通过实战代码来逐步解锁这些能力。

环境搭建与基础配置

首先安装最新版 Anthropic SDK,确保支持 Claude 4.5 的全部特性:

# 安装 SDK
pip install anthropic>=0.30.0

# 验证安装
python3 -c "import anthropic; print(anthropic.__version__)"

基础客户端初始化:

import anthropic
import os

client = anthropic.Anthropic(
    api_key=os.environ.get("ANTHROPIC_API_KEY")
)

# 测试基本对话
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "请简述你的核心能力"}
    ]
)
print(response.content[0].text)

对于国内开发者,如果无法直接访问 Anthropic API,可以通过腾讯云、阿里云等云厂商提供的代理端点,或者使用 AWS Bedrock、Google Vertex AI 上的 Claude 模型。

构建支持工具调用的 AI Agent

Claude 4.5 最强大的特性之一是工具调用(Tool Use)。我们来构建一个能够查询天气、搜索新闻的智能助手:

import anthropic
import json
import requests

client = anthropic.Anthropic()

# 定义工具
tools = [
    {
        "name": "get_weather",
        "description": "获取指定城市的实时天气信息",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名称,如:北京、上海"
                }
            },
            "required": ["city"]
        }
    },
    {
        "name": "search_news",
        "description": "搜索最新技术新闻",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "搜索关键词"
                },
                "limit": {
                    "type": "integer",
                    "description": "返回结果数量,默认5",
                    "default": 5
                }
            },
            "required": ["query"]
        }
    }
]

# 工具执行函数
def execute_tool(tool_name: str, tool_input: dict) -> str:
    if tool_name == "get_weather":
        # 实际项目中调用真实天气 API
        city = tool_input["city"]
        return json.dumps({
            "city": city,
            "temperature": "28°C",
            "condition": "晴天",
            "humidity": "65%"
        }, ensure_ascii=False)
    
    elif tool_name == "search_news":
        query = tool_input["query"]
        limit = tool_input.get("limit", 5)
        # 模拟搜索结果
        return json.dumps({
            "results": [
                {"title": f"关于{query}的最新进展", "url": "https://example.com/1"},
                {"title": f"{query}技术深度解析", "url": "https://example.com/2"}
            ][:limit]
        }, ensure_ascii=False)
    
    return "工具执行失败"

# Agent 主循环
def run_agent(user_message: str):
    messages = [{"role": "user", "content": user_message}]
    
    while True:
        response = client.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=4096,
            tools=tools,
            messages=messages
        )
        
        # 如果没有工具调用,返回最终结果
        if response.stop_reason == "end_turn":
            return response.content[0].text
        
        # 处理工具调用
        tool_results = []
        for block in response.content:
            if block.type == "tool_use":
                result = execute_tool(block.name, block.input)
                tool_results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": result
                })
        
        # 将工具结果加入对话历史
        messages.append({"role": "assistant", "content": response.content})
        messages.append({"role": "user", "content": tool_results})

# 测试
result = run_agent("帮我查一下北京今天的天气,同时搜索一下最新的 AI 技术新闻")
print(result)

上面的代码实现了一个基础的 ReAct(Reasoning + Acting)循环。Claude 会自动判断何时需要调用工具,调用后将结果整合进推理过程,最终给出综合回答。

视觉理解:让 AI 读懂图表和截图

Claude 4.5 的视觉能力在工程场景中极为实用。以下是常见的三种用法:

1. 分析上传的图片文件

import base64

def analyze_image(image_path: str, question: str) -> str:
    with open(image_path, "rb") as f:
        image_data = base64.standard_b64encode(f.read()).decode("utf-8")
    
    # 自动检测图片格式
    ext = image_path.split(".")[-1].lower()
    media_type_map = {
        "jpg": "image/jpeg", "jpeg": "image/jpeg",
        "png": "image/png", "gif": "image/gif",
        "webp": "image/webp"
    }
    media_type = media_type_map.get(ext, "image/jpeg")
    
    response = client.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=2048,
        messages=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "image",
                        "source": {
                            "type": "base64",
                            "media_type": media_type,
                            "data": image_data
                        }
                    },
                    {
                        "type": "text",
                        "text": question
                    }
                ]
            }
        ]
    )
    return response.content[0].text

# 使用示例
result = analyze_image("chart.png", "请分析这张图表中的数据趋势,指出关键拐点")
print(result)

2. 直接通过 URL 分析网络图片

response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "url",
                        "url": "https://example.com/architecture-diagram.png"
                    }
                },
                {
                    "type": "text",
                    "text": "请描述这张系统架构图,并指出潜在的单点故障"
                }
            ]
        }
    ]
)
print(response.content[0].text)

生产实践:流式输出与错误处理

在生产环境中,流式输出(Streaming)和健壮的错误处理是必不可少的。以下是一个完整的生产级封装示例:

from anthropic import APIError, APITimeoutError, RateLimitError
import time
from typing import Generator

def stream_response(
    messages: list,
    system: str = "",
    max_retries: int = 3
) -> Generator[str, None, None]:
    """流式输出,带自动重试逻辑"""
    
    for attempt in range(max_retries):
        try:
            with client.messages.stream(
                model="claude-sonnet-4-5",
                max_tokens=8192,
                system=system,
                messages=messages
            ) as stream:
                for text in stream.text_stream:
                    yield text
            return  # 成功,退出重试循环
            
        except RateLimitError as e:
            if attempt < max_retries - 1:
                wait_time = 2 ** attempt  # 指数退避
                print(f"触发限流,{wait_time}秒后重试...")
                time.sleep(wait_time)
            else:
                raise
                
        except APITimeoutError:
            if attempt < max_retries - 1:
                print(f"请求超时,正在重试({attempt+1}/{max_retries})...")
                time.sleep(1)
            else:
                raise
                
        except APIError as e:
            print(f"API 错误: {e.status_code} - {e.message}")
            raise

# 使用示例
for chunk in stream_response(
    messages=[{"role": "user", "content": "请写一篇关于 Transformer 架构的技术博客"}],
    system="你是一名专业的技术博客作者"
):
    print(chunk, end="", flush=True)

对于需要处理超长文档的场景(如代码库分析),可以利用 Claude 4.5 的 200K 上下文,一次性传入整个代码仓库进行分析,而无需复杂的分块和检索逻辑。

总结与最佳实践

Claude 4.5 为 AI 应用开发提供了强大的基础能力。在实际项目中,建议遵循以下最佳实践:

  • 合理设置 max_tokens:根据任务复杂度调整,避免不必要的 token 消耗
  • 使用 system prompt 定义角色:清晰的系统提示能显著提升输出质量
  • 工具定义要精确:详细的参数描述帮助模型正确理解何时及如何调用工具
  • 实现指数退避重试:生产环境必须处理 API 限流和超时情况
  • 缓存常用提示:利用 Prompt Caching 特性减少重复 token 消耗
  • 监控 token 使用量:通过 response.usage 跟踪成本,设置预算告警

随着 AI 能力的持续进化,掌握像 Claude 4.5 这样的前沿模型的工程用法,将成为开发者的核心竞争力。希望本文的代码示例能帮助你快速上手,在实际项目中落地 AI 应用。

发布评论

热门评论区: