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

inspector-apm/neuron-ai

Neuron is a PHP framework for building agentic AI apps: define and orchestrate AI agents, connect to LLM providers, load data, use tools, coordinate multiple agents, and monitor/debug runs. Works with Laravel or Symfony and supports end-to-end agent workflows.

View on GitHub
Deep Wiki
Context7
## Getting Started

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

Ensure PHP 8.1+ is used.

  1. Generate a basic agent:

    vendor/bin/neuron make:agent MyFirstAgent
    

    This creates a scaffold in app/Neuron/MyFirstAgent.php.

  2. Configure your agent:

    • Set up an AI provider (e.g., Anthropic, OpenAI) in the provider() method.
    • Define system instructions in instructions() using SystemPrompt.
    • Add tools (e.g., MySQLToolkit) in tools() if needed.
  3. Run a simple chat:

    $response = MyFirstAgent::make()->chat(new UserMessage("Hello!"))
        ->getMessage();
    echo $response->getContent();
    

Key First Use Case: Laravel Chatbot

  • Create a route:
    Route::post('/chat', function (Request $request) {
        $response = MyFirstAgent::make()->chat(new UserMessage($request->input('message')))
            ->getMessage();
        return response()->json(['response' => $response->getContent()]);
    });
    
  • Test with curl or Postman.

Implementation Patterns

1. Agent Lifecycle

  • Instantiation: Use MyAgent::make() for singleton-like behavior (Laravel service container integration).
  • Execution Modes:
    • Chat: Synchronous, full response.
    • Stream: Real-time chunks (e.g., for UI updates).
    • Structured: Extract PHP objects from LLM output.
  • Example Workflow:
    // Chat mode
    $agent->chat(new UserMessage("Analyze this data: ..."));
    
    // Stream mode (for UI)
    $stream = $agent->stream(new UserMessage("..."));
    foreach ($stream->events() as $chunk) {
        if ($chunk instanceof TextChunk) {
            echo $chunk->content;
        }
    }
    
    // Structured output
    $data = $agent->structured(new UserMessage("..."), MyClass::class);
    

2. Tool Integration

  • Built-in Toolkits:
    protected function tools(): array {
        return [
            MySQLToolkit::make(\DB::connection()->getPdo()),
            CalculatorToolkit::make(),
        ];
    }
    
  • Custom Tools:
    class MyTool extends Tool {
        public function __invoke(string $input) {
            return "Processed: " . $input;
        }
    }
    
    Register in tools() array.

3. RAG (Retrieval-Augmented Generation)

  • Setup:
    vendor/bin/neuron make:rag MyRagAgent
    
  • Configuration:
    class MyRagAgent extends RAG {
        protected function embeddings(): EmbeddingsProviderInterface {
            return new VoyageEmbeddingProvider(key: '...');
        }
        protected function vectorStore(): VectorStoreInterface {
            return new PineconeVectorStore(key: '...');
        }
    }
    
  • Usage:
    $response = MyRagAgent::make()->chat(new UserMessage("Query about docs..."));
    

4. Laravel Integration

  • Service Provider:
    // app/Providers/NeuronServiceProvider.php
    public function register() {
        $this->app->singleton(MyAgent::class, fn() => new MyAgent());
    }
    
  • Dependency Injection:
    public function __construct(private MyAgent $agent) {}
    

5. Streaming for UI

  • Vercel AI Adapter:
    use NeuronAI\Chat\Messages\Stream\Adapters\VercelAIAdapter;
    
    Route::post('/stream', function (Request $request) {
        $stream = MyAgent::make()->stream(new UserMessage($request->input('message')))
            ->events(new VercelAIAdapter());
    
        return response()->stream(fn() => yield from $stream);
    });
    

6. Structured Output

  • Define Schema:
    class UserProfile {
        #[SchemaProperty(description: "User's full name")]
        public string $name;
    }
    
  • Extract Data:
    $profile = $agent->structured(new UserMessage("..."), UserProfile::class);
    

7. Memory Management

  • Custom History:
    protected function chatHistory(): ChatHistoryInterface {
        return new FileChatHistory(storage_path('app/agent_memory.json'));
    }
    
  • Types: InMemory, File, SQL, Eloquent.

Gotchas and Tips

1. Common Pitfalls

  • Tool Execution Errors:

    • Ensure tools return serializable data (e.g., json_encode()-able).
    • Validate tool inputs in __invoke() to avoid LLM hallucinations.
    • Tip: Use ToolProperty annotations for strict typing.
  • Prompt Engineering:

    • Avoid overly long SystemPrompt backgrounds. Use steps for clarity:
      new SystemPrompt(
          steps: ["Step 1: Analyze", "Step 2: Respond"]
      )
      
    • Tip: Test prompts with chat() first before streaming.
  • Streaming Quirks:

    • Chunks may arrive out of order. Use TextChunk::isFinal() to detect completion.
    • Tip: Buffer chunks in UI for smooth rendering.
  • RAG Performance:

    • Vector store queries can be slow. Cache embeddings:
      $embeddings = new VoyageEmbeddingProvider(key: '...', cache: true);
      
    • Tip: Limit k (nearest neighbors) to reduce latency.
  • Memory Leaks:

    • InMemoryChatHistory resets on agent restart. Use FileChatHistory for persistence.
    • Tip: Clear old memory files periodically.

2. Debugging Tips

  • Inspector APM:

    • Set INSPECTOR_INGESTION_KEY in .env to visualize agent execution.
    • Tip: Use the timeline to debug tool calls or RAG retrievals.
  • Logging:

    • Enable debug logs for providers:
      new Anthropic(key: '...', debug: true)
      
    • Tip: Log UserMessage and AIMessage content for auditing.
  • Tool Debugging:

    • Add try-catch in __invoke() to log errors:
      public function __invoke(string $input) {
          try {
              return $this->process($input);
          } catch (\Exception $e) {
              logger()->error("Tool failed: " . $e->getMessage());
              throw $e;
          }
      }
      

3. Configuration Quirks

  • Environment Variables:

    • Use env() or Laravel's .env for API keys:
      new Anthropic(key: env('ANTHROPIC_API_KEY'))
      
    • Tip: Add .env.example with placeholder keys.
  • Provider Switching:

    • Change providers without modifying agent code:
      // Swap Anthropic for OpenAI
      protected function provider(): AIProviderInterface {
          return new OpenAI(key: env('OPENAI_API_KEY'));
      }
      
    • Tip: Use a config file for dynamic provider selection.
  • Laravel Caching:

    • Cache agent instances in Laravel:
      $agent = Cache::remember('agent_instance', now()->addHours(1), fn() => MyAgent::make());
      

4. Extension Points

  • Custom Workflows:

    • Extend Workflow for non-agent logic:
      use NeuronAI\Workflow\Workflow;
      
      class MyWorkflow extends Workflow {
          protected function steps(): array {
              return [
                  new ChatStep($agent, new UserMessage("...")),
                  new ToolStep(new MyTool()),
              ];
          }
      }
      
    • Tip: Use Workflow::run() for complex sequences.
  • Human-in-the-Loop:

    • Pause workflows for approval:
      $workflow->pause("Review this before proceeding");
      
    • Tip: Integrate with Laravel Notifications for alerts.
  • Evaluation Framework:

    • Test agent responses with:
      vendor/bin/neuron evaluate MyAgent
      
    • Tip: Use EvaluationTestCase for unit tests.

5. Laravel-Specific Tips

  • Service Container:

    • Bind agents as singletons:
      $this->app->singleton(MyAgent::class, fn() => new MyAgent());
      
    • Tip: Use when() for conditional binding.
  • Queue Jobs:

    • Offload long-running agent tasks:
      MyAgentJob::dispatch(new UserMessage("..."))->onQueue('ai');
      
    • Tip: Store chat history in a database queue table.
  • Filament Integration:

    • Create a
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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views