// PHP EDITION

Simple AI Agents
with PHP & Claude API

A beginner-friendly, open-source tutorial. No frameworks. No fluff. Just PHP doing cool AI things.

By Orlando Ritchie Natonton & Anthropic Claude.AI

What is an AI Agent?

An AI agent is a program that can perceive a task, think using an AI model like Claude, and act — respond, calculate, search, or call other agents.

Think of it like a smart employee. You assign it work. It figures out how to do it.

STEPWHAT HAPPENS
1. PerceiveReceives a task or question from the user
2. ThinkSends the task to Claude API for reasoning
3. ActReturns an answer, uses a tool, or calls another agent

Before You Start

01

PHP 7.4+

Install PHP or use XAMPP / WAMP locally

02

Anthropic API Key

Free at console.anthropic.com

03

cURL enabled

Comes with PHP by default. Just check php.ini

04

A terminal

CMD, Terminal, or any shell will do

Set your API key as an environment variable:

# Mac / Linux export ANTHROPIC_API_KEY="your-key-here" # Windows CMD set ANTHROPIC_API_KEY=your-key-here
⚠️

Never hardcode your API key directly in PHP files. Always use environment variables or a .env file that's listed in .gitignore.

Three Levels — Build Up From Zero

LEVEL 01 / BEGINNER
Hello Agent — Your First AI Call

The simplest agent: send a question to Claude, get an answer back. This is the foundation of everything.

RUN › php 01_hello_agent/hello_agent.php
hello_agent.php <?php // Simple AI Agent — Level 1 // Requires: PHP 7.4+, cURL, Anthropic API key function hello_agent($question) { $api_key = getenv('ANTHROPIC_API_KEY'); // Build the request payload $payload = json_encode([ 'model' => 'claude-sonnet-4-5-20250929', 'max_tokens' => 300, 'messages' => [[ 'role' => 'user', 'content' => $question ]] ]); // Send to Claude API via cURL $ch = curl_init('https://api.anthropic.com/v1/messages'); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'x-api-key: ' . $api_key, 'anthropic-version: 2023-06-01' ] ]); $response = json_decode(curl_exec($ch), true); curl_close($ch); // Extract the answer text return $response['content'][0]['text']; } // Run the agent $question = "What is an AI agent in simple terms?"; echo "\n🧠 Question: $question\n"; echo "\n✅ Agent says:\n" . hello_agent($question) . "\n";
🎯

Challenge: Change the question on the last line. Try: "What is SQL injection in simple terms?"

LEVEL 02 / INTERMEDIATE
Tool Agent — Give Your Agent Superpowers

Real agents use tools. We give this agent a calculator and a date checker. Claude decides on its own which tool to use.

RUN › php 02_tool_agent/tool_agent.php
TOOLWHAT IT DOES
🔢 calculatorEvaluates a math expression safely
📅 get_current_dateReturns today's date
tool_agent.php <?php // Tool Agent — Level 2 // --- PHP Tool Functions --- function calculator($expr) { // WARNING: eval is powerful — only safe inputs in real apps! return "Result: " . eval("return $expr;"); } function get_current_date() { return "Today is " . date('F j, Y'); } // --- Tool definitions for Claude --- $tool_defs = [ ['name' => 'calculator', 'description' => 'Evaluates a math expression', 'input_schema' => [ 'type' => 'object', 'properties' => ['expression' => ['type' => 'string']], 'required' => ['expression'] ]], ['name' => 'get_current_date', 'description' => 'Returns today\'s date', 'input_schema' => ['type' => 'object', 'properties' => (object)[]] ] ]; function call_claude($messages, $tools = []) { $api_key = getenv('ANTHROPIC_API_KEY'); $body = ['model' => 'claude-sonnet-4-5-20250929', 'max_tokens' => 500, 'messages' => $messages]; if (!empty($tools)) $body['tools'] = $tools; $ch = curl_init('https://api.anthropic.com/v1/messages'); curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($body), CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'x-api-key: ' . $api_key, 'anthropic-version: 2023-06-01']]); $r = json_decode(curl_exec($ch), true); curl_close($ch); return $r; } function tool_agent($question) { global $tool_defs; echo "\n🧠 Question: $question\n"; $messages = [['role' => 'user', 'content' => $question]]; while (true) { $resp = call_claude($messages, $tool_defs); if ($resp['stop_reason'] === 'tool_use') { $tool_results = []; foreach ($resp['content'] as $block) { if ($block['type'] === 'tool_use') { $name = $block['name']; $input = $block['input']; echo "🔧 Using: $name\n"; $result = ($name === 'calculator') ? calculator($input['expression']) : get_current_date(); echo " → $result\n"; $tool_results[] = ['type' => 'tool_result', 'tool_use_id' => $block['id'], 'content' => $result]; } } $messages[] = ['role' => 'assistant', 'content' => $resp['content']]; $messages[] = ['role' => 'user', 'content' => $tool_results]; } else { echo "\n✅ " . $resp['content'][0]['text'] . "\n"; break; } } } tool_agent("What is 128 multiplied by 37?"); tool_agent("What day is today?"); tool_agent("If I have 500 pesos and spend 175, how much is left?");
🎯

Challenge: Add a word_counter($text) tool that returns the number of words in a sentence!

LEVEL 03 / ADVANCED
Multi-Agent System — Agents Working as a Team

Multiple specialized agents collaborate. A Coordinator reads each task and delegates to the right expert. This is the architecture behind MoltFlask.

RUN › php 03_multi_agent/multi_agent.php
AGENTSPECIALTY
🎯 CoordinatorRoutes tasks to the right specialist
🔐 Security AgentCybersecurity questions
📊 Data AgentData analysis questions
✍️ Writer AgentWriting and summaries
multi_agent.php <?php // Multi-Agent System — Level 3 // Based on MoltFlask architecture function ask_claude($system, $user_msg, $tokens = 400) { $api_key = getenv('ANTHROPIC_API_KEY'); $ch = curl_init('https://api.anthropic.com/v1/messages'); curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode([ 'model' => 'claude-sonnet-4-5-20250929', 'max_tokens' => $tokens, 'system' => $system, 'messages' => [['role' => 'user', 'content' => $user_msg]] ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'x-api-key: ' . $api_key, 'anthropic-version: 2023-06-01']]); $r = json_decode(curl_exec($ch), true); curl_close($ch); return $r['content'][0]['text']; } // --- Specialist Agents --- function security_agent($task) { return ask_claude( 'You are a cybersecurity expert. Answer clearly for beginners.', $task ); } function data_agent($task) { return ask_claude( 'You are a data expert. Use simple examples.', $task ); } function writer_agent($task) { return ask_claude( 'You are a professional writer. Be clear and engaging.', $task ); } // --- Coordinator Agent --- function coordinator_agent($task) { echo "\n📋 Task: $task\n"; $route = strtoupper(trim(ask_claude( 'You are a task router. Reply with ONE word only: SECURITY (cybersecurity topics) DATA (data/analysis topics) WRITER (writing/summarizing topics)', $task, 20 ))); echo "🔀 Routing to: $route\n"; if (str_contains($route, 'SECURITY')) { echo "\n🔐 Security Agent:\n" . security_agent($task) . "\n"; } elseif (str_contains($route, 'DATA')) { echo "\n📊 Data Agent:\n" . data_agent($task) . "\n"; } else { echo "\n✍️ Writer Agent:\n" . writer_agent($task) . "\n"; } } // --- Run it --- $tasks = [ "What is SQL injection and how to prevent it?", "Explain what a CSV file is and how to read it.", "Write an intro paragraph about AI agents for beginners." ]; echo str_repeat("=", 60) . "\nMULTI-AGENT SYSTEM DEMO\n" . str_repeat("=", 60); foreach ($tasks as $t) { echo "\n" . str_repeat("-",60); coordinator_agent($t); }
🎯

Challenge: Add a teacher_agent() that explains topics like a patient professor. Then add it to the coordinator's routing!

📄

This multi-agent architecture is the foundation of MoltFlask 2 — a cloud-deployed AI agent social network security research platform. Read the paper →

Key Concepts at a Glance

CONCEPTSIMPLE MEANING
AgentA program that receives tasks and uses AI to complete them
ToolA PHP function the agent can call to do real-world actions
CoordinatorAn agent that reads and delegates tasks to specialists
Multi-agent systemMultiple agents working together, each with a specialty
Agent loopThe cycle: receive → think → act → respond
cURLPHP's built-in tool for making HTTP requests (how we call Claude)