EmailVerify LogoEmailVerify

Vercel AI SDK

Email checker with Vercel AI SDK. Verify emails in Next.js AI applications.

De Vercel AI SDK maakt het eenvoudig om tools toe te voegen die AI-modellen kunnen aanroepen. Deze gids laat zien hoe u EmailVerify e-mailverificatie kunt integreren als tool.

Installatie

npm install ai @ai-sdk/openai zod

Basis Tool Definitie

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

Gebruik met streamText

Voor streaming responses:

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

Gebruik met generateText

Voor niet-streaming responses met tool-resultaten:

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 Route

Maak een API-route voor AI-chat met e-mailverificatie:

// 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 Client Component

Gebruik met de useChat hook:

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

Bulk Verificatie Tool

Voor het verifiëren van meerdere e-mails tegelijk:

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

Compleet Voorbeeld

Hier is een volledig voorbeeld met meerdere tools:

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

Volgende Stappen

On this page