Claude Sonnet 4.6 API 接入教程:Python/Node.js 完整示例
前言
Claude Sonnet 4.6 是 Anthropic 推出的主力模型,支持 200K context,tool calling 稳定,适合 Agent 开发、RAG 系统、批量文本处理等场景。
本文提供完整的接入教程,包括 Python 和 Node.js 示例,以及通用的成本优化方案。
本文介绍了 Claude Sonnet 4.6 模型的 API 接入方法,涵盖 Python 和 Node.js 两种语言的基础调用、流式输出、函数调用及多轮对话示例。文章提供了 Token 用量计算逻辑,并解答了关于接口兼容性、模型支持及并发限制的常见问题。通过通用配置指南,开发者可实现低成本、高效率的大模型集成应用。
Claude Sonnet 4.6 是 Anthropic 推出的主力模型,支持 200K context,tool calling 稳定,适合 Agent 开发、RAG 系统、批量文本处理等场景。
本文提供完整的接入教程,包括 Python 和 Node.js 示例,以及通用的成本优化方案。
https://api.anthropic.com/v1)pip install openai
from openai import OpenAI
client = OpenAI(
api_key="your-api-key",
base_url="https://api.anthropic.com/v1"
)
response = client.chat.completions.create(
model="claude-sonnet-4-6",
messages=[
{"role": "system", "content": "你是一个专业的技术助手"},
{"role": "user", "content": "解释一下什么是 RAG?"}
],
max_tokens=1000,
temperature=0.7
)
print(response.choices[0].message.content)
stream = client.chat.completions.create(
model="claude-sonnet-4-6",
messages=[{"role": "user", "content": "写一个快速排序算法"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
import json
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称,如:北京、上海"}
},
"required": ["city"]
}
}
}
]
response = client.chat.completions.create(
model="claude-sonnet-4-6",
messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
tools=tools,
tool_choice="auto"
)
# 处理工具调用
message = response.choices[0].message
if message.tool_calls:
for tool_call in message.tool_calls:
func_name = tool_call.function.name
func_args = json.loads(tool_call.function.arguments)
print(f"调用工具:{func_name},参数:{func_args}")
def calculate_cost(usage):
# 请根据实际计费标准修改价格
input_price = 0.00001 # ¥/token (示例)
output_price = 0.00005 # ¥/token (示例)
input_cost = usage.prompt_tokens * input_price
output_cost = usage.completion_tokens * output_price
total = input_cost + output_cost
print(f"输入 tokens:{usage.prompt_tokens},费用:¥{input_cost:.6f}")
print(f"输出 tokens:{usage.completion_tokens},费用:¥{output_cost:.6f}")
print(f"本次总费用:¥{total:.6f}")
response = client.chat.completions.create(
model="claude-sonnet-4-6",
messages=[{"role": "user", "content": "你好"}]
)
calculate_cost(response.usage)
npm install openai
const OpenAI = require('openai');
const client = new OpenAI({
apiKey: 'your-api-key',
baseURL: 'https://api.anthropic.com/v1'
});
async function main() {
const response = await client.chat.completions.create({
model: 'claude-sonnet-4-6',
messages: [
{ role: 'system', content: '你是一个专业的技术助手' },
{ role: 'user', content: '解释一下什么是 RAG?' }
],
max_tokens: 1000
});
console.log(response.choices[0].message.content);
}
main();
async function streamChat() {
const stream = await client.chat.completions.create({
model: 'claude-sonnet-4-6',
messages: [{ role: 'user', content: '写一个快速排序算法' }],
stream: true
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}
}
streamChat();
async function multiTurnChat() {
const messages = [
{ role: 'system', content: '你是一个代码审查专家' }
];
// 第一轮
messages.push({ role: 'user', content: '帮我审查这段代码:function add(a,b){return a+b}' });
let response = await client.chat.completions.create({
model: 'claude-sonnet-4-6',
messages
});
const reply1 = response.choices[0].message.content;
messages.push({ role: 'assistant', content: reply1 });
console.log('第一轮回复:', reply1);
// 第二轮
messages.push({ role: 'user', content: '如果要加类型检查,怎么改?' });
response = await client.chat.completions.create({
model: 'claude-sonnet-4-6',
messages
});
console.log('第二轮回复:', response.choices[0].message.content);
}
multiTurnChat();
接口完全兼容 OpenAI SDK,只需修改 base_url 和 api_key。部分中转服务可能提供不同的定价策略或并发限制。
部分服务商通过规模效应降低成本,具体价格需参考服务商公告。建议对比官方与第三方渠道的实时报价。
主流大模型通常支持多种系列,包括 Claude 系列、GPT 系列、Gemini 系列等,具体以服务商列表为准。
满血分组支持高并发,具体限制见控制台。企业高并发需求可联系服务商咨询专属方案。
Claude Sonnet 4.6 接入步骤:
base_url 为对应地址model 为 claude-sonnet-4-6
微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML 转 Markdown在线工具,online