第 3 章 · 02 TypeScript SDK 详解


第 3 章 · 02 TypeScript SDK 详解

本节摘要:TypeScript(@anthropic-ai/sdk)是另一大主力 SDK,在概念上与 Python SDK 完全对齐——同样的 messages.create、同样的 system/tools/messages 结构、同样的缓存与思考参数。区别在语言层面:TypeScript 用 await 异步、response.content 是判别联合(discriminated union)必须先收窄 .type 再访问字段、ESM 模块里 __dirname 未定义要用 import.meta.url 推导、流式用 for await 迭代。本节对照 Python 讲清这些差异:客户端初始化、单次请求与判别联合、多轮对话、缓存与思考、视觉、错误处理,以及 Tool Runner 用 Zod 定义工具的写法。读完本节,你能在 Node/TS 环境里落地 Claude 应用。

内容来源:Anthropic 官方 Claude API 文档 typescript/claude-api/README.md、typescript/claude-api/streaming.md、typescript/claude-api/tool-use.md(随 Claude Code 分发,从泄露素材库提取),汉化并套用体系化模板。

学习目标

阅读完本节,你应当能够:

  1. 用 new Anthropic() 初始化 TS 客户端,并知道 ESM 下读本地文件不能用 __dirname。
  2. 处理 response.content 这个判别联合——先收窄 .type 再访问 .text,否则 TS 编译报错。
  3. 用 for await 消费流式,用 stream.finalMessage() 拿最终消息。
  4. 用 betaZodTool 配合 Zod schema 定义工具,跑 Tool Runner。
  5. 按 instanceof 链捕获类型化异常,注意 APIConnectionError 是 APIError 子类要先判。

一、安装与客户端初始化

npm install @anthropic-ai/sdk ​
import Anthropic from "@anthropic-ai/sdk"; // 默认:从 process.env.ANTHROPIC_API_KEY 读 const client = new Anthropic(); // 必须注入特定 key 时 const client = new Anthropic({ apiKey: "your-api-key" }); ​

⚠️ ESM 读本地文件的坑:在 ES 模块(.ts/.mts 用 ESM)里,__dirname 和 __filename 是 undefined,直接用会抛 ReferenceError。读 cwd 相对路径就直接传裸相对路径(fs.readFileSync("./sample.png"));读脚本相对路径,从 import.meta.url 推导:const here = path.dirname(fileURLToPath(import.meta.url))。永远不要在 ESM 的 .ts 文件里写 path.join(__dirname, …)。

二、单次请求与判别联合

const response = await client.messages.create({ model: "claude-opus-4-8", max_tokens: 16000, messages: [{ role: "user", content: "What is the capital of France?" }], }); // response.content 是 ContentBlock[] —— 判别联合 // 先用 .type 收窄,再访问 .text,否则 TS 编译报错 for (const block of response.content) { if (block.type === "text") { console.log(block.text); } } ​

⚠️ 判别联合是 TS SDK 的核心特征:content[0].text 在不先收窄 .type 时会 TS 编译报错——因为 ContentBlock 是 TextBlock | ThinkingBlock | ToolUseBlock | ... 的联合,只有 TextBlock 有 .text。必须 if (block.type === "text") 或 switch 收窄后再访问。这是 TS 与 Python(Pydantic 模型属性宽松)最大的体验差异。

system prompt 同样是顶层参数:

const response = await client.messages.create({ model: "claude-opus-4-8", max_tokens: 16000, system: "You are a helpful coding assistant. Always provide examples in Python.", messages: [{ role: "user", content: "How do I read a JSON file?" }], }); ​

三、多轮对话与无状态

与 Python 一样,API 无状态,每次发完整历史。TS 封装多轮对话:

class ConversationManager { private messages: Anthropic.MessageParam[] = []; constructor(private client: Anthropic, private model: string, private system?: string) {} async send(userMessage: string): Promise<string> { this.messages.push({ role: "user", content: userMessage }); const response = await this.client.messages.create({ model: this.model, max_tokens: 16000, system: this.system, messages: this.messages, }); const text = response.content .filter((b): b is Anthropic.TextBlock => b.type === "text") .map((b) => b.text) .join(""); this.messages.push({ role: "assistant", content: text }); return text; } } const conv = new ConversationManager(new Anthropic(), "claude-opus-4-8", "You are helpful."); await conv.send("My name is Alice."); console.log(await conv.send("What's my name?")); // "Alice" ​

💡 类型守卫:上面用 (b): b is Anthropic.TextBlock => b.type === "text" 做类型谓词,filter 后数组就是 TextBlock[],直接 .map((b) => b.text) 无需再判。

四、缓存与扩展思考

提示缓存(第 2 章 03 节)——TS 自动与手动两种:

// 自动:顶层 cache_control const r1 = await client.messages.create({ model: "claude-opus-4-8", max_tokens: 16000, cache_control: { type: "ephemeral" }, system: largeDocumentText, messages: [{ role: "user", content: "Summarize" }], }); // 手动:具体块加标记,可设 TTL const r2 = await client.messages.create({ model: "claude-opus-4-8", max_tokens: 16000, system: [{ type: "text", text: largeDocumentText, cache_control: { type: "ephemeral", ttl: "1h" } }], messages: [{ role: "user", content: "Summarize" }], }); // 验证命中 console.log(r2.usage.cache_read_input_tokens); ​

扩展思考——新模型用 adaptive thinking:

const response = await client.messages.create({ model: "claude-opus-4-8", max_tokens: 16000, thinking: { type: "adaptive", display: "summarized" }, output_config: { effort: "high" }, messages: [{ role: "user", content: "Solve step by step" }], }); for (const block of response.content) { if (block.type === "thinking") console.log("Thinking:", block.thinking); else if (block.type === "text") console.log("Response:", block.text); } ​

五、视觉与流式

图片支持 URL 与 base64:

const response = await client.messages.create({ model: "claude-opus-4-8", max_tokens: 16000, messages: [{ role: "user", content: [ { type: "image", source: { type: "url", url: "https://example.com/img.png" } }, { type: "text", text: "Describe this" }, ], }], }); ​

流式用 messages.stream() + for await,详见第 2 章 02 节:

const stream = client.messages.stream({ model: "claude-opus-4-8", max_tokens: 64000, messages: [{ role: "user", content: "Write a story" }], }); for await (const event of stream) { if (event.type === "content_block_delta" && event.delta.type === "text_delta") { process.stdout.write(event.delta.text); } } const finalMessage = await stream.finalMessage(); // 拿完整消息 console.log(`Tokens: ${finalMessage.usage.output_tokens}`); ​

⚠️ 不要自己包 Promise:文档明确提醒,别把 .on() 事件手动包进 new Promise() 等结束——finalMessage() 内部已处理完成/错误/中断所有状态。还有个便捷事件 stream.on("text", ...) 直接拿增量字符串,比手动过滤 content_block_delta 更省事。

六、Tool Runner 与 Zod

TS SDK 的 Tool Runner 配合 Zod schema 定义工具,类型安全。详见第 2 章 01 节,这里给典型写法:

import Anthropic from "@anthropic-ai/sdk"; import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod"; import { z } from "zod"; const client = new Anthropic(); const getWeather = betaZodTool({ name: "get_weather", description: "Get current weather for a location", inputSchema: z.object({ location: z.string().describe("City and state, e.g., San Francisco, CA"), }), run: async ({ location }) => `72°F and sunny in ${location}`, }); // Tool Runner 自动跑 agent 循环 const response = await client.beta.messages.toolRunner({ model: "claude-opus-4-8", max_tokens: 64000, tools: [getWeather], messages: [{ role: "user", content: "Weather in Paris?" }], }).finalMessage(); ​

💡 Tool Runner 不强制 Zod:第 2 章 01 节澄清过,betaTool()(TS)和 @beta_tool(Python)也接受原始 JSON Schema,Zod 只是 TS 下获得类型安全的便捷路径。流式 Tool Runner 是两层循环(外层每回合、内层事件),见第 2 章 02 节。

七、错误处理:instanceof 链

import Anthropic from "@anthropic-ai/sdk"; try { const response = await client.messages.create({ /* ... */ }); } catch (e) { if (e instanceof Anthropic.BadRequestError) { console.log("Bad request:", e.message); } else if (e instanceof Anthropic.NotFoundError) { console.log("Bad model or endpoint"); } else if (e instanceof Anthropic.RateLimitError) { const retryAfter = e.response?.headers?.get("retry-after") ?? "60"; console.log(`Rate limited, retry after ${retryAfter}s`); } else if (e instanceof Anthropic.APIConnectionError) { console.log("Network error"); // ← 必须在 APIError 之前判 } else if (e instanceof Anthropic.APIError) { console.log("API error:", e); } } ​

⚠️ 顺序细节:TS 里 APIConnectionError 是 APIError 的子类(与 Python 不同,Python 里两者平级),所以必须先 instanceof APIConnectionError 再 instanceof APIError,否则网络错误会被泛 APIError 吞掉。max_retries 同样可配(默认 2)。

本节要点回顾

  1. 初始化:new Anthropic() 默认从环境变量读 key;ESM 下读本地文件不能用 __dirname,要用 import.meta.url 推导。
  2. 判别联合:response.content 是 ContentBlock 联合,必须先 if (block.type === "text") 收窄再访问 .text,否则 TS 报错——这是与 Python 最大差异。
  3. 多轮无状态:每次发完整历史;用类型谓词 (b): b is TextBlock => 做 filter 类型守卫。
  4. 缓存与思考:与 Python 概念一致,顶层 cache_control 自动、具体块手动(可设 TTL);adaptive thinking 配 effort。
  5. 流式:messages.stream() + for await;用 stream.finalMessage() 拿完整消息,别自己包 Promise;stream.on("text", ...) 拿增量更省事。
  6. Tool Runner + Zod:betaZodTool 配 Zod schema 定义工具获类型安全;Runner 也接受原始 JSON Schema。
  7. 错误 instanceof 链:按具体性顺序判;TS 里 APIConnectionError 是 APIError 子类,必须先判连接错误。

下一节合并对照其余六种语言(Go/Java/PHP/Ruby/C#/curl)——它们在概念上与 Python/TS 完全一致,差异主要在包名、客户端构造、异常类命名与异步模型。我们只讲配置差异,不逐篇重复。

作者与出处
原作者:灏天文库
来源:asgeirtj
许可证:CC BY-NC-SA 1.0
整理人: 灏天文库整理
由灏天文库结构化整理,提供目录导航、全文检索与在线阅读,便于系统化学习
发布者: 作者: 灏天文库 转发
评论区 (0)
U