[ PROMPT_NODE_23884 ]
Claude API 说明文档
[ SKILL_DOCUMENTATION ]
# Claude API — TypeScript
## 安装
bash
npm install @anthropic-ai/sdk
## 客户端初始化
typescript
import Anthropic from "@anthropic-ai/sdk";
// 默认(使用 ANTHROPIC_API_KEY 环境变量)
const client = new Anthropic();
// 显式指定 API Key
const client = new Anthropic({ apiKey: "your-api-key" });
---
## 基础消息请求
typescript
const response = await client.messages.create({
model: "claude-opus-4-7",
max_tokens: 16000,
messages: [{ role: "user", content: "法国的首都是哪里?" }],
});
// response.content 是 ContentBlock[] — 一个可辨识联合类型。在访问 .text 之前
// 请先通过 .type 进行收窄(否则 TypeScript 会在 content[0].text 处报错)。
for (const block of response.content) {
if (block.type === "text") {
console.log(block.text);
}
}
---
## 系统提示词
typescript
const response = await client.messages.create({
model: "claude-opus-4-7",
max_tokens: 16000,
system:
"你是一个有用的编程助手。请始终使用 Python 提供示例。",
messages: [{ role: "user", content: "我该如何读取 JSON 文件?" }],
});
---
## 视觉(图像)
### URL
typescript
const response = await client.messages.create({
model: "claude-opus-4-7",
max_tokens: 16000,
messages: [
{
role: "user",
content: [
{
type: "image",
source: { type: "url", url: "https://example.com/image.png" },
},
{ type: "text", text: "描述这张图片" },
],
},
],
});
### Base64
typescript
import fs from "fs";
const imageData = fs.readFileSync("image.png").toString("base64");
const response = await client.messages.create({
model: "claude-opus-4-7",
max_tokens: 16000,
messages: [
{
role: "user",
content: [
{
type: "image",
source: { type: "base64", media_type: "image/png", data: imageData },
},
{ type: "text", text: "这张图片里有什么?" },
],
},
],
});
---
## 提示词缓存
**缓存是基于前缀匹配的** — 前缀中任何字节的改变都会导致其后所有内容的缓存失效。关于放置模式、架构指导(固定的系统提示词、确定性的工具顺序、易变内容的位置)以及静默失效审计清单,请阅读 `shared/prompt-caching.md`。
### 自动缓存(推荐)
使用顶层的 `cache_control` 来自动缓存请求中最后一个可缓存的块:
typescript
con