Neuron AI Agent Builder
This skill helps you create and configure Neuron AI agents for building agentic applications in PHP.
Core Agent Structure
A Neuron agent extends the Agent class and implements key methods:
use NeuronAI\Agent;
use NeuronAI\Agent\SystemPrompt;
use NeuronAI\Providers\AIProviderInterface;
use NeuronAI\Providers\Anthropic\Anthropic;
class MyAgent extends Agent
{
protected function provider(): AIProviderInterface
{
return new Anthropic(
key: 'ANTHROPIC_API_KEY',
model: 'ANTHROPIC_MODEL',
);
}
protected function instructions(): string
{
return (string) new SystemPrompt(
background: [
"You are a helpful AI assistant."
]
);
}
}
Agent Execution Methods
Chat Mode (Synchronous)
For standard back-and-forth conversations:
$agent = MyAgent::make();
$response = $agent->chat(
new UserMessage("Hello!")
)->getMessage();
echo $response->getContent();
Stream Mode (Real-time)
For streaming responses as chunks arrive. Chunks represents pieces of context that are generated by the model.
The TextChunk class is used to represent a piece of text, but there are other chunk types available:
NeuronAI\Chat\Messages\Chunks\TextChunkNeuronAI\Chat\Messages\Chunks\ImageChunkNeuronAI\Chat\Messages\Chunks\AudioChunkNeuronAI\Chat\Messages\Chunks\ToolCallChunkNeuronAI\Chat\Messages\Chunks\ToolResultChunk
$handler = $agent->stream(new UserMessage("Hello"));
foreach ($handler->events() as $event) {
if ($event instanceof TextChunk) {
echo $event->content;
}
}
Streaming Adapters for UI Integration
When connecting a frontend UI to an agent, use streaming adapters to format the response for specific protocols. This enables seamless integration with popular AI UI libraries.
When to use:
- Building a chat interface with React/Vue/Next.js
- Using Vercel AI SDK's
useChathook - Implementing AG-UI protocol for agent-frontend communication
- Any SSE-based real-time UI updates
Available adapters:
VercelAIAdapter- Compatible with Vercel AI SDK (useChat,useCompletion)AGUIAdapter- AG-UI protocol for agent interactions
Laravel example:
use NeuronAI\Chat\Messages\Stream\Adapters\VercelAIAdapter;
Route::post('/chat', function (Request $request) {
$handler = MyAgent::make()->stream(
new UserMessage($request->input('message'))
);
$stream = $handler->events(new VercelAIAdapter());
return response()->stream(
function () use ($stream) {
foreach ($stream as $line) {
echo $line;
ob_flush();
flush();
}
},
200,
$adapter->getHeaders()
);
});
Structured Output Mode
For extracting structured data from a natural language:
class Person
{
#[SchemaProperty(description: 'The user name', required: true)]
public string $name;
#[SchemaProperty(description: 'What the user loves to eat')]
public string $preference;
}
$person = $agent->structured(
new UserMessage("I'm John and I like pizza!"),
Person::class
);
Providers Configuration
Anthropic
new Anthropic(
key: $_ENV['ANTHROPIC_API_KEY'],
model: 'ANTHROPIC_MODEL',
)
OpenAI
new OpenAI(
key: $_ENV['OPENAI_API_KEY'],
model: 'OPENAI_MODEL',
)
Ollama (Local)
new Ollama(
baseUrl: 'http://localhost:11434',
model: 'OLLAMA_MODEL',
)
Other Providers
Gemini- Google AI modelsVertexAI- Google Vertex AI platformMistral- Mistral AI modelsHuggingFace- Open models via HuggingFaceDeepseek- DeepSeek modelsGrok- XAI modelsAWSBedrockRuntime- AWS Bedrock inference platformCohere- Cohere modelsAzureOpenAI- Use OpenAI models on the Azure platformZAI- ZAI for GLM models
Tools Integration
Adding Built-in Toolkits
use NeuronAI\Tools\Toolkits\MySQL\MySQLToolkit;
use NeuronAI\Tools\Toolkits\Calculator\CalculatorToolkit;
protected function tools(): array
{
return [
MySQLToolkit::make(\DB::connection()->getPdo()),
CalculatorToolkit::make(),
];
}
Available Toolkits
- MySQLToolkit - Database queries via MySQL
- PostgreSQLToolkit - Database queries via PostgreSQL
- CalculatorToolkit - Math operations (sum, mean, std, etc.)
- TavilyToolkit - Web search with Tavily
- SESToolkit - Email sending via AWS SES
- JinaToolkit - Reranking with Jina
Creating Custom Tools
use the neuron-tool-creator skills for more complex tool creation:
use NeuronAI\Tools\Tool;
use NeuronAI\Tools\ToolProperty;
class WeatherTool extends Tool
{
public function __construct()
{
parent::__construct(
name: 'get_weather',
description: 'Get the current weather for a location',
);
}
/**
* @return ToolProperty[]
*/
protected function properties(): array
{
return [
new ToolProperty(
name: 'location',
type: ToolPropertyType::String,
description: 'The city name',
required: true,
),
];
}
public function __invoke(string $location): mixed
{
// Call weather API and return result
return "The weather in {$location} is sunny, 72°F";
}
}
System Prompt Engineering
Use SystemPrompt for structured agent instructions:
new SystemPrompt(
background: [
"You are a data analyst expert in creating reports.",
],
steps: [
"Analyze the user's request",
"Query the database",
"Generate a summary",
],
output: [
"Always cite your sources",
"Never make up data",
]
)
Chat History
Agents automatically maintain conversation history. For custom components:
use NeuronAI\History\FileChatHistory;
// In agent class
protected function chatHistory(): ChatHistoryInterface
{
return new FileChatHistory('/path/to/memory.json');
}
Memory Types
InMemoryChatHistory- Default, session-basedFileChatHistory- Persist to fileSQLChatHistory- Database-backedEloquentChatHistory- Laravel Eloquent integration
Content Blocks (Multi-modal)
Agents support multiple content types:
use NeuronAI\Chat\Messages\ContentBlocks\TextContent;
use NeuronAI\Chat\Messages\ContentBlocks\ImageContent;
use NeuronAI\Chat\Enums\MediaType;
use NeuronAI\Chat\Enums\SourceType;
$message = new UserMessage([
new TextContent('Analyze this image:'),
new ImageContent(
content: 'https://example.com/image.jpg',
sourceType: SourceType::URL,
mediaType: MediaType::JPEG
),
]);
Use the MediaType enum for common MIME types (images, audio, video, documents). A raw MIME string is still accepted for custom types.
CLI Generation
Use the Neuron CLI to generate an agent boilerplate:
vendor/bin/neuron make:agent MyCustomAgent
Common Patterns
Tool Approval Middleware
For human oversight of tool execution:
use NeuronAI\Agent\Middleware\ToolApproval;
use NeuronAI\Agent\Nodes\ChatNode;
use NeuronAI\Agent\Nodes\StreamNode;
use NeuronAI\Agent\Nodes\StructuredOutputNode;
// In agent constructor
$this->middleware([
ChatNode::class,
StreamNode::class,
StructuredOutputNode::class
], new ToolApproval());
Observability with Inspector
Monitor agent execution:
# Set environment variable
INSPECTOR_INGESTION_KEY=your_key_here
Parallel Tool Calls
Execute tools in parallel (requires pcntl):
$agent->parallelToolCalls(true);
Key Decisions
When helping users build agents:
Choose execution mode based on requirements:
chat()for standard conversationsstream()for real-time streamingstructured()for data extraction
Add tools when the agent needs to:
- Access external systems (databases, APIs)
- Perform calculations
- Search the web
- Send emails
Configure chat history when:
- Long-running conversations need persistence
- Multiple sessions should share history
- Conversation context needs to be shared across agents
Use middleware for:
- Context summarization
- Tool approval workflows
- Custom pre/post nodes processing
Project Structure Considerations
For Laravel projects:
namespace App\Neuron;
class MyAgent extends Agent { ... }
For Symfony projects:
- Use dependency injection for providers
- Configure a service in services.yaml