---
name: neuron-agent-builder
description: Create and configure Neuron AI agents with providers, tools, instructions, and memory. Use this skill whenever the user mentions building agents, creating AI assistants, setting up LLM-powered chat bots, configuring chat agents, or wants to create an agent that can talk, use tools, or handle conversations. Also trigger for any task involving agent configuration, provider setup, tool integration, or chat history management in Neuron AI.
---

# 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:

```php
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:

```php
$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\TextChunk`
- `NeuronAI\Chat\Messages\Chunks\ImageChunk`
- `NeuronAI\Chat\Messages\Chunks\AudioChunk`
- `NeuronAI\Chat\Messages\Chunks\ToolCallChunk`
- `NeuronAI\Chat\Messages\Chunks\ToolResultChunk`

```php
$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 `useChat` hook
- 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:**

```php
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:

```php
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
```php
new Anthropic(
    key: $_ENV['ANTHROPIC_API_KEY'],
    model: 'claude-3-5-sonnet-20241022',
)
```

### OpenAI
```php
new OpenAI(
    key: $_ENV['OPENAI_API_KEY'],
    model: 'gpt-4',
)
```

### Ollama (Local)
```php
new Ollama(
    baseUrl: 'http://localhost:11434',
    model: 'llama3',
)
```

### Other Providers
- `Gemini` - Google AI models
- `VertexAI` - Google Vertex AI platform
- `Mistral` - Mistral AI models
- `HuggingFace` - Open models via HuggingFace
- `Deepseek` - DeepSeek models
- `Grok` - XAI models
- `AWSBedrockRuntime` - AWS Bedrock inference platform
- `Cohere` - Cohere models
- `AzureOpenAI` - Use OpenAI models on the Azure platform
- `ZAI` - ZAI for GLM models

## Tools Integration

### Adding Built-in Toolkits

```php
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:

```php
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:

```php
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:

```php
use NeuronAI\History\FileChatHistory;

// In agent class
protected function chatHistory(): ChatHistoryInterface
{
    return new FileChatHistory('/path/to/memory.json');
}
```

### Memory Types
- `InMemoryChatHistory` - Default, session-based
- `FileChatHistory` - Persist to file
- `SQLChatHistory` - Database-backed
- `EloquentChatHistory` - Laravel Eloquent integration

## Content Blocks (Multi-modal)

Agents support multiple content types:

```php
use NeuronAI\Chat\Messages\ContentBlocks\TextContent;
use NeuronAI\Chat\Messages\ContentBlocks\ImageContent;
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: 'image/jpeg'
    ),
]);
```

## CLI Generation

Use the Neuron CLI to generate an agent boilerplate:

```bash
vendor/bin/neuron make:agent MyCustomAgent
```

## Common Patterns

### Tool Approval Middleware
For human oversight of tool execution:

```php
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:

```bash
# Set environment variable
INSPECTOR_INGESTION_KEY=your_key_here
```

### Parallel Tool Calls
Execute tools in parallel (requires pcntl):

```php
$agent->parallelToolCalls(true);
```

## Key Decisions

When helping users build agents:

1. **Choose execution mode** based on requirements:
   - `chat()` for standard conversations
   - `stream()` for real-time streaming
   - `structured()` for data extraction

2. **Add tools** when the agent needs to:
   - Access external systems (databases, APIs)
   - Perform calculations
   - Search the web
   - Send emails

3. **Configure chat history** when:
   - Long-running conversations need persistence
   - Multiple sessions should share history
   - Conversation context needs to be shared across agents

4. **Use middleware** for:
   - Context summarization
   - Tool approval workflows
   - Custom pre/post nodes processing

## Project Structure Considerations

**For Laravel projects:**
```php
namespace App\Neuron;

class MyAgent extends Agent { ... }
```

**For Symfony projects:**
- Use dependency injection for providers
- Configure a service in services.yaml
