### Workflow Execution with Loop Example Source: https://github.com/neuron-core/neuron-php-doc/blob/main/workflow/loops-and-branches.md Demonstrates a workflow setup that includes a node capable of looping back to itself. ```php $state = Workflow::make() ->addNodes([ new InitialNode(), new NodeOne(), new NodeTwo() ]) ->init() ->run(); /* - Handling StartEvent - InitialNode complete - Running a loop on NodeOne - Running a loop on NodeOne - NodeOne complete, move forward - NodeTwo complete */ ``` -------------------------------- ### Install spatie/fork Package Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/tools.md Install the necessary package to enable parallel tool execution. ```shellscript composer require spatie/fork ``` -------------------------------- ### Install Amp HTTP Client Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/async.md Install the necessary package to enable Amp's HTTP client for asynchronous requests. ```bash composer require amphp/http-client ``` -------------------------------- ### AWS Bedrock Runtime Installation Source: https://github.com/neuron-core/neuron-php-doc/blob/main/providers/ai-provider.md Install the AWS SDK for PHP using Composer to enable the Bedrock Runtime provider. ```bash composer require aws/aws-sdk-php ``` -------------------------------- ### Install OpenSearch PHP Client Source: https://github.com/neuron-core/neuron-php-doc/blob/main/rag/vector-store.md Install the official OpenSearch PHP client using Composer. This is a prerequisite for integrating OpenSearch as a vector store. ```bash composer require opensearch-project/opensearch-php ``` -------------------------------- ### Installing Async Package Source: https://github.com/neuron-core/neuron-php-doc/blob/main/workflow/loops-and-branches.md To utilize the AsyncExecutor for concurrent branch execution, the amphp/amp package must be installed via composer. ```bash composer require amphp/amp ``` -------------------------------- ### Installing Composer Dependencies Source: https://github.com/neuron-core/neuron-php-doc/blob/main/resources/examples.md Install project dependencies using Composer. This is a common first step for PHP projects. ```bash composer install ``` -------------------------------- ### Install Neuron PHP Router Source: https://github.com/neuron-core/neuron-php-doc/blob/main/providers/ai-provider.md Install the router package using Composer. ```shellscript composer require neuron-core/router ``` -------------------------------- ### Setup FakeAIProvider Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/testing.md Instantiate FakeAIProvider with expected AI responses and inject it into your agent. This replaces actual API calls for testing. ```php use NeuronAI\Chat\Messages\Stream\AssistantMessage; use NeuronAI\Testing\FakeAIProvider; $provider = new FakeAIProvider( new AssistantMessage('Hello! How can I help you?') ); $agent = MyAgent::make()->setAiProvider($provider); ``` -------------------------------- ### Environment Configuration Example Source: https://github.com/neuron-core/neuron-php-doc/blob/main/resources/examples.md Configure API keys and service settings in the .env file. Ensure at least one AI provider key and the SerpAPI key are provided. ```dotenv # At least one required ANTHROPIC_API_KEY= GEMINI_API_KEY= OPENAI_API_KEY= #Required SERPAPI_KEY= # Optional INSPECTOR_INGESTION_KEY= INSPECTOR_TRANSPORT=sync ``` -------------------------------- ### Initialize and Run Workflow Source: https://github.com/neuron-core/neuron-php-doc/blob/main/workflow/loops-and-branches.md Set up and execute a workflow by adding nodes and then calling the run method. This example shows how to add multiple nodes, including those that handle branching. ```php $state = Workflow::make() ->addNodes([ new InitialNode(), new A1Node(), new A2Node(), new B1Node(), new B2Node(), ]) ->init() ->run(); ``` -------------------------------- ### Full Vector Store Implementation Example Source: https://github.com/neuron-core/neuron-php-doc/blob/main/rag/vector-store.md A comprehensive example of a custom vector store implementation using Guzzle HTTP client for API interaction. ```php namespace App\Neuron\VectorStore; use GuzzleHttp\Client; use GuzzleHttp\RequestOptions; use NeuronAI\RAG\Document; use NeuronAI\RAG\VectorStore\VectorStoreInterface; class MyVectorStore implements VectorStoreInterface { protected Client $client; public function __construct( string $key, protected string $index, protected int $topK = 5 ) { $this->client = new Client([ 'base_uri' => 'https://api.vector-store.com', 'headers' => [ 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'Authorization' => "Bearer {$key}", ] ]); } public function addDocument(Document $document): void { $this->addDocuments([$document]); } /** * @param Document[] $documents */ public function addDocuments(array $documents): { $this->client->post("indexes/{$this->index}", [ RequestOptions::JSON => \array_map(function (Document $document) { return [ 'vector' => $document->embedding, ]; }, $documents) ]); } /** * @return Document[] */ public function similaritySearch(array $embedding): iterable { // perform similarity search and return an array of Document objects } } ``` -------------------------------- ### Install Neuron PHP with Composer Source: https://github.com/neuron-core/neuron-php-doc/blob/main/overview/getting-started.md Run this command to install the latest version of the Neuron AI package using Composer. ```bash composer require neuron-core/neuron-ai ``` -------------------------------- ### Install Elasticsearch Client Source: https://github.com/neuron-core/neuron-php-doc/blob/main/rag/vector-store.md Install the official Elasticsearch PHP client using Composer. This is required before using Elasticsearch as a vector store. ```bash composer require elasticsearch/elasticsearch ``` -------------------------------- ### Install Typesense PHP Client Source: https://github.com/neuron-core/neuron-php-doc/blob/main/rag/vector-store.md Install the official Typesense PHP client using Composer. This is necessary for using Typesense as a vector store in your RAG implementation. ```bash composer require typesense/typesense-php ``` -------------------------------- ### AgentJudge Assertion Setup Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/evaluation.md Demonstrates setting up an AI agent as a judge for custom evaluation criteria. Requires configuring the AI provider and instructions. ```php use NeuronAI\Evaluation\Assertions\AgentJudge; class AgentJudgeEvaluator extends BaseEvaluator { protected AgentInterface $judge; public function setUp(): void { $this->judge = Agent::make() ->setAiProvider( new Antrhopic(...) ) ->setInstructions('You are an expert evaluator for customer support responses.'); } public function getDataset(): DatasetInterface { return new JsonDataset(...); } public function run(array $datasetItem): mixed { $response = MyAgent::make()->chat( new UserMessage($datasetItem['input']) )->getMessage(); return $response->getContent(); } public function evaluate(mixed $output, array $datasetItem): void { $this->assert(new AgentJudge( judge: $this->judge, criteria: 'Response should be helpful, polite, and address the customer\'s question directly', threshold: $datasetItem['threshold'] ), $output); } } ``` -------------------------------- ### Install Google Auth for Gemini Vertex AI Source: https://github.com/neuron-core/neuron-php-doc/blob/main/providers/ai-provider.md Install the necessary Google Auth package via Composer to use the Gemini Vertex AI provider. ```bash composer require google/auth ``` -------------------------------- ### Interact with Agent (PHP) Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/tools.md Demonstrates how to instantiate an agent, send a user message, and retrieve the agent's response. This example shows a typical interaction flow for an agent designed to process YouTube video URLs. ```php use NeuronAI\Chat\Messages\UserMessage; $message = YouTubeAgent::make($user)->chat( new UserMessage('What about this video: https://www.youtube.com/watch?v=WmVLcj-XKnM') )->getMessage(); echo $message->getContent(); /** Based on the transcription, I'll provide a summary of this powerful environmental message from "Mother Nature": This video presents ... Three most important takeaways: 1. Nature has existed ... 2. The wellbeing of humanity is ... 3. How humans choose to act toward Nature determines ... */ ``` -------------------------------- ### Integrate Ollama AI Provider Source: https://github.com/neuron-core/neuron-php-doc/blob/main/README.md Example of setting up the Ollama AI provider for use with Neuron agents. Ensure you have your OLLAMA_URL and OLLAMA_MODEL configured. ```php namespace App\Neuron; use NeuronAI\Agent\Agent; use NeuronAI\Chat\Messages\UserMessage; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\Ollama\Ollama; class MyAgent extends Agent { protected function provider(): AIProviderInterface { return new Ollama( url: 'OLLAMA_URL', model: 'OLLAMA_MODEL', ); } } $message = MyAgent::make() ->chat(new UserMessage("Hi!")) ->getMessage(); echo $message->getContent(); // Hi, how can I help you today? ``` -------------------------------- ### Attach Tool to Agent (PHP) Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/tools.md Example of how to attach a custom tool to an agent by returning an array of tool instances from the `tools()` method. ```php chat(new UserMessage("Hi!")) ->getMessage(); echo $message->getContent(); // Hi, how can I help you today? ``` -------------------------------- ### Configure ZAI AI Provider Source: https://github.com/neuron-core/neuron-php-doc/blob/main/providers/ai-provider.md Set up the ZAI AI provider with an API key and model. This example uses the 'glm-5' model. ```php namespace App\Neuron; use NeuronAI\Agent\Agent; use NeuronAI\Chat\Messages\UserMessage; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\ZAI\ZAI; class MyAgent extends Agent { protected function provider(): AIProviderInterface { return new ZAI( key: 'ZAI_API_KEY', model: 'glm-5', parameters: [], // Add custom params (temperature, logprobs, etc) ); } } $message = MyAgent::make() ->chat(new UserMessage("Hi!")) ->getMessage(); echo $message->getContent(); // Hi, how can I help you today? ``` -------------------------------- ### DatabaseChatHistory Serialization Example Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/chat-history-and-memory.md An example implementation of a custom chat history using PDO. It demonstrates how to use serializeMessage() and deserializeMessage() for storing and retrieving messages from a database. ```php db->select(...); // Deserialize properly initialize the correct message types with the correct data. $this->history = $this->deserializeMessages($messages); } protected function onNewMessage(Message $message): void { // Store the serialized version. $this->db->insert($message->jsonSerialize()); } ... } ``` -------------------------------- ### Define YouTube Agent with Transcription Tool Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/tools.md This example demonstrates how to create a YouTube Agent that can retrieve video transcriptions. It defines the `provider`, `instructions`, and `tools` methods, including a `get_transcription` tool with a `video_url` property. ```php namespace App\Neuron; use NeuronAI\Agent\Agent; use NeuronAI\Agent\SystemPrompt; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\Anthropic\Anthropic; use NeuronAI\Tools\PropertyType; use NeuronAI\Tools\Tool; use NeuronAI\Tools\ToolProperty; class YouTubeAgent extends Agent { protected function provider(): AIProviderInterface { // return an AI provider instance (Anthropic, OpenAI, Ollama, Gemini, etc.) return new Anthropic( key: 'ANTHROPIC_API_KEY', model: 'ANTHROPIC_MODEL', ); } protected function instructions(): string { return (string) new SystemPrompt( background: ["You are an AI Agent specialized in writing YouTube video summaries."], steps: [ "Get the url of a YouTube video, or ask the user to provide one.", "Use the tools you have available to retrieve the transcription of the video.", "Write the summary.", ], output: [ "Write a summary in a paragraph without using lists. Use just fluent text.", "After the summary add a list of three sentences as the three most important take away from the video.", ] ); } protected function tools(): array { return [ Tool::make( 'get_transcription', 'Retrieve the transcription of a youtube video.' )->addProperty( new ToolProperty( name: 'video_url', type: PropertyType::STRING, description: 'The URL of the YouTube video.', required: true ) )->setCallable(function (string $video_url) { return "Video transcripton..."; }) ]; } } ``` -------------------------------- ### Start Workflow and Listen for Events Source: https://github.com/neuron-core/neuron-php-doc/blob/main/workflow/streaming.md Initiate the workflow and iterate over the event stream to process progress updates. The final state can be retrieved after the stream concludes. ```php $handler = Workflow::make() ->addNodes([ new InitialNode(), new NodeOne(), new NodeTwo(), ]) ->init(); $stream = $handler->events(); foreach ($stream as $event) { if ($event instanceof ProgressEvent) { echo "\n- ".$event->message; } } $finalState = $stream->getResult(); // It will print "Streaming end" echo "\n- ".$finalState->get('message'); ``` -------------------------------- ### Integrate Mistral AI Provider Source: https://github.com/neuron-core/neuron-php-doc/blob/main/README.md Example of setting up the Mistral AI provider for use with Neuron agents. Ensure you have your MISTRAL_API_KEY and MISTRAL_MODEL configured. ```php namespace App\Neuron; use NeuronAI\Agent\Agent; use NeuronAI\Chat\Messages\UserMessage; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\Gemini\Mistral; class MyAgent extends Agent { protected function provider(): AIProviderInterface { return new Mistral( key: 'MISTRAL_API_KEY', model: 'MISTRAL_MODEL', ); } } $message = MyAgent::make() ->chat(new UserMessage("Hi!")) ->getMessage(); echo $message->getContent(); // Hi, how can I help you today? ``` -------------------------------- ### Implement a Workout Tips RAG Agent Source: https://github.com/neuron-core/neuron-php-doc/blob/main/rag/rag.md Create a RAG agent specialized in providing workout tips. This example demonstrates setting up AI providers, embeddings, vector stores, and tools for a custom agent. ```php namespace App\Neuron; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\Anthropic\Anthropic; use NeuronAI\RAG\Embeddings\EmbeddingsProviderInterface; use NeuronAI\RAG\Embeddings\OpenAIEmbeddingsProvider; use NeuronAI\RAG\RAG; use NeuronAI\RAG\VectorStore\FileVectorStore; use NeuronAI\RAG\VectorStore\VectorStoreInterface; use NeuronAI\Tools\Toolkits\Calculator\CalculatorToolkit; class WorkoutTipsAgent extends RAG { protected function provider(): AIProviderInterface { return new Anthropic( key: 'ANTHROPIC_API_KEY', model: 'ANTHROPIC_MODEL', ); } public function instructions(): string { return (string) new SystemPrompt( background: ["You are an AI Agent specialized in providing workout tips."], ); } protected function embeddings(): EmbeddingsProviderInterface { return new OpenAIEmbeddingsProvider( key: 'OPENAI_API_KEY', model: 'OPENAI_MODEL' ); } protected function vectorStore(): VectorStoreInterface { return new FileVectorStore( directory: __DIR__, name: 'demo' ); } protected function tools(): array { return [ CalculatorToolkit::make(), ]; } } ``` -------------------------------- ### Integrate Gemini AI Provider Source: https://github.com/neuron-core/neuron-php-doc/blob/main/README.md Example of setting up the Gemini AI provider for use with Neuron agents. Ensure you have your GEMINI_API_KEY and GEMINI_MODEL configured. ```php namespace App\Neuron; use NeuronAI\Agent\Agent; use NeuronAI\Chat\Messages\UserMessage; use NeuronAI\Providers\AIProviderInterface; use NeuronAI\Providers\Gemini\Gemini; class MyAgent extends Agent { protected function provider(): AIProviderInterface { return new Gemini( key: 'GEMINI_API_KEY', model: 'GEMINI_MODEL', ); } } $message = MyAgent::make() ->chat(new UserMessage("Hi!")) ->getMessage(); echo $message->getContent(); // Hi, how can I help you today? ``` -------------------------------- ### Adding a Provider Tool to an Agent Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/tools.md Integrate provider-specific tools, such as 'web_search', into your agent by defining them in the tools array. This example uses OpenAIResponses. ```php use NeuronAI\Tools\ProviderTool; class MyAgent extends Agent { protected function provider(): AIProviderInterface { return new OpenAIResponses( key: 'OPENAI_API_KEY', model: 'OPENAI_MODEL', ); } protected function tools(): array { return [ ProviderTool:make( type: 'web_search' )->setOptions([...]), ]; } } ``` -------------------------------- ### Stream AI Response with Tools and Handle Chunks Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/streaming.md This example demonstrates streaming AI responses when the agent is configured with tools. It shows how to handle `ToolCallChunk` and `ToolResultChunk` alongside text and reasoning chunks. ```php use App\Neuron\MyAgent; use NeuronAI\Chat\Messages\UserMessage; use NeuronAI\Tools\Tool; $handler = MyAgent::make() ->addTool( Tool::make( 'get_server_configuration', 'retrieve the server network configuration' )->addProperty(...)->setCallable(...) ) ->stream( new UserMessage("What's the IP address of the server?") ); // Iterate chunks foreach ($handler->events() as $chunk) { if ($chunk instanceof ToolCallChunk) { // Output the ongoing tool call echo "\n- Calling tool: ".$chunk->tool->getName(); echo "\n- Input: ".json_encode($chunk->tool->getInputs()); continue; } if ($chunk instanceof ToolResultChunk) { echo "\n- Tool ".$chunk->tool->getName()." completed"; echo "\n- Result: ".$chunk->tool->getResult(); continue; } // Handle TextChunk and ReasoningChunk echo $chunk->content; } // Let me retrieve the server configuration. // - Calling tool: get_server_configuration // - Tool get_server_configuration completed // The IP address of the server is: 192.168.0.10 ``` -------------------------------- ### Instantiate McpConnector for Agent Tools Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/mcp-connector.md Use McpConnector::make to integrate MCP server tools into your agent. This example shows how to configure it for a local PHP script. ```php use NeuronAI\MCP\McpConnector; class MyAgent extends Agent { ... protected function tools(): array { return [ ...McpConnector::make([ 'command' => 'php', 'args' => ['/home/code/mcp_server.php'], ])->tools(), ]; } } ``` -------------------------------- ### YouTubeAgent with Anthropic Provider Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/agent.md This example shows how to implement the provider() method to use the Anthropic AI provider. Ensure you replace 'ANTHROPIC_API_KEY' and 'ANTHROPIC_MODEL' with your actual credentials. ```php structured( new UserMessage("I'm John and I want a pizza at st. James Street 00560!"), Person::class ); echo $person->name.' like '.$person->preference.'. Address: '.$person->address->street; // John like pizza. Address: st.James Street ``` -------------------------------- ### Define Global Middleware with ToolSearchMiddleware Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/middleware.md Implement the `globalMiddleware` method to include `ToolSearchMiddleware`, providing it with a list of tools to manage dynamically. This setup allows the agent to query and select tools as needed. ```php class MyAgent extends Agennt { ... /** * Define the global middleware. */ protected function globalMiddleware(): array { return [ new ToolSearchMiddleware([ MyCustomTool::make(), ...CalculatorToolkit::make()->tools() ...MCPConnector::make([...])->tools() ]), ]; } /** * Provide core tools to the agent. */ protected function tools(): array { return [ // A list of core tools that the model always has available TavilySearchTool::make(...), ]; } } ``` -------------------------------- ### Interact with a Neuron Agent Source: https://github.com/neuron-core/neuron-php-doc/blob/main/README.md Instantiate your custom agent, send a user message, and retrieve the agent's response. The example demonstrates a simple chat interaction. ```php use NeuronAI\Chat\Messages\UserMessage; $message = MyAgent::make() ->chat(new UserMessage("Hi, who are you?")) ->getMessage(); echo $message->getContent(); // I'm a friendly AI Agent built with Neuron AI framework, how can I help you today? ``` -------------------------------- ### Send User Message and Get Assistant Response Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/messages.md Demonstrates how to send a simple user message to an agent and retrieve the assistant's response. Ensure the agent class is correctly configured. ```php use NeuronAI\Chat\Messages\UserMssage; $response = MyAgent::make() ->chat(new UserMessage("Hi, who are you?")) ->getMessage(); echo $response->getContent(); ``` -------------------------------- ### Interact with RAG Chatbot Source: https://github.com/neuron-core/neuron-php-doc/blob/main/rag/rag.md Example of how to instantiate and use the chat() method of a RAG agent to get a response to a user message. ```php use App\Neuron\MyChatBot; use NeuronAI\Chat\Messages\UserMessage; $message = MyChatBot::make() ->chat( new UserMessage('I want to know more about Inspector AI Bug Fix.') ) ->getMessage(); echo $message->getContent(); // Sure, Inspector AI Bug Fix is an agentic monitoring tool // that provides bug fix proposals in real-time as an error occurs // in your application. ``` -------------------------------- ### Custom Tool Implementation (PHP) Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/tools.md Example of a custom tool class extending the base `Tool` class. It defines the tool's name, description, properties, and the core logic executed via the `__invoke` method. ```php getClient() ->get('transcript?url=' . $video_url.'&text=true') ->getBody() ->getContents(); $response = json_decode($response, true); return $response['content']; } protected function getClient(): Client { return $this->client ??= new Client([ 'base_uri' => 'https://api.supadata.ai/v1/youtube/', 'headers' => [ 'x-api-key' => $this->key, ] ]); } } ``` -------------------------------- ### Configure OpenSearch Vector Store Source: https://github.com/neuron-core/neuron-php-doc/blob/main/rag/vector-store.md Set up an OpenSearch vector store by creating an OpenSearch client instance and then instantiating the `OpenSearchVectorStore`. Ensure the client configuration matches your OpenSearch endpoint. ```php namespace App\Neuron; use NeuronAI\RAG\RAG; use NeuronAI\RAG\VectorStore\OpenSearchVectorStore; use NeuronAI\RAG\VectorStore\VectorStoreInterface; use OpenSearch\GuzzleClientFactory; class MyChatBot extends RAG { ... protected function vectorStore(): VectorStoreInterface { $opensearch = new GuzzleClientFactory()->create([ 'base_uri' => 'http://localhost:9200', ]); return new OpenSearchVectorStore( client: $opensearch, index: 'neuron-ai', ); } } ``` -------------------------------- ### Running the Workflow Source: https://github.com/neuron-core/neuron-php-doc/blob/main/workflow/single-step-workflow.md This code snippet demonstrates how to instantiate, initialize, and run the workflow, then retrieve and display the final state. ```php $finalState = MyWorkflow::make()->init()->run(); echo $finalState->get('answer'); // Print Hello World! ``` -------------------------------- ### Initialize MySQL and PostgreSQL Toolkits Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/tools.md Connect to MySQL or PostgreSQL databases using PDO instances. The same approach applies to both toolkits. ```php setAiProvider( new Anthropic( key: 'ANTHROPIC_API_KEY', model: 'ANTHROPIC_MODEL', ) ) ->setInstructions( (string) new SystemPrompt(...) ) ->addTool([...]); $message = $agent->chat(new UserMessage(...))->getMessage(); echo $message->gentContent(); ``` -------------------------------- ### Performing Async Agentic Tasks Source: https://github.com/neuron-core/neuron-php-doc/blob/main/workflow/loops-and-branches.md This example demonstrates using an AsyncAgent with AmpHttpClient to perform chat operations, suitable for parallel agentic tasks. It shows how to construct a user message with image content and retrieve the response. ```php use NeuronAI\HttpClient\AmpHttpClient; class DescriptionGenerationNode extends Node { public function __invoke(TextProcessEvent $event, WorkflowState $state): StopEvent { $input = new UserMessage('Describe this image'); $input->addContent( new ImageContent(...) ); $response = AsyncAgent::make() ->chat($input) ->getMessage(); return new StopEvent(result: $response); } } ``` -------------------------------- ### Define YouTube Agent with Simple String Instructions Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/agent.md A simplified approach to defining agent instructions using a plain string. This is an alternative to using the `SystemPrompt` class. ```php 'TYPESENSE_API_KEY', 'nodes' => [ [ 'host' => 'TYPESENSE_NODE_HOST', 'port' => 'TYPESENSE_NODE_PORT', 'protocol' => 'TYPESENSE_NODE_PROTOCOL' ], ] ]); return new TypesenseVectorStore( client: $typesense, collection: 'neuron-ai', vectorDimension: 1024 ); } } ``` -------------------------------- ### Configure Qdrant Vector Store Source: https://github.com/neuron-core/neuron-php-doc/blob/main/rag/vector-store.md Instantiate QdrantVectorStore with your collection URL and API key. Ensure a Qdrant collection is pre-configured with matching attributes. ```php namespace App\Neuron; use NeuronAI\RAG\RAG; use NeuronAI\RAG\VectorStore\QdrantVectorStore; use NeuronAI\RAG\VectorStore\VectorStoreInterface; class MyChatBot extends RAG { ... protected function vectorStore(): VectorStoreInterface { return new QdrantVectorStore( collectionUrl: 'http://localhost:6333/collections/neuron-ai/', key: 'QDRANT_API_KEY' ); } } ``` -------------------------------- ### Get All Textual Content from Message Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/messages.md Retrieves all text content blocks from a message and concatenates them into a single string. This is a convenient way to get the primary textual output. ```php $response = MyAgent::make() ->chat(new UserMessage("...")) ->getMessage(); // Get all text blocks concatenated as a single string echo $response->getContent(); ``` -------------------------------- ### Eloquent ChatMessage Model Example Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/chat-history-and-memory.md An example Eloquent model for chat messages. It specifies fillable attributes, cast types for JSON columns, and defines a relationship to the Conversation model. ```php class ChatMessage extends Model { protected $fillable = [ 'thread_id', 'role', 'content', 'meta' ]; protected $casts = [ 'content' => 'array', 'meta' => 'array' ]; /** * return BelongsTo */ public function conversation(): BelongsTo { return $this->belongsTo(Conversation::class, 'thread_id'); } } ``` -------------------------------- ### Install Neuron AI Agent Skills with Skills CLI Source: https://github.com/neuron-core/neuron-php-doc/blob/main/overview/agentic-development.md Use this npx command to add Neuron AI's Agent Skills to your local environment for use with Claude Code. The skills are installed as a symlink for automatic updates. ```bash npx skills add ./vendor/neuron-core/neuron-ai/skills ``` -------------------------------- ### Agent Using Custom Vector Store Source: https://github.com/neuron-core/neuron-php-doc/blob/main/rag/vector-store.md Demonstrates how to integrate a custom vector store implementation into an Agent. ```php namespace App\Neuron; use App\Neuron\VectorStore\MyVectorStore; use NeuronAI\Agent; use NeuronAI\RAG\VectorStore\VectorStoreInterface; class MyAgent extends Agent { protected function vectorStore(): VectorStoreInterface { return new MyVectorStore( key: 'VECTORSTORE_API_KEY', index: 'neuron-ai', ); } } ``` -------------------------------- ### Similarity Search with Score Conversion Source: https://github.com/neuron-core/neuron-php-doc/blob/main/rag/vector-store.md Example implementation of the similaritySearch method, converting distance to a similarity score using VectorSimilarity. ```php namespace App\Neuron\VectorStore; use NeuronAI\RAG\Document; use NeuronAI\RAG\VectorSimilarity; use NeuronAI\RAG\VectorStore\VectorStoreInterface; class MyVectorStore implements VectorStoreInterface { ... /** * @param float[] $embeddings */ public function similaritySearch(array $embedding): iterable { $documents = // get documents from the vector store return \array_map(function (Document $document) { return $document->setScore( VectorSimilarity::similarityFromDistance($similarity) ); }, $documents); } } ``` -------------------------------- ### Set State in InitialNode Source: https://github.com/neuron-core/neuron-php-doc/blob/main/workflow/managing-the-state.md Example of a node that modifies the workflow state. The `InitialNode` sets a 'message' property on the `WorkflowState` object. ```php namespace App\Neuron; use NeuronAI\Workflow\Node; use NeuronAI\Workflow\StartEvent; use NeuronAI\Workflow\StopEvent; use NeuronAI\Workflow\WorkflowState; class InitialNode extends Node { public function __invoke(StartEvent $event, WorkflowState $state): StopEvent { $state->set('message', 'Hello World!'); return new StopEvent(); } } ``` -------------------------------- ### Retrieve YouTube Playlist Metadata Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/tools.md Enables the agent to get metadata for a YouTube playlist, such as title and video count, through Supadata. ```php namespace App\Neuron; use NeuronAI\Agent; use NeuronAI\Tools\Toolkits\Supadata\SupadataYoutubePlaylistTool; class MyAgent extends Agent { ... protected function tools(): array { return [ SupadataYoutubePlaylistTool::make( key: 'SUPADATA_API_KEY', ), ]; } } ``` -------------------------------- ### Create Initial Node (Unix) Source: https://github.com/neuron-core/neuron-php-doc/blob/main/workflow/multi-step-workflow.md Use the Neuron CLI to generate the `InitialNode` class. This node handles the `StartEvent` and emits `FirstEvent`. ```bash vendor/bin/neuron make:node App\Neuron\InitialNode ``` -------------------------------- ### Create Initial Node (Windows) Source: https://github.com/neuron-core/neuron-php-doc/blob/main/workflow/multi-step-workflow.md Use the Neuron CLI to generate the `InitialNode` class. This node handles the `StartEvent` and emits `FirstEvent`. ```powershell .\vendor\bin\neuron make:node App\Neuron\InitialNode ``` -------------------------------- ### JsonDataset Implementation Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/evaluation.md Example of using JsonDataset to load test cases from a JSON file. The path to the dataset file is specified during instantiation. ```php class AgentEvaluator extends BaseEvaluator { public function getDataset(): DatasetInterface { return new JsonDataset(__DIR__ . '/datasets/dataset.json'); } ... } ``` -------------------------------- ### Implement Initial Node Logic Source: https://github.com/neuron-core/neuron-php-doc/blob/main/workflow/multi-step-workflow.md The `InitialNode` extends `Node`, accepts a `StartEvent`, and returns a `FirstEvent`. It logs its execution. ```php namespace App\Neuron; use NeuronAI\Workflow\Node; use NeuronAI\Workflow\StartEvent; use App\Neuron\FirstEvent; class InitialNode extends Node { /** * Gets the "StartEvent" and returns "FirstEvent" */ public function __invoke(StartEvent $event, WorkflowState $state): FirstEvent { echo "\n- Handling StartEvent"; return new FirstEvent("InitialNode complete"); } } ``` -------------------------------- ### Initialize and Run Workflow with State Source: https://github.com/neuron-core/neuron-php-doc/blob/main/workflow/managing-the-state.md Provide an initial state to a workflow and retrieve the final state after execution. This demonstrates how to feed input data and collect results. ```php // 1. Provide an initial state as workflow input to feed in some data $workflow = Workflow::make(state: new WorkflowState(['query' => 'Hi!'])) ->addNode(new InitialNode()) ->addNode(...) ->addNode(...); // 2. Execute the workflow and get the final state $finalState = $workflow->init()->run(); // 3. Use the final state data echo $finalState->get('message'); ``` -------------------------------- ### Use CustomState in ExampleNode Source: https://github.com/neuron-core/neuron-php-doc/blob/main/workflow/managing-the-state.md Demonstrates how a node can accept and utilize a `CustomState` instance. Type hinting ensures that the node receives the expected custom state object. ```php class ExampleNode extends Node { public function __invoke(StartEvent $event, CustomState $state): StopEvent { // Use state properties in your nodes if ($state->getUser()->isAdmin()) { //... } return new StopEvent(); } } ``` -------------------------------- ### Integrate Anthropic AI Provider Source: https://github.com/neuron-core/neuron-php-doc/blob/main/README.md Example of setting up the Anthropic AI provider for use with Neuron agents. Ensure you have your ANTHROPIC_API_KEY and ANTHROPIC_MODEL configured. ```php namespace App\Neuron; use NeuronAI\Agent\Agent; use NeuronAI\Chat\Messages\UserMessage; 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', ); } } $message = MyAgent::make() ->chat(new UserMessage("Hi!")) ->getMessage(); echo $message->getContent(); // Hi, how can I help you today? ``` -------------------------------- ### Implement Custom CutOffPostProcessor in PHP Source: https://github.com/neuron-core/neuron-php-doc/blob/main/rag/pre-post-processor.md Example of a custom post-processor that extends `PostProcessorInterface`. This specific implementation is intended to apply a cutoff on document scores. ```php namespace App\Neuron\PostProcessors; use NeuronAI\Chat\Messages\Message; use NeuronAI\RAG\PostProcessor\PostProcessorInterface; // Implement your custom component class CutOffPostProcessor implements PostProcessorInterface { public function __constructor(protected int $level) {} public function process(Message $question, array $documents): array { /* * Apply a cut off on the score returned by the vector store */ return $documents; } } ``` -------------------------------- ### Custom GreaterThanAssertion Implementation Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/evaluation.md Example of creating a custom assertion class that extends AbstractAssertion. This checks if a numeric value is greater than a specified threshold. ```php use NeuronAI\Evaluation\Assertions\AbstractAssertion; use NeuronAI\Evaluation\AssertionResult; class GreaterThanAssertion extends AbstractAssertion { public function __construct( private readonly float $threshold ) {} public function evaluate(mixed $actual): AssertionResult { if (!is_numeric($actual)) { return AssertionResult::fail( 0.0, 'Expected numeric value, got ' . gettype($actual), ); } if ($actual > $this->threshold) { return AssertionResult::pass(1.0); } return AssertionResult::fail( 0.0, "Expected {$actual} to be greater than {$this->threshold}", ); } } ``` -------------------------------- ### Define an Array of Strings Property Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/tools.md Use ArrayProperty to define an array where each item must conform to a specified ToolProperty. This example requires an array of strings. ```php namespace App\Neuron\Tools; use NeuronAI\Tools\PropertyType; use NeuronAI\Tools\Tool; use NeuronAI\Tools\ArrayProperty; use NeuronAI\Tools\ToolProperty; class MyTool extends Tool { public function __construct(){...} protected function properties(): array { return [ new ArrayProperty( name: 'prop_array', description: 'Describe the value you expect', required: true, items: new ToolProperty( name: 'prop', type: PropertyType::STRING, description: 'Describe the value you expect', required: true ) ) ]; } public function __invoke(string $arg){...} } ``` -------------------------------- ### Define a Custom Agent Class Source: https://github.com/neuron-core/neuron-php-doc/blob/main/overview/getting-started.md Example of a custom agent class extending the base Neuron Agent. It configures the AI provider and system prompt. ```php namespace App\Neuron; use NeuronAI\Agent\Agent; use NeuronAI\Agent\SystemPrompt; use NeuronAI\Providers\Anthropic\Anthropic; class MyAgent extends Agent { protected function provider(): AIProviderInterface { // return an AI provider (Anthropic, OpenAI, Ollama, Gemini, etc.) return new Anthropic( key: 'ANTHROPIC_API_KEY', model: 'ANTHROPIC_MODEL', ); } public function instructions(): string { return (string) new SystemPrompt( background: ["You are a friendly AI Agent created with Neuron framework."], ); } } ``` -------------------------------- ### Chat with the Agent Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/agent.md Demonstrates how to initiate a chat with an agent and retrieve its response. The agent is instantiated and then interacts with a user message. ```php use NeuronAI\Chat\Messages\UserMessage; $message = YouTubeAgent::make() ->chat(new UserMessage("Who are you?")) ->getMessage(); echo $message->getContent(); // Hi, I'm a frindly AI agent specialized in summarizing YouTube videos! // Can you give me the URL of a YouTube video you want a quick summary of? ``` -------------------------------- ### Disable Retries for LLM Structured Output Source: https://github.com/neuron-core/neuron-php-doc/blob/main/agent/structured-output.md Disable retries by passing zero to maxRetries. This results in a one-shot attempt to get a valid answer from the LLM. ```php $person = MyAgent::make()->structured( messages: new UserMessage("I'm John and I like pizza!"), class: Person::class, maxRetries: 0 ); ```