Claude Code中英文系列教程26:API开发入门之通过API实现网络搜索助手
Make your first API call to Claude and build a simple web search assistant
下面我们通过向 Claude 发起第一个 API 调用,并构建一个简单的网络搜索助手
# Prerequisites 先决条件
An Anthropic Console account
Anthropic 控制台账户
console.anthropic.com 已迁移至 platform.claude.com
An API key
一个 API 密钥
# Call the API 调用 API
可以通过cURL命令行,Python或Java,下面我们以TypeScript进行示例:
## Set your API key 设置 API 密钥
Get your API key from the Claude Console and set it as an environment variable:
从 Claude 控制台获取 API 密钥并将其设置为环境变量:
export ANTHROPIC_API_KEY='your-api-key-here'
## Install the SDK 安装 SDK
Install the Anthropic TypeScript SDK:
安装 Anthropic TypeScript SDK:
npm install @anthropic-ai/sdk
## Create your code 编写你的代码
Save this as quickstart.ts:
将下面代码保存为 quickstart.ts :
```js
import Anthropic from "@anthropic-ai/sdk";
async function main() {
const anthropic = new Anthropic();
const msg = await anthropic.messages.create({
model: "claude-sonnet-4-5",
max_tokens: 1000,
messages: [
{
role: "user",
content: "What should I search for to find the latest developments in renewable energy?"
}
]
});
console.log(msg);
}
main().catch(console.error);
```
我该如何搜索以找到最新的可再生能源发展动态
## Run your code 运行你的代码
npx tsx quickstart.ts
Example output: 示例输出:
```bash
{
id: 'msg_01ThFHzad6Bh4TpQ6cHux9t8',
type: 'message',
role: 'assistant',
model: 'claude-sonnet-4-5-20250929',
content: [
{
type: 'text',
text: 'Here are some effective search strategies to find the latest renewable energy developments:\n\n' + //这里有一些有效的搜索策略,用于查找最新的可再生能源发展动态
'## Search Terms to Use:\n' +
'- "renewable energy news 2024"\n' +
'- "clean energy breakthroughs"\n' +
'- "solar wind technology advances"\n' +
'- "energy storage innovations"\n' +
'- "green hydrogen developments"\n' +
'- "offshore wind projects"\n' +
'- "battery technology renewable"\n\n' +
'## Best Sources to Check:\n\n' +
'**News & Industry Sites:**\n' +
'- Renewable Energy World\n' +
'- CleanTechnica\n' +
'- GreenTech Media (now Wood Mackenzie)\n' +
'- Energy Storage News\n' +
'- PV Magazine (for solar)...'
}
],
stop_reason: 'end_turn',
usage: {
input_tokens: 21,
output_tokens: 302
}
}
```

浙公网安备 33010602011771号