Claude SDK 设置
设置您的开发环境,以便使用首选语言的 SDK 调用 Claude API。
⚠️ 注意: Claude API 目前仅支持
Claude模型,其他模型无法使用 Claude API 进行调用。
1. 创建并导出 API 密钥
开始之前,请通过 令牌说明 创建一个 API 密钥。将密钥存储在安全位置,然后在终端中将其导出为环境变量。
macOS / Linux
export ANTHROPIC_API_KEY="your_api_key_here"Windows
set ANTHROPIC_API_KEY=your_api_key_hereClaude SDK 会自动从系统环境中读取您的 API 密钥。建议使用环境变量,避免在代码中直接硬编码密钥。
2. 安装 SDK
JavaScript
npm install @anthropic-ai/sdk创建 example.mjs:
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
baseURL: "https://api.floxai.io",
});
const msg = await anthropic.messages.create({
model: "claude-opus-4-20250514",
max_tokens: 1000,
temperature: 1,
system: "Respond only with short poems.",
messages: [
{
role: "user",
content: [{ type: "text", text: "Why is the ocean salty?" }],
},
],
});
console.log(msg);node example.mjsPython
pip install anthropic创建 example.py:
import anthropic
client = anthropic.Anthropic(
api_key="your_api_key_here",
base_url="https://api.uniapi.io/claude",
)
message = client.messages.create(
model="claude-opus-4-20250514",
max_tokens=1000,
temperature=1,
system="You are a world-class poet. Respond only with short poems.",
messages=[
{
"role": "user",
"content": [{"type": "text", "text": "Why is the ocean salty?"}],
}
],
)
print(message.content)python example.pyJava
Maven 依赖:
<dependency>
<groupId>com.anthropic</groupId>
<artifactId>anthropic-java</artifactId>
<version>2.2.0</version>
</dependency>import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.*;
// 通过环境变量 ANTHROPIC_API_KEY / ANTHROPIC_BASE_URL 自动配置
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_SONNET_4_20250514)
.build();
Message message = client.messages().create(params);Go
import "github.com/anthropics/anthropic-sdk-go"package main
import (
"context"
"fmt"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
)
func main() {
client := anthropic.NewClient(
option.WithAPIKey("my-anthropic-api-key"),
option.WithBaseURL("https://api.uniapi.io/claude"),
)
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
MaxTokens: 1024,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("What is a quaternion?")),
},
Model: anthropic.ModelClaudeSonnet4_20250514,
})
if err != nil {
panic(err.Error())
}
fmt.Printf("%+v\n", message.Content)
}Ruby
gem "anthropic", "~> 1.2.0"require "bundler/setup"
require "anthropic"
anthropic = Anthropic::Client.new(
api_key: ENV["ANTHROPIC_API_KEY"],
base_url: "https://api.uniapi.io/claude",
)
message = anthropic.messages.create(
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, Claude" }],
model: :"claude-sonnet-4-20250514",
)
puts(message.content)