Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Neuron Ai Laravel Package

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.

View on GitHub
Deep Wiki
Context7
## Getting Started

### First Steps
1. **Installation**:
   ```bash
   composer require neuron-core/neuron-ai

Verify PHP 8.1+ compatibility in your project.

  1. Generate a Basic Agent:

    vendor/bin/neuron make:agent CustomerSupportAgent
    

    This creates a scaffold with provider(), instructions(), and tools() methods.

  2. First Interaction:

    $agent = CustomerSupportAgent::make();
    $response = $agent->chat(new UserMessage("How do I reset my password?"))
                     ->getMessage();
    echo $response->getContent();
    

Key Starting Points


Implementation Patterns

1. Agent Lifecycle

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;
    }
}

2. Tool Integration Patterns

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
});

3. RAG Implementation

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')
        );
    }
}

4. Structured Output

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
);

5. Laravel Integration

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()
    ]);
});

6. Observability

Inspector Integration:

# .env
INSPECTOR_INGESTION_KEY=your_key_here

Automatically captures:

  • Agent execution timeline
  • Tool calls
  • Prompt/response pairs
  • Latency metrics

Gotchas and Tips

Common Pitfalls

  1. Tool Execution Errors:

    • Issue: Tools may fail silently if not properly typed.
    • Fix: Implement ToolExceptionHandler:
      $agent->setToolExceptionHandler(function($tool, $exception) {
          return new ToolResultChunk([
              'error' => $exception->getMessage(),
              'trace' => $exception->getTraceAsString()
          ]);
      });
      
  2. Prompt Engineering:

    • Issue: Vague instructions lead to unpredictable outputs.
    • Tip: Use 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"]
      ])
      
  3. Memory Management:

    • Issue: Chat history grows unbounded.
    • Solution: Configure history limits:
      protected function chatHistory(): ChatHistoryInterface {
          return new InMemoryChatHistory(maxMessages: 50);
      }
      
  4. Provider Rate Limits:

    • Tip: Implement retry logic with exponential backoff:
      $provider = new OpenAI(
          key: env('OPENAI_KEY'),
          model: 'gpt-4',
          retry: new RetryStrategy(maxAttempts: 3, delay: 1000)
      );
      
  5. Structured Output Validation:

    • Issue: Schema mismatches cause parsing failures.
    • Fix: Validate schemas at runtime:
      if (!$agent->validateSchema(OrderRequest::class)) {
          throw new \InvalidArgumentException("Schema validation failed");
      }
      

Debugging Techniques

  1. Inspect Agent State:

    $agent = CustomerSupportAgent::make();
    dump($agent->getState()); // Shows current memory, tools, etc.
    
  2. Log Prompts:

    $agent->setPromptLogger(function($prompt) {
        \Log::debug('Generated prompt:', ['prompt' => $prompt]);
    });
    
  3. Tool Call Tracing:

    $agent->setToolCallObserver(function($toolCall) {
        \Log::info('Tool called', [
            'name' => $toolCall->name,
            'args' => $toolCall->arguments
        ]);
    });
    

Configuration Quirks

  1. Environment Variables:

    • Always use env() for API keys:
      new Anthropic(key: env('ANTHROPIC_API_KEY'))
      
    • Never hardcode credentials.
  2. Model Selection:

    • Test different models for cost/performance:
      // Start with cheaper model, upgrade as needed
      $provider = new OpenAI(model: 'gpt-3.5-turbo');
      
  3. Toolkit Dependencies:

    • Some toolkits require additional PHP extensions:
      pecl install pdo_pgsql  # For PostgreSQLToolkit
      

Extension Points

  1. Custom Providers:

    class CustomProvider implements AIProviderInterface {
        public function chat(ChatRequest $request): ChatResponse {
            // Implement custom LLM logic
        }
    }
    
  2. Middleware Pipeline:

    $agent->addMiddleware(function($request, $next) {
        \Log::info('Agent request', $request->toArray());
        return $next($request);
    });
    
  3. Event Observers:

    $agent->on('tool.called', function($event) {
        // Handle tool execution events
    });
    
  4. Custom Vector Stores:

    class RedisVectorStore implements VectorStoreInterface {
        // Implement required methods
        public function addEmbedding(...): void { /* ... */ }
        public function search(...): array { /* ... */ }
    }
    

Performance Tips

  1. Prompt Caching:

    $provider = new Anthropic(
        key: env('ANTHROPIC_KEY'),
        model: 'claude-3-haiku',
        cache: new FileCache('/path/to/prompt_cache')
    );
    
  2. Batch Processing:

    $agent->setBatchMode(true); // For bulk operations
    
  3. Stream Optimization:

    $stream = $
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin