Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
Add Docs
Neuron AI
https://github.com/neuron-core/neuron-ai
Admin
Neuron AI is a PHP framework designed for creating and orchestrating AI Agents, providing tools for
...
Tokens:
18,649
Snippets:
110
Trust Score:
7
Update:
2 months ago
Context
Skills
Chat
Benchmark
91.4
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Neuron AI - PHP Agentic Framework Neuron AI is a comprehensive PHP framework for building AI-powered applications and agents. It provides a flexible architecture for integrating Large Language Models (LLMs) into PHP applications, supporting multiple providers including OpenAI, Anthropic (Claude), Google Gemini, Ollama, and more. The framework handles complex mechanisms like conversation memory, tool/function calling, structured output, and Retrieval-Augmented Generation (RAG) systems automatically. The framework is designed for production use with enterprise-grade features including built-in observability via Inspector.dev, type safety with 100% PHPStan coverage, and seamless integration with popular PHP frameworks like Laravel and Symfony. Neuron enables developers to create everything from simple chatbots to complex multi-agent workflows with human-in-the-loop capabilities. ## Installation Install Neuron AI via Composer: ```bash composer require neuron-core/neuron-ai ``` ## Creating an Agent Extend the base `Agent` class to create a custom AI agent with a specific provider and system instructions. ```php <?php namespace App\Neuron; use NeuronAI\Agent; use NeuronAI\SystemPrompt; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\Anthropic\Anthropic; class CustomerServiceAgent extends Agent { protected function provider(): AIProviderInterface { return new Anthropic( key: 'your-anthropic-api-key', model: 'claude-sonnet-4-20250514', max_tokens: 8192 ); } protected function instructions(): string { return (string) new SystemPrompt( background: [ 'You are a helpful customer service assistant.', 'Provide clear, friendly, and accurate responses.' ], steps: [ '1. Understand the customer question', '2. Search for relevant information', '3. Provide a helpful response' ], output: [ 'Keep responses concise and actionable', 'Use bullet points for complex information' ] ); } } // Usage $agent = CustomerServiceAgent::make(); ``` ## Chat with Agent Send messages to an agent and receive responses. The agent maintains conversation memory automatically. ```php <?php use App\Neuron\CustomerServiceAgent; use NeuronAI\Chat\Messages\UserMessage; $agent = CustomerServiceAgent::make(); // First message $response = $agent->chat(new UserMessage("Hi, I'm John. What products do you sell?")); echo $response->getContent(); // Output: "Hello John! We offer a wide range of products including..." // Agent remembers previous context $response = $agent->chat(new UserMessage("Do you remember my name?")); echo $response->getContent(); // Output: "Yes, your name is John, as you mentioned earlier." // Get token usage $usage = $response->getUsage(); echo "Input tokens: " . $usage->inputTokens; echo "Output tokens: " . $usage->outputTokens; ``` ## Streaming Responses Stream responses in real-time for better user experience in chat interfaces. ```php <?php use App\Neuron\CustomerServiceAgent; use NeuronAI\Chat\Messages\UserMessage; $agent = CustomerServiceAgent::make(); $stream = $agent->stream(new UserMessage("Tell me about your return policy")); foreach ($stream as $chunk) { echo $chunk; // Output each chunk as it arrives flush(); // Immediately send to browser } // Get the final complete response $response = $stream->getReturn(); echo "\n\nFull response: " . $response->getContent(); ``` ## AI Providers Switch between different LLM providers with a single line change. All providers implement the same interface. ```php <?php use NeuronAI\Agent; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\OpenAI\OpenAI; use NeuronAI\Providers\Anthropic\Anthropic; use NeuronAI\Providers\Gemini\Gemini; use NeuronAI\Providers\Ollama\Ollama; class MyAgent extends Agent { protected function provider(): AIProviderInterface { // OpenAI return new OpenAI( key: 'your-openai-api-key', model: 'gpt-4o' ); // OR Anthropic Claude return new Anthropic( key: 'your-anthropic-api-key', model: 'claude-sonnet-4-20250514' ); // OR Google Gemini return new Gemini( key: 'your-google-api-key', model: 'gemini-2.0-flash' ); // OR Local Ollama return new Ollama( url: 'http://localhost:11434/api', model: 'llama3.2' ); } protected function instructions(): string { return 'You are a helpful assistant.'; } } ``` ## Tools and Function Calling Add tools to enable agents to perform actions like database queries, API calls, or calculations. ```php <?php use NeuronAI\Agent; use NeuronAI\Tools\Tool; use NeuronAI\Tools\ToolProperty; use NeuronAI\Tools\PropertyType; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\OpenAI\OpenAI; class WeatherAgent extends Agent { protected function provider(): AIProviderInterface { return new OpenAI(key: 'your-api-key', model: 'gpt-4o'); } protected function instructions(): string { return 'You help users get weather information for any city.'; } protected function tools(): array { return [ Tool::make( name: 'get_weather', description: 'Get current weather for a city', properties: [ new ToolProperty( name: 'city', type: PropertyType::STRING, description: 'The city name', required: true ), new ToolProperty( name: 'unit', type: PropertyType::STRING, description: 'Temperature unit', required: false, enum: ['celsius', 'fahrenheit'] ) ] )->setCallable(function (string $city, ?string $unit = 'celsius'): string { // Call weather API here return json_encode([ 'city' => $city, 'temperature' => 22, 'unit' => $unit, 'condition' => 'sunny' ]); }) ]; } } // Usage - the agent will automatically call the tool when needed $agent = WeatherAgent::make(); $response = $agent->chat(new UserMessage("What's the weather in Paris?")); echo $response->getContent(); // Output: "The weather in Paris is currently sunny with a temperature of 22°C." ``` ## Built-in Toolkits Use pre-built toolkits for common tasks like database operations, file system access, and web searches. ```php <?php use NeuronAI\Agent; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\Anthropic\Anthropic; use NeuronAI\Tools\Toolkits\MySQL\MySQLToolkit; use NeuronAI\Tools\Toolkits\Calculator\CalculatorToolkit; use NeuronAI\Tools\Toolkits\FileSystem\FileSystemToolkit; use NeuronAI\Tools\Toolkits\Tavily\TavilyToolkit; use NeuronAI\Chat\Messages\UserMessage; class DataAnalystAgent extends Agent { public function __construct(private \PDO $pdo) {} protected function provider(): AIProviderInterface { return new Anthropic( key: 'your-anthropic-key', model: 'claude-sonnet-4-20250514' ); } protected function instructions(): string { return 'You are a data analyst. Query databases and perform calculations.'; } protected function tools(): array { return [ // MySQL database tools (schema, select, write) MySQLToolkit::make($this->pdo), // Calculator tools (sum, multiply, statistics, etc.) CalculatorToolkit::make(), // File system tools (read, list, grep) FileSystemToolkit::make('/path/to/data'), // Web search via Tavily TavilyToolkit::make('your-tavily-api-key'), ]; } } // Usage $pdo = new \PDO('mysql:host=localhost;dbname=sales', 'user', 'password'); $agent = new DataAnalystAgent($pdo); $response = $agent->chat(new UserMessage("How many orders were placed last month?")); echo $response->getContent(); // Agent queries database and returns: "There were 1,247 orders placed last month." ``` ## MCP Connector Connect to Model Context Protocol (MCP) servers to use external tools. ```php <?php use NeuronAI\Agent; use NeuronAI\MCP\McpConnector; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\Anthropic\Anthropic; class MCPAgent extends Agent { protected function provider(): AIProviderInterface { return new Anthropic( key: 'your-anthropic-key', model: 'claude-sonnet-4-20250514' ); } protected function instructions(): string { return 'You can use various MCP server tools.'; } protected function tools(): array { return [ // Connect to an MCP server and import all its tools ...McpConnector::make([ 'command' => 'npx', 'args' => ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/files'], ])->tools(), // You can filter which tools to import ...McpConnector::make([ 'command' => 'npx', 'args' => ['-y', '@modelcontextprotocol/server-everything'], ]) ->only(['read_file', 'write_file']) // Only include these ->exclude(['delete_file']) // Or exclude these ->tools(), ]; } } ``` ## Structured Output Get typed, validated responses from the AI in a specific format. ```php <?php use NeuronAI\Agent; use NeuronAI\StructuredOutput\SchemaProperty; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\OpenAI\OpenAI; use NeuronAI\Chat\Messages\UserMessage; // Define output structure as a PHP class class ProductReview { #[SchemaProperty(description: 'The product name mentioned in the review')] public string $productName; #[SchemaProperty(description: 'Sentiment score from 1-5')] public int $sentiment; #[SchemaProperty(description: 'Key points from the review')] public array $keyPoints; #[SchemaProperty(description: 'Whether the reviewer would recommend')] public bool $recommended; } class ReviewAnalyzer extends Agent { protected function provider(): AIProviderInterface { return new OpenAI(key: 'your-api-key', model: 'gpt-4o'); } protected function instructions(): string { return 'Extract structured data from product reviews.'; } } // Usage $agent = ReviewAnalyzer::make(); $review = $agent->structured( new UserMessage("This laptop is amazing! Great battery life and super fast. The keyboard is comfortable. Would definitely recommend to anyone looking for a reliable work machine."), ProductReview::class ); echo $review->productName; // "laptop" echo $review->sentiment; // 5 echo $review->recommended; // true print_r($review->keyPoints); // ["Great battery life", "Super fast", "Comfortable keyboard"] ``` ## RAG (Retrieval-Augmented Generation) Create knowledge-based chatbots that retrieve relevant information from documents. ```php <?php use NeuronAI\RAG\RAG; use NeuronAI\RAG\Document; use NeuronAI\RAG\DataLoader\FileDataLoader; use NeuronAI\RAG\Splitter\SentenceTextSplitter; use NeuronAI\RAG\Embeddings\OpenAIEmbeddingsProvider; use NeuronAI\RAG\VectorStore\PineconeVectorStore; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\Anthropic\Anthropic; use NeuronAI\Chat\Messages\UserMessage; class DocumentChatBot extends RAG { protected function provider(): AIProviderInterface { return new Anthropic( key: 'your-anthropic-key', model: 'claude-sonnet-4-20250514' ); } protected function instructions(): string { return 'Answer questions based on the provided documentation. If you cannot find the answer in the context, say so.'; } protected function embeddings(): EmbeddingsProviderInterface { return new OpenAIEmbeddingsProvider( key: 'your-openai-key', model: 'text-embedding-3-small', dimensions: 1024 ); } protected function vectorStore(): VectorStoreInterface { return new PineconeVectorStore( key: 'your-pinecone-key', indexUrl: 'https://your-index.pinecone.io' ); } } // Index documents $chatbot = DocumentChatBot::make(); $loader = new FileDataLoader( path: '/path/to/documents', readers: ['pdf' => PdfReader::class] ); $loader->withSplitter(new SentenceTextSplitter(maxWords: 200, overlapWords: 20)); $documents = $loader->getDocuments(); $chatbot->addDocuments($documents); // Query the knowledge base $response = $chatbot->chat( new UserMessage("What is the refund policy for digital products?") ); echo $response->getContent(); // Output: "Based on the documentation, digital products have a 14-day refund policy..." ``` ## Workflow System Build complex multi-step processes with event-driven nodes and human-in-the-loop capabilities. ```php <?php use NeuronAI\Workflow\Workflow; use NeuronAI\Workflow\Node; use NeuronAI\Workflow\Event; use NeuronAI\Workflow\StartEvent; use NeuronAI\Workflow\StopEvent; use NeuronAI\Workflow\WorkflowState; use NeuronAI\Workflow\WorkflowInterrupt; use NeuronAI\Workflow\Persistence\FilePersistence; // Define custom events class DataCollected extends Event { public function __construct(public array $data) {} } class ApprovalRequired extends Event { public function __construct(public string $summary) {} } // Define workflow nodes class CollectDataNode extends Node { public function __invoke(StartEvent $event, WorkflowState $state): DataCollected { // Collect data from various sources $data = ['users' => 150, 'revenue' => 50000, 'orders' => 320]; $state->set('raw_data', $data); return new DataCollected($data); } } class AnalyzeDataNode extends Node { public function __invoke(DataCollected $event, WorkflowState $state): ApprovalRequired { $data = $event->data; $summary = "Revenue: \${$data['revenue']}, Orders: {$data['orders']}"; $state->set('analysis', $summary); return new ApprovalRequired($summary); } } class ApprovalNode extends Node { public function __invoke(ApprovalRequired $event, WorkflowState $state): StopEvent { // Request human approval - this will pause the workflow $approval = $this->interruptIf( !$state->has('approved'), ['message' => 'Please review and approve: ' . $event->summary] ); $state->set('approved_by', $approval); return new StopEvent(); } } // Create and run workflow $persistence = new FilePersistence('/tmp/workflows'); $workflow = Workflow::make(new WorkflowState(), $persistence, 'report_workflow') ->addNodes([ new CollectDataNode(), new AnalyzeDataNode(), new ApprovalNode(), ]); // Start workflow - will interrupt at ApprovalNode try { $result = $workflow->start()->getResult(); } catch (WorkflowInterrupt $interrupt) { echo "Approval needed: " . $interrupt->getData()['message']; // Workflow state is automatically persisted } // Later: Resume workflow with approval $finalState = $workflow->wakeup('manager@company.com')->getResult(); echo "Report approved by: " . $finalState->get('approved_by'); ``` ## Message Attachments Send images and documents along with text messages for multimodal interactions. ```php <?php use NeuronAI\Agent; use NeuronAI\Chat\Messages\UserMessage; use NeuronAI\Chat\Attachments\Image; use NeuronAI\Chat\Attachments\Document; use NeuronAI\Chat\Enums\AttachmentContentType; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\Anthropic\Anthropic; class VisionAgent extends Agent { protected function provider(): AIProviderInterface { return new Anthropic( key: 'your-anthropic-key', model: 'claude-sonnet-4-20250514' ); } protected function instructions(): string { return 'Analyze images and documents provided by users.'; } } $agent = VisionAgent::make(); // Attach image from URL $message = new UserMessage("What's in this image?"); $message->addAttachment(new Image( 'https://example.com/photo.jpg', AttachmentContentType::URL )); // Or attach base64 encoded image $message->addAttachment(new Image( base64_encode(file_get_contents('/path/to/image.png')), AttachmentContentType::BASE64, 'image/png' )); $response = $agent->chat($message); echo $response->getContent(); // Output: "The image shows a sunset over a mountain range..." ``` ## Observability and Monitoring Enable automatic monitoring with Inspector.dev by setting an environment variable. ```php <?php // Set environment variable for automatic monitoring $_ENV['INSPECTOR_INGESTION_KEY'] = 'your-inspector-key'; // Or manually attach observers use NeuronAI\Agent; use SplObserver; use SplSubject; class CustomObserver implements SplObserver { public function update(SplSubject $subject, string $event = '*', mixed $data = null): void { match ($event) { 'chat-start' => $this->logStart($data), 'chat-stop' => $this->logComplete($data), 'tool-start' => $this->logToolCall($data), 'error' => $this->logError($data), default => null }; } private function logStart($data): void { echo "Chat started\n"; } private function logComplete($data): void { echo "Chat completed\n"; } private function logToolCall($data): void { echo "Tool called: " . $data->getName() . "\n"; } private function logError($data): void { echo "Error: " . $data->getMessage() . "\n"; } } $agent = MyAgent::make() ->observe(new CustomObserver(), 'chat-start') ->observe(new CustomObserver(), 'chat-stop') ->observe(new CustomObserver(), 'tool-start') ->observe(new CustomObserver(), 'error'); ``` ## CLI Commands Neuron provides CLI commands to scaffold agents, tools, and RAG components. ```bash # Create a new agent php vendor/bin/neuron make:agent CustomerServiceAgent # Create a custom tool php vendor/bin/neuron make:tool SearchProductsTool # Create a RAG chatbot php vendor/bin/neuron make:rag DocumentChatBot # Create a workflow node php vendor/bin/neuron make:node ProcessOrderNode # Create a complete workflow php vendor/bin/neuron make:workflow OrderProcessingWorkflow ``` ## Chat History and Memory Configure conversation memory with different storage backends. ```php <?php use NeuronAI\Agent; use NeuronAI\Chat\History\InMemoryChatHistory; use NeuronAI\Chat\History\FileChatHistory; use NeuronAI\Chat\History\SQLChatHistory; use NeuronAI\Chat\Messages\UserMessage; $agent = MyAgent::make(); // Default: In-memory (resets each request) $agent->withChatHistory(new InMemoryChatHistory()); // File-based persistence $agent->withChatHistory(new FileChatHistory('/path/to/chat/storage', 'session_123')); // SQL database persistence $agent->withChatHistory(new SQLChatHistory($pdo, 'chat_messages', 'user_123')); // Chat history automatically maintains context $response = $agent->chat(new UserMessage("My name is Alice")); $response = $agent->chat(new UserMessage("What did I just tell you?")); echo $response->getContent(); // "You told me your name is Alice." ``` ## Summary Neuron AI is designed for building production-ready AI applications in PHP. Primary use cases include conversational chatbots with memory, RAG-powered knowledge bases, autonomous agents with tool usage, data analysis agents that query databases, document processing and extraction pipelines, and multi-agent workflows with human oversight. The framework excels at integrating AI capabilities into existing PHP applications without requiring a complete stack change. Integration follows a consistent pattern: extend the base `Agent` or `RAG` class, implement the `provider()` method to select your LLM, define instructions via `instructions()`, and optionally add tools through `tools()`. The framework handles message formatting, tool execution, memory management, and response parsing automatically. For complex processes, the Workflow system provides event-driven orchestration with persistence and human-in-the-loop interrupts, enabling approval workflows, multi-step pipelines, and stateful long-running processes.