Development
Claude API
有效利用 Claude API 的指南. 包括提示、流线、工具使用和与 Claude 一起构建应用程序的最佳做法.
使用 Claude API 构建应用程序,遵循提示、流式传输和工具使用方面的最佳实践。
快速开始
安装
npm install @anthropic-ai/sdk
基本用法
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'Hello, Claude' }
],
});
提示工程
系统提示
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
system: 'You are a helpful assistant.',
messages: [
{ role: 'user', content: 'What is the capital of France?' }
],
});
结构化输出
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [
{
role: 'user',
content: 'Extract the name and age from: John is 25 years old.'
}
],
});
流式传输
const stream = client.messages.stream({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'Write a story' }
],
});
for await (const event of stream) {
if (event.type === 'content_block_delta') {
process.stdout.write(event.delta.text);
}
}
工具使用
定义工具
const tools = [
{
name: 'get_weather',
description: 'Get the weather for a location',
input_schema: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'City name'
}
},
required: ['location']
}
}
];
处理工具调用
const response = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
tools,
messages: [
{ role: 'user', content: 'What is the weather in Paris?' }
],
});
// 检查是否使用了工具
if (response.content[0].type === 'tool_use') {
const toolCall = response.content[0];
// 执行工具并返回结果
}
最佳实践
- 使用流式传输以获得更好的用户体验
- 实施适当的错误处理
- 设置合适的 max_tokens
- 使用系统提示来保持一致的行为
- 使用 Zod 验证工具输入
- 优雅地处理速率限制
- 尽可能缓存响应