EmailVerify LogoEmailVerify

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();
}

次のステップ

On this page