EmailVerify LogoEmailVerify

Anthropic Claude

Email checker with Anthropic Claude SDK. Verify emails using Claude AI tool calling.

Use EmailVerify directly with Anthropic's Claude models through their native tool use feature.

Installation

npm install @anthropic-ai/sdk

Basic Setup

import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic();

const tools: Anthropic.Tool[] = [
  {
    name: 'verify_email',
    description: 'Verify if an email address is valid and deliverable. Returns status, deliverability, disposable flag, and confidence score.',
    input_schema: {
      type: 'object' as const,
      properties: {
        email: {
          type: 'string',
          description: 'The email address to verify',
        },
      },
      required: ['email'],
    },
  },
];

Implementation

import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic();

const tools: Anthropic.Tool[] = [
  {
    name: 'verify_email',
    description: 'Verify if an email address is valid and deliverable. Returns status, deliverability, disposable flag, and confidence score.',
    input_schema: {
      type: 'object' as const,
      properties: {
        email: {
          type: 'string',
          description: 'The email address to verify',
        },
      },
      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,
  });

  // Handle tool use
  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;
}

// Usage
const result = await chat('Verify test@example.com for me');
console.log(result);

Multiple Tools

const tools: Anthropic.Tool[] = [
  {
    name: 'verify_email',
    description: 'Verify a single email address',
    input_schema: {
      type: 'object' as const,
      properties: {
        email: {
          type: 'string',
          description: 'The email address to verify',
        },
      },
      required: ['email'],
    },
  },
  {
    name: 'verify_emails_bulk',
    description: 'Verify multiple email addresses at once',
    input_schema: {
      type: 'object' as const,
      properties: {
        emails: {
          type: 'array',
          items: { type: 'string' },
          description: 'Array of email addresses to verify',
        },
      },
      required: ['emails'],
    },
  },
  {
    name: 'check_credits',
    description: 'Check remaining verification credits',
    input_schema: {
      type: 'object' as const,
      properties: {},
    },
  },
];

Handling Multiple Tool Calls

Claude may call tools multiple times in a conversation:

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

    // Check if Claude wants to use a tool
    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 {
      // No more tool calls, return the final response
      const textBlock = response.content.find(
        (block): block is Anthropic.TextBlock => block.type === 'text'
      );
      return textBlock?.text;
    }
  }
}

With Streaming

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

  // Handle tool use if needed
  if (finalMessage.stop_reason === 'tool_use') {
    // Process tool calls...
  }
}

Python Example

import anthropic
import requests
import json
import os

client = anthropic.Anthropic()

tools = [
    {
        "name": "verify_email",
        "description": "Verify if an email address is valid and deliverable",
        "input_schema": {
            "type": "object",
            "properties": {
                "email": {
                    "type": "string",
                    "description": "The email address to verify"
                }
            },
            "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")
    )

# Usage
result = chat("Is john@google.com a valid email?")
print(result)

Next Steps

On this page