Claude API指南:2026年用Anthropic Claude构建AI应用

Claude API指南:2026年用Anthropic Claude构建AI应用

Claude API完整指南。认证、请求、流式传输、工具调用及实战AI应用开发全覆盖。

2026年3月17日5分钟阅读

为什么选择Claude API?

Anthropic的Claude已经成为2026年最受开发者欢迎的AI模型之一。Claude以其出色的推理能力、长上下文处理、代码生成质量和遵循指令的准确性著称。对于需要构建可靠AI应用的开发者来说,Claude API提供了一个强大且相对一致的接口。

本文将带你从零开始,掌握Claude API的核心功能,并构建实际可用的AI应用。

获取API密钥

  1. 访问console.anthropic.com注册账号
  2. 进入"API Keys"页面,创建新的API密钥
  3. 将密钥安全保存(只显示一次)

重要提醒:永远不要将API密钥硬编码在代码中,使用环境变量管理。

# 设置环境变量
export ANTHROPIC_API_KEY="sk-ant-..."

# 或在.env文件中
ANTHROPIC_API_KEY=sk-ant-...

可用模型

模型最适用场景上下文窗口特点
claude-opus-4-5复杂推理、分析200K tokens最强大
claude-sonnet-4-5平衡性能和速度200K tokens推荐日常使用
claude-haiku-3-5简单任务、高速200K tokens最快最便宜

Python集成

安装SDK

pip install anthropic

基础请求

import anthropic

client = anthropic.Anthropic()
# 自动读取 ANTHROPIC_API_KEY 环境变量

message = client.messages.create(
    model="claude-opus-4-5",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "用Python写一个快速排序算法,并解释时间复杂度"
        }
    ]
)

print(message.content[0].text)

系统提示词(System Prompt)

response = client.messages.create(
    model="claude-opus-4-5",
    max_tokens=2048,
    system="""你是ToolBox Hub的AI助手,专门帮助开发者解决技术问题。
你应该:
- 提供准确、实用的技术建议
- 代码示例使用现代最佳实践
- 回答简洁明了,避免不必要的冗余
- 如果不确定,坦诚说明""",
    messages=[
        {"role": "user", "content": "如何在Python中实现单例模式?"}
    ]
)

多轮对话

def create_chat_session():
    client = anthropic.Anthropic()
    conversation_history = []

    def chat(user_message):
        conversation_history.append({
            "role": "user",
            "content": user_message
        })

        response = client.messages.create(
            model="claude-opus-4-5",
            max_tokens=1024,
            system="你是一位友好的编程助手",
            messages=conversation_history
        )

        assistant_message = response.content[0].text
        conversation_history.append({
            "role": "assistant",
            "content": assistant_message
        })

        return assistant_message

    return chat

# 使用
chat = create_chat_session()
print(chat("你好!帮我解释什么是递归"))
print(chat("能给我一个Python示例吗?"))
print(chat("能用尾递归优化吗?"))

流式传输(Streaming)

流式传输让AI响应可以实时显示,大幅提升用户体验,适合需要显示长文本的场景。

import anthropic

client = anthropic.Anthropic()

# 方式1:使用stream上下文管理器
with client.messages.stream(
    model="claude-opus-4-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "写一首关于编程的七言绝句"}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

print()  # 换行

# 方式2:原始流处理
with client.messages.stream(
    model="claude-opus-4-5",
    max_tokens=2048,
    messages=[{"role": "user", "content": "详细解释HTTP和HTTPS的区别"}]
) as stream:
    for event in stream:
        if hasattr(event, 'delta') and hasattr(event.delta, 'text'):
            print(event.delta.text, end="", flush=True)

FastAPI集成流式响应

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import anthropic

app = FastAPI()
client = anthropic.Anthropic()

@app.post("/chat/stream")
async def stream_chat(request: dict):
    user_message = request.get("message")

    async def generate():
        with client.messages.stream(
            model="claude-opus-4-5",
            max_tokens=1024,
            messages=[{"role": "user", "content": user_message}]
        ) as stream:
            for text in stream.text_stream:
                # Server-Sent Events格式
                yield f"data: {text}\n\n"
        yield "data: [DONE]\n\n"

    return StreamingResponse(generate(), media_type="text/event-stream")

工具调用(Tool Use)

工具调用是Claude最强大的功能之一,让模型能够调用外部函数和API。

import anthropic
import json
import requests

client = anthropic.Anthropic()

# 定义工具
tools = [
    {
        "name": "get_weather",
        "description": "获取指定城市的当前天气信息",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名称,如北京、上海"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "温度单位"
                }
            },
            "required": ["city"]
        }
    },
    {
        "name": "search_database",
        "description": "搜索产品数据库",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {"type": "string", "description": "搜索关键词"},
                "limit": {"type": "integer", "description": "返回结果数量"}
            },
            "required": ["query"]
        }
    }
]

# 工具实现
def get_weather(city: str, unit: str = "celsius") -> dict:
    # 实际应用中这里调用真实天气API
    return {
        "city": city,
        "temperature": 22 if unit == "celsius" else 72,
        "unit": unit,
        "condition": "晴天",
        "humidity": "65%"
    }

def search_database(query: str, limit: int = 5) -> list:
    # 实际应用中这里查询数据库
    return [{"id": i, "name": f"{query}相关产品{i}", "price": i * 99}
            for i in range(1, limit + 1)]

def process_tool_call(tool_name: str, tool_input: dict) -> str:
    if tool_name == "get_weather":
        result = get_weather(**tool_input)
    elif tool_name == "search_database":
        result = search_database(**tool_input)
    else:
        result = {"error": f"未知工具: {tool_name}"}
    return json.dumps(result, ensure_ascii=False)

# 工具调用主循环
def chat_with_tools(user_message: str) -> str:
    messages = [{"role": "user", "content": user_message}]

    while True:
        response = client.messages.create(
            model="claude-opus-4-5",
            max_tokens=1024,
            tools=tools,
            messages=messages
        )

        # 添加助手回复到历史
        messages.append({"role": "assistant", "content": response.content})

        # 检查是否需要工具调用
        if response.stop_reason == "tool_use":
            tool_results = []
            for block in response.content:
                if block.type == "tool_use":
                    result = process_tool_call(block.name, block.input)
                    tool_results.append({
                        "type": "tool_result",
                        "tool_use_id": block.id,
                        "content": result
                    })

            # 将工具结果加入对话
            messages.append({"role": "user", "content": tool_results})
        else:
            # 获取最终文本回复
            for block in response.content:
                if hasattr(block, 'text'):
                    return block.text

# 测试
result = chat_with_tools("北京今天天气怎么样?我想找一些Python相关的工具")
print(result)

视觉(Vision)功能

Claude支持图像理解,可以分析截图、图表、UI设计等:

import anthropic
import base64
from pathlib import Path

client = anthropic.Anthropic()

# 方式1:Base64编码本地图片
def analyze_image(image_path: str, question: str) -> str:
    image_data = base64.standard_b64encode(
        Path(image_path).read_bytes()
    ).decode("utf-8")

    # 根据文件扩展名确定媒体类型
    ext = Path(image_path).suffix.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-opus-4-5",
        max_tokens=1024,
        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(
    "screenshot.png",
    "请分析这个UI截图,指出可以改进的地方"
)
print(result)

# 方式2:使用URL
response = client.messages.create(
    model="claude-opus-4-5",
    max_tokens=512,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "url",
                        "url": "https://example.com/chart.png"
                    }
                },
                {"type": "text", "text": "这张图表说明了什么趋势?"}
            ]
        }
    ]
)

JavaScript/Node.js集成

npm install @anthropic-ai/sdk
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic();
// 自动读取 ANTHROPIC_API_KEY 环境变量

// 基础请求
async function basicRequest() {
  const message = await client.messages.create({
    model: 'claude-opus-4-5',
    max_tokens: 1024,
    messages: [
      { role: 'user', content: '用JavaScript实现一个防抖函数' }
    ]
  });
  return message.content[0].text;
}

// 流式传输
async function streamResponse() {
  const stream = await client.messages.stream({
    model: 'claude-opus-4-5',
    max_tokens: 1024,
    messages: [
      { role: 'user', content: '解释JavaScript的事件循环机制' }
    ]
  });

  for await (const chunk of stream) {
    if (chunk.type === 'content_block_delta' &&
        chunk.delta.type === 'text_delta') {
      process.stdout.write(chunk.delta.text);
    }
  }
}

streamResponse();

最佳实践

1. 错误处理

import anthropic
from anthropic import APIError, RateLimitError, APIConnectionError

def safe_api_call(client, **kwargs):
    try:
        return client.messages.create(**kwargs)
    except RateLimitError as e:
        print(f"速率限制,请稍后重试: {e}")
        # 实现指数退避重试
    except APIConnectionError as e:
        print(f"网络连接错误: {e}")
    except APIError as e:
        print(f"API错误 {e.status_code}: {e.message}")

2. 提示词工程技巧

# 结构化输出
system_prompt = """
请以JSON格式返回结果,格式如下:
{
  "summary": "内容摘要",
  "key_points": ["要点1", "要点2"],
  "sentiment": "positive|negative|neutral",
  "confidence": 0.0-1.0
}
不要返回JSON以外的任何内容。
"""

3. 成本控制

  • 使用claude-haiku-3-5处理简单分类任务
  • 合理设置max_tokens,避免浪费
  • 使用Prompt Caching(系统提示词缓存)减少重复计费
  • 监控API使用量,设置预算警报

总结

Claude API为开发者提供了强大的AI能力,从简单的文本生成到复杂的工具调用和视觉理解,都能通过简洁的API接口实现。掌握本文介绍的核心功能,你就能构建出高质量的AI应用。

下一步探索方向:Prompt Caching(缓存常用提示词节省费用)、Batch API(批量处理大量请求)以及与LangChain等框架的集成,进一步扩展Claude的能力边界。

相关文章