立即体验
首页 / Claude 国内访问方式 - 镜像站推荐 / Claude API 使用指南 - 开发者接入教程

Claude API 使用指南 - 开发者接入教程

Claude API 简介

Claude API 允许开发者将 Claude 的能力集成到自己的应用中。本文介绍如何使用 Claude API。

快速开始

1. 获取 API Key

首先需要在 Anthropic 官网注册并获取 API Key。

2. 安装 SDK

Python:

pip install anthropic

Node.js:

npm install @anthropic-ai/sdk

3. 基础调用

Python 示例:

import anthropic

client = anthropic.Anthropic(
    api_key="your-api-key"
)

message = client.messages.create(
    model="claude-sonnet-4-5-20250929",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "你好,请介绍一下你自己"}
    ]
)

print(message.content[0].text)

Node.js 示例:

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

const client = new Anthropic({
    apiKey: 'your-api-key',
});

async function main() {
    const message = await client.messages.create({
        model: 'claude-sonnet-4-5-20250929',
        max_tokens: 1024,
        messages: [
            { role: 'user', content: '你好,请介绍一下你自己' }
        ],
    });
    
    console.log(message.content[0].text);
}

main();

API 参数说明

主要参数

参数说明示例
model模型名称claude-sonnet-4-5-20250929
max_tokens最大输出 token 数1024
messages对话消息列表[{“role”: “user”, “content”: “…”}]
temperature随机性(0-1)0.7
system系统提示词“你是一个专业的助手”

模型选择

模型特点适用场景
claude-sonnet-4-5-20250929最新最强复杂任务
claude-3-opus深度思考研究分析
claude-3-haiku快速响应简单查询

高级用法

流式输出

import anthropic

client = anthropic.Anthropic()

with client.messages.stream(
    model="claude-sonnet-4-5-20250929",
    max_tokens=1024,
    messages=[{"role": "user", "content": "写一首诗"}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

多轮对话

messages = [
    {"role": "user", "content": "我想学习 Python"},
    {"role": "assistant", "content": "很好!Python 是一门很棒的编程语言..."},
    {"role": "user", "content": "应该从哪里开始?"}
]

response = client.messages.create(
    model="claude-sonnet-4-5-20250929",
    max_tokens=1024,
    messages=messages
)

系统提示词

response = client.messages.create(
    model="claude-sonnet-4-5-20250929",
    max_tokens=1024,
    system="你是一个专业的 Python 开发专家,回答要简洁专业。",
    messages=[
        {"role": "user", "content": "如何处理异常?"}
    ]
)

错误处理

import anthropic

try:
    response = client.messages.create(...)
except anthropic.APIError as e:
    print(f"API 错误: {e}")
except anthropic.AuthenticationError as e:
    print(f"认证错误: {e}")
except anthropic.RateLimitError as e:
    print(f"速率限制: {e}")

不想用 API?试试这些平台

如果你不想自己接入 API,可以直接使用这些平台:

总结

Claude API 功能强大,接入简单。无论是构建聊天机器人、内容生成工具还是智能助手,Claude API 都是理想的选择。

🔗 推荐 Claude 访问方式

想要体验 Claude Sonnet 4.5 的强大功能?试试以下国内可用的访问方式: