Neuron AI

repository·3.x·Indexed 24 days ago

https://github.com/neuron-core/neuron-ai

A PHP framework for creating, orchestrating, and managing AI Agents. It features a structured Workflow architecture supporting LLM interfaces, tool integration, multi-agent orchestration, and observability. Key capabilities include RAG (Retrieval-Augmented Generation), structured output via PHP classes, Model Context Protocol (MCP) server connectivity, and integration with Inspector for monitoring. It supports various execution modes including synchronous chat, real-time streaming with Vercel AI SDK adapter, and structured data extraction.

Tokens
45.8K
Snippets
93
Records
144
Agent score
83%

What's inside neuron-ai

  1. How RAG works in Neuron AI

    3.x

    Retrieval-Augmented Generation (RAG) in Neuron AI is implemented by extending the RAG class. A RAG system is composed of three core architectural components that must be defined within your class:

    1. Vector Store: A component that stores document embeddings to enable semantic search (implements VectorStoreInterface).
    2. Embeddings Provider: A component that converts raw text into vector embeddings (implements EmbeddingsProviderInterface).
    3. Retrieval Strategy: A component that determines the logic for searching and ranking retrieved documents (implements RetrievalInterface).

    To use RAG, you create a class that extends NeuronAI ag ag ag and overrides the provider(), embeddings(), and vectorStore() methods.

    use NeuronAI\RAG\RAG;
    use NeuronAI\Providers\AIProviderInterface;
    use NeuronAI\Providers\Anthropic\Anthropic;
    use NeuronAI\RAG\Embeddings\EmbeddingsProviderInterface;
    use NeuronAI\RAG\Embeddings\OpenAIEmbeddingProvider;
    use NeuronAI\RAG\VectorStore\VectorStoreInterface;
    use NeuronAI\RAG\VectorStore\PineconeVectorStore;
    
    class MyChatBot extends RAG
    {
        protected function provider(): AIProviderInterface
        {
            return new Anthropic(
                key: $_ENV['ANTHROPIC_API_KEY'],
                model: 'claude-3-5-sonnet-20241022',
            );
        }
    
        protected function embeddings(): EmbeddingsProviderInterface
        {
            return new OpenAIEmbeddingProvider(
                key: $_ENV['OPENAI_API_KEY'],
                model: 'text-embedding-3-small',
            );
        }
    
        protected function vectorStore(): VectorStoreInterface
        {
            return new PineconeVectorStore(
                key: $_ENV['PINECONE_API_KEY'],
                indexUrl: $_ENV['PINECONE_INDEX_URL']
            );
        }
    }
  2. How Neuron AI workflows and nodes work together

    3.x

    Neuron AI workflows are built on an event-driven architecture where nodes communicate by passing typed events. A workflow follows a sequence like: StartEvent → Node1 → Event2 → Node2 → Event3 → Node3 → StopEvent.

    To create a node, extend the Node base class and implement the __invoke magic method. The workflow automatically routes events to a node based on the type hint of the first parameter in the __invoke signature. Each node receives the event and the shared WorkflowState, processes the data, and returns a new Event (or StopEvent to finish).

    use NeuronAI\Workflow\Node;
    use NeuronAI\Workflow\Event;
    use NeuronAI\Workflow\StartEvent;
    use NeuronAI\Workflow\WorkflowState;
    
    class ValidationNode extends Node
    {
        // The workflow maps events to this node based on the StartEvent type hint
        public function __invoke(StartEvent $event, WorkflowState $state): ProcessEvent
        {
            $input = $state->get('input');
            $validated = $this->validate($input);
            $state->set('validated', $validated);
            return new ProcessEvent($validated);
        }
    
        private function validate(mixed $input): array
        {
            return ['valid' => true, 'data' => $input];
        }
    }
  3. DateTime support in structured output

    3.x

    The Deserializer automatically handles various date formats when mapping JSON to DateTime or DateTimeImmutable properties. Supported formats include:

    • ISO 8601 strings (e.g., "2024-01-15T10:30:00Z")
    • Unix timestamps (e.g., 1705320600)
    • Relative formats (e.g., "next Monday")
    class Event
    {
        public string $name;
    
        public DateTime $startDate;
    
        public DateTimeImmutable $createdAt;
    }
  4. Execute agents in Chat, Stream, or Structured modes

    3.x

    Neuron agents support three primary execution modes depending on your application requirements:

    1. Chat Mode (Synchronous): Best for standard back-and-forth conversations where you wait for the full response.
    2. Stream Mode (Real-time): Best for real-time UI updates. It yields chunks of content (e.g., TextChunk, ImageChunk, ToolCallChunk) as they are generated.
    3. Structured Output Mode: Best for extracting data into specific PHP classes using attributes like #[SchemaProperty].
  5. How the Neuron AI evaluation system works

    3.x

    The evaluation system tests AI systems using three core components:

    1. Evaluators: Test classes that define the execution logic and validation rules.
    2. Datasets: Data sources such as PHP arrays or JSON files.
    3. Assertions: Validation rules used to check the outputs against expected results.

    The data flow follows this pattern: Dataset Items $\rightarrow$ Evaluator::run() $\rightarrow$ Output $\rightarrow$ Evaluator::evaluate() $\rightarrow$ Assertions $\rightarrow$ Results.

    For every item in a dataset, the evaluator follows a specific lifecycle:

    1. setUp(): Initializes resources (called once per evaluator).
    2. run(datasetItem): Executes the AI logic (e.g., calling an agent).
    3. evaluate(output, datasetItem): Performs assertions against the results.
    Dataset Items → Evaluator::run() → Output → Evaluator::evaluate() → Assertions → Results
  6. When to use Workflow vs Agent

    3.x

    Choosing between a Workflow and an Agent depends on your orchestration needs:

    Use Workflow when:

    • You need complete control over the execution flow.
    • You are building custom orchestration patterns.
    • You require complex branching or looping logic.
    • You want to run multiple agents in parallel for heavy tasks.
    • You need to use individual components (like audio providers or embeddings) independently.

    Use Agent when:

    • You are building chat-based applications.
    • You need built-in tool calling.
    • You want built-in features like chat history, streaming, or structured output.
    • You are following common conversational patterns.
  7. What are tools in Neuron AI?

    3.x

    Tools allow agents to perform actions, retrieve information, and interact with external systems. Every tool is defined by four core components:

    • Name: A unique identifier for the tool.
    • Description: A text explanation of what the tool does. This is critical as it is used by the LLM to decide when to call the tool.
    • Properties: A schema defining the input parameters, including their types and descriptions.
    • Callable: The actual logic (code) that executes when the tool is invoked.

    Tools can be implemented as classes extending Tool, via a fluent builder, or as part of a Toolkit for grouping related functionality.

  8. Use the EventBus for observability

    3.x

    Neuron uses a static EventBus to monitor framework events. Components automatically emit events such as workflow-start, workflow-end, tool-calling, rag-retrieving, inference-start, and more.

    You can monitor these events by implementing the ObserverInterface and registering your observer via EventBus::observe() (global) or directly on a workflow/agent instance.

    use NeuronAI//Observability/ObserverInterface;
    
    class CustomObserver implements ObserverInterface
    {
        public function handle(string $event, object $source, mixed $data): void
        {
            // Handle events
            echo "Event: {$event}\n";
            echo "Source: " . $source::class . "\n";
            var_dump($data);
        }
    }
    
    // Register globally
    use NeuronAI\Observability\EventBus;
    EventBus::observe(new CustomObserver());
  9. Understand the Workflow abstraction

    3.x

    A Workflow is a low-level abstraction that allows you to build custom agentic systems from scratch using Neuron's standalone components (AI providers, embeddings, data loaders, chat history, vector stores, etc.).

    While Agent and RAG classes are ready-to-use implementations for common patterns (like tool calls or retrieval), Workflow is intended for developers who need to program a complex, customized flowchart of logic. Workflows also support a human-in-the-loop pattern, allowing for manual intervention, validation, or correction at any point in the automated process.

  10. How Neuron AI structured output works

    3.x

    Neuron AI uses a two-layer approach to ensure LLM responses are both correctly formatted and valid:

    1. SchemaProperty (Generation Layer): An attribute used on class properties to define the JSON schema sent to the LLM. This guides the LLM on how to generate the data (e.g., providing descriptions, types, and constraints).
    2. Validation Rules (Verification Layer): PHP attributes applied to properties to verify that the LLM's response actually meets your requirements. If validation fails, Neuron can automatically retry the request.

    By combining these two layers, you can force the LLM to follow a specific structure and then programmatically ensure the content of that structure is correct.

    use NeuronAI\\StructuredOutput\\SchemaProperty;
    use NeuronAI\\StructuredOutput\\Validation\\Rules\\NotBlank;
    
    class Person
    {
        #[SchemaProperty(description: 'The user name.', required: true)]
        #[NotBlank]
        public string $name;
    }
  11. Load and chunk documents for RAG

    3.x

    To ingest data, you must load documents and split them into manageable chunks.

    Document Loaders:

    • TextLoader: For .txt files.
    • PDFLoader: For .pdf files.
    • HtmlLoader: For web pages (accepts URL).
    • DirectoryLoader: For entire directories.

    Chunking: Use RecursiveCharacterTextSplitter to split documents. Recommended chunkSize is 500-1000 tokens with a 10-20% chunkOverlap to maintain context.

    use NeuronAI\RAG\DocumentLoader\TextLoader;
    use NeuronAI\RAG\Chunker\RecursiveCharacterTextSplitter;
    
    $loader = new TextLoader('/path/to/document.txt');
    $documents = $loader->load();
    
    // Chunk documents
    $chunker = new RecursiveCharacterTextSplitter(
        chunkSize: 1000,
        chunkOverlap: 200
    );
    $chunks = $chunker->chunk($documents);
  12. Use AI Judge assertions

    3.x

    For complex semantic validation, use AgentJudge to let an AI agent evaluate the output based on specific criteria.

    Reference-free evaluation

    Evaluate based only on criteria (e.g., "be polite").

    Reference-based evaluation

    Compare the output against an expected answer provided in the dataset.

    Few-shot calibration

    Provide examples of inputs, outputs, scores, and reasoning to calibrate the judge's behavior.

    use NeuronAI\Evaluation\Assertions\AgentJudge;
    use NeuronAI\Agent;
    
    $judge = Agent::make()
        ->setInstructions('You are an expert evaluator for customer support responses.');
    
    // Reference-free
    $this->assert(new AgentJudge(
        judge: $judge,
        criteria: 'Response should be helpful, polite, and address the customer\'s question directly',
        threshold: 0.7
    ), $output);
    
    // Reference-based
    $this->assert(new AgentJudge(
        judge: $judge,
        criteria: 'The response should convey the same meaning as the reference',
        threshold: 0.8,
        reference: $datasetItem['expected_answer']
    ), $output);
    
    // With few-shot examples
    $this->assert(new AgentJudge(
        judge: $judge,
        criteria: 'Rate the factual accuracy of the response',
        threshold: 0.7,
        examples: [
            [
                'input' => 'What is 2+2?',
                'output' => '2+2 equals 4',
                'score' => 1.0,
                'reasoning' => 'Mathematically correct and clear.',
            ],
        ]
    ), $output);