neuron-core/neuron-ai
Neuron is a PHP framework for building agentic apps: create and orchestrate AI agents, integrate LLM providers, load data, run multi-agent workflows, and monitor/debug behavior. Works well with Laravel and Symfony.
## Getting Started
### First Steps
1. **Installation**:
```bash
composer require neuron-core/neuron-ai
Verify PHP 8.1+ compatibility in your project.
Generate a Basic Agent:
vendor/bin/neuron make:agent CustomerSupportAgent
This creates a scaffold with provider(), instructions(), and tools() methods.
First Interaction:
$agent = CustomerSupportAgent::make();
$response = $agent->chat(new UserMessage("How do I reset my password?"))
->getMessage();
echo $response->getContent();
Typical Workflow:
// 1. Define agent (via CLI or manually)
class SupportAgent extends Agent {
protected function provider(): AIProviderInterface { /* ... */ }
protected function instructions(): string { /* ... */ }
protected function tools(): array { /* ... */ }
}
// 2. Instantiate and interact
$agent = SupportAgent::make();
// 3. Chat interaction
$response = $agent->chat(new UserMessage("..."))
->getMessage();
// 4. Stream interaction (for real-time)
$stream = $agent->stream(new UserMessage("..."));
foreach ($stream->events() as $chunk) {
if ($chunk instanceof TextChunk) {
echo $chunk->content;
}
}
Database Query Tool:
protected function tools(): array {
return [
MySQLToolkit::make(\DB::connection()->getPdo()),
// OR custom tool
new CustomTool(
name: 'get_user_orders',
description: 'Retrieve orders for a specific user',
callback: fn($userId) => Order::where('user_id', $userId)->get()
)
];
}
Tool Approval Workflow:
$agent = SupportAgent::make();
$agent->setToolApprovalMiddleware(function($toolCall) {
// Log or notify admin before execution
return true; // or false to reject
});
Vector Store + Embeddings:
class ProductKnowledgeBot extends RAG {
protected function embeddings(): EmbeddingsProviderInterface {
return new VoyageEmbeddingProvider(
key: env('VOYAGE_API_KEY'),
model: 'voyage-large'
);
}
protected function vectorStore(): VectorStoreInterface {
return new PineconeVectorStore(
key: env('PINECONE_API_KEY'),
indexUrl: env('PINECONE_INDEX_URL')
);
}
}
Schema-Driven Responses:
class OrderRequest {
#[SchemaProperty(description: 'Customer ID', required: true)]
public string $customerId;
#[SchemaProperty(description: 'Product SKU', required: true)]
public string $productSku;
}
$order = $agent->structured(
new UserMessage("I want to order product ABC123"),
OrderRequest::class
);
Service Provider Binding:
// app/Providers/NeuronServiceProvider.php
public function register() {
$this->app->singleton(CustomerSupportAgent::class, function($app) {
return CustomerSupportAgent::make();
});
}
// Usage in controller
public function handleRequest(Request $request) {
$agent = app(CustomerSupportAgent::class);
// ...
}
Route Integration:
Route::post('/support-chat', function(Request $request) {
$agent = CustomerSupportAgent::make();
$response = $agent->chat(new UserMessage($request->input('message')))
->getMessage();
return response()->json([
'content' => $response->getContent(),
'tools' => $response->getToolCalls()
]);
});
Inspector Integration:
# .env
INSPECTOR_INGESTION_KEY=your_key_here
Automatically captures:
Tool Execution Errors:
ToolExceptionHandler:
$agent->setToolExceptionHandler(function($tool, $exception) {
return new ToolResultChunk([
'error' => $exception->getMessage(),
'trace' => $exception->getTraceAsString()
]);
});
Prompt Engineering:
SystemPrompt with explicit steps:
new SystemPrompt([
'background' => ["You are a Laravel expert."],
'steps' => [
"Analyze the error message",
"Suggest 1-3 solutions with code examples",
"Explain tradeoffs"
],
'output' => ["Always use PHP 8.1+ syntax"]
])
Memory Management:
protected function chatHistory(): ChatHistoryInterface {
return new InMemoryChatHistory(maxMessages: 50);
}
Provider Rate Limits:
$provider = new OpenAI(
key: env('OPENAI_KEY'),
model: 'gpt-4',
retry: new RetryStrategy(maxAttempts: 3, delay: 1000)
);
Structured Output Validation:
if (!$agent->validateSchema(OrderRequest::class)) {
throw new \InvalidArgumentException("Schema validation failed");
}
Inspect Agent State:
$agent = CustomerSupportAgent::make();
dump($agent->getState()); // Shows current memory, tools, etc.
Log Prompts:
$agent->setPromptLogger(function($prompt) {
\Log::debug('Generated prompt:', ['prompt' => $prompt]);
});
Tool Call Tracing:
$agent->setToolCallObserver(function($toolCall) {
\Log::info('Tool called', [
'name' => $toolCall->name,
'args' => $toolCall->arguments
]);
});
Environment Variables:
env() for API keys:
new Anthropic(key: env('ANTHROPIC_API_KEY'))
Model Selection:
// Start with cheaper model, upgrade as needed
$provider = new OpenAI(model: 'gpt-3.5-turbo');
Toolkit Dependencies:
pecl install pdo_pgsql # For PostgreSQLToolkit
Custom Providers:
class CustomProvider implements AIProviderInterface {
public function chat(ChatRequest $request): ChatResponse {
// Implement custom LLM logic
}
}
Middleware Pipeline:
$agent->addMiddleware(function($request, $next) {
\Log::info('Agent request', $request->toArray());
return $next($request);
});
Event Observers:
$agent->on('tool.called', function($event) {
// Handle tool execution events
});
Custom Vector Stores:
class RedisVectorStore implements VectorStoreInterface {
// Implement required methods
public function addEmbedding(...): void { /* ... */ }
public function search(...): array { /* ... */ }
}
Prompt Caching:
$provider = new Anthropic(
key: env('ANTHROPIC_KEY'),
model: 'claude-3-haiku',
cache: new FileCache('/path/to/prompt_cache')
);
Batch Processing:
$agent->setBatchMode(true); // For bulk operations
Stream Optimization:
$stream = $
How can I help you explore Laravel packages today?