用途:为 Python 或 TypeScript 项目安装 Anthropic 官方 SDK,并配置 API Key 认证,SDK 封装了 https://api.anthropic.com/v1/messages 的 Claude Messages API。
前提条件:Node.js 18+ 或 Python 3.8+;包管理器(npm、pnpm、yarn 或 pip);拥有 console.anthropic.com 的 Anthropic API 访问账号;在 Console 的 API Keys 页面获取密钥。
主要步骤:
- 安装 SDK。Python 执行 pip install anthropic;TypeScript/Node.js 执行 npm install @anthropic-ai/sdk,或使用 pnpm add @anthropic-ai/sdk。
- 配置 API Key。推荐设置环境变量 export ANTHROPIC_API_KEY="sk-ant-api03-...",也可写入 .env 文件,并用 echo $ANTHROPIC_API_KEY | head -c 15 验证。
- 验证连接。Python 中创建 anthropic.Anthropic() 客户端(自动读取环境变量),调用 client.messages.create 并传入 model、max_tokens 和 messages;TypeScript 中创建 new Anthropic() 客户端,调用 client.messages.create。
输出:已安装的 SDK 包、已配置的 ANTHROPIC_API_KEY 环境变量、确认认证成功的 API 响应。
错误处理:401 authentication_error 表示密钥无效或缺失,需确认以 sk-ant-api03- 开头;403 permission_error 表示密钥权限不足,需在 Console 重新生成;404 not_found_error 表示端点无效,需更新 SDK;ModuleNotFoundError 表示未安装 SDK;连接错误需确保允许 HTTPS 访问 api.anthropic.com。
企业配置:可自定义 base_url、timeout、max_retries 及 default_headers。
安全建议:不要将密钥提交到版本控制;使用 .env 并加入 .gitignore;定期轮换密钥;按环境使用不同密钥;可考虑 Workspace 隔离团队密钥。
限制:资料未提供具体收费、价格或平台支持范围等信息。