Vercel AI SDK
Email checker with Vercel AI SDK. Verify emails in Next.js AI applications.
Vercel AI SDK를 사용하면 AI 모델이 호출할 수 있는 도구를 쉽게 추가할 수 있습니다. 이 가이드는 EmailVerify 이메일 검증을 도구로 통합하는 방법을 보여줍니다.
설치
npm install ai @ai-sdk/openai zod기본 도구 정의
import { tool } from 'ai';
import { z } from 'zod';
export const verifyEmailTool = tool({
description: 'Verify if an email address is valid and deliverable. Returns status, deliverability, and whether the email is disposable or role-based.',
parameters: z.object({
email: z.string().email().describe('The email address to verify'),
}),
execute: async ({ email }) => {
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 }),
});
if (!response.ok) {
throw new Error(`Verification failed: ${response.statusText}`);
}
return response.json();
},
});streamText와 함께 사용
스트리밍 응답의 경우:
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { verifyEmailTool } from './tools/verify-email';
const result = await streamText({
model: openai('gpt-4-turbo'),
tools: {
verifyEmail: verifyEmailTool,
},
prompt: 'Verify if user@example.com is a valid email address',
});
for await (const chunk of result.textStream) {
process.stdout.write(chunk);
}generateText와 함께 사용
도구 결과가 포함된 비스트리밍 응답의 경우:
import { generateText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { verifyEmailTool } from './tools/verify-email';
const { text, toolCalls, toolResults } = await generateText({
model: anthropic('claude-3-5-sonnet-20241022'),
tools: {
verifyEmail: verifyEmailTool,
},
maxToolRoundtrips: 3,
prompt: 'Check these emails and tell me which are valid: john@google.com, test@mailinator.com',
});
console.log(text);
console.log('Tool calls:', toolCalls);
console.log('Tool results:', toolResults);Next.js API 라우트
이메일 검증이 포함된 AI 채팅용 API 라우트 생성:
// app/api/chat/route.ts
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { verifyEmailTool } from '@/lib/tools/verify-email';
export async function POST(req: Request) {
const { messages } = await req.json();
const result = await streamText({
model: openai('gpt-4-turbo'),
messages,
tools: {
verifyEmail: verifyEmailTool,
},
});
return result.toDataStreamResponse();
}React 클라이언트 컴포넌트
useChat 훅과 함께 사용:
'use client';
import { useChat } from 'ai/react';
export function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat({
api: '/api/chat',
});
return (
<div>
{messages.map((m) => (
<div key={m.id}>
<strong>{m.role}:</strong> {m.content}
</div>
))}
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={handleInputChange}
placeholder="Ask me to verify an email..."
/>
<button type="submit">Send</button>
</form>
</div>
);
}대량 검증 도구
한 번에 여러 이메일을 검증하는 경우:
import { tool } from 'ai';
import { z } from 'zod';
export const verifyEmailsBulkTool = tool({
description: 'Verify multiple email addresses at once. Use this when checking a list of emails.',
parameters: z.object({
emails: z.array(z.string().email()).max(100).describe('Array of email addresses to verify'),
}),
execute: async ({ emails }) => {
const response = await fetch('https://api.emailverify.ai/v1/verify/bulk', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.EMAILVERIFY_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ emails }),
});
return response.json();
},
});완전한 예제
다중 도구가 포함된 전체 예제입니다:
// lib/tools/index.ts
import { tool } from 'ai';
import { z } from 'zod';
export const verifyEmailTool = tool({
description: `Verify if an email address is valid and deliverable.
Returns:
- status: "valid", "invalid", or "unknown"
- deliverable: whether the email can receive messages
- disposable: whether it's a temporary email service
- role: whether it's a role-based address like info@ or support@
- score: confidence score from 0 to 1
Use this tool when:
- User asks to verify an email
- Checking if an email is real
- Validating contact information`,
parameters: z.object({
email: z.string().email().describe('The email address to verify'),
}),
execute: async ({ email }) => {
try {
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 }),
});
if (!response.ok) {
if (response.status === 429) {
return { error: 'Rate limit exceeded. Please try again later.' };
}
return { error: `Verification failed: ${response.statusText}` };
}
return response.json();
} catch (error) {
return { error: 'Network error. Could not reach verification service.' };
}
},
});
export const checkCreditsTool = tool({
description: 'Check remaining email verification credits',
parameters: z.object({}),
execute: async () => {
const response = await fetch('https://api.emailverify.ai/v1/credits', {
headers: {
'Authorization': `Bearer ${process.env.EMAILVERIFY_API_KEY}`,
},
});
return response.json();
},
});// app/api/chat/route.ts
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { verifyEmailTool, checkCreditsTool } from '@/lib/tools';
export async function POST(req: Request) {
const { messages } = await req.json();
const result = await streamText({
model: openai('gpt-4-turbo'),
system: 'You are a helpful assistant that can verify email addresses. When asked to verify emails, use the verifyEmail tool.',
messages,
tools: {
verifyEmail: verifyEmailTool,
checkCredits: checkCreditsTool,
},
maxToolRoundtrips: 5,
});
return result.toDataStreamResponse();
}