Anthropic
Email checker with Anthropic Claude SDK. Verify emails using Claude AI tool calling.
透過 Anthropic 的原生工具使用功能,直接在 Claude 模型中使用 EmailVerify。
安装
npm install @anthropic-ai/sdk基礎設定
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
const tools: Anthropic.Tool[] = [
{
name: 'verify_email',
description: '驗證郵箱地址是否有效和可送達。返回狀態、可送達性、一次性郵箱標誌和置信度評分。',
input_schema: {
type: 'object' as const,
properties: {
email: {
type: 'string',
description: '要驗證的郵箱地址',
},
},
required: ['email'],
},
},
];實作
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
const tools: Anthropic.Tool[] = [
{
name: 'verify_email',
description: '驗證郵箱地址是否有效和可送達。返回狀態、可送達性、一次性郵箱標誌和置信度評分。',
input_schema: {
type: 'object' as const,
properties: {
email: {
type: 'string',
description: '要驗證的郵箱地址',
},
},
required: ['email'],
},
},
];
async function verifyEmail(email: string) {
const response = await fetch('https://api.emailverify.ai/v1/verify', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.EMAILVERIFY_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
});
return response.json();
}
async function chat(userMessage: string) {
const messages: Anthropic.MessageParam[] = [
{ role: 'user', content: userMessage },
];
const response = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
tools,
messages,
});
// 處理工具使用
if (response.stop_reason === 'tool_use') {
const toolUseBlock = response.content.find(
(block): block is Anthropic.ToolUseBlock => block.type === 'tool_use'
);
if (toolUseBlock && toolUseBlock.name === 'verify_email') {
const result = await verifyEmail((toolUseBlock.input as { email: string }).email);
messages.push({ role: 'assistant', content: response.content });
messages.push({
role: 'user',
content: [
{
type: 'tool_result',
tool_use_id: toolUseBlock.id,
content: JSON.stringify(result),
},
],
});
const finalResponse = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
tools,
messages,
});
const textBlock = finalResponse.content.find(
(block): block is Anthropic.TextBlock => block.type === 'text'
);
return textBlock?.text;
}
}
const textBlock = response.content.find(
(block): block is Anthropic.TextBlock => block.type === 'text'
);
return textBlock?.text;
}
// 使用範例
const result = await chat('幫我驗證 test@example.com');
console.log(result);多個工具
const tools: Anthropic.Tool[] = [
{
name: 'verify_email',
description: '驗證單個郵箱地址',
input_schema: {
type: 'object' as const,
properties: {
email: {
type: 'string',
description: '要驗證的郵箱地址',
},
},
required: ['email'],
},
},
{
name: 'verify_emails_bulk',
description: '一次驗證多個郵箱地址',
input_schema: {
type: 'object' as const,
properties: {
emails: {
type: 'array',
items: { type: 'string' },
description: '要驗證的郵箱地址陣列',
},
},
required: ['emails'],
},
},
{
name: 'check_credits',
description: '檢查剩餘驗證額度',
input_schema: {
type: 'object' as const,
properties: {},
},
},
];處理多次工具呼叫
Claude 可能在對話中多次呼叫工具:
async function chatWithMultipleTools(userMessage: string) {
let messages: Anthropic.MessageParam[] = [
{ role: 'user', content: userMessage },
];
while (true) {
const response = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
tools,
messages,
});
// 檢查 Claude 是否想要使用工具
if (response.stop_reason === 'tool_use') {
const toolResults: Anthropic.ToolResultBlockParam[] = [];
for (const block of response.content) {
if (block.type === 'tool_use') {
let result: any;
switch (block.name) {
case 'verify_email':
result = await verifyEmail((block.input as { email: string }).email);
break;
case 'verify_emails_bulk':
result = await verifyEmailsBulk((block.input as { emails: string[] }).emails);
break;
case 'check_credits':
result = await checkCredits();
break;
}
toolResults.push({
type: 'tool_result',
tool_use_id: block.id,
content: JSON.stringify(result),
});
}
}
messages.push({ role: 'assistant', content: response.content });
messages.push({ role: 'user', content: toolResults });
} else {
// 沒有更多工具呼叫,返回最終回應
const textBlock = response.content.find(
(block): block is Anthropic.TextBlock => block.type === 'text'
);
return textBlock?.text;
}
}
}使用串流傳輸
async function chatStream(userMessage: string) {
const messages: Anthropic.MessageParam[] = [
{ role: 'user', content: userMessage },
];
const stream = anthropic.messages.stream({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
tools,
messages,
});
for await (const event of stream) {
if (event.type === 'content_block_delta') {
if (event.delta.type === 'text_delta') {
process.stdout.write(event.delta.text);
}
}
}
const finalMessage = await stream.finalMessage();
// 如果需要,處理工具使用
if (finalMessage.stop_reason === 'tool_use') {
// 處理工具呼叫...
}
}Python 範例
import anthropic
import requests
import json
import os
client = anthropic.Anthropic()
tools = [
{
"name": "verify_email",
"description": "驗證郵箱地址是否有效和可送達",
"input_schema": {
"type": "object",
"properties": {
"email": {
"type": "string",
"description": "要驗證的郵箱地址"
}
},
"required": ["email"]
}
}
]
def verify_email(email: str) -> dict:
response = requests.post(
'https://api.emailverify.ai/v1/verify',
headers={
'Authorization': f'Bearer {os.environ["EMAILVERIFY_API_KEY"]}',
'Content-Type': 'application/json',
},
json={'email': email}
)
return response.json()
def chat(user_message: str) -> str:
messages = [{"role": "user", "content": user_message}]
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=tools,
messages=messages
)
if response.stop_reason == "tool_use":
tool_use = next(
block for block in response.content
if block.type == "tool_use"
)
result = verify_email(tool_use.input["email"])
messages.append({"role": "assistant", "content": response.content})
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": json.dumps(result)
}]
})
final_response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=tools,
messages=messages
)
return next(
block.text for block in final_response.content
if hasattr(block, "text")
)
return next(
block.text for block in response.content
if hasattr(block, "text")
)
# 使用範例
result = chat("john@google.com 是有效的郵箱嗎?")
print(result)