5 分钟快速上手
本教程将带你从零开始完成一个完整的 SDK 使用流程。
1. 初始化项目
mkdir my-claude-app && cd my-claude-app
npm init -y
npm install claude-code-sdk-ts typescript @types/node
npx tsc --init --target ES2022 --module ESNext --moduleResolution bundler
2. 设置环境变量
export ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxx
3. 编写第一个对话
创建 index.ts:
import { ClaudeCodeSDK } from 'claude-code-sdk-ts'
async function main() {
// 初始化 SDK
const sdk = new ClaudeCodeSDK({
llm: {
provider: 'anthropic',
apiKey: process.env.ANTHROPIC_API_KEY!,
model: 'claude-sonnet-4-20250514',
},
})
// 创建会话并发送消息
const session = sdk.createSession()
const response = await session.send('Hello! What can you do?')
console.log(response.text)
// 输出: Hello! I'm Claude, and I can help you with...
}
main().catch(console.error)
4. 使用 ask() 快速对话
更简单的方式是使用 ask() 函数,自动完成一轮对话:
import { ask } from 'claude-code-sdk-ts'
const result = await ask({
llm: {
provider: 'anthropic',
apiKey: process.env.ANTHROPIC_API_KEY!,
model: 'claude-sonnet-4-20250514',
},
prompt: 'What is TypeScript?',
})
console.log(result.text)
5. 使用工具
import { ask } from 'claude-code-sdk-ts'
const result = await ask({
llm: {
provider: 'anthropic',
apiKey: process.env.ANTHROPIC_API_KEY!,
model: 'claude-sonnet-4-20250514',
},
prompt: 'List the files in the current directory',
tools: ['BashTool', 'GlobTool'],
})
console.log(result.text)
// 输出: Current directory contains: package.json, tsconfig.json, src/...
完整示例
import { ClaudeCodeSDK } from 'claude-code-sdk-ts'
const sdk = new ClaudeCodeSDK({
llm: {
provider: 'anthropic',
apiKey: process.env.ANTHROPIC_API_KEY!,
model: 'claude-sonnet-4-20250514',
},
defaultTools: true, // 启用所有内置工具
})
async function chat() {
const session = sdk.createSession()
// 多轮对话
const r1 = await session.send('What is 2+2?')
console.log('Claude:', r1.text)
// Claude: 2+2 = 4
const r2 = await session.send('Now multiply that by 3')
console.log('Claude:', r2.text)
// Claude: 4 × 3 = 12
}
chat()