Agent SDK
快速开始
5 分钟创建你的第一个 Claude Agent — 安装、初始化与基本用法
安装
# 创建新项目
mkdir my-agent && cd my-agent
npm init -y
npm install @anthropic-ai/claude-code-sdk
# 使用 TypeScript
npm install -D typescript @types/node
npx tsc --init环境配置
# 设置 API Key
export ANTHROPIC_API_KEY="sk-ant-..."第一个 Agent
基本对话
import { ClaudeCode } from "@anthropic-ai/claude-code-sdk";
async function main() {
const claude = new ClaudeCode({
// 可选配置
model: "claude-sonnet-4-6",
maxTokens: 4096,
});
// 发送消息并获取流式响应
const stream = await claude.sendMessage(
"读取 package.json 并告诉我这个项目用了哪些依赖"
);
for await (const event of stream) {
switch (event.type) {
case "text":
process.stdout.write(event.text);
break;
case "tool_use":
console.log(`\n[工具调用] ${event.name}: ${JSON.stringify(event.input)}`);
break;
case "tool_result":
console.log(`[工具结果] 完成`);
break;
}
}
}
main();非交互模式
适用于脚本和 CI/CD:
import { ClaudeCode } from "@anthropic-ai/claude-code-sdk";
const claude = new ClaudeCode({
// 非交互模式:自动接受所有工具调用
allowedTools: ["Read", "Glob", "Grep", "Bash(npm test)"],
});
const result = await claude.sendMessage("运行测试并报告结果", {
// 等待完成而非流式
stream: false,
});
console.log(result.text);
console.log(`Token 使用: ${result.usage.totalTokens}`);指定工作目录
const claude = new ClaudeCode({
cwd: "/path/to/project", // Agent 的工作目录
});
const stream = await claude.sendMessage("分析这个项目的架构");多轮对话
import { ClaudeCode } from "@anthropic-ai/claude-code-sdk";
const claude = new ClaudeCode();
// 第一轮
let stream = await claude.sendMessage("这个项目是做什么的?");
for await (const event of stream) {
if (event.type === "text") process.stdout.write(event.text);
}
// 第二轮(自动保持上下文)
stream = await claude.sendMessage("有哪些改进建议?");
for await (const event of stream) {
if (event.type === "text") process.stdout.write(event.text);
}错误处理
import { ClaudeCode } from "@anthropic-ai/claude-code-sdk";
try {
const claude = new ClaudeCode();
const stream = await claude.sendMessage("执行任务");
for await (const event of stream) {
if (event.type === "error") {
console.error(`错误: ${event.message}`);
break;
}
if (event.type === "text") {
process.stdout.write(event.text);
}
}
} catch (error) {
if (error.code === "RATE_LIMIT") {
console.error("API 限流,请稍后重试");
} else {
console.error("未知错误:", error);
}
}运行
npx tsx my-agent.ts