⚡ TECH BLOG
Home
Blog
Tags
About
⚡

Powered by Next.js 15 & Modern Web Tech ⚡

Back to Home

Building AI Agents with Claude API

January 15, 2024
aiclaudeagentsjavascript
Building AI Agents with Claude API

Building AI Agents with Claude API

Claude API enables building sophisticated AI agents for autonomous task execution.

Basic Agent Structure

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

const client = new Anthropic();

async function runAgent(prompt: string) {
  const message = await client.messages.create({
    model: 'claude-sonnet-4-20250514',
    max_tokens: 4096,
    messages: [{ role: 'user', content: prompt }],
    tools: [
      {
        name: 'search',
        description: 'Search the web for information',
        input_schema: {
          type: 'object',
          properties: {
            query: { type: 'string' },
          },
        },
      },
    ],
  });
  
  return message;
}

Tool Use

async function handleToolUse(content: any) {
  if (content.type === 'tool_use') {
    switch (content.name) {
      case 'search':
        return await search(content.input.query);
      case 'calculate':
        return await calculate(content.input);
      default:
        return 'Unknown tool';
    }
  }
}

Agentic Loop

async function agenticLoop(prompt: string, maxIterations = 10) {
  let messages = [{ role: 'user', content: prompt }];
  
  for (let i = 0; i < maxIterations; i++) {
    const response = await client.messages.create({
      model: 'claude-sonnet-4-20250514',
      max_tokens: 4096,
      messages,
      tools: [...],
    });
    
    // Check if agent is done
    if (response.stop_reason === 'end_turn') {
      return response.content;
    }
    
    // Handle tool calls
    const toolResults = await Promise.all(
      response.content
        .filter(c => c.type === 'tool_use')
        .map(handleToolUse)
    );
    
    messages.push(
      { role: 'assistant', content: response.content },
      { role: 'user', content: toolResults }
    );
  }
}

Conclusion

Claude API provides powerful capabilities for building autonomous AI agents that can reason and use tools.

Share:

💬 Comments