{"repo_name": "neuron-ai", "file_name": "/neuron-ai/src/Providers/Anthropic/Anthropic.php", "inference_info": {"prefix_code": "client = new Client([\n 'base_uri' => \\trim($this->baseUri, '/').'/',\n 'headers' => [\n 'Content-Type' => 'application/json',\n 'x-api-key' => $this->key,\n 'anthropic-version' => $version,\n ]\n ]);\n }\n\n public function systemPrompt(?string $prompt): AIProviderInterface\n {\n $this->system = $prompt;\n return $this;\n }\n\n public function messageMapper(): MessageMapperInterface\n {\n return new MessageMapper();\n }\n\n ", "suffix_code": "\n\n public function createToolCallMessage(array $content): Message\n {\n $tool = $this->findTool($content['name'])\n ->setInputs($content['input'])\n ->setCallId($content['id']);\n\n // During serialization and deserialization PHP convert the original empty object {} to empty array []\n // causing an error on the Anthropic API. If there are no inputs, we need to restore the empty JSON object.\n if (empty($content['input'])) {\n $content['input'] = new \\stdClass();\n }\n\n return new ToolCallMessage(\n [$content],\n [$tool] // Anthropic call one tool at a time. So we pass an array with one element.\n );\n }\n}\n", "middle_code": "protected function generateToolsPayload(): array\n {\n return \\array_map(function (ToolInterface $tool): array {\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n return [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'input_schema' => [\n 'type' => 'object',\n 'properties' => empty($properties) ? null : $properties,\n 'required' => $tool->getRequiredProperties(),\n ],\n ];\n }, $this->tools);\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/neuron-ai/src/Providers/Gemini/Gemini.php", "client = new Client([\n // Since Gemini use colon \":\" into the URL guzzle fire an exception using base_uri configuration.\n //'base_uri' => trim($this->baseUri, '/').'/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'x-goog-api-key' => $this->key,\n ]\n ]);\n }\n\n public function systemPrompt(?string $prompt): AIProviderInterface\n {\n $this->system = $prompt;\n return $this;\n }\n\n public function messageMapper(): MessageMapperInterface\n {\n return new MessageMapper();\n }\n\n protected function generateToolsPayload(): array\n {\n $tools = \\array_map(function (ToolInterface $tool): array {\n $payload = [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'parameters' => [\n 'type' => 'object',\n 'properties' => new \\stdClass(),\n 'required' => [],\n ],\n ];\n\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property) {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n\n if (!empty($properties)) {\n $payload['parameters'] = [\n 'type' => 'object',\n 'properties' => $properties,\n 'required' => $tool->getRequiredProperties(),\n ];\n }\n\n return $payload;\n }, $this->tools);\n\n return [\n 'functionDeclarations' => $tools\n ];\n }\n\n protected function createToolCallMessage(array $message): Message\n {\n $tools = \\array_map(function (array $item): ?\\NeuronAI\\Tools\\ToolInterface {\n if (!isset($item['functionCall'])) {\n return null;\n }\n\n // Gemini does not use ID. It uses the tool's name as a unique identifier.\n return $this->findTool($item['functionCall']['name'])\n ->setInputs($item['functionCall']['args'])\n ->setCallId($item['functionCall']['name']);\n }, $message['parts']);\n\n $result = new ToolCallMessage(\n $message['content'] ?? null,\n \\array_filter($tools)\n );\n $result->setRole(MessageRole::MODEL);\n\n return $result;\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/OpenAI.php", "client = new Client([\n 'base_uri' => \\trim($this->baseUri, '/').'/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer ' . $this->key,\n ]\n ]);\n }\n\n public function systemPrompt(?string $prompt): AIProviderInterface\n {\n $this->system = $prompt;\n return $this;\n }\n\n public function messageMapper(): MessageMapperInterface\n {\n return new MessageMapper();\n }\n\n protected function generateToolsPayload(): array\n {\n return \\array_map(function (ToolInterface $tool): array {\n $payload = [\n 'type' => 'function',\n 'function' => [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'parameters' => [\n 'type' => 'object',\n 'properties' => new \\stdClass(),\n 'required' => [],\n ],\n ]\n ];\n\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n\n if (!empty($properties)) {\n $payload['function']['parameters'] = [\n 'type' => 'object',\n 'properties' => $properties,\n 'required' => $tool->getRequiredProperties(),\n ];\n }\n\n return $payload;\n }, $this->tools);\n }\n\n protected function createToolCallMessage(array $message): Message\n {\n $tools = \\array_map(\n fn (array $item): ToolInterface => $this->findTool($item['function']['name'])\n ->setInputs(\n \\json_decode((string) $item['function']['arguments'], true)\n )\n ->setCallId($item['id']),\n $message['tool_calls']\n );\n\n $result = new ToolCallMessage(\n $message['content'],\n $tools\n );\n\n return $result->addMetadata('tool_calls', $message['tool_calls']);\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/Ollama.php", "client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n ]);\n }\n\n public function systemPrompt(?string $prompt): AIProviderInterface\n {\n $this->system = $prompt;\n\n return $this;\n }\n\n public function messageMapper(): MessageMapperInterface\n {\n return new MessageMapper();\n }\n\n protected function generateToolsPayload(): array\n {\n return \\array_map(function (ToolInterface $tool): array {\n $payload = [\n 'type' => 'function',\n 'function' => [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'parameters' => [\n 'type' => 'object',\n 'properties' => new \\stdClass(),\n 'required' => [],\n ]\n ],\n ];\n\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n $carry[$property->getName()] = [\n 'type' => $property->getType()->value,\n 'description' => $property->getDescription(),\n ];\n\n return $carry;\n }, []);\n\n if (! empty($properties)) {\n $payload['function']['parameters'] = [\n 'type' => 'object',\n 'properties' => $properties,\n 'required' => $tool->getRequiredProperties(),\n ];\n }\n\n return $payload;\n }, $this->tools);\n }\n\n protected function createToolCallMessage(array $message): Message\n {\n $tools = \\array_map(fn (array $item): ToolInterface => $this->findTool($item['function']['name'])\n ->setInputs($item['function']['arguments']), $message['tool_calls']);\n\n $result = new ToolCallMessage(\n $message['content'],\n $tools\n );\n\n return $result->addMetadata('tool_calls', $message['tool_calls']);\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/HandleStream.php", " true,\n 'model' => $this->model,\n 'max_tokens' => $this->max_tokens,\n 'system' => $this->system ?? null,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n // https://docs.anthropic.com/claude/reference/messages_post\n $stream = $this->client->post('messages', [\n 'stream' => true,\n ...['json' => $json]\n ])->getBody();\n\n $toolCalls = [];\n\n while (! $stream->eof()) {\n if (!$line = $this->parseNextDataLine($stream)) {\n continue;\n }\n\n // https://docs.anthropic.com/en/api/messages-streaming\n if ($line['type'] === 'message_start') {\n yield \\json_encode(['usage' => $line['message']['usage']]);\n continue;\n }\n\n if ($line['type'] === 'message_delta') {\n yield \\json_encode(['usage' => $line['usage']]);\n continue;\n }\n\n // Tool calls detection (https://docs.anthropic.com/en/api/messages-streaming#streaming-request-with-tool-use)\n if (\n (isset($line['content_block']['type']) && $line['content_block']['type'] === 'tool_use') ||\n (isset($line['delta']['type']) && $line['delta']['type'] === 'input_json_delta')\n ) {\n $toolCalls = $this->composeToolCalls($line, $toolCalls);\n continue;\n }\n\n // Handle tool call\n if ($line['type'] === 'content_block_stop' && !empty($toolCalls)) {\n // Restore the input field as an array\n $toolCalls = \\array_map(function (array $call) {\n $call['input'] = \\json_decode((string) $call['input'], true);\n return $call;\n }, $toolCalls);\n\n yield from $executeToolsCallback(\n $this->createToolCallMessage(\\end($toolCalls))\n );\n }\n\n // Process regular content\n $content = $line['delta']['text'] ?? '';\n\n yield $content;\n }\n }\n\n /**\n * Recreate the tool_call format of anthropic API from streaming.\n *\n * @param array $line\n * @param array> $toolCalls\n * @return array>\n */\n protected function composeToolCalls(array $line, array $toolCalls): array\n {\n if (!\\array_key_exists($line['index'], $toolCalls)) {\n $toolCalls[$line['index']] = [\n 'type' => 'tool_use',\n 'id' => $line['content_block']['id'],\n 'name' => $line['content_block']['name'],\n 'input' => '',\n ];\n } elseif ($input = $line['delta']['partial_json'] ?? null) {\n $toolCalls[$line['index']]['input'] .= $input;\n }\n\n return $toolCalls;\n }\n\n protected function parseNextDataLine(StreamInterface $stream): ?array\n {\n $line = $this->readLine($stream);\n\n if (! \\str_starts_with((string) $line, 'data:')) {\n return null;\n }\n\n $line = \\trim(\\substr((string) $line, \\strlen('data: ')));\n\n try {\n return \\json_decode($line, true, flags: \\JSON_THROW_ON_ERROR);\n } catch (\\Throwable $exception) {\n throw new ProviderException('Anthropic streaming error - '.$exception->getMessage());\n }\n }\n\n protected function readLine(StreamInterface $stream): string\n {\n $buffer = '';\n\n while (! $stream->eof()) {\n $byte = $stream->read(1);\n\n if ($byte === '') {\n return $buffer;\n }\n\n $buffer .= $byte;\n\n if ($byte === \"\\n\") {\n break;\n }\n }\n\n return $buffer;\n }\n}\n"], ["/neuron-ai/src/Tools/Tool.php", "properties = $properties;\n }\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n public function getDescription(): ?string\n {\n return $this->description;\n }\n\n public function addProperty(ToolPropertyInterface $property): ToolInterface\n {\n $this->properties[] = $property;\n return $this;\n }\n\n /**\n * @return ToolPropertyInterface[]\n */\n protected function properties(): array\n {\n return [];\n }\n\n /**\n * @return ToolPropertyInterface[]\n */\n public function getProperties(): array\n {\n if ($this->properties === []) {\n foreach ($this->properties() as $property) {\n $this->addProperty($property);\n }\n }\n\n return $this->properties;\n }\n\n public function getRequiredProperties(): array\n {\n return \\array_reduce($this->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n if ($property->isRequired()) {\n $carry[] = $property->getName();\n }\n\n return $carry;\n }, []);\n }\n\n public function setCallable(callable $callback): self\n {\n $this->callback = $callback;\n return $this;\n }\n\n public function getInputs(): array\n {\n return $this->inputs ?? [];\n }\n\n public function setInputs(?array $inputs): self\n {\n $this->inputs = $inputs ?? [];\n return $this;\n }\n\n public function getCallId(): ?string\n {\n return $this->callId;\n }\n\n public function setCallId(?string $callId): self\n {\n $this->callId = $callId;\n return $this;\n }\n\n public function getResult(): string\n {\n return $this->result;\n }\n\n public function setResult(mixed $result): self\n {\n $this->result = \\is_array($result) ? \\json_encode($result) : (string) $result;\n\n return $this;\n }\n\n /**\n * Execute the client side function.\n *\n * @throws MissingCallbackParameter\n * @throws ToolCallableNotSet\n * @throws DeserializerException\n * @throws \\ReflectionException\n */\n public function execute(): void\n {\n if (!\\is_callable($this->callback) && !\\method_exists($this, '__invoke')) {\n throw new ToolCallableNotSet('No function defined for tool execution.');\n }\n\n // Validate required parameters\n foreach ($this->getProperties() as $property) {\n if ($property->isRequired() && !\\array_key_exists($property->getName(), $this->getInputs())) {\n throw new MissingCallbackParameter(\"Missing required parameter: {$property->getName()}\");\n }\n }\n\n $parameters = \\array_reduce($this->getProperties(), function (array $carry, ToolPropertyInterface $property) {\n $propertyName = $property->getName();\n $inputs = $this->getInputs();\n\n // Normalize missing optional properties by assigning them a null value\n // Treat it as explicitly null to ensure a consistent structure\n if (!\\array_key_exists($propertyName, $inputs)) {\n $carry[$propertyName] = null;\n return $carry;\n }\n\n // Find the corresponding input value\n $inputValue = $inputs[$propertyName];\n\n // If there is an object property with a class definition,\n // deserialize the tool input into an instance of that class\n if ($property instanceof ObjectProperty && $property->getClass()) {\n $carry[$propertyName] = Deserializer::fromJson(\\json_encode($inputValue), $property->getClass());\n return $carry;\n }\n\n // If a property is an array of objects and each item matches a class definition,\n // deserialize each item into an instance of that class\n if ($property instanceof ArrayProperty) {\n $items = $property->getItems();\n if ($items instanceof ObjectProperty && $items->getClass()) {\n $class = $items->getClass();\n $carry[$propertyName] = \\array_map(fn (array|object $input): object => Deserializer::fromJson(\\json_encode($input), $class), $inputValue);\n return $carry;\n }\n }\n\n // No extra treatments for basic property types\n $carry[$propertyName] = $inputValue;\n return $carry;\n\n }, []);\n\n $this->setResult(\n \\method_exists($this, '__invoke') ? $this->__invoke(...$parameters)\n : \\call_user_func($this->callback, ...$parameters)\n );\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'name' => $this->name,\n 'description' => $this->description,\n 'inputs' => $this->inputs === [] ? new \\stdClass() : $this->inputs,\n 'callId' => $this->callId,\n 'result' => $this->result,\n ];\n }\n}\n"], ["/neuron-ai/src/Providers/Mistral/Mistral.php", "system !== null) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'stream' => true,\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n // Attach tools\n if ($this->tools !== []) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n $stream = $this->client->post('chat/completions', [\n 'stream' => true,\n ...['json' => $json]\n ])->getBody();\n\n $text = '';\n $toolCalls = [];\n\n while (! $stream->eof()) {\n if (($line = $this->parseNextDataLine($stream)) === null) {\n continue;\n }\n\n // Inform the agent about usage when stream\n if (empty($line['choices']) && !empty($line['usage'])) {\n yield \\json_encode(['usage' => [\n 'input_tokens' => $line['usage']['prompt_tokens'],\n 'output_tokens' => $line['usage']['completion_tokens'],\n ]]);\n continue;\n }\n\n if (empty($line['choices'])) {\n continue;\n }\n\n // Compile tool calls\n if ($this->isToolCallPart($line)) {\n $toolCalls = $this->composeToolCalls($line, $toolCalls);\n\n // Handle tool calls\n if ($line['choices'][0]['finish_reason'] === 'tool_calls') {\n yield from $executeToolsCallback(\n $this->createToolCallMessage([\n 'content' => $text,\n 'tool_calls' => $toolCalls\n ])\n );\n }\n\n continue;\n }\n\n // Process regular content\n $content = $line['choices'][0]['delta']['content'] ?? '';\n $text .= $content;\n\n yield $content;\n }\n }\n\n protected function isToolCallPart(array $line): bool\n {\n $calls = $line['choices'][0]['delta']['tool_calls'] ?? [];\n\n foreach ($calls as $call) {\n if (isset($call['function'])) {\n return true;\n }\n }\n\n return false;\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/HandleStream.php", " $this->messageMapper()->map($messages),\n ...$this->parameters\n ];\n\n if (isset($this->system)) {\n $json['system_instruction'] = [\n 'parts' => [\n ['text' => $this->system]\n ]\n ];\n }\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n $stream = $this->client->post(\\trim($this->baseUri, '/').\"/{$this->model}:streamGenerateContent\", [\n 'stream' => true,\n ...[RequestOptions::JSON => $json]\n ])->getBody();\n\n $text = '';\n $toolCalls = [];\n\n while (! $stream->eof()) {\n $line = $this->readLine($stream);\n\n if (($line = \\json_decode((string) $line, true)) === null) {\n continue;\n }\n\n // Inform the agent about usage when stream\n if (\\array_key_exists('usageMetadata', $line)) {\n yield \\json_encode(['usage' => [\n 'input_tokens' => $line['usageMetadata']['promptTokenCount'],\n 'output_tokens' => $line['usageMetadata']['candidatesTokenCount'] ?? 0,\n ]]);\n }\n\n // Process tool calls\n if ($this->hasToolCalls($line)) {\n $toolCalls = $this->composeToolCalls($line, $toolCalls);\n\n // Handle tool calls\n if (isset($line['candidates'][0]['finishReason']) && $line['candidates'][0]['finishReason'] === 'STOP') {\n yield from $executeToolsCallback(\n $this->createToolCallMessage([\n 'content' => $text,\n 'parts' => $toolCalls\n ])\n );\n\n return;\n }\n\n continue;\n }\n\n // Process regular content\n $content = $line['candidates'][0]['content']['parts'][0]['text'] ?? '';\n $text .= $content;\n\n yield $content;\n }\n }\n\n /**\n * Recreate the tool_calls format from streaming Gemini API.\n */\n protected function composeToolCalls(array $line, array $toolCalls): array\n {\n $parts = $line['candidates'][0]['content']['parts'] ?? [];\n\n foreach ($parts as $index => $part) {\n if (isset($part['functionCall'])) {\n $toolCalls[$index]['functionCall'] = $part['functionCall'];\n }\n }\n\n return $toolCalls;\n }\n\n /**\n * Determines if the given line contains tool function calls.\n *\n * @param array $line The data line to check for tool function calls.\n * @return bool Returns true if the line contains tool function calls, otherwise false.\n */\n protected function hasToolCalls(array $line): bool\n {\n $parts = $line['candidates'][0]['content']['parts'] ?? [];\n\n foreach ($parts as $part) {\n if (isset($part['functionCall'])) {\n return true;\n }\n }\n\n return false;\n }\n\n private function readLine(StreamInterface $stream): string\n {\n $buffer = '';\n\n while (! $stream->eof()) {\n $buffer .= $stream->read(1);\n\n if (\\strlen($buffer) === 1 && $buffer !== '{') {\n $buffer = '';\n }\n\n if (\\json_decode($buffer) !== null) {\n return $buffer;\n }\n }\n\n return \\rtrim($buffer, ']');\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/MessageMapper.php", "mapping = [];\n\n foreach ($messages as $message) {\n match ($message::class) {\n Message::class,\n UserMessage::class,\n AssistantMessage::class => $this->mapMessage($message),\n ToolCallMessage::class => $this->mapToolCall($message),\n ToolCallResultMessage::class => $this->mapToolsResult($message),\n default => throw new ProviderException('Could not map message type '.$message::class),\n };\n }\n\n return $this->mapping;\n }\n\n protected function mapMessage(Message $message): void\n {\n $payload = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $payload)) {\n unset($payload['usage']);\n }\n\n $attachments = $message->getAttachments();\n\n if (\\is_string($payload['content']) && $attachments) {\n $payload['content'] = [\n [\n 'type' => 'text',\n 'text' => $payload['content'],\n ],\n ];\n }\n\n foreach ($attachments as $attachment) {\n $payload['content'][] = $this->mapAttachment($attachment);\n }\n\n unset($payload['attachments']);\n\n $this->mapping[] = $payload;\n }\n\n protected function mapAttachment(Attachment $attachment): array\n {\n return match($attachment->contentType) {\n AttachmentContentType::URL => [\n 'type' => $attachment->type->value,\n 'source' => [\n 'type' => 'url',\n 'url' => $attachment->content,\n ],\n ],\n AttachmentContentType::BASE64 => [\n 'type' => $attachment->type->value,\n 'source' => [\n 'type' => 'base64',\n 'media_type' => $attachment->mediaType,\n 'data' => $attachment->content,\n ],\n ],\n };\n }\n\n protected function mapToolCall(ToolCallMessage $message): void\n {\n $message = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $message)) {\n unset($message['usage']);\n }\n\n unset($message['type']);\n unset($message['tools']);\n\n $this->mapping[] = $message;\n }\n\n protected function mapToolsResult(ToolCallResultMessage $message): void\n {\n $this->mapping[] = [\n 'role' => MessageRole::USER,\n 'content' => \\array_map(fn (ToolInterface $tool): array => [\n 'type' => 'tool_result',\n 'tool_use_id' => $tool->getCallId(),\n 'content' => $tool->getResult(),\n ], $message->getTools())\n ];\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/HandleStream.php", "system)) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'stream' => true,\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n 'stream_options' => ['include_usage' => true],\n ...$this->parameters,\n ];\n\n // Attach tools\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n $stream = $this->client->post('chat/completions', [\n 'stream' => true,\n ...['json' => $json]\n ])->getBody();\n\n $text = '';\n $toolCalls = [];\n\n while (! $stream->eof()) {\n if (!$line = $this->parseNextDataLine($stream)) {\n continue;\n }\n\n // Inform the agent about usage when stream\n if (!empty($line['usage'])) {\n yield \\json_encode(['usage' => [\n 'input_tokens' => $line['usage']['prompt_tokens'],\n 'output_tokens' => $line['usage']['completion_tokens'],\n ]]);\n }\n\n if (empty($line['choices'])) {\n continue;\n }\n\n // Compile tool calls\n if (isset($line['choices'][0]['delta']['tool_calls'])) {\n $toolCalls = $this->composeToolCalls($line, $toolCalls);\n continue;\n }\n\n // Handle tool calls\n if (isset($line['choices'][0]['finish_reason']) && $line['choices'][0]['finish_reason'] === 'tool_calls') {\n yield from $executeToolsCallback(\n $this->createToolCallMessage([\n 'content' => $text,\n 'tool_calls' => $toolCalls\n ])\n );\n\n return;\n }\n\n // Process regular content\n $content = $line['choices'][0]['delta']['content'] ?? '';\n $text .= $content;\n\n yield $content;\n }\n }\n\n /**\n * Recreate the tool_calls format from streaming OpenAI API.\n *\n * @param array $line\n * @param array> $toolCalls\n * @return array>\n */\n protected function composeToolCalls(array $line, array $toolCalls): array\n {\n foreach ($line['choices'][0]['delta']['tool_calls'] as $call) {\n $index = $call['index'];\n\n if (!\\array_key_exists($index, $toolCalls)) {\n if ($name = $call['function']['name'] ?? null) {\n $toolCalls[$index]['function'] = ['name' => $name, 'arguments' => $call['function']['arguments'] ?? ''];\n $toolCalls[$index]['id'] = $call['id'];\n $toolCalls[$index]['type'] = 'function';\n }\n } else {\n $arguments = $call['function']['arguments'] ?? null;\n if ($arguments !== null) {\n $toolCalls[$index]['function']['arguments'] .= $arguments;\n }\n }\n }\n\n return $toolCalls;\n }\n\n protected function parseNextDataLine(StreamInterface $stream): ?array\n {\n $line = $this->readLine($stream);\n\n if (! \\str_starts_with((string) $line, 'data:')) {\n return null;\n }\n\n $line = \\trim(\\substr((string) $line, \\strlen('data: ')));\n\n if (\\str_contains($line, 'DONE')) {\n return null;\n }\n\n try {\n return \\json_decode($line, true, flags: \\JSON_THROW_ON_ERROR);\n } catch (\\Throwable $exception) {\n throw new ProviderException('OpenAI streaming error - '.$exception->getMessage());\n }\n }\n\n protected function readLine(StreamInterface $stream): string\n {\n $buffer = '';\n\n while (! $stream->eof()) {\n $byte = $stream->read(1);\n\n if ($byte === '') {\n return $buffer;\n }\n\n $buffer .= $byte;\n\n if ($byte === \"\\n\") {\n break;\n }\n }\n\n return $buffer;\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(array $messages): PromiseInterface\n {\n $json = [\n 'model' => $this->model,\n 'max_tokens' => $this->max_tokens,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n if (isset($this->system)) {\n $json['system'] = $this->system;\n }\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n\n return $this->client->postAsync('messages', ['json' => $json])\n ->then(function (ResponseInterface $response) {\n $result = \\json_decode($response->getBody()->getContents(), true);\n\n $content = \\end($result['content']);\n\n if ($content['type'] === 'tool_use') {\n $response = $this->createToolCallMessage($content);\n } else {\n $response = new AssistantMessage($content['text']);\n }\n\n // Attach the usage for the current interaction\n if (\\array_key_exists('usage', $result)) {\n $response->setUsage(\n new Usage(\n $result['usage']['input_tokens'],\n $result['usage']['output_tokens']\n )\n );\n }\n\n return $response;\n });\n }\n}\n"], ["/neuron-ai/src/Tools/ObjectProperty.php", "properties === [] && \\class_exists($this->class)) {\n $schema = (new JsonSchema())->generate($this->class);\n $this->properties = $this->buildPropertiesFromClass($schema);\n }\n }\n\n /**\n * Recursively build properties from a class schema\n *\n * @return ToolPropertyInterface[]\n * @throws \\ReflectionException\n * @throws ToolException\n * @throws ArrayPropertyException\n */\n protected function buildPropertiesFromClass(array $schema): array\n {\n $required = $schema['required'] ?? [];\n $properties = [];\n\n foreach ($schema['properties'] as $propertyName => $propertyData) {\n $isRequired = \\in_array($propertyName, $required);\n $property = $this->createPropertyFromSchema($propertyName, $propertyData, $isRequired);\n\n if ($property instanceof ToolPropertyInterface) {\n $properties[] = $property;\n }\n }\n\n return $properties;\n }\n\n /**\n * Create a property from schema data recursively\n *\n * @throws \\ReflectionException\n * @throws ToolException\n * @throws ArrayPropertyException\n */\n protected function createPropertyFromSchema(string $propertyName, array $propertyData, bool $isRequired): ?ToolPropertyInterface\n {\n $type = $propertyData['type'] ?? 'string';\n $description = $propertyData['description'] ?? null;\n\n return match ($type) {\n 'object' => $this->createObjectProperty($propertyName, $propertyData, $isRequired, $description),\n 'array' => $this->createArrayProperty($propertyName, $propertyData, $isRequired, $description),\n 'string', 'integer', 'number', 'boolean' => $this->createScalarProperty($propertyName, $propertyData, $isRequired, $description),\n default => new ToolProperty(\n $propertyName,\n PropertyType::STRING,\n $description,\n $isRequired,\n $propertyData['enum'] ?? []\n ),\n };\n }\n\n /**\n * Create an object property recursively\n *\n * @throws \\ReflectionException\n * @throws ToolException\n * @throws ArrayPropertyException\n */\n protected function createObjectProperty(string $name, array $propertyData, bool $required, ?string $description): ObjectProperty\n {\n $nestedProperties = [];\n $nestedRequired = $propertyData['required'] ?? [];\n\n // If there's a class reference in the schema, use it\n $className = $propertyData['class'] ?? null;\n\n // If no class is specified, but we have nested properties, build them recursively\n if (!$className && isset($propertyData['properties'])) {\n foreach ($propertyData['properties'] as $nestedPropertyName => $nestedPropertyData) {\n $nestedIsRequired = \\in_array($nestedPropertyName, $nestedRequired);\n $nestedProperty = $this->createPropertyFromSchema($nestedPropertyName, $nestedPropertyData, $nestedIsRequired);\n\n if ($nestedProperty instanceof ToolPropertyInterface) {\n $nestedProperties[] = $nestedProperty;\n }\n }\n }\n\n return new ObjectProperty(\n $name,\n $description,\n $required,\n $className,\n $nestedProperties\n );\n }\n\n /**\n * Create an array property with recursive item handling\n *\n * @throws \\ReflectionException\n * @throws ToolException\n * @throws ArrayPropertyException\n */\n protected function createArrayProperty(string $name, array $propertyData, bool $required, ?string $description): ArrayProperty\n {\n $items = null;\n $minItems = $propertyData['minItems'] ?? null;\n $maxItems = $propertyData['maxItems'] ?? null;\n\n // Handle array items recursively\n if (isset($propertyData['items'])) {\n $itemsData = $propertyData['items'];\n $items = $this->createPropertyFromSchema($name . '_item', $itemsData, false);\n }\n\n return new ArrayProperty(\n $name,\n $description,\n $required,\n $items,\n $minItems,\n $maxItems\n );\n }\n\n /**\n * Create a scalar property (string, integer, number, boolean)\n *\n * @throws ToolException\n */\n protected function createScalarProperty(string $name, array $propertyData, bool $required, ?string $description): ToolProperty\n {\n return new ToolProperty(\n $name,\n PropertyType::fromSchema($propertyData['type']),\n $description,\n $required,\n $propertyData['enum'] ?? []\n );\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'name' => $this->name,\n ...(\\is_null($this->description) ? [] : ['description' => $this->description]),\n 'type' => $this->type,\n 'properties' => $this->getJsonSchema(),\n 'required' => $this->required,\n ];\n }\n\n // The mapped class required properties and required properties are merged\n public function getRequiredProperties(): array\n {\n return \\array_values(\\array_filter(\\array_map(fn (\n ToolPropertyInterface $property\n ): ?string => $property->isRequired() ? $property->getName() : null, $this->properties)));\n }\n\n public function getJsonSchema(): array\n {\n $schema = [\n 'type' => $this->type->value,\n ];\n\n if (!\\is_null($this->description)) {\n $schema['description'] = $this->description;\n }\n\n $properties = \\array_reduce($this->properties, function (array $carry, ToolPropertyInterface $property) {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n\n if (!empty($properties)) {\n $schema['properties'] = $properties;\n $schema['required'] = $this->getRequiredProperties();\n }\n\n return $schema;\n }\n\n public function isRequired(): bool\n {\n return $this->required;\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n public function getType(): PropertyType\n {\n return $this->type;\n }\n\n public function getDescription(): ?string\n {\n return $this->description;\n }\n\n public function getProperties(): array\n {\n return $this->properties;\n }\n\n public function getClass(): ?string\n {\n return $this->class;\n }\n}\n"], ["/neuron-ai/src/Chat/History/AbstractChatHistory.php", "history[] = $message;\n\n $this->trimHistory();\n\n $this->setMessages($this->history);\n\n return $this;\n }\n\n public function getMessages(): array\n {\n return $this->history;\n }\n\n public function getLastMessage(): Message|false\n {\n return \\end($this->history);\n }\n\n public function flushAll(): ChatHistoryInterface\n {\n $this->clear();\n $this->history = [];\n return $this;\n }\n\n public function calculateTotalUsage(): int\n {\n return $this->tokenCounter->count($this->history);\n }\n\n protected function trimHistory(): void\n {\n if ($this->history === []) {\n return;\n }\n\n $tokenCount = $this->tokenCounter->count($this->history);\n\n // Early exit if all messages fit within the token limit\n if ($tokenCount <= $this->contextWindow) {\n $this->ensureValidMessageSequence();\n return;\n }\n\n // Binary search to find how many messages to skip from the beginning\n $skipFrom = $this->findMaxFittingMessages();\n\n $this->history = \\array_slice($this->history, $skipFrom);\n\n // Ensure valid message sequence\n $this->ensureValidMessageSequence();\n }\n\n /**\n * Binary search to find the maximum number of messages that fit within the token limit.\n *\n * @return int The index of the first element to retain (keeping most recent messages) - 0 Skip no messages (include all) - count($this->history): Skip all messages (include none)\n */\n private function findMaxFittingMessages(): int\n {\n $totalMessages = \\count($this->history);\n $left = 0;\n $right = $totalMessages;\n\n while ($left < $right) {\n $mid = \\intval(($left + $right) / 2);\n $subset = \\array_slice($this->history, $mid);\n\n if ($this->tokenCounter->count($subset) <= $this->contextWindow) {\n // Fits! Try including more messages (skip fewer)\n $right = $mid;\n } else {\n // Doesn't fit! Need to skip more messages\n $left = $mid + 1;\n }\n }\n\n return $left;\n }\n\n /**\n * Ensures the message list:\n * 1. Starts with a UserMessage\n * 2. Ends with an AssistantMessage\n * 3. Maintains tool call/result pairs\n */\n protected function ensureValidMessageSequence(): void\n {\n // Ensure it starts with a UserMessage\n $this->ensureStartsWithUser();\n\n // Ensure it ends with an AssistantMessage\n $this->ensureValidAlternation();\n }\n\n /**\n * Ensures the message list starts with a UserMessage.\n */\n protected function ensureStartsWithUser(): void\n {\n // Find the first UserMessage\n $firstUserIndex = null;\n foreach ($this->history as $index => $message) {\n if ($message->getRole() === MessageRole::USER->value) {\n $firstUserIndex = $index;\n break;\n }\n }\n\n if ($firstUserIndex === null) {\n // No UserMessage found\n $this->history = [];\n return;\n }\n\n if ($firstUserIndex === 0) {\n return;\n }\n\n if ($firstUserIndex > 0) {\n // Remove messages before the first user message\n $this->history = \\array_slice($this->history, $firstUserIndex);\n }\n }\n\n /**\n * Ensures valid alternation between user and assistant messages.\n */\n protected function ensureValidAlternation(): void\n {\n $result = [];\n $expectingRole = [MessageRole::USER->value]; // Should start with user\n\n foreach ($this->history as $message) {\n $messageRole = $message->getRole();\n\n // Tool result messages have a special case - they're user messages\n // but can only follow tool call messages (assistant)\n // This is valid after a ToolCallMessage\n if ($message instanceof ToolCallResultMessage && ($result !== [] && $result[\\count($result) - 1] instanceof ToolCallMessage)) {\n $result[] = $message;\n // After the tool result, we expect assistant again\n $expectingRole = [MessageRole::ASSISTANT->value, MessageRole::MODEL->value];\n continue;\n }\n\n // Check if this message has the expected role\n if (\\in_array($messageRole, $expectingRole, true)) {\n $result[] = $message;\n // Toggle the expected role\n $expectingRole = ($expectingRole === [MessageRole::USER->value])\n ? [MessageRole::ASSISTANT->value, MessageRole::MODEL->value]\n : [MessageRole::USER->value];\n }\n // If not the expected role, we have an invalid alternation\n // Skip this message to maintain a valid sequence\n }\n\n $this->history = $result;\n }\n\n public function jsonSerialize(): array\n {\n return $this->getMessages();\n }\n\n protected function deserializeMessages(array $messages): array\n {\n return \\array_map(fn (array $message): Message => match ($message['type'] ?? null) {\n 'tool_call' => $this->deserializeToolCall($message),\n 'tool_call_result' => $this->deserializeToolCallResult($message),\n default => $this->deserializeMessage($message),\n }, $messages);\n }\n\n protected function deserializeMessage(array $message): Message\n {\n $messageRole = MessageRole::from($message['role']);\n $messageContent = $message['content'] ?? null;\n\n $item = match ($messageRole) {\n MessageRole::ASSISTANT => new AssistantMessage($messageContent),\n MessageRole::USER => new UserMessage($messageContent),\n default => new Message($messageRole, $messageContent)\n };\n\n $this->deserializeMeta($message, $item);\n\n return $item;\n }\n\n protected function deserializeToolCall(array $message): ToolCallMessage\n {\n $tools = \\array_map(fn (array $tool) => Tool::make($tool['name'], $tool['description'])\n ->setInputs($tool['inputs'])\n ->setCallId($tool['callId'] ?? null), $message['tools']);\n\n $item = new ToolCallMessage($message['content'], $tools);\n\n $this->deserializeMeta($message, $item);\n\n return $item;\n }\n\n protected function deserializeToolCallResult(array $message): ToolCallResultMessage\n {\n $tools = \\array_map(fn (array $tool) => Tool::make($tool['name'], $tool['description'])\n ->setInputs($tool['inputs'])\n ->setCallId($tool['callId'])\n ->setResult($tool['result']), $message['tools']);\n\n return new ToolCallResultMessage($tools);\n }\n\n protected function deserializeMeta(array $message, Message $item): void\n {\n foreach ($message as $key => $value) {\n if ($key === 'role') {\n continue;\n }\n if ($key === 'content') {\n continue;\n }\n if ($key === 'usage') {\n $item->setUsage(\n new Usage($message['usage']['input_tokens'], $message['usage']['output_tokens'])\n );\n continue;\n }\n if ($key === 'attachments') {\n foreach ($message['attachments'] as $attachment) {\n switch (AttachmentType::from($attachment['type'])) {\n case AttachmentType::IMAGE:\n $item->addAttachment(\n new Image(\n $attachment['content'],\n AttachmentContentType::from($attachment['content_type']),\n $attachment['media_type'] ?? null\n )\n );\n break;\n case AttachmentType::DOCUMENT:\n $item->addAttachment(\n new Document(\n $attachment['content'],\n AttachmentContentType::from($attachment['content_type']),\n $attachment['media_type'] ?? null\n )\n );\n break;\n }\n\n }\n continue;\n }\n $item->addMetadata($key, $value);\n }\n }\n}\n"], ["/neuron-ai/src/Observability/AgentMonitoring.php", "\n */\n protected array $segments = [];\n\n\n /**\n * @var array\n */\n protected array $methodsMap = [\n 'error' => 'reportError',\n 'chat-start' => 'start',\n 'chat-stop' => 'stop',\n 'stream-start' => 'start',\n 'stream-stop' => 'stop',\n 'structured-start' => 'start',\n 'structured-stop' => 'stop',\n 'chat-rag-start' => 'start',\n 'chat-rag-stop' => 'stop',\n 'stream-rag-start' => 'start',\n 'stream-rag-stop' => 'stop',\n 'structured-rag-start' => 'start',\n 'structured-rag-stop' => 'stop',\n\n 'message-saving' => 'messageSaving',\n 'message-saved' => 'messageSaved',\n 'tools-bootstrapping' => 'toolsBootstrapping',\n 'tools-bootstrapped' => 'toolsBootstrapped',\n 'inference-start' => 'inferenceStart',\n 'inference-stop' => 'inferenceStop',\n 'tool-calling' => 'toolCalling',\n 'tool-called' => 'toolCalled',\n 'schema-generation' => 'schemaGeneration',\n 'schema-generated' => 'schemaGenerated',\n 'structured-extracting' => 'extracting',\n 'structured-extracted' => 'extracted',\n 'structured-deserializing' => 'deserializing',\n 'structured-deserialized' => 'deserialized',\n 'structured-validating' => 'validating',\n 'structured-validated' => 'validated',\n 'rag-retrieving' => 'ragRetrieving',\n 'rag-retrieved' => 'ragRetrieved',\n 'rag-preprocessing' => 'preProcessing',\n 'rag-preprocessed' => 'preProcessed',\n 'rag-postprocessing' => 'postProcessing',\n 'rag-postprocessed' => 'postProcessed',\n 'workflow-start' => 'workflowStart',\n 'workflow-end' => 'workflowEnd',\n 'workflow-node-start' => 'workflowNodeStart',\n 'workflow-node-end' => 'workflowNodeEnd',\n ];\n\n protected static ?AgentMonitoring $instance = null;\n\n /**\n * @param Inspector $inspector The monitoring instance\n */\n public function __construct(\n protected Inspector $inspector,\n protected bool $autoFlush = false,\n ) {\n }\n\n\n public static function instance(): AgentMonitoring\n {\n $configuration = new Configuration($_ENV['INSPECTOR_INGESTION_KEY']);\n $configuration->setTransport($_ENV['INSPECTOR_TRANSPORT'] ?? 'async');\n $configuration->setVersion($_ENV['INSPECTOR_VERSION'] ?? $configuration->getVersion());\n\n // Split monitoring between agents and workflows.\n if (isset($_ENV['NEURON_SPLIT_MONITORING'])) {\n return new self(new Inspector($configuration), $_ENV['NEURON_AUTOFLUSH'] ?? false);\n }\n\n if (!self::$instance instanceof AgentMonitoring) {\n self::$instance = new self(new Inspector($configuration), $_ENV['NEURON_AUTOFLUSH'] ?? false);\n }\n return self::$instance;\n }\n\n public function update(\\SplSubject $subject, ?string $event = null, mixed $data = null): void\n {\n if (!\\is_null($event) && \\array_key_exists($event, $this->methodsMap)) {\n $method = $this->methodsMap[$event];\n $this->$method($subject, $event, $data);\n }\n }\n\n public function start(Agent $agent, string $event, mixed $data = null): void\n {\n if (!$this->inspector->isRecording()) {\n return;\n }\n\n $method = $this->getPrefix($event);\n $class = $agent::class;\n\n if ($this->inspector->needTransaction()) {\n $this->inspector->startTransaction($class.'::'.$method)\n ->setType('ai-agent')\n ->setContext($this->getContext($agent));\n } elseif ($this->inspector->canAddSegments() && !$agent instanceof RAG) { // do not add \"parent\" agent segments on RAG\n $key = $class.$method;\n\n if (\\array_key_exists($key, $this->segments)) {\n $key .= '-'.\\uniqid();\n }\n\n $segment = $this->inspector->startSegment(self::SEGMENT_TYPE.'-'.$method, \"{$class}::{$method}\")\n ->setColor(self::SEGMENT_COLOR);\n $segment->setContext($this->getContext($agent));\n $this->segments[$key] = $segment;\n }\n }\n\n /**\n * @throws \\Exception\n */\n public function stop(Agent $agent, string $event, mixed $data = null): void\n {\n $method = $this->getPrefix($event);\n $class = $agent::class;\n\n if (\\array_key_exists($class.$method, $this->segments)) {\n // End the last segment for the given method and agent class\n foreach (\\array_reverse($this->segments, true) as $key => $segment) {\n if ($key === $class.$method) {\n $segment->setContext($this->getContext($agent));\n $segment->end();\n unset($this->segments[$key]);\n break;\n }\n }\n } elseif ($this->inspector->canAddSegments()) {\n $transaction = $this->inspector->transaction()->setResult('success');\n $transaction->setContext($this->getContext($agent));\n\n if ($this->autoFlush) {\n $this->inspector->flush();\n }\n }\n }\n\n public function reportError(\\SplSubject $subject, string $event, AgentError $data): void\n {\n $this->inspector->reportException($data->exception, !$data->unhandled);\n\n if ($data->unhandled) {\n $this->inspector->transaction()->setResult('error');\n if ($subject instanceof Agent) {\n $this->inspector->transaction()->setContext($this->getContext($subject));\n }\n }\n }\n\n public function getPrefix(string $event): string\n {\n return \\explode('-', $event)[0];\n }\n\n protected function getContext(Agent $agent): array\n {\n $mapTool = fn (ToolInterface $tool) => [\n $tool->getName() => [\n 'description' => $tool->getDescription(),\n 'properties' => \\array_map(\n fn (ToolPropertyInterface $property) => $property->jsonSerialize(),\n $tool->getProperties()\n )\n ]\n ];\n\n return [\n 'Agent' => [\n 'provider' => $agent->resolveProvider()::class,\n 'instructions' => $agent->resolveInstructions(),\n ],\n 'Tools' => \\array_map(\n fn (ToolInterface|ToolkitInterface $tool) => $tool instanceof ToolInterface\n ? $mapTool($tool)\n : [$tool::class => \\array_map($mapTool, $tool->tools())],\n $agent->getTools()\n ),\n //'Messages' => $agent->resolveChatHistory()->getMessages(),\n ];\n }\n\n public function getMessageId(Message $message): string\n {\n $content = $message->getContent();\n\n if (!\\is_string($content)) {\n $content = \\json_encode($content, \\JSON_UNESCAPED_UNICODE);\n }\n\n return \\md5($content.$message->getRole());\n }\n\n protected function getBaseClassName(string $class): string\n {\n return \\substr(\\strrchr($class, '\\\\'), 1);\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/MessageMapper.php", "mapping = [];\n\n foreach ($messages as $message) {\n match ($message::class) {\n Message::class,\n UserMessage::class,\n AssistantMessage::class => $this->mapMessage($message),\n ToolCallMessage::class => $this->mapToolCall($message),\n ToolCallResultMessage::class => $this->mapToolsResult($message),\n default => throw new ProviderException('Could not map message type '.$message::class),\n };\n }\n\n return $this->mapping;\n }\n\n protected function mapMessage(Message $message): void\n {\n $payload = [\n 'role' => $message->getRole(),\n 'parts' => [\n ['text' => $message->getContent()]\n ],\n ];\n\n $attachments = $message->getAttachments();\n\n foreach ($attachments as $attachment) {\n $payload['parts'][] = $this->mapAttachment($attachment);\n }\n\n $this->mapping[] = $payload;\n }\n\n protected function mapAttachment(Attachment $attachment): array\n {\n return match($attachment->contentType) {\n AttachmentContentType::URL => [\n 'file_data' => [\n 'file_uri' => $attachment->content,\n 'mime_type' => $attachment->mediaType,\n ],\n ],\n AttachmentContentType::BASE64 => [\n 'inline_data' => [\n 'data' => $attachment->content,\n 'mime_type' => $attachment->mediaType,\n ]\n ]\n };\n }\n\n protected function mapToolCall(ToolCallMessage $message): void\n {\n $this->mapping[] = [\n 'role' => MessageRole::MODEL->value,\n 'parts' => [\n ...\\array_map(fn (ToolInterface $tool): array => [\n 'functionCall' => [\n 'name' => $tool->getName(),\n 'args' => $tool->getInputs() !== [] ? $tool->getInputs() : new \\stdClass(),\n ]\n ], $message->getTools())\n ]\n ];\n }\n\n protected function mapToolsResult(ToolCallResultMessage $message): void\n {\n $this->mapping[] = [\n 'role' => MessageRole::USER->value,\n 'parts' => \\array_map(fn (ToolInterface $tool): array => [\n 'functionResponse' => [\n 'name' => $tool->getName(),\n 'response' => [\n 'name' => $tool->getName(),\n 'content' => $tool->getResult(),\n ],\n ],\n ], $message->getTools()),\n ];\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(array $messages): PromiseInterface\n {\n // Include the system prompt\n if (isset($this->system)) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'stream' => false,\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n if (! empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n return $this->client->postAsync('chat', ['json' => $json])\n ->then(function (ResponseInterface $response): Message {\n if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) {\n throw new ProviderException(\"Ollama chat error: {$response->getBody()->getContents()}\");\n }\n\n $response = \\json_decode($response->getBody()->getContents(), true);\n $message = $response['message'];\n\n if (\\array_key_exists('tool_calls', $message)) {\n $message = $this->createToolCallMessage($message);\n } else {\n $message = new AssistantMessage($message['content']);\n }\n\n if (\\array_key_exists('prompt_eval_count', $response) && \\array_key_exists('eval_count', $response)) {\n $message->setUsage(\n new Usage($response['prompt_eval_count'], $response['eval_count'])\n );\n }\n\n return $message;\n });\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/MessageMapper.php", "mapping = [];\n\n foreach ($messages as $message) {\n match ($message::class) {\n Message::class,\n UserMessage::class,\n AssistantMessage::class => $this->mapMessage($message),\n ToolCallMessage::class => $this->mapToolCall($message),\n ToolCallResultMessage::class => $this->mapToolsResult($message),\n default => throw new ProviderException('Could not map message type '.$message::class),\n };\n }\n\n return $this->mapping;\n }\n\n protected function mapMessage(Message $message): void\n {\n $payload = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $payload)) {\n unset($payload['usage']);\n }\n\n $attachments = $message->getAttachments();\n\n if (\\is_string($payload['content']) && $attachments) {\n $payload['content'] = [\n [\n 'type' => 'text',\n 'text' => $payload['content'],\n ],\n ];\n }\n\n foreach ($attachments as $attachment) {\n if ($attachment->type === AttachmentType::DOCUMENT) {\n throw new ProviderException('This provider does not support document attachments.');\n }\n\n $payload['content'][] = $this->mapAttachment($attachment);\n }\n\n unset($payload['attachments']);\n\n $this->mapping[] = $payload;\n }\n\n protected function mapAttachment(Attachment $attachment): array\n {\n return match($attachment->contentType) {\n AttachmentContentType::URL => [\n 'type' => 'image_url',\n 'image_url' => [\n 'url' => $attachment->content,\n ],\n ],\n AttachmentContentType::BASE64 => [\n 'type' => 'image_url',\n 'image_url' => [\n 'url' => 'data:'.$attachment->mediaType.';base64,'.$attachment->content,\n ],\n ]\n };\n }\n\n protected function mapToolCall(ToolCallMessage $message): void\n {\n $message = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $message)) {\n unset($message['usage']);\n }\n\n unset($message['type']);\n unset($message['tools']);\n\n $this->mapping[] = $message;\n }\n\n protected function mapToolsResult(ToolCallResultMessage $message): void\n {\n foreach ($message->getTools() as $tool) {\n $this->mapping[] = [\n 'role' => MessageRole::TOOL->value,\n 'tool_call_id' => $tool->getCallId(),\n 'content' => $tool->getResult()\n ];\n }\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/HandleStream.php", "system)) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'stream' => true,\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n $stream = $this->client->post('chat', [\n 'stream' => true,\n ...['json' => $json]\n ])->getBody();\n\n while (! $stream->eof()) {\n if (!$line = $this->parseNextJson($stream)) {\n continue;\n }\n\n // Last chunk will contain the usage information.\n if ($line['done'] === true) {\n yield \\json_encode(['usage' => [\n 'input_tokens' => $line['prompt_eval_count'],\n 'output_tokens' => $line['eval_count'],\n ]]);\n continue;\n }\n\n // Process tool calls\n if (isset($line['message']['tool_calls'])) {\n yield from $executeToolsCallback(\n $this->createToolCallMessage($line['message'])\n );\n }\n\n // Process regular content\n $content = $line['message']['content'] ?? '';\n\n yield $content;\n }\n }\n\n protected function parseNextJson(StreamInterface $stream): ?array\n {\n $line = $this->readLine($stream);\n\n if (empty($line)) {\n return null;\n }\n\n $json = \\json_decode((string) $line, true);\n\n if ($json['done']) {\n return null;\n }\n\n if (! isset($json['message']) || $json['message']['role'] !== 'assistant') {\n return null;\n }\n\n return $json;\n }\n\n protected function readLine(StreamInterface $stream): string\n {\n $buffer = '';\n\n while (! $stream->eof()) {\n if ('' === ($byte = $stream->read(1))) {\n return $buffer;\n }\n $buffer .= $byte;\n if ($byte === \"\\n\") {\n break;\n }\n }\n\n return $buffer;\n }\n}\n"], ["/neuron-ai/src/MCP/McpConnector.php", "client = new McpClient($config);\n }\n\n /**\n * @param string[] $tools\n */\n public function exclude(array $tools): McpConnector\n {\n $this->exclude = $tools;\n return $this;\n }\n\n /**\n * @param string[] $tools\n */\n public function only(array $tools): McpConnector\n {\n $this->only = $tools;\n return $this;\n }\n\n /**\n * Get the list of available Tools from the server.\n *\n * @return ToolInterface[]\n * @throws \\Exception\n */\n public function tools(): array\n {\n // Filter by the only and exclude preferences.\n $tools = \\array_filter(\n $this->client->listTools(),\n fn (array $tool): bool =>\n !\\in_array($tool['name'], $this->exclude) &&\n ($this->only === [] || \\in_array($tool['name'], $this->only)),\n );\n\n return \\array_map(fn (array $tool): ToolInterface => $this->createTool($tool), $tools);\n }\n\n /**\n * Convert the list of tools from the MCP server to Neuron compatible entities.\n * @throws ArrayPropertyException\n * @throws \\ReflectionException\n * @throws ToolException\n */\n protected function createTool(array $item): ToolInterface\n {\n $tool = Tool::make(\n name: $item['name'],\n description: $item['description'] ?? null\n )->setCallable(function (...$arguments) use ($item) {\n $response = \\call_user_func($this->client->callTool(...), $item['name'], $arguments);\n\n if (\\array_key_exists('error', $response)) {\n throw new McpException($response['error']['message']);\n }\n\n $response = $response['result']['content'][0];\n\n if ($response['type'] === 'text') {\n return $response['text'];\n }\n\n if ($response['type'] === 'image') {\n return $response;\n }\n\n throw new McpException(\"Tool response format not supported: {$response['type']}\");\n });\n\n foreach ($item['inputSchema']['properties'] as $name => $prop) {\n $required = \\in_array($name, $item['inputSchema']['required'] ?? []);\n\n $type = PropertyType::fromSchema($prop['type']);\n\n $property = match ($type) {\n PropertyType::ARRAY => $this->createArrayProperty($name, $required, $prop),\n PropertyType::OBJECT => $this->createObjectProperty($name, $required, $prop),\n default => $this->createToolProperty($name, $type, $required, $prop),\n };\n\n $tool->addProperty($property);\n }\n\n return $tool;\n }\n\n protected function createToolProperty(string $name, PropertyType $type, bool $required, array $prop): ToolProperty\n {\n return new ToolProperty(\n name: $name,\n type: $type,\n description: $prop['description'] ?? null,\n required: $required,\n enum: $prop['items']['enum'] ?? []\n );\n }\n\n /**\n * @throws ArrayPropertyException\n */\n protected function createArrayProperty(string $name, bool $required, array $prop): ArrayProperty\n {\n return new ArrayProperty(\n name: $name,\n description: $prop['description'] ?? null,\n required: $required,\n items: new ToolProperty(\n name: 'type',\n type: PropertyType::from($prop['items']['type'] ?? 'string'),\n )\n );\n }\n\n /**\n * @throws \\ReflectionException\n */\n protected function createObjectProperty(string $name, bool $required, array $prop): ObjectProperty\n {\n return new ObjectProperty(\n name: $name,\n description: $prop['description'] ?? null,\n required: $required,\n );\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(array $messages): PromiseInterface\n {\n // Include the system prompt\n if (isset($this->system)) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters\n ];\n\n // Attach tools\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n return $this->client->postAsync('chat/completions', ['json' => $json])\n ->then(function (ResponseInterface $response) {\n $result = \\json_decode($response->getBody()->getContents(), true);\n\n if ($result['choices'][0]['finish_reason'] === 'tool_calls') {\n $response = $this->createToolCallMessage($result['choices'][0]['message']);\n } else {\n $response = new AssistantMessage($result['choices'][0]['message']['content']);\n }\n\n if (\\array_key_exists('usage', $result)) {\n $response->setUsage(\n new Usage($result['usage']['prompt_tokens'], $result['usage']['completion_tokens'])\n );\n }\n\n return $response;\n });\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/PineconeVectorStore.php", "client = new Client([\n 'base_uri' => \\trim($this->indexUrl, '/').'/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Api-Key' => $key,\n 'X-Pinecone-API-Version' => $version,\n ]\n ]);\n }\n\n public function addDocument(Document $document): void\n {\n $this->addDocuments([$document]);\n }\n\n public function addDocuments(array $documents): void\n {\n $this->client->post(\"vectors/upsert\", [\n RequestOptions::JSON => [\n 'namespace' => $this->namespace,\n 'vectors' => \\array_map(fn (Document $document): array => [\n 'id' => $document->getId(),\n 'values' => $document->getEmbedding(),\n 'metadata' => [\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ],\n ], $documents)\n ]\n ]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->post(\"vectors/delete\", [\n RequestOptions::JSON => [\n 'namespace' => $this->namespace,\n 'filter' => [\n 'sourceType' => ['$eq' => $sourceType],\n 'sourceName' => ['$eq' => $sourceName],\n ]\n ]\n ]);\n }\n\n public function similaritySearch(array $embedding): iterable\n {\n $result = $this->client->post(\"query\", [\n RequestOptions::JSON => [\n 'namespace' => $this->namespace,\n 'includeMetadata' => true,\n 'includeValues' => true,\n 'vector' => $embedding,\n 'topK' => $this->topK,\n 'filters' => $this->filters, // Hybrid search\n ]\n ])->getBody()->getContents();\n\n $result = \\json_decode($result, true);\n\n return \\array_map(function (array $item): Document {\n $document = new Document();\n $document->id = $item['id'];\n $document->embedding = $item['values'];\n $document->content = $item['metadata']['content'];\n $document->sourceType = $item['metadata']['sourceType'];\n $document->sourceName = $item['metadata']['sourceName'];\n $document->score = $item['score'];\n\n foreach ($item['metadata'] as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $result['matches']);\n }\n\n public function withFilters(array $filters): self\n {\n $this->filters = $filters;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/MessageMapper.php", "mapping = [];\n\n foreach ($messages as $message) {\n match ($message::class) {\n Message::class,\n UserMessage::class,\n AssistantMessage::class => $this->mapMessage($message),\n ToolCallMessage::class => $this->mapToolCall($message),\n ToolCallResultMessage::class => $this->mapToolsResult($message),\n default => throw new ProviderException('Could not map message type '.$message::class),\n };\n }\n\n return $this->mapping;\n }\n\n public function mapMessage(Message $message): void\n {\n $payload = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $payload)) {\n unset($payload['usage']);\n }\n\n $attachments = $message->getAttachments();\n\n foreach ($attachments as $attachment) {\n if ($attachment->type === AttachmentType::DOCUMENT) {\n throw new ProviderException('This provider does not support document attachments.');\n }\n\n $payload['images'][] = $this->mapAttachment($attachment);\n }\n\n unset($payload['attachments']);\n\n $this->mapping[] = $payload;\n }\n\n protected function mapAttachment(Attachment $attachment): string\n {\n return match ($attachment->contentType) {\n AttachmentContentType::BASE64 => $attachment->content,\n AttachmentContentType::URL => throw new ProviderException('Ollama support only base64 attachment type.'),\n };\n }\n\n protected function mapToolCall(ToolCallMessage $message): void\n {\n $message = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $message)) {\n unset($message['usage']);\n }\n\n if (\\array_key_exists('tool_calls', $message)) {\n $message['tool_calls'] = \\array_map(function (array $toolCall) {\n if (empty($toolCall['function']['arguments'])) {\n $toolCall['function']['arguments'] = new \\stdClass();\n }\n return $toolCall;\n }, $message['tool_calls']);\n }\n\n unset($message['type']);\n unset($message['tools']);\n\n $this->mapping[] = $message;\n }\n\n public function mapToolsResult(ToolCallResultMessage $message): void\n {\n foreach ($message->getTools() as $tool) {\n $this->mapping[] = [\n 'role' => MessageRole::TOOL->value,\n 'content' => $tool->getResult()\n ];\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Tavily/TavilySearchTool.php", " 'basic',\n 'chunks_per_source' => 3,\n 'max_results' => 1,\n ];\n\n /**\n * @param string $key Tavily API key.\n * @param array $topics Explicit the topics you want to force the Agent to perform web search.\n */\n public function __construct(\n protected string $key,\n protected array $topics = [],\n ) {\n\n parent::__construct(\n 'web_search',\n 'Use this tool to search the web for additional information '.\n ($this->topics === [] ? '' : 'about '.\\implode(', ', $this->topics).', or ').\n 'if the question is outside the scope of the context you have.'\n );\n\n }\n\n protected function properties(): array\n {\n return [\n new ToolProperty(\n 'search_query',\n PropertyType::STRING,\n 'The search query to perform web search.',\n true\n ),\n new ToolProperty(\n 'topic',\n PropertyType::STRING,\n 'Explicit the topic you want to perform the web search on.',\n false,\n ['general', 'news']\n ),\n new ToolProperty(\n 'time_range',\n PropertyType::STRING,\n '',\n false,\n ['day, week, month, year']\n ),\n new ToolProperty(\n 'days',\n PropertyType::INTEGER,\n 'Filter search results for a certain range of days up to today.',\n false,\n )\n ];\n }\n\n protected function getClient(): Client\n {\n return $this->client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function __invoke(\n string $search_query,\n ?string $topic = null,\n ?string $time_range = null,\n ?int $days = null,\n ): array {\n $topic ??= 'general';\n $time_range ??= 'day';\n $days ??= 7;\n\n $result = $this->getClient()->post('search', [\n RequestOptions::JSON => \\array_merge(\n ['topic' => $topic, 'time_range' => $time_range, 'days' => $days],\n $this->options,\n [\n 'query' => $search_query,\n ]\n )\n ])->getBody()->getContents();\n\n $result = \\json_decode($result, true);\n\n return [\n 'answer' => $result['answer'],\n 'results' => \\array_map(fn (array $item): array => [\n 'title' => $item['title'],\n 'url' => $item['url'],\n 'content' => $item['content'],\n ], $result['results']),\n ];\n }\n\n public function withOptions(array $options): self\n {\n $this->options = $options;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(array $messages): PromiseInterface\n {\n $json = [\n 'contents' => $this->messageMapper()->map($messages),\n ...$this->parameters\n ];\n\n if (isset($this->system)) {\n $json['system_instruction'] = [\n 'parts' => [\n ['text' => $this->system]\n ]\n ];\n }\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n return $this->client->postAsync(\\trim($this->baseUri, '/').\"/{$this->model}:generateContent\", [RequestOptions::JSON => $json])\n ->then(function (ResponseInterface $response): Message {\n $result = \\json_decode($response->getBody()->getContents(), true);\n\n $content = $result['candidates'][0]['content'];\n\n if (!isset($content['parts']) && isset($result['candidates'][0]['finishReason']) && $result['candidates'][0]['finishReason'] === 'MAX_TOKENS') {\n return new Message(MessageRole::from($content['role']), '');\n }\n\n $parts = $content['parts'];\n\n if (\\array_key_exists('functionCall', $parts[0]) && !empty($parts[0]['functionCall'])) {\n $response = $this->createToolCallMessage($content);\n } else {\n $response = new Message(MessageRole::from($content['role']), $parts[0]['text'] ?? '');\n }\n\n // Attach the usage for the current interaction\n if (\\array_key_exists('usageMetadata', $result)) {\n $response->setUsage(\n new Usage(\n $result['usageMetadata']['promptTokenCount'],\n $result['usageMetadata']['candidatesTokenCount'] ?? 0\n )\n );\n }\n\n return $response;\n });\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/JsonSchema.php", "processedClasses = [];\n\n // Generate the main schema\n return [\n ...$this->generateClassSchema($class),\n 'additionalProperties' => false,\n ];\n }\n\n /**\n * Generate schema for a class\n *\n * @param string $class Class name\n * @return array The schema\n * @throws ReflectionException\n */\n private function generateClassSchema(string $class): array\n {\n $reflection = new ReflectionClass($class);\n\n // Check for circular reference\n if (\\in_array($class, $this->processedClasses)) {\n // For circular references, return a simple object schema to break the cycle\n return ['type' => 'object'];\n }\n\n $this->processedClasses[] = $class;\n\n // Handle enum types differently\n if ($reflection->isEnum()) {\n $result = $this->processEnum(new ReflectionEnum($class));\n // Remove the class from the processed list after processing\n \\array_pop($this->processedClasses);\n return $result;\n }\n\n // Create a basic object schema\n $schema = [\n 'type' => 'object',\n 'properties' => [],\n ];\n\n $requiredProperties = [];\n\n // Process all public properties\n $properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);\n\n // Process each property\n foreach ($properties as $property) {\n $propertyName = $property->getName();\n\n $schema['properties'][$propertyName] = $this->processProperty($property);\n\n $attribute = $this->getPropertyAttribute($property);\n if ($attribute instanceof SchemaProperty && $attribute->required !== null) {\n if ($attribute->required) {\n $requiredProperties[] = $propertyName;\n }\n } else {\n // If the attribute is not available,\n // use the default logic for required properties\n $type = $property->getType();\n\n $isNullable = $type ? $type->allowsNull() : true;\n\n if (!$isNullable && !$property->hasDefaultValue()) {\n $requiredProperties[] = $propertyName;\n }\n }\n }\n\n // Add required properties\n if ($requiredProperties !== []) {\n $schema['required'] = $requiredProperties;\n }\n\n // Remove the class from the processed list after processing\n \\array_pop($this->processedClasses);\n\n return $schema;\n }\n\n /**\n * Process a single property to generate its schema\n *\n * @return array Property schema\n * @throws ReflectionException\n */\n private function processProperty(ReflectionProperty $property): array\n {\n $schema = [];\n\n // Process Property attribute if present\n $attribute = $this->getPropertyAttribute($property);\n if ($attribute instanceof SchemaProperty) {\n if ($attribute->title !== null) {\n $schema['title'] = $attribute->title;\n }\n\n if ($attribute->description !== null) {\n $schema['description'] = $attribute->description;\n }\n }\n\n /** @var ?ReflectionNamedType $type */\n $type = $property->getType();\n $typeName = $type?->getName();\n\n // Handle default values\n if ($property->hasDefaultValue()) {\n $schema['default'] = $property->getDefaultValue();\n }\n\n // Process different types\n if ($typeName === 'array') {\n $schema['type'] = 'array';\n\n // Parse PHPDoc for the array item type\n $docComment = $property->getDocComment();\n if ($docComment) {\n // Extract type from both \"@var \\App\\Type[]\" and \"@var array<\\App\\Type>\"\n \\preg_match('/@var\\s+(?:([a-zA-Z0-9_\\\\\\\\]+)\\[\\]|array<([a-zA-Z0-9_\\\\\\\\]+)>)/', $docComment, $matches);\n\n if (isset($matches[1]) || isset($matches[2])) {\n $itemType = empty($matches[1]) ? ((isset($matches[2]) && $matches[2] !== '0') ? $matches[2] : null) : ($matches[1]);\n\n // Handle class type for array items\n if (\\class_exists($itemType) || \\enum_exists($itemType)) {\n $schema['items'] = $this->generateClassSchema($itemType);\n } else {\n // Basic type\n $schema['items'] = $this->getBasicTypeSchema($itemType);\n }\n } else {\n // Default to string if no specific type found\n $schema['items'] = ['type' => 'string'];\n }\n } else {\n // Default to string if no doc comment\n $schema['items'] = ['type' => 'string'];\n }\n }\n // Handle enum types\n elseif ($typeName && \\enum_exists($typeName)) {\n $enumReflection = new ReflectionEnum($typeName);\n $schema = \\array_merge($schema, $this->processEnum($enumReflection));\n }\n // Handle class types\n elseif ($typeName && \\class_exists($typeName)) {\n $classSchema = $this->generateClassSchema($typeName);\n $schema = \\array_merge($schema, $classSchema);\n }\n // Handle basic types\n elseif ($typeName) {\n $typeSchema = $this->getBasicTypeSchema($typeName);\n $schema = \\array_merge($schema, $typeSchema);\n } else {\n // Default to string if no type hint\n $schema['type'] = 'string';\n }\n\n // Handle nullable types - for basic types only\n if ($type && $type->allowsNull() && isset($schema['type']) && !isset($schema['$ref']) && !isset($schema['allOf'])) {\n if (\\is_array($schema['type'])) {\n if (!\\in_array('null', $schema['type'])) {\n $schema['type'][] = 'null';\n }\n } else {\n $schema['type'] = [$schema['type'], 'null'];\n }\n }\n\n return $schema;\n }\n\n /**\n * Process an enum to generate its schema\n */\n private function processEnum(ReflectionEnum $enum): array\n {\n // Create enum schema\n $schema = [\n 'type' => 'string',\n 'enum' => [],\n ];\n\n // Extract enum values\n foreach ($enum->getCases() as $case) {\n if ($enum->isBacked()) {\n /** @var ReflectionEnumBackedCase $case */\n // For backed enums, use the backing value\n $schema['enum'][] = $case->getBackingValue();\n } else {\n // For non-backed enums, use case name\n $schema['enum'][] = $case->getName();\n }\n }\n\n return $schema;\n }\n\n /**\n * Get the Property attribute if it exists on a property\n */\n private function getPropertyAttribute(ReflectionProperty $property): ?SchemaProperty\n {\n $attributes = $property->getAttributes(SchemaProperty::class);\n if ($attributes !== []) {\n return $attributes[0]->newInstance();\n }\n return null;\n }\n\n /**\n * Get schema for a basic PHP type\n *\n * @param string $type PHP type name\n * @return array Schema for the type\n * @throws ReflectionException\n */\n private function getBasicTypeSchema(string $type): array\n {\n switch ($type) {\n case 'string':\n return ['type' => 'string'];\n\n case 'int':\n case 'integer':\n return ['type' => 'integer'];\n\n case 'float':\n case 'double':\n return ['type' => 'number'];\n\n case 'bool':\n case 'boolean':\n return ['type' => 'boolean'];\n\n case 'array':\n return [\n 'type' => 'array',\n 'items' => ['type' => 'string'],\n ];\n\n default:\n // Check if it's a class or enum\n if (\\class_exists($type)) {\n return $this->generateClassSchema($type);\n }\n // Check if it's a class or enum\n if (\\enum_exists($type)) {\n return $this->processEnum(new ReflectionEnum($type));\n }\n\n // Default to string for unknown types\n return ['type' => 'string'];\n }\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/CohereRerankerPostProcessor.php", "client ?? $this->client = new Client([\n 'base_uri' => 'https://api.cohere.com/v2/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer '.$this->key,\n ],\n ]);\n }\n\n public function process(Message $question, array $documents): array\n {\n $response = $this->getClient()->post('rerank', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'query' => $question->getContent(),\n 'top_n' => $this->topN,\n 'documents' => \\array_map(fn (Document $document): string => $document->getContent(), $documents),\n ],\n ])->getBody()->getContents();\n\n $result = \\json_decode($response, true);\n\n return \\array_map(function (array $item) use ($documents): Document {\n $document = $documents[$item['index']];\n $document->setScore($item['relevance_score']);\n return $document;\n }, $result['results']);\n }\n\n public function setClient(Client $client): PostProcessorInterface\n {\n $this->client = $client;\n return $this;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/QdrantVectorStore.php", "client = new Client([\n 'base_uri' => \\trim($this->collectionUrl, '/').'/',\n 'headers' => [\n 'Content-Type' => 'application/json',\n 'api-key' => $this->key,\n ]\n ]);\n }\n\n public function addDocument(Document $document): void\n {\n $this->client->put('points', [\n RequestOptions::JSON => [\n 'points' => [\n [\n 'id' => $document->getId(),\n 'payload' => [\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n 'metadata' => $document->metadata,\n ],\n 'vector' => $document->getEmbedding(),\n ]\n ]\n ]\n ]);\n }\n\n /**\n * Bulk save documents.\n *\n * @param Document[] $documents\n * @throws GuzzleException\n */\n public function addDocuments(array $documents): void\n {\n $points = \\array_map(fn (Document $document): array => [\n 'id' => $document->getId(),\n 'payload' => [\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ],\n 'vector' => $document->getEmbedding(),\n ], $documents);\n\n $this->client->put('points', [\n RequestOptions::JSON => ['points' => $points]\n ]);\n }\n\n /**\n * @throws GuzzleException\n */\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->post('points/delete', [\n RequestOptions::JSON => [\n 'wait' => true,\n 'filter' => [\n 'must' => [\n [\n 'key' => 'sourceType',\n 'match' => [\n 'value' => $sourceType,\n ]\n ],\n [\n 'key' => 'sourceName',\n 'match' => [\n 'value' => $sourceName,\n ]\n ]\n ]\n ]\n ]\n ]);\n }\n\n public function similaritySearch(array $embedding): iterable\n {\n $response = $this->client->post('points/search', [\n RequestOptions::JSON => [\n 'vector' => $embedding,\n 'limit' => $this->topK,\n 'with_payload' => true,\n 'with_vector' => true,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return \\array_map(function (array $item): Document {\n $document = new Document($item['payload']['content']);\n $document->id = $item['id'];\n $document->embedding = $item['vector'];\n $document->sourceType = $item['payload']['sourceType'];\n $document->sourceName = $item['payload']['sourceName'];\n $document->score = $item['score'];\n\n foreach ($item['payload'] as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName', 'score', 'embedding', 'id'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $response['result']);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Tavily/TavilyExtractTool.php", "getClient()->post('extract', [\n RequestOptions::JSON => \\array_merge(\n $this->options,\n ['urls' => [$url]]\n )\n ])->getBody()->getContents();\n\n $result = \\json_decode($result, true);\n\n return $result['results'][0];\n }\n\n\n protected function getClient(): Client\n {\n return $this->client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function withOptions(array $options): self\n {\n $this->options = $options;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/AWS/SESTool.php", "validateRecipients($to);\n\n $result = $this->sesClient->sendEmail([\n 'Source' => $this->fromEmail,\n 'Destination' => $this->buildDestinations($to, $cc, $bcc),\n 'Message' => $this->buildMessage($subject, $body),\n ]);\n\n return [\n 'success' => true,\n 'message_id' => $result['MessageId'] ?? null,\n 'status' => 'sent',\n 'recipients_count' => \\count($to),\n 'aws_request_id' => $result['@metadata']['requestId'] ?? null\n ];\n } catch (\\Exception $e) {\n return [\n 'success' => false,\n 'error' => $e->getMessage(),\n 'error_type' => $e::class,\n 'status' => 'failed'\n ];\n }\n }\n\n /**\n * @param array $to\n * @throws ToolException\n */\n protected function validateRecipients(array $to): void\n {\n foreach ($to as $recipient) {\n if (\\filter_var($recipient, \\FILTER_VALIDATE_EMAIL) === false) {\n throw new ToolException('Invalid email address: ' . $recipient . '.');\n }\n }\n }\n\n protected function buildDestinations(array $to, ?array $cc = null, ?array $bcc = null): array\n {\n $destinations = [\n 'ToAddresses' => $to,\n ];\n\n if ($cc !== null && $cc !== []) {\n $destinations['CcAddresses'] = $cc;\n }\n\n if ($bcc !== null && $bcc !== []) {\n $destinations['BccAddresses'] = $bcc;\n }\n\n return $destinations;\n }\n\n protected function buildMessage(string $subject, string $body): array\n {\n return [\n 'Subject' => [\n 'Data' => $subject,\n 'Charset' => 'UTF-8'\n ],\n 'Body' => [\n 'Html' => [\n 'Data' => $body,\n 'Charset' => 'UTF-8'\n ],\n 'Text' => [\n 'Data' => \\strip_tags($body),\n 'Charset' => 'UTF-8'\n ]\n ]\n ];\n }\n}\n"], ["/neuron-ai/src/Providers/HandleWithTools.php", "\n */\n protected array $tools = [];\n\n public function setTools(array $tools): AIProviderInterface\n {\n $this->tools = $tools;\n return $this;\n }\n\n public function findTool(string $name): ToolInterface\n {\n foreach ($this->tools as $tool) {\n if ($tool->getName() === $name) {\n // We return a copy to allow multiple call to the same tool.\n return clone $tool;\n }\n }\n\n throw new ProviderException(\n \"It seems the model is asking for a non-existing tool: {$name}. You could try writing more verbose tool descriptions and prompts to help the model in the task.\"\n );\n }\n}\n"], ["/neuron-ai/src/MCP/McpClient.php", "transport = new StdioTransport($config);\n $this->transport->connect();\n $this->initialize();\n } else {\n // todo: implement support for SSE with URL config property\n throw new McpException('Transport not supported!');\n }\n }\n\n protected function initialize(): void\n {\n $request = [\n \"jsonrpc\" => \"2.0\",\n \"id\" => ++$this->requestId,\n \"method\" => \"initialize\",\n \"params\" => [\n 'protocolVersion' => '2024-11-05',\n 'capabilities' => (object)[\n 'sampling' => new \\stdClass(),\n ],\n 'clientInfo' => (object)[\n 'name' => 'neuron-ai',\n 'version' => '1.0.0',\n ],\n ],\n ];\n $this->transport->send($request);\n $response = $this->transport->receive();\n\n if ($response['id'] !== $this->requestId) {\n throw new McpException('Invalid response ID');\n }\n\n $request = [\n \"jsonrpc\" => \"2.0\",\n \"method\" => \"notifications/initialized\",\n ];\n $this->transport->send($request);\n }\n\n /**\n * List all available tools from the MCP server\n *\n * @throws \\Exception\n */\n public function listTools(): array\n {\n $tools = [];\n\n do {\n $request = [\n \"jsonrpc\" => \"2.0\",\n \"id\" => ++$this->requestId,\n \"method\" => \"tools/list\",\n ];\n\n // Eventually add pagination\n if (isset($response['result']['nextCursor'])) {\n $request['params'] = ['cursor' => $response['result']['nextCursor']];\n }\n\n $this->transport->send($request);\n $response = $this->transport->receive();\n\n if ($response['id'] !== $this->requestId) {\n throw new McpException('Invalid response ID');\n }\n\n $tools = \\array_merge($tools, $response['result']['tools']);\n } while (isset($response['result']['nextCursor']));\n\n return $tools;\n }\n\n /**\n * Call a tool on the MCP server\n *\n * @throws \\Exception\n */\n public function callTool(string $toolName, array $arguments = []): array\n {\n $request = [\n \"jsonrpc\" => \"2.0\",\n \"id\" => ++$this->requestId,\n \"method\" => \"tools/call\",\n \"params\" => [\n \"name\" => $toolName,\n \"arguments\" => $arguments\n ]\n ];\n\n $this->transport->send($request);\n return $this->transport->receive();\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/JinaRerankerPostProcessor.php", "client ?? $this->client = new Client([\n 'base_uri' => 'https://api.jina.ai/v1/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer '.$this->key,\n ],\n ]);\n }\n\n public function process(Message $question, array $documents): array\n {\n $response = $this->getClient()->post('rerank', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'query' => $question->getContent(),\n 'top_n' => $this->topN,\n 'documents' => \\array_map(fn (Document $document): array => ['text' => $document->getContent()], $documents),\n 'return_documents' => false,\n ],\n ])->getBody()->getContents();\n\n $result = \\json_decode($response, true);\n\n return \\array_map(function (array $item) use ($documents): Document {\n $document = $documents[$item['index']];\n $document->setScore($item['relevance_score']);\n return $document;\n }, $result['results']);\n }\n\n public function setClient(Client $client): PostProcessorInterface\n {\n $this->client = $client;\n return $this;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/MeilisearchVectorStore.php", "client = new Client([\n 'base_uri' => \\trim($host, '/').'/indexes/'.$indexUid.'/',\n 'headers' => [\n 'Content-Type' => 'application/json',\n ...(\\is_null($key) ? [] : ['Authorization' => \"Bearer {$key}\"])\n ]\n ]);\n\n try {\n $this->client->get('');\n } catch (\\Exception) {\n throw new VectorStoreException(\"Index {$indexUid} doesn't exists. Remember to attach a custom embedder to the index in order to process vectors.\");\n }\n }\n\n public function addDocument(Document $document): void\n {\n $this->addDocuments([$document]);\n }\n\n public function addDocuments(array $documents): void\n {\n $this->client->put('documents', [\n RequestOptions::JSON => \\array_map(fn (Document $document) => [\n 'id' => $document->getId(),\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n '_vectors' => [\n 'default' => [\n 'embeddings' => $document->getEmbedding(),\n 'regenerate' => false,\n ],\n ]\n ], $documents),\n ]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->post('documents/delete', [\n RequestOptions::JSON => [\n 'filter' => \"sourceType = {$sourceType} AND sourceName = {$sourceName}\",\n ]\n ]);\n }\n\n public function similaritySearch(array $embedding): iterable\n {\n $response = $this->client->post('search', [\n RequestOptions::JSON => [\n 'vector' => $embedding,\n 'limit' => \\min($this->topK, 20),\n 'retrieveVectors' => true,\n 'showRankingScore' => true,\n 'hybrid' => [\n 'semanticRatio' => 1.0,\n 'embedder' => $this->embedder,\n ],\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return \\array_map(function (array $item): Document {\n $document = new Document($item['content']);\n $document->id = $item['id'] ?? \\uniqid();\n $document->sourceType = $item['sourceType'] ?? null;\n $document->sourceName = $item['sourceName'] ?? null;\n $document->embedding = $item['_vectors']['default']['embeddings'];\n $document->score = $item['_rankingScore'];\n\n foreach ($item as $name => $value) {\n if (!\\in_array($name, ['_vectors', '_rankingScore', 'content', 'sourceType', 'sourceName', 'score', 'embedding', 'id'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $response['hits']);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Riza/RizaFunctionExecutor.php", "client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json; charset=utf-8',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function __invoke(\n string $code,\n array $input = [],\n array $env = [],\n ): mixed {\n $result = $this->getClient()->post('execute-function', [\n RequestOptions::JSON => [\n 'language' => $this->language,\n 'code' => $code,\n 'input' => $input,\n 'env' => $env,\n ]\n ])->getBody()->getContents();\n\n return \\json_decode($result, true);\n }\n}\n"], ["/neuron-ai/src/Chat/History/TokenCounter.php", "getContent();\n if (\\is_string($content)) {\n $messageChars += \\strlen($content);\n } elseif ($content !== null) {\n // For arrays and other types, use JSON representation\n $messageChars += \\strlen(\\json_encode($content));\n }\n\n // Handle tool calls for AssistantMessage (excluding array content format)\n if ($message instanceof ToolCallMessage && !\\is_array($content)) {\n $tools = $message->getTools();\n if ($tools !== []) {\n // Convert tools to their JSON representation for counting\n $toolsContent = \\json_encode(\\array_map(fn (ToolInterface $tool): array => $tool->jsonSerialize(), $tools));\n $messageChars += \\strlen($toolsContent);\n }\n }\n\n // Handle tool call results\n if ($message instanceof ToolCallResultMessage) {\n $tools = $message->getTools();\n // Add tool IDs to the count\n foreach ($tools as $tool) {\n $serialized = $tool->jsonSerialize();\n // Assuming tool IDs are in the serialized data\n if (isset($serialized['id'])) {\n $messageChars += \\strlen($serialized['id']);\n }\n }\n }\n\n // Count role characters\n $messageChars += \\strlen($message->getRole());\n\n // Round up per message to ensure individual counts add up correctly\n $tokenCount += \\ceil($messageChars / $this->charsPerToken);\n\n // Add extra tokens per message\n $tokenCount += $this->extraTokensPerMessage;\n }\n\n // Final round up in case extraTokensPerMessage is a float\n return (int) \\ceil($tokenCount);\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/ElasticsearchVectorStore.php", "client->indices()->exists(['index' => $this->index]);\n $existStatusCode = $existResponse->getStatusCode();\n\n if ($existStatusCode === 200) {\n // Map vector embeddings dimension on the fly adding a document.\n $this->mapVectorDimension(\\count($document->getEmbedding()));\n return;\n }\n\n $properties = [\n 'content' => [\n 'type' => 'text',\n ],\n 'sourceType' => [\n 'type' => 'keyword',\n ],\n 'sourceName' => [\n 'type' => 'keyword',\n ]\n ];\n\n // Map metadata\n foreach (\\array_keys($document->metadata) as $name) {\n $properties[$name] = [\n 'type' => 'keyword',\n ];\n }\n\n $this->client->indices()->create([\n 'index' => $this->index,\n 'body' => [\n 'mappings' => [\n 'properties' => $properties,\n ],\n ],\n ]);\n }\n\n /**\n * @throws \\Exception\n */\n public function addDocument(Document $document): void\n {\n if ($document->embedding === []) {\n throw new \\Exception('Document embedding must be set before adding a document');\n }\n\n $this->checkIndexStatus($document);\n\n $this->client->index([\n 'index' => $this->index,\n 'body' => [\n 'embedding' => $document->getEmbedding(),\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ],\n ]);\n\n $this->client->indices()->refresh(['index' => $this->index]);\n }\n\n /**\n * @param Document[] $documents\n *\n * @throws \\Exception\n */\n public function addDocuments(array $documents): void\n {\n if ($documents === []) {\n return;\n }\n\n if (empty($documents[0]->getEmbedding())) {\n throw new \\Exception('Document embedding must be set before adding a document');\n }\n\n $this->checkIndexStatus($documents[0]);\n\n /*\n * Generate a bulk payload\n */\n $params = ['body' => []];\n foreach ($documents as $document) {\n $params['body'][] = [\n 'index' => [\n '_index' => $this->index,\n ],\n ];\n $params['body'][] = [\n 'embedding' => $document->getEmbedding(),\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ];\n }\n $this->client->bulk($params);\n $this->client->indices()->refresh(['index' => $this->index]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->deleteByQuery([\n 'index' => $this->index,\n 'q' => \"sourceType:{$sourceType} AND sourceName:{$sourceName}\",\n 'body' => []\n ]);\n $this->client->indices()->refresh(['index' => $this->index]);\n }\n\n /**\n * {@inheritDoc}\n *\n * num_candidates are used to tune approximate kNN for speed or accuracy (see : https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy)\n * @return Document[]\n * @throws ClientResponseException\n * @throws ServerResponseException\n */\n public function similaritySearch(array $embedding): array\n {\n $searchParams = [\n 'index' => $this->index,\n 'body' => [\n 'knn' => [\n 'field' => 'embedding',\n 'query_vector' => $embedding,\n 'k' => $this->topK,\n 'num_candidates' => \\max(50, $this->topK * 4),\n ],\n 'sort' => [\n '_score' => [\n 'order' => 'desc',\n ],\n ],\n ],\n ];\n\n // Hybrid search\n if ($this->filters !== []) {\n $searchParams['body']['knn']['filter'] = $this->filters;\n }\n\n $response = $this->client->search($searchParams);\n\n return \\array_map(function (array $item): Document {\n $document = new Document($item['_source']['content']);\n //$document->embedding = $item['_source']['embedding']; // avoid carrying large data\n $document->sourceType = $item['_source']['sourceType'];\n $document->sourceName = $item['_source']['sourceName'];\n $document->score = $item['_score'];\n\n foreach ($item['_source'] as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName', 'score', 'embedding', 'id'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $response['hits']['hits']);\n }\n\n /**\n * Map vector embeddings dimension on the fly.\n */\n private function mapVectorDimension(int $dimension): void\n {\n if ($this->vectorDimSet) {\n return;\n }\n\n $response = $this->client->indices()->getFieldMapping([\n 'index' => $this->index,\n 'fields' => 'embedding',\n ]);\n\n $mappings = $response[$this->index]['mappings'];\n if (\n \\array_key_exists('embedding', $mappings)\n && $mappings['embedding']['mapping']['embedding']['dims'] === $dimension\n ) {\n return;\n }\n\n $this->client->indices()->putMapping([\n 'index' => $this->index,\n 'body' => [\n 'properties' => [\n 'embedding' => [\n 'type' => 'dense_vector',\n //'element_type' => 'float', // it's float by default\n 'dims' => $dimension,\n 'index' => true,\n 'similarity' => 'cosine',\n ],\n ],\n ],\n ]);\n\n $this->vectorDimSet = true;\n }\n\n public function withFilters(array $filters): self\n {\n $this->filters = $filters;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Tavily/TavilyCrawlTool.php", " false,\n 'allow_external' => false\n ];\n\n /**\n * @param string $key Tavily API key.\n */\n public function __construct(\n protected string $key,\n ) {\n parent::__construct(\n 'url_crawl',\n 'Get the entire website in markdown format.'\n );\n }\n\n protected function properties(): array\n {\n return [\n new ToolProperty(\n 'url',\n PropertyType::STRING,\n 'The URL to crawl.',\n true\n ),\n ];\n }\n\n public function __invoke(string $url): array\n {\n if (!\\filter_var($url, \\FILTER_VALIDATE_URL)) {\n throw new ToolException('Invalid URL.');\n }\n\n $result = $this->getClient()->post('crawl', [\n RequestOptions::JSON => \\array_merge(\n $this->options,\n ['url' => $url]\n )\n ])->getBody()->getContents();\n\n return \\json_decode($result, true);\n }\n\n\n protected function getClient(): Client\n {\n return $this->client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function withOptions(array $options): self\n {\n $this->options = $options;\n return $this;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/TypesenseVectorStore.php", "client->collections[$this->collection]->retrieve();\n $this->checkVectorDimension(\\count($document->getEmbedding()));\n return;\n } catch (ObjectNotFound) {\n $fields = [\n [\n 'name' => 'content',\n 'type' => 'string',\n ],\n [\n 'name' => 'sourceType',\n 'type' => 'string',\n 'facet' => true,\n ],\n [\n 'name' => 'sourceName',\n 'type' => 'string',\n 'facet' => true,\n ],\n [\n 'name' => 'embedding',\n 'type' => 'float[]',\n 'num_dim' => $this->vectorDimension,\n ],\n ];\n\n // Map custom fields\n foreach ($document->metadata as $name => $value) {\n $fields[] = [\n 'name' => $name,\n 'type' => \\gettype($value),\n 'facet' => true,\n ];\n }\n\n $this->client->collections->create([\n 'name' => $this->collection,\n 'fields' => $fields,\n ]);\n }\n }\n\n public function addDocument(Document $document): void\n {\n if ($document->getEmbedding() === []) {\n throw new \\Exception('document embedding must be set before adding a document');\n }\n\n $this->checkIndexStatus($document);\n\n $this->client->collections[$this->collection]->documents->create([\n 'id' => $document->getId(), // Unique ID is required\n 'content' => $document->getContent(),\n 'embedding' => $document->getEmbedding(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->collections[$this->collection]->documents->delete([\n \"filter_by\" => \"sourceType:={$sourceType} && sourceName:={$sourceName}\",\n ]);\n }\n\n /**\n * Bulk save.\n *\n * @param Document[] $documents\n * @throws Exception\n * @throws \\JsonException\n * @throws TypesenseClientError\n */\n public function addDocuments(array $documents): void\n {\n if ($documents === []) {\n return;\n }\n\n if (empty($documents[0]->getEmbedding())) {\n throw new \\Exception('document embedding must be set before adding a document');\n }\n\n $this->checkIndexStatus($documents[0]);\n\n $lines = [];\n foreach ($documents as $document) {\n $lines[] = \\json_encode([\n 'id' => $document->getId(), // Unique ID is required\n 'embedding' => $document->getEmbedding(),\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ]);\n }\n\n $ndjson = \\implode(\"\\n\", $lines);\n\n $this->client->collections[$this->collection]->documents->import($ndjson);\n }\n\n public function similaritySearch(array $embedding): array\n {\n $params = [\n 'collection' => $this->collection,\n 'q' => '*',\n 'vector_query' => 'embedding:(' . \\json_encode($embedding) . ')',\n 'exclude_fields' => 'embedding',\n 'per_page' => $this->topK,\n 'num_candidates' => \\max(50, \\intval($this->topK) * 4),\n ];\n\n $searchRequests = ['searches' => [$params]];\n\n $response = $this->client->multiSearch->perform($searchRequests);\n return \\array_map(function (array $hit): Document {\n $item = $hit['document'];\n $document = new Document($item['content']);\n //$document->embedding = $item['embedding']; // avoid carrying large data\n $document->sourceType = $item['sourceType'];\n $document->sourceName = $item['sourceName'];\n $document->score = VectorSimilarity::similarityFromDistance($hit['vector_distance']);\n\n foreach ($item as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName', 'score', 'embedding', 'id', 'vector_distance'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $response['results'][0]['hits']);\n }\n\n private function checkVectorDimension(int $dimension): void\n {\n $schema = $this->client->collections[$this->collection]->retrieve();\n\n $embeddingField = null;\n\n foreach ($schema['fields'] as $field) {\n if ($field['name'] === 'embedding') {\n $embeddingField = $field;\n break;\n }\n }\n\n if (\n \\array_key_exists('num_dim', $embeddingField)\n && $embeddingField['num_dim'] === $dimension\n ) {\n return;\n }\n\n throw new \\Exception(\n \"Vector embeddings dimension {$dimension} must be the same as the initial setup {$this->vectorDimension} - \".\n \\json_encode($embeddingField)\n );\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/VoyageEmbeddingsProvider.php", "client = new Client([\n 'base_uri' => $this->baseUri,\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer ' . $key,\n ],\n ]);\n }\n\n public function embedText(string $text): array\n {\n $response = $this->client->post('', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'input' => $text,\n 'output_dimension' => $this->dimensions,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['data'][0]['embedding'];\n }\n\n public function embedDocuments(array $documents): array\n {\n $chunks = \\array_chunk($documents, 100);\n\n foreach ($chunks as $chunk) {\n $response = $this->client->post('', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'input' => \\array_map(fn (Document $document): string => $document->getContent(), $chunk),\n 'output_dimension' => $this->dimensions,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n foreach ($response['data'] as $index => $item) {\n $chunk[$index]->embedding = $item['embedding'];\n }\n }\n\n return \\array_merge(...$chunks);\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/GeminiEmbeddingsProvider.php", "client = new Client([\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'x-goog-api-key' => $this->key,\n ]\n ]);\n }\n\n public function embedText(string $text): array\n {\n $response = $this->client->post(\\trim($this->baseUri, '/').\"/{$this->model}:embedContent\", [\n RequestOptions::JSON => [\n 'content' => [\n 'parts' => [['text' => $text]]\n ],\n ...($this->config !== [] ? ['embedding_config' => $this->config] : []),\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['embedding']['values'];\n }\n}\n"], ["/neuron-ai/src/RAG/PreProcessor/QueryTransformationPreProcessor.php", "prepareMessage($question);\n\n return $this->provider\n ->systemPrompt($this->getSystemPrompt())\n ->chat([$preparedMessage]);\n }\n\n public function getSystemPrompt(): string\n {\n return $this->customPrompt ?? match ($this->transformation) {\n QueryTransformationType::REWRITING => $this->getRewritingPrompt(),\n QueryTransformationType::DECOMPOSITION => $this->getDecompositionPrompt(),\n QueryTransformationType::HYDE => $this->getHydePrompt(),\n };\n }\n\n public function setCustomPrompt(string $prompt): self\n {\n $this->customPrompt = $prompt;\n return $this;\n }\n\n public function setTransformation(QueryTransformationType $transformation): self\n {\n $this->transformation = $transformation;\n return $this;\n }\n\n public function setProvider(AIProviderInterface $provider): self\n {\n $this->provider = $provider;\n return $this;\n }\n\n protected function prepareMessage(Message $question): UserMessage\n {\n return new UserMessage('' . $question->getContent() . '');\n }\n\n protected function getRewritingPrompt(): string\n {\n return (string) new SystemPrompt(\n background: [\n 'You are an AI assistant tasked with reformulating user queries to improve retrieval in a RAG system.'\n ],\n steps: [\n 'Given the original query, rewrite it to be more specific, detailed, and likely to retrieve relevant information.',\n 'Focus on expanding vocabulary and technical terminology while preserving the original intent and meaning.',\n ],\n output: [\n 'Output only the reformulated query',\n 'Do not add temporal references, dates, or years unless they are present in the original query'\n ]\n );\n }\n\n protected function getDecompositionPrompt(): string\n {\n return (string) new SystemPrompt(\n background: [\n 'You are an AI assistant that breaks down complex queries into simpler sub-queries for comprehensive information retrieval in a RAG system.'\n ],\n steps: [\n 'Given the original complex query, decompose it into focused sub-queries.',\n 'Each sub-query should address a specific aspect of the original question.',\n 'Ensure all sub-queries together cover the full scope of the original query.',\n ],\n output: [\n 'Output each sub-query on a separate line',\n 'Use clear, specific language for each sub-query',\n 'Do not add temporal references, dates, or years unless they are present in the original query',\n ]\n );\n }\n\n protected function getHydePrompt(): string\n {\n return (string) new SystemPrompt(\n background: [\n 'You are an AI assistant that generates hypothetical answer to the user query, to improve retrieval in a RAG system.'\n ],\n steps: [\n 'Given the original query, write a hypothetical document passage that would directly answer this question.',\n 'Create content that resembles what you would expect to find in a relevant document.',\n ],\n output: [\n 'Output only the hypothetical document passage',\n 'Do not add temporal references, dates, or years unless they are present in the original query',\n 'Keep the response as concise as possible'\n ]\n );\n }\n}\n"], ["/neuron-ai/src/ResolveTools.php", "tools, $this->tools());\n }\n\n /**\n * If toolkits have already bootstrapped, this function\n * just traverses the array of tools without any action.\n *\n * @return ToolInterface[]\n */\n public function bootstrapTools(): array\n {\n $guidelines = [];\n\n if (!empty($this->toolsBootstrapCache)) {\n return $this->toolsBootstrapCache;\n }\n\n $this->notify('tools-bootstrapping');\n\n foreach ($this->getTools() as $tool) {\n if ($tool instanceof ToolkitInterface) {\n $kitGuidelines = $tool->guidelines();\n if ($kitGuidelines !== null && $kitGuidelines !== '') {\n $name = (new \\ReflectionClass($tool))->getShortName();\n $kitGuidelines = '# '.$name.\\PHP_EOL.$kitGuidelines;\n }\n\n // Merge the tools\n $innerTools = $tool->tools();\n $this->toolsBootstrapCache = \\array_merge($this->toolsBootstrapCache, $innerTools);\n\n // Add guidelines to the system prompt\n if ($kitGuidelines !== null && $kitGuidelines !== '' && $kitGuidelines !== '0') {\n $kitGuidelines .= \\PHP_EOL.\\implode(\n \\PHP_EOL.'- ',\n \\array_map(\n fn (ToolInterface $tool): string => \"{$tool->getName()}: {$tool->getDescription()}\",\n $innerTools\n )\n );\n\n $guidelines[] = $kitGuidelines;\n }\n } else {\n // If the item is a simple tool, add to the list as it is\n $this->toolsBootstrapCache[] = $tool;\n }\n }\n\n $instructions = $this->removeDelimitedContent($this->resolveInstructions(), '', '');\n if ($guidelines !== []) {\n $this->withInstructions(\n $instructions.\\PHP_EOL.''.\\PHP_EOL.\\implode(\\PHP_EOL.\\PHP_EOL, $guidelines).\\PHP_EOL.''\n );\n }\n\n $this->notify('tools-bootstrapped', new ToolsBootstrapped($this->toolsBootstrapCache, $guidelines));\n\n return $this->toolsBootstrapCache;\n }\n\n /**\n * Add tools.\n *\n * @throws AgentException\n */\n public function addTool(ToolInterface|ToolkitInterface|array $tools): AgentInterface\n {\n $tools = \\is_array($tools) ? $tools : [$tools];\n\n foreach ($tools as $t) {\n if (! $t instanceof ToolInterface && ! $t instanceof ToolkitInterface) {\n throw new AgentException('Tools must be an instance of ToolInterface or ToolkitInterface');\n }\n $this->tools[] = $t;\n }\n\n // Empty the cache for the next turn.\n $this->toolsBootstrapCache = [];\n\n return $this;\n }\n\n protected function executeTools(ToolCallMessage $toolCallMessage): ToolCallResultMessage\n {\n $toolCallResult = new ToolCallResultMessage($toolCallMessage->getTools());\n\n foreach ($toolCallResult->getTools() as $tool) {\n $this->notify('tool-calling', new ToolCalling($tool));\n try {\n $tool->execute();\n } catch (\\Throwable $exception) {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n $this->notify('tool-called', new ToolCalled($tool));\n }\n\n return $toolCallResult;\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/ToolCallMessage.php", " $tools\n */\n public function __construct(\n protected array|string|int|float|null $content,\n protected array $tools\n ) {\n parent::__construct($this->content);\n }\n\n /**\n * @return array\n */\n public function getTools(): array\n {\n return $this->tools;\n }\n\n public function jsonSerialize(): array\n {\n return \\array_merge(\n parent::jsonSerialize(),\n [\n 'type' => 'tool_call',\n 'tools' => \\array_map(fn (ToolInterface $tool): array => $tool->jsonSerialize(), $this->tools)\n ]\n );\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Riza/RizaCodeInterpreter.php", "client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json; charset=utf-8',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function __invoke(\n string $code,\n array $args = [],\n array $env = [],\n ): mixed {\n $result = $this->getClient()->post('execute', [\n RequestOptions::JSON => [\n 'language' => $this->language,\n 'code' => $code,\n 'args' => $args,\n 'env' => $env,\n ]\n ])->getBody()->getContents();\n\n return \\json_decode($result, true);\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/ChromaVectorStore.php", "client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->host, '/').\"/api/v1/collections/{$this->collection}/\",\n 'headers' => [\n 'Content-Type' => 'application/json',\n ]\n ]);\n }\n\n public function addDocument(Document $document): void\n {\n $this->addDocuments([$document]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->getClient()->post('delete', [\n RequestOptions::JSON => [\n 'where' => [\n 'sourceType' => $sourceType,\n 'sourceName' => $sourceName,\n ]\n ]\n ]);\n }\n\n public function addDocuments(array $documents): void\n {\n $this->getClient()->post('upsert', [\n RequestOptions::JSON => $this->mapDocuments($documents),\n ])->getBody()->getContents();\n }\n\n public function similaritySearch(array $embedding): iterable\n {\n $response = $this->getClient()->post('query', [\n RequestOptions::JSON => [\n 'queryEmbeddings' => $embedding,\n 'nResults' => $this->topK,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n // Map the result\n $size = \\count($response['distances']);\n $result = [];\n for ($i = 0; $i < $size; $i++) {\n $document = new Document();\n $document->id = $response['ids'][$i] ?? \\uniqid();\n $document->embedding = $response['embeddings'][$i];\n $document->content = $response['documents'][$i];\n $document->sourceType = $response['metadatas'][$i]['sourceType'] ?? null;\n $document->sourceName = $response['metadatas'][$i]['sourceName'] ?? null;\n $document->score = VectorSimilarity::similarityFromDistance($response['distances'][$i]);\n\n foreach ($response['metadatas'][$i] as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName', 'score', 'embedding', 'id'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n $result[] = $document;\n }\n\n return $result;\n }\n\n /**\n * @param Document[] $documents\n */\n protected function mapDocuments(array $documents): array\n {\n $payload = [\n 'ids' => [],\n 'documents' => [],\n 'embeddings' => [],\n 'metadatas' => [],\n ];\n\n foreach ($documents as $document) {\n $payload['ids'][] = $document->getId();\n $payload['documents'][] = $document->getContent();\n $payload['embeddings'][] = $document->getEmbedding();\n $payload['metadatas'][] = [\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ];\n }\n\n return $payload;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Zep/ZepSearchGraphTool.php", "createUser();\n }\n\n protected function properties(): array\n {\n return [\n new ToolProperty(\n 'query',\n PropertyType::STRING,\n 'The search term to find relevant facts or nodes',\n true\n ),\n new ToolProperty(\n 'search_scope',\n PropertyType::STRING,\n 'The scope of the search to perform. Can be \"facts\" or \"nodes\"',\n false,\n ['facts', 'nodes']\n )\n ];\n }\n\n public function __invoke(string $query, string $search_scope = 'facts', int $limit = 5): array\n {\n $response = $this->getClient()->post('graph/search', [\n RequestOptions::JSON => [\n 'user_id' => $this->user_id,\n 'query' => $query,\n 'scope' => $search_scope === 'facts' ? 'edges' : 'nodes',\n 'limit' => $limit,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return match ($search_scope) {\n 'nodes' => $this->mapNodes($response['nodes']),\n default => $this->mapEdges($response['edges']),\n };\n }\n\n protected function mapEdges(array $edges): array\n {\n return \\array_map(fn (array $edge): array => [\n 'fact' => $edge['fact'],\n 'created_at' => $edge['created_at'],\n ], $edges);\n }\n\n protected function mapNodes(array $nodes): array\n {\n return \\array_map(fn (array $node): array => [\n 'name' => $node['name'],\n 'summary' => $node['summary'],\n ], $nodes);\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/HandleStructured.php", "parameters)) {\n $this->parameters['generationConfig'] = [\n 'temperature' => 0,\n ];\n }\n\n // Gemini does not support structured output in combination with tools.\n // So we try to work with a JSON mode in case the agent has some tools defined.\n if (!empty($this->tools)) {\n $last_message = \\end($messages);\n if ($last_message instanceof Message && $last_message->getRole() === MessageRole::USER->value) {\n $last_message->setContent(\n $last_message->getContent() . ' Respond using this JSON schema: '.\\json_encode($response_format)\n );\n }\n } else {\n // If there are no tools, we can enforce the structured output.\n $this->parameters['generationConfig']['response_schema'] = $this->adaptSchema($response_format);\n $this->parameters['generationConfig']['response_mime_type'] = 'application/json';\n }\n\n return $this->chat($messages);\n }\n\n /**\n * Gemini does not support additionalProperties attribute.\n */\n protected function adaptSchema(array $schema): array\n {\n if (\\array_key_exists('additionalProperties', $schema)) {\n unset($schema['additionalProperties']);\n }\n\n foreach ($schema as $key => $value) {\n if (\\is_array($value)) {\n $schema[$key] = $this->adaptSchema($value);\n }\n }\n\n return $schema;\n }\n}\n"], ["/neuron-ai/src/HandleStream.php", "notify('stream-start');\n\n $this->fillChatHistory($messages);\n\n $tools = $this->bootstrapTools();\n\n $stream = $this->resolveProvider()\n ->systemPrompt($this->resolveInstructions())\n ->setTools($tools)\n ->stream(\n $this->resolveChatHistory()->getMessages(),\n function (ToolCallMessage $toolCallMessage) {\n $toolCallResult = $this->executeTools($toolCallMessage);\n yield from self::stream([$toolCallMessage, $toolCallResult]);\n }\n );\n\n $content = '';\n $usage = new Usage(0, 0);\n foreach ($stream as $text) {\n // Catch usage when streaming\n $decoded = \\json_decode((string) $text, true);\n if (\\is_array($decoded) && \\array_key_exists('usage', $decoded)) {\n $usage->inputTokens += $decoded['usage']['input_tokens'] ?? 0;\n $usage->outputTokens += $decoded['usage']['output_tokens'] ?? 0;\n continue;\n }\n\n $content .= $text;\n yield $text;\n }\n\n $response = new AssistantMessage($content);\n $response->setUsage($usage);\n\n // Avoid double saving due to the recursive call.\n $last = $this->resolveChatHistory()->getLastMessage();\n if ($response->getRole() !== $last->getRole()) {\n $this->fillChatHistory($response);\n }\n\n $this->notify('stream-stop');\n } catch (\\Throwable $exception) {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/OpenAIEmbeddingsProvider.php", "client = new Client([\n 'base_uri' => $this->baseUri,\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer ' . $this->key,\n ]\n ]);\n }\n\n public function embedText(string $text): array\n {\n $response = $this->client->post('', [\n 'json' => [\n 'model' => $this->model,\n 'input' => $text,\n 'encoding_format' => 'float',\n 'dimensions' => $this->dimensions,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['data'][0]['embedding'];\n }\n}\n"], ["/neuron-ai/src/Tools/ArrayProperty.php", "validateConstraints();\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'name' => $this->name,\n 'description' => $this->description,\n 'type' => $this->type->value,\n 'items' => $this->getJsonSchema(),\n 'required' => $this->required,\n ];\n }\n\n public function getJsonSchema(): array\n {\n $schema = [\n 'type' => $this->type->value,\n ];\n\n if (!\\is_null($this->description)) {\n $schema['description'] = $this->description;\n }\n\n if ($this->items instanceof ToolPropertyInterface) {\n $schema['items'] = $this->items->getJsonSchema();\n }\n\n if ($this->minItems !== null && $this->minItems !== 0) {\n $schema['minItems'] = $this->minItems;\n }\n\n if ($this->maxItems !== null && $this->maxItems !== 0) {\n $schema['maxItems'] = $this->maxItems;\n }\n\n return $schema;\n }\n\n public function isRequired(): bool\n {\n return $this->required;\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n public function getType(): PropertyType\n {\n return $this->type;\n }\n\n public function getDescription(): ?string\n {\n return $this->description;\n }\n\n public function getItems(): ?ToolPropertyInterface\n {\n return $this->items;\n }\n\n /**\n * @throws ArrayPropertyException\n */\n protected function validateConstraints(): void\n {\n if ($this->minItems !== null && $this->minItems < 0) {\n throw new ArrayPropertyException(\"minItems must be >= 0, got {$this->minItems}\");\n }\n\n if ($this->maxItems !== null && $this->maxItems < 0) {\n throw new ArrayPropertyException(\"maxItems must be >= 0, got {$this->maxItems}\");\n }\n\n if ($this->minItems !== null && $this->maxItems !== null && $this->minItems > $this->maxItems) {\n throw new ArrayPropertyException(\n \"minItems ({$this->minItems}) cannot be greater than maxItems ({$this->maxItems})\"\n );\n }\n }\n}\n"], ["/neuron-ai/src/HandleStructured.php", "notify('structured-start');\n\n $this->fillChatHistory($messages);\n\n $tools = $this->bootstrapTools();\n\n // Get the JSON schema from the response model\n $class ??= $this->getOutputClass();\n $this->notify('schema-generation', new SchemaGeneration($class));\n $schema = (new JsonSchema())->generate($class);\n $this->notify('schema-generated', new SchemaGenerated($class, $schema));\n\n $error = '';\n do {\n try {\n // If something goes wrong, retry informing the model about the error\n if (\\trim($error) !== '') {\n $correctionMessage = new UserMessage(\n \"There was a problem in your previous response that generated the following errors\".\n \\PHP_EOL.\\PHP_EOL.'- '.$error.\\PHP_EOL.\\PHP_EOL.\n \"Try to generate the correct JSON structure based on the provided schema.\"\n );\n $this->fillChatHistory($correctionMessage);\n }\n\n $messages = $this->resolveChatHistory()->getMessages();\n\n $last = clone $this->resolveChatHistory()->getLastMessage();\n $this->notify(\n 'inference-start',\n new InferenceStart($last)\n );\n $response = $this->resolveProvider()\n ->systemPrompt($this->resolveInstructions())\n ->setTools($tools)\n ->structured($messages, $class, $schema);\n $this->notify(\n 'inference-stop',\n new InferenceStop($last, $response)\n );\n\n $this->fillChatHistory($response);\n\n if ($response instanceof ToolCallMessage) {\n $toolCallResult = $this->executeTools($response);\n return self::structured($toolCallResult, $class, $maxRetries);\n }\n\n $output = $this->processResponse($response, $schema, $class);\n $this->notify('structured-stop');\n return $output;\n } catch (RequestException $exception) {\n $error = $exception->getResponse()?->getBody()->getContents() ?? $exception->getMessage();\n $this->notify('error', new AgentError($exception, false));\n } catch (\\Exception $exception) {\n $error = $exception->getMessage();\n $this->notify('error', new AgentError($exception, false));\n }\n\n $maxRetries--;\n } while ($maxRetries >= 0);\n\n $exception = new AgentException(\n \"Impossible to generate a structured response for the class {$class}: {$error}\"\n );\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n\n protected function processResponse(\n Message $response,\n array $schema,\n string $class,\n ): mixed {\n // Try to extract a valid JSON object from the LLM response\n $this->notify('structured-extracting', new Extracting($response));\n $json = (new JsonExtractor())->getJson($response->getContent());\n $this->notify('structured-extracted', new Extracted($response, $schema, $json));\n if ($json === null || $json === '') {\n throw new AgentException(\"The response does not contains a valid JSON Object.\");\n }\n\n // Deserialize the JSON response from the LLM into an instance of the response model\n $this->notify('structured-deserializing', new Deserializing($class));\n $obj = Deserializer::fromJson($json, $class);\n $this->notify('structured-deserialized', new Deserialized($class));\n\n // Validate if the object fields respect the validation attributes\n // https://symfony.com/doc/current/validation.html#constraints\n $this->notify('structured-validating', new Validating($class, $json));\n\n $violations = Validator::validate($obj);\n\n if (\\count($violations) > 0) {\n $this->notify('structured-validated', new Validated($class, $json, $violations));\n throw new AgentException(\\PHP_EOL.'- '.\\implode(\\PHP_EOL.'- ', $violations));\n }\n $this->notify('structured-validated', new Validated($class, $json));\n\n return $obj;\n }\n\n protected function getOutputClass(): string\n {\n throw new AgentException('You need to specify an output class.');\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Zep/HandleZepClient.php", "client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => \"Api-Key {$this->key}\",\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n protected function createUser(): self\n {\n // Create the user if it doesn't exist\n try {\n $this->getClient()->get('users/'.$this->user_id);\n } catch (\\Exception) {\n $this->getClient()->post('users', [\n RequestOptions::JSON => ['user_id' => $this->user_id]\n ]);\n }\n\n return $this;\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Deserializer/Deserializer.php", "newInstanceWithoutConstructor();\n\n // Get all properties including private/protected\n $properties = $reflection->getProperties();\n\n foreach ($properties as $property) {\n $propertyName = $property->getName();\n\n // Check if data contains this property (case-sensitive and snake_case/camelCase variants)\n $value = self::findPropertyValue($data, $propertyName);\n\n if ($value !== null) {\n // Get property type information\n $type = $property->getType();\n\n if ($type) {\n $value = self::castValue($value, $type, $property);\n }\n\n $property->setValue($instance, $value);\n }\n }\n\n // Call constructor if it exists and is public\n $constructor = $reflection->getConstructor();\n if ($constructor && $constructor->isPublic() && $constructor->getNumberOfRequiredParameters() === 0) {\n $constructor->invoke($instance);\n }\n\n return $instance;\n }\n\n /**\n * Find property value in data, supporting different naming conventions\n */\n private static function findPropertyValue(array $data, string $propertyName): mixed\n {\n // Direct match\n if (\\array_key_exists($propertyName, $data)) {\n return $data[$propertyName];\n }\n\n // Convert camelCase to snake_case\n $snakeCase = \\strtolower((string) \\preg_replace('/(?getTypes() as $unionType) {\n try {\n return self::castToSingleType($value, $unionType, $property);\n } catch (\\Exception) {\n continue;\n }\n }\n throw new DeserializerException(\"Cannot cast value to any type in union for property {$property->getName()}\");\n }\n\n // @phpstan-ignore-next-line\n return self::castToSingleType($value, $type, $property);\n }\n\n /**\n * Cast value to a single type\n *\n * @throws DeserializerException|\\ReflectionException\n */\n private static function castToSingleType(\n mixed $value,\n \\ReflectionNamedType $type,\n \\ReflectionProperty $property\n ): mixed {\n $typeName = $type->getName();\n\n // Handle null values\n if ($value === null) {\n if ($type->allowsNull()) {\n return null;\n }\n throw new DeserializerException(\"Property {$property->getName()} does not allow null values\");\n }\n\n return match ($typeName) {\n 'string' => (string) $value,\n 'int' => (int) $value,\n 'float' => (float) $value,\n 'bool' => (bool) $value,\n 'array' => self::handleArray($value, $property),\n 'DateTime' => self::createDateTime($value),\n 'DateTimeImmutable' => self::createDateTimeImmutable($value),\n default => self::handleSingleObject($value, $typeName)\n };\n }\n\n /**\n * @throws DeserializerException|\\ReflectionException\n */\n private static function handleSingleObject(mixed $value, string $typeName): mixed\n {\n if (\\is_array($value) && \\class_exists($typeName)) {\n return self::deserializeObject($value, $typeName);\n }\n\n if (\\enum_exists($typeName)) {\n return self::handleEnum($typeName, $value);\n }\n\n // Fallback: return the value as-is\n return $value;\n }\n\n /**\n * Handle collections\n *\n * @throws DeserializerException|\\ReflectionException\n */\n private static function handleArray(mixed $value, \\ReflectionProperty $property): mixed\n {\n // Handle arrays of objects using docblock annotations\n if (self::isArrayOfObjects($property)) {\n $elementType = self::getArrayElementType($property);\n if ($elementType && \\class_exists($elementType)) {\n return \\array_map(fn (array $item): object => self::deserializeObject($item, $elementType), $value);\n }\n }\n\n // Fallback: return the value as-is\n return $value;\n }\n\n /**\n * Check if a property represents an array of objects based on docblock\n */\n private static function isArrayOfObjects(\\ReflectionProperty $property): bool\n {\n $docComment = $property->getDocComment();\n if (!$docComment) {\n return false;\n }\n\n return \\preg_match('/@var\\s+(?:([a-zA-Z0-9_\\\\\\\\]+)\\[\\]|array<([a-zA-Z0-9_\\\\\\\\]+)>)/', $docComment) === 1;\n }\n\n /**\n * Extract an element type from array docblock annotation\n */\n private static function getArrayElementType(\\ReflectionProperty $property): ?string\n {\n $docComment = $property->getDocComment();\n if (!$docComment) {\n return null;\n }\n\n // Extract type from both \"@var \\App\\Type[]\" and \"@var array<\\App\\Type>\"\n if (\\preg_match('/@var\\s+(?:([a-zA-Z0-9_\\\\\\\\]+)\\[\\]|array<([a-zA-Z0-9_\\\\\\\\]+)>)/', $docComment, $matches) === 1) {\n return empty($matches[1]) ? ((isset($matches[2]) && $matches[2] !== '0') ? $matches[2] : null) : ($matches[1]);\n }\n\n return null;\n }\n\n /**\n * Create a DateTime object from various input formats\n *\n * @throws DeserializerException\n */\n private static function createDateTime(mixed $value): \\DateTime\n {\n if ($value instanceof \\DateTime) {\n return $value;\n }\n\n if (\\is_string($value)) {\n try {\n return new \\DateTime($value);\n } catch (\\Exception) {\n throw new DeserializerException(\"Cannot create DateTime from: {$value}\");\n }\n }\n\n if (\\is_numeric($value)) {\n return new \\DateTime('@'.$value);\n }\n\n throw new DeserializerException(\"Cannot create DateTime from value type: \".\\gettype($value));\n }\n\n /**\n * Create a DateTimeImmutable object from various input formats\n *\n * @throws DeserializerException\n */\n private static function createDateTimeImmutable(mixed $value): \\DateTimeImmutable\n {\n if ($value instanceof \\DateTimeImmutable) {\n return $value;\n }\n\n if (\\is_string($value)) {\n try {\n return new \\DateTimeImmutable($value);\n } catch (\\Exception) {\n throw new DeserializerException(\"Cannot create DateTimeImmutable from: {$value}\");\n }\n }\n\n if (\\is_numeric($value)) {\n return new \\DateTimeImmutable('@'.$value);\n }\n\n throw new DeserializerException(\"Cannot create DateTimeImmutable from value type: \".\\gettype($value));\n }\n\n private static function handleEnum(BackedEnum|string $typeName, mixed $value): BackedEnum\n {\n if (!\\is_subclass_of($typeName, BackedEnum::class)) {\n throw new DeserializerException(\"Cannot create BackedEnum from: {$typeName}\");\n }\n\n $enum = $typeName::tryFrom($value);\n\n if (!$enum instanceof \\BackedEnum) {\n throw new DeserializerException(\"Invalid enum value '{$value}' for {$typeName}\");\n }\n\n return $enum;\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/AzureOpenAI.php", "setBaseUrl();\n\n $this->client = new Client([\n 'base_uri' => $this->baseUri,\n 'query' => [\n 'api-version' => $this->version,\n ],\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n ],\n ]);\n }\n\n private function setBaseUrl(): void\n {\n $this->endpoint = \\preg_replace('/^https?:\\/\\/([^\\/]*)\\/?$/', '$1', $this->endpoint);\n $this->baseUri = \\sprintf($this->baseUri, $this->endpoint, $this->model);\n $this->baseUri = \\trim($this->baseUri, '/').'/';\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Zep/ZepAddToGraphTool.php", "createUser();\n }\n\n protected function properties(): array\n {\n return [\n new ToolProperty(\n 'data',\n PropertyType::STRING,\n 'The search term to find relevant facts or nodes',\n true\n ),\n new ToolProperty(\n 'type',\n PropertyType::STRING,\n 'The scope of the search to perform. Can be \"facts\" or \"nodes\"',\n true,\n ['text', 'json', 'message']\n )\n ];\n }\n\n public function __invoke(string $data, string $type): string\n {\n $response = $this->getClient()->post('graph', [\n RequestOptions::JSON => [\n 'user_id' => $this->user_id,\n 'data' => $data,\n 'type' => $type,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['content'];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Jina/JinaWebSearch.php", "client ?? $this->client = new Client([\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'X-Respond-With' => 'no-content',\n ]\n ]);\n }\n\n public function __invoke(string $search_query): string\n {\n return $this->getClient()->post('https://s.jina.ai/', [\n RequestOptions::JSON => [\n 'q' => $search_query,\n ]\n ])->getBody()->getContents();\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Jina/JinaUrlReader.php", "client ?? $this->client = new Client([\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n 'X-Return-Format' => 'Markdown',\n ]\n ]);\n }\n\n public function __invoke(string $url): string\n {\n if (!\\filter_var($url, \\FILTER_VALIDATE_URL)) {\n throw new ToolException('Invalid URL.');\n }\n\n return $this->getClient()->post('https://r.jina.ai/', [\n RequestOptions::JSON => [\n 'url' => $url,\n ]\n ])->getBody()->getContents();\n }\n}\n"], ["/neuron-ai/src/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(Message|array $messages): PromiseInterface\n {\n $this->notify('chat-start');\n\n $this->fillChatHistory($messages);\n\n $tools = $this->bootstrapTools();\n\n $this->notify(\n 'inference-start',\n new InferenceStart($this->resolveChatHistory()->getLastMessage())\n );\n\n return $this->resolveProvider()\n ->systemPrompt($this->resolveInstructions())\n ->setTools($tools)\n ->chatAsync(\n $this->resolveChatHistory()->getMessages()\n )->then(function (Message $response): Message|PromiseInterface {\n $this->notify(\n 'inference-stop',\n new InferenceStop($this->resolveChatHistory()->getLastMessage(), $response)\n );\n\n $this->fillChatHistory($response);\n\n if ($response instanceof ToolCallMessage) {\n $toolCallResult = $this->executeTools($response);\n return self::chatAsync($toolCallResult);\n }\n\n $this->notify('chat-stop');\n return $response;\n }, function (\\Throwable $exception): void {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n });\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/VarianceTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|float|int $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n if (\\count($numericData) === 1 && $this->sample) {\n return ['error' => 'Cannot calculate sample variance with only one data point'];\n }\n\n // Convert to float values\n $numericData = \\array_map('floatval', $numericData);\n\n // Calculate mean\n $mean = \\array_sum($numericData) / \\count($numericData);\n\n // Calculate the sum of squared differences\n $sumSquaredDifferences = 0;\n foreach ($numericData as $value) {\n $sumSquaredDifferences += ($value - $mean) ** 2;\n }\n\n // Calculate variance\n $divisor = $this->sample ? \\count($numericData) - 1 : \\count($numericData);\n $variance = $sumSquaredDifferences / $divisor;\n\n return \\round($variance, $this->precision);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/StandardDeviationTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|float|int $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n if (\\count($numericData) === 1 && $this->sample) {\n return ['error' => 'Cannot calculate sample standard deviation with only one data point'];\n }\n\n // Convert to float values\n $numericData = \\array_map('floatval', $numericData);\n\n // Calculate mean\n $mean = \\array_sum($numericData) / \\count($numericData);\n\n // Calculate the sum of squared differences\n $sumSquaredDifferences = 0;\n foreach ($numericData as $value) {\n $sumSquaredDifferences += ($value - $mean) ** 2;\n }\n\n // Calculate variance\n $divisor = $this->sample ? \\count($numericData) - 1 : \\count($numericData);\n $variance = $sumSquaredDifferences / $divisor;\n\n // Calculate standard deviation\n $standardDeviation = \\sqrt($variance);\n\n return \\round($standardDeviation, $this->precision);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/MeanTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|float|int $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n // Convert to float values\n $numericData = \\array_map('floatval', $numericData);\n $mean = \\array_sum($numericData) / \\count($numericData);\n\n return \\round($mean, $this->precision);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/MedianTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|float|int $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n // Convert to float values and sort\n $numericData = \\array_map('floatval', $numericData);\n \\sort($numericData);\n\n $count = \\count($numericData);\n $middle = (int) \\floor($count / 2);\n\n if ($count % 2 === 0) {\n // Even number of elements - average of two middle values\n $median = ($numericData[$middle - 1] + $numericData[$middle]) / 2;\n } else {\n // Odd number of elements - middle value\n $median = $numericData[$middle];\n }\n\n return \\round($median, $this->precision);\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/ToolCallResultMessage.php", " $tools\n */\n public function __construct(protected array $tools)\n {\n parent::__construct(null);\n }\n\n /**\n * @return array\n */\n public function getTools(): array\n {\n return $this->tools;\n }\n\n public function jsonSerialize(): array\n {\n return \\array_merge(\n parent::jsonSerialize(),\n [\n 'type' => 'tool_call_result',\n 'tools' => \\array_map(fn (ToolInterface $tool): array => $tool->jsonSerialize(), $this->tools)\n ]\n );\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/JsonExtractor.php", "extractors = [\n fn (string $text): array => [$text], // Try as it is\n fn (string $text): array => $this->findByMarkdown($text),\n fn (string $text): ?string => $this->findByBrackets($text),\n fn (string $text): array => $this->findJSONLikeStrings($text),\n ];\n }\n\n /**\n * Attempt to find and parse a complete valid JSON string in the input.\n * Returns a JSON-encoded string on success or an empty string on failure.\n */\n public function getJson(string $input): ?string\n {\n foreach ($this->extractors as $extractor) {\n $candidates = $extractor($input);\n if (empty($candidates)) {\n continue;\n }\n if (\\is_string($candidates)) {\n $candidates = [$candidates];\n }\n\n foreach ($candidates as $candidate) {\n if (!\\is_string($candidate)) {\n continue;\n }\n if (\\trim($candidate) === '') {\n continue;\n }\n try {\n $data = $this->tryParse($candidate);\n } catch (\\Throwable) {\n continue;\n }\n\n if ($data !== null) {\n // Re-encode in canonical JSON form\n $result = \\json_encode($data);\n if ($result !== false) {\n return $result;\n }\n }\n }\n }\n\n return null;\n }\n\n /**\n * Returns an associative array on success, or null if the parsing fails.\n *\n * @throws \\JsonException\n */\n private function tryParse(string $maybeJson): ?array\n {\n $data = \\json_decode($maybeJson, true, 512, \\JSON_THROW_ON_ERROR);\n\n if ($data === false || $data === null || $data === '') {\n return null;\n }\n\n return $data;\n }\n\n /**\n * Find ALL fenced code blocks that start with ```json, and extract\n * the portion between the first '{' and the matching last '}' inside\n * that block. Return an array of candidates.\n */\n private function findByMarkdown(string $text): array\n {\n if (\\trim($text) === '') {\n return [];\n }\n\n $candidates = [];\n $offset = 0;\n $fenceTag = '```json';\n\n while (($startFence = \\strpos($text, $fenceTag, $offset)) !== false) {\n // Find the next triple-backtick fence AFTER the \"```json\"\n $closeFence = \\strpos($text, '```', $startFence + \\strlen($fenceTag));\n if ($closeFence === false) {\n // No closing fence found, stop scanning\n break;\n }\n\n // Substring that represents the code block between \"```json\" and \"```\"\n $codeBlock = \\substr(\n $text,\n $startFence + \\strlen($fenceTag),\n $closeFence - ($startFence + \\strlen($fenceTag))\n );\n\n // Now find the first '{' and last '}' within this code block\n $firstBrace = \\strpos($codeBlock, '{');\n $lastBrace = \\strrpos($codeBlock, '}');\n if ($firstBrace !== false && $lastBrace !== false && $firstBrace < $lastBrace) {\n $jsonCandidate = \\substr($codeBlock, $firstBrace, $lastBrace - $firstBrace + 1);\n $candidates[] = $jsonCandidate;\n }\n\n // Advance offset past the closing fence, so we can find subsequent code blocks\n $offset = $closeFence + 3; // skip '```'\n }\n\n return $candidates;\n }\n\n /**\n * Find a substring from the first '{' to the last '}'.\n */\n private function findByBrackets(string $text): ?string\n {\n $trimmed = \\trim($text);\n if ($trimmed === '') {\n return null;\n }\n $firstOpen = \\strpos($trimmed, '{');\n if ($firstOpen === 0 || $firstOpen === false) {\n return null;\n }\n\n $lastClose = \\strrpos($trimmed, '}');\n if ($lastClose === false || $lastClose < $firstOpen) {\n return null;\n }\n\n return \\substr($trimmed, $firstOpen, $lastClose - $firstOpen + 1);\n }\n\n /**\n * Scan through the text, capturing any substring that begins at '{'\n * and ends at its matching '}'—accounting for nested braces and strings.\n * Returns an array of all such candidates found.\n */\n private function findJSONLikeStrings(string $text): array\n {\n $text = \\trim($text);\n if ($text === '') {\n return [];\n }\n\n $candidates = [];\n $currentCandidate = '';\n $bracketCount = 0;\n $inString = false;\n $escape = false;\n $len = \\strlen($text);\n\n for ($i = 0; $i < $len; $i++) {\n $char = $text[$i];\n\n if (!$inString) {\n if ($char === '{') {\n if ($bracketCount === 0) {\n $currentCandidate = '';\n }\n $bracketCount++;\n } elseif ($char === '}') {\n $bracketCount--;\n }\n }\n\n // Toggle inString if we encounter an unescaped quote\n if ($char === '\"' && !$escape) {\n $inString = !$inString;\n }\n\n // Determine if current char is a backslash for next iteration\n $escape = ($char === '\\\\' && !$escape);\n\n if ($bracketCount > 0) {\n $currentCandidate .= $char;\n }\n\n // If bracketCount just went back to 0, we’ve closed a JSON-like block\n if ($bracketCount === 0 && $currentCandidate !== '') {\n $currentCandidate .= $char; // include the closing '}'\n $candidates[] = $currentCandidate;\n $currentCandidate = '';\n }\n }\n\n return $candidates;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/MySQL/MySQLSchemaTool.php", "formatForLLM([\n 'tables' => $this->getTables(),\n 'relationships' => $this->getRelationships(),\n 'indexes' => $this->getIndexes(),\n 'constraints' => $this->getConstraints()\n ]);\n }\n\n protected function formatForLLM(array $structure): string\n {\n $output = \"# MySQL Database Schema Analysis\\n\\n\";\n $output .= \"This database contains \" . \\count($structure['tables']) . \" tables with the following structure:\\n\\n\";\n\n // Tables overview\n $output .= \"## Tables Overview\\n\";\n foreach ($structure['tables'] as $table) {\n $pkColumns = empty($table['primary_key']) ? 'None' : \\implode(', ', $table['primary_key']);\n $output .= \"- **{$table['name']}**: {$table['estimated_rows']} rows, Primary Key: {$pkColumns}\";\n if ($table['comment']) {\n $output .= \" - {$table['comment']}\";\n }\n $output .= \"\\n\";\n }\n $output .= \"\\n\";\n\n // Detailed table structures\n $output .= \"## Detailed Table Structures\\n\\n\";\n foreach ($structure['tables'] as $table) {\n $output .= \"### Table: `{$table['name']}`\\n\";\n if ($table['comment']) {\n $output .= \"**Description**: {$table['comment']}\\n\";\n }\n $output .= \"**Estimated Rows**: {$table['estimated_rows']}\\n\\n\";\n\n $output .= \"**Columns**:\\n\";\n foreach ($table['columns'] as $column) {\n $nullable = $column['nullable'] ? 'NULL' : 'NOT NULL';\n $autoInc = $column['auto_increment'] ? ' AUTO_INCREMENT' : '';\n $default = $column['default'] !== null ? \" DEFAULT '{$column['default']}'\" : '';\n\n $output .= \"- `{$column['name']}` {$column['full_type']} {$nullable}{$default}{$autoInc}\";\n if ($column['comment']) {\n $output .= \" - {$column['comment']}\";\n }\n $output .= \"\\n\";\n }\n\n if (!empty($table['primary_key'])) {\n $output .= \"\\n**Primary Key**: \" . \\implode(', ', $table['primary_key']) . \"\\n\";\n }\n\n if (!empty($table['unique_keys'])) {\n $output .= \"**Unique Keys**: \" . \\implode(', ', $table['unique_keys']) . \"\\n\";\n }\n\n $output .= \"\\n\";\n }\n\n // Relationships\n if (!empty($structure['relationships'])) {\n $output .= \"## Foreign Key Relationships\\n\\n\";\n $output .= \"Understanding these relationships is crucial for JOIN operations:\\n\\n\";\n\n foreach ($structure['relationships'] as $rel) {\n $output .= \"- `{$rel['source_table']}.{$rel['source_column']}` → `{$rel['target_table']}.{$rel['target_column']}`\";\n $output .= \" (ON DELETE {$rel['DELETE_RULE']}, ON UPDATE {$rel['UPDATE_RULE']})\\n\";\n }\n $output .= \"\\n\";\n }\n\n // Indexes for query optimization\n if (!empty($structure['indexes'])) {\n $output .= \"## Available Indexes (for Query Optimization)\\n\\n\";\n $output .= \"These indexes can significantly improve query performance:\\n\\n\";\n\n foreach ($structure['indexes'] as $index) {\n $unique = $index['unique'] ? 'UNIQUE ' : '';\n $columns = \\implode(', ', $index['columns']);\n $output .= \"- {$unique}INDEX `{$index['name']}` on `{$index['table']}` ({$columns})\\n\";\n }\n $output .= \"\\n\";\n }\n\n // Query generation guidelines\n $output .= \"## MySQL Query Generation Guidelines\\n\\n\";\n $output .= \"**Best Practices for this database**:\\n\";\n $output .= \"1. Always use table aliases for better readability\\n\";\n $output .= \"2. Prefer indexed columns in WHERE clauses for better performance\\n\";\n $output .= \"3. Use appropriate JOINs based on the foreign key relationships listed above\\n\";\n $output .= \"4. Consider the estimated row counts when writing queries - larger tables may need LIMIT clauses\\n\";\n $output .= \"5. Pay attention to nullable columns when using comparison operators\\n\\n\";\n\n // Common patterns\n $output .= \"**Common Query Patterns**:\\n\";\n $this->addCommonPatterns($output, $structure['tables']);\n\n return $output;\n }\n\n protected function getTables(): array\n {\n $whereClause = \"WHERE t.TABLE_SCHEMA = DATABASE() AND t.TABLE_TYPE = 'BASE TABLE'\";\n $params = [];\n\n // Add table filtering if specific tables are requested\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = \\str_repeat('?,', \\count($this->tables) - 1) . '?';\n $whereClause .= \" AND t.TABLE_NAME IN ($placeholders)\";\n $params = $this->tables;\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n t.TABLE_NAME,\n t.ENGINE,\n t.TABLE_ROWS,\n t.TABLE_COMMENT,\n c.COLUMN_NAME,\n c.ORDINAL_POSITION,\n c.COLUMN_DEFAULT,\n c.IS_NULLABLE,\n c.DATA_TYPE,\n c.CHARACTER_MAXIMUM_LENGTH,\n c.NUMERIC_PRECISION,\n c.NUMERIC_SCALE,\n c.COLUMN_TYPE,\n c.COLUMN_KEY,\n c.EXTRA,\n c.COLUMN_COMMENT\n FROM INFORMATION_SCHEMA.TABLES t\n LEFT JOIN INFORMATION_SCHEMA.COLUMNS c ON t.TABLE_NAME = c.TABLE_NAME\n AND t.TABLE_SCHEMA = c.TABLE_SCHEMA\n $whereClause\n ORDER BY t.TABLE_NAME, c.ORDINAL_POSITION\n \");\n\n $stmt->execute($params);\n $results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n $tables = [];\n foreach ($results as $row) {\n $tableName = $row['TABLE_NAME'];\n\n if (!isset($tables[$tableName])) {\n $tables[$tableName] = [\n 'name' => $tableName,\n 'engine' => $row['ENGINE'],\n 'estimated_rows' => $row['TABLE_ROWS'],\n 'comment' => $row['TABLE_COMMENT'],\n 'columns' => [],\n 'primary_key' => [],\n 'unique_keys' => [],\n 'indexes' => []\n ];\n }\n\n if ($row['COLUMN_NAME']) {\n $column = [\n 'name' => $row['COLUMN_NAME'],\n 'type' => $row['DATA_TYPE'],\n 'full_type' => $row['COLUMN_TYPE'],\n 'nullable' => $row['IS_NULLABLE'] === 'YES',\n 'default' => $row['COLUMN_DEFAULT'],\n 'auto_increment' => \\str_contains((string) $row['EXTRA'], 'auto_increment'),\n 'comment' => $row['COLUMN_COMMENT']\n ];\n\n // Add length/precision info for better LLM understanding\n if ($row['CHARACTER_MAXIMUM_LENGTH']) {\n $column['max_length'] = $row['CHARACTER_MAXIMUM_LENGTH'];\n }\n if ($row['NUMERIC_PRECISION']) {\n $column['precision'] = $row['NUMERIC_PRECISION'];\n $column['scale'] = $row['NUMERIC_SCALE'];\n }\n\n $tables[$tableName]['columns'][] = $column;\n\n // Track key information\n if ($row['COLUMN_KEY'] === 'PRI') {\n $tables[$tableName]['primary_key'][] = $row['COLUMN_NAME'];\n } elseif ($row['COLUMN_KEY'] === 'UNI') {\n $tables[$tableName]['unique_keys'][] = $row['COLUMN_NAME'];\n } elseif ($row['COLUMN_KEY'] === 'MUL') {\n $tables[$tableName]['indexes'][] = $row['COLUMN_NAME'];\n }\n }\n }\n\n return $tables;\n }\n\n protected function getRelationships(): array\n {\n $whereClause = \"WHERE kcu.TABLE_SCHEMA = DATABASE() AND kcu.REFERENCED_TABLE_NAME IS NOT NULL\";\n $params = [];\n\n // Add table filtering if specific tables are requested\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = \\str_repeat('?,', \\count($this->tables) - 1) . '?';\n $whereClause .= \" AND (kcu.TABLE_NAME IN ($placeholders) OR kcu.REFERENCED_TABLE_NAME IN ($placeholders))\";\n $params = \\array_merge($this->tables, $this->tables);\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n kcu.CONSTRAINT_NAME,\n kcu.TABLE_NAME as source_table,\n kcu.COLUMN_NAME as source_column,\n kcu.REFERENCED_TABLE_NAME as target_table,\n kcu.REFERENCED_COLUMN_NAME as target_column,\n rc.UPDATE_RULE,\n rc.DELETE_RULE\n FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu\n JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc\n ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME\n AND kcu.CONSTRAINT_SCHEMA = rc.CONSTRAINT_SCHEMA\n $whereClause\n ORDER BY kcu.TABLE_NAME, kcu.ORDINAL_POSITION\n \");\n\n $stmt->execute($params);\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n protected function getIndexes(): array\n {\n $stmt = $this->pdo->prepare(\"\n SELECT\n TABLE_NAME,\n INDEX_NAME,\n COLUMN_NAME,\n SEQ_IN_INDEX,\n NON_UNIQUE,\n INDEX_TYPE,\n CARDINALITY\n FROM INFORMATION_SCHEMA.STATISTICS\n WHERE TABLE_SCHEMA = DATABASE()\n AND INDEX_NAME != 'PRIMARY'\n ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX\n \");\n\n $stmt->execute();\n $results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n $indexes = [];\n foreach ($results as $row) {\n $key = $row['TABLE_NAME'] . '.' . $row['INDEX_NAME'];\n if (!isset($indexes[$key])) {\n $indexes[$key] = [\n 'table' => $row['TABLE_NAME'],\n 'name' => $row['INDEX_NAME'],\n 'unique' => $row['NON_UNIQUE'] == 0,\n 'type' => $row['INDEX_TYPE'],\n 'columns' => []\n ];\n }\n $indexes[$key]['columns'][] = $row['COLUMN_NAME'];\n }\n\n return \\array_values($indexes);\n }\n\n protected function getConstraints(): array\n {\n $whereClause = \"WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_TYPE IN ('UNIQUE')\";\n $params = [];\n\n // Add table filtering if specific tables are requested\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = \\str_repeat('?,', \\count($this->tables) - 1) . '?';\n $whereClause .= \" AND TABLE_NAME IN ($placeholders)\";\n $params = $this->tables;\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n CONSTRAINT_NAME,\n TABLE_NAME,\n CONSTRAINT_TYPE\n FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS\n $whereClause\n \");\n\n $stmt->execute($params);\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n protected function addCommonPatterns(string &$output, array $tables): void\n {\n // Find tables with timestamps for temporal queries\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['timestamp', 'datetime', 'date']) &&\n (\\str_contains(\\strtolower((string) $column['name']), 'created') ||\n \\str_contains(\\strtolower((string) $column['name']), 'updated'))) {\n $output .= \"- For temporal queries on `{$table['name']}`, use `{$column['name']}` column\\n\";\n break;\n }\n }\n }\n\n // Find potential text search columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['varchar', 'text', 'longtext']) &&\n (\\str_contains(\\strtolower((string) $column['name']), 'name') ||\n \\str_contains(\\strtolower((string) $column['name']), 'title') ||\n \\str_contains(\\strtolower((string) $column['name']), 'description'))) {\n $output .= \"- For text searches on `{$table['name']}`, consider using `{$column['name']}` with LIKE or FULLTEXT\\n\";\n break;\n }\n }\n }\n\n $output .= \"\\n\";\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/OllamaEmbeddingsProvider.php", "client = new Client(['base_uri' => \\trim($this->url, '/').'/']);\n }\n\n public function embedText(string $text): array\n {\n $response = $this->client->post('embed', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'input' => $text,\n ...$this->parameters,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['embeddings'][0];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/PGSQL/PGSQLSchemaTool.php", "formatForLLM([\n 'tables' => $this->getTables(),\n 'relationships' => $this->getRelationships(),\n 'indexes' => $this->getIndexes(),\n 'constraints' => $this->getConstraints()\n ]);\n }\n\n private function getTables(): array\n {\n $whereClause = \"WHERE t.table_schema = current_schema() AND t.table_type = 'BASE TABLE'\";\n $params = [];\n\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = [];\n foreach ($this->tables as $table) {\n $placeholders[] = '?';\n $params[] = $table;\n }\n $whereClause .= \" AND t.table_name = ANY(ARRAY[\" . \\implode(',', $placeholders) . \"])\";\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n t.table_name,\n obj_description(pgc.oid) as table_comment,\n c.column_name,\n c.ordinal_position,\n c.column_default,\n c.is_nullable,\n c.data_type,\n c.character_maximum_length,\n c.numeric_precision,\n c.numeric_scale,\n c.udt_name,\n CASE\n WHEN pk.column_name IS NOT NULL THEN 'PRI'\n WHEN uk.column_name IS NOT NULL THEN 'UNI'\n WHEN idx.column_name IS NOT NULL THEN 'MUL'\n ELSE ''\n END as column_key,\n CASE\n WHEN c.column_default LIKE 'nextval%' THEN 'auto_increment'\n ELSE ''\n END as extra,\n col_description(pgc.oid, c.ordinal_position) as column_comment\n FROM information_schema.tables t\n LEFT JOIN information_schema.columns c ON t.table_name = c.table_name\n AND t.table_schema = c.table_schema\n LEFT JOIN pg_class pgc ON pgc.relname = t.table_name AND pgc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = current_schema())\n LEFT JOIN (\n SELECT ku.table_name, ku.column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage ku ON tc.constraint_name = ku.constraint_name\n WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = current_schema()\n ) pk ON pk.table_name = c.table_name AND pk.column_name = c.column_name\n LEFT JOIN (\n SELECT ku.table_name, ku.column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage ku ON tc.constraint_name = ku.constraint_name\n WHERE tc.constraint_type = 'UNIQUE' AND tc.table_schema = current_schema()\n ) uk ON uk.table_name = c.table_name AND uk.column_name = c.column_name\n LEFT JOIN (\n SELECT\n t.relname as table_name,\n a.attname as column_name\n FROM pg_index i\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(i.indkey)\n JOIN pg_namespace n ON n.oid = t.relnamespace\n WHERE i.indisprimary = false AND i.indisunique = false AND n.nspname = current_schema()\n ) idx ON idx.table_name = c.table_name AND idx.column_name = c.column_name\n $whereClause\n ORDER BY t.table_name, c.ordinal_position\n \");\n\n $stmt->execute($params);\n $results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n $tables = [];\n foreach ($results as $row) {\n $tableName = $row['table_name'];\n\n if (!isset($tables[$tableName])) {\n $tables[$tableName] = [\n 'name' => $tableName,\n 'engine' => 'PostgreSQL',\n 'estimated_rows' => $this->getTableRowCount($tableName),\n 'comment' => $row['table_comment'],\n 'columns' => [],\n 'primary_key' => [],\n 'unique_keys' => [],\n 'indexes' => []\n ];\n }\n\n if ($row['column_name']) {\n // Map PostgreSQL types to a more readable format\n $fullType = $this->formatPostgreSQLType($row);\n\n $column = [\n 'name' => $row['column_name'],\n 'type' => $row['data_type'],\n 'full_type' => $fullType,\n 'nullable' => $row['is_nullable'] === 'YES',\n 'default' => $row['column_default'],\n 'auto_increment' => \\str_contains((string) $row['extra'], 'auto_increment'),\n 'comment' => $row['column_comment']\n ];\n\n if ($row['character_maximum_length']) {\n $column['max_length'] = $row['character_maximum_length'];\n }\n if ($row['numeric_precision']) {\n $column['precision'] = $row['numeric_precision'];\n $column['scale'] = $row['numeric_scale'];\n }\n\n $tables[$tableName]['columns'][] = $column;\n\n if ($row['column_key'] === 'PRI') {\n $tables[$tableName]['primary_key'][] = $row['column_name'];\n } elseif ($row['column_key'] === 'UNI') {\n $tables[$tableName]['unique_keys'][] = $row['column_name'];\n } elseif ($row['column_key'] === 'MUL') {\n $tables[$tableName]['indexes'][] = $row['column_name'];\n }\n }\n }\n\n return $tables;\n }\n\n private function getTableRowCount(string $tableName): string\n {\n try {\n $stmt = $this->pdo->prepare(\"\n SELECT n_tup_ins - n_tup_del as estimate\n FROM pg_stat_user_tables\n WHERE relname = $1\n \");\n $stmt->execute([$tableName]);\n $result = $stmt->fetchColumn();\n return $result !== false ? (string)$result : 'N/A';\n } catch (\\Exception) {\n return 'N/A';\n }\n }\n\n private function formatPostgreSQLType(array $row): string\n {\n $type = $row['udt_name'] ?? $row['data_type'];\n\n // Handle specific PostgreSQL types\n if ($type === 'varchar' || $type === 'character varying') {\n $type = 'character varying';\n }\n if ($row['character_maximum_length']) {\n return \"{$type}({$row['character_maximum_length']})\";\n }\n if ($row['numeric_precision'] && $row['numeric_scale']) {\n return \"{$type}({$row['numeric_precision']},{$row['numeric_scale']})\";\n }\n\n if ($row['numeric_precision']) {\n return \"{$type}({$row['numeric_precision']})\";\n }\n\n return $type;\n }\n\n private function getRelationships(): array\n {\n $whereClause = \"WHERE tc.table_schema = current_schema()\";\n $paramIndex = 1;\n $params = [];\n\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = [];\n foreach ($this->tables as $table) {\n $placeholders[] = '?';\n $params[] = $table;\n }\n $additionalPlaceholders = [];\n foreach ($this->tables as $table) {\n $additionalPlaceholders[] = '$' . $paramIndex++;\n $params[] = $table;\n }\n $whereClause .= \" AND (tc.table_name = ANY(ARRAY[\" . \\implode(',', $placeholders) . \"]) OR ccu.table_name = ANY(ARRAY[\" . \\implode(',', $additionalPlaceholders) . \"]))\";\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n tc.constraint_name,\n tc.table_name as source_table,\n kcu.column_name as source_column,\n ccu.table_name as target_table,\n ccu.column_name as target_column,\n rc.update_rule,\n rc.delete_rule\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n JOIN information_schema.constraint_column_usage ccu\n ON ccu.constraint_name = tc.constraint_name\n AND ccu.table_schema = tc.table_schema\n JOIN information_schema.referential_constraints rc\n ON tc.constraint_name = rc.constraint_name\n AND tc.table_schema = rc.constraint_schema\n $whereClause\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.table_name\n \");\n\n $stmt->execute($params);\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n private function getIndexes(): array\n {\n $whereClause = \"WHERE schemaname = current_schema() AND indexname NOT LIKE '%_pkey'\";\n $params = [];\n\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = [];\n foreach ($this->tables as $table) {\n $placeholders[] = '?';\n $params[] = $table;\n }\n $whereClause .= \" AND tablename = ANY(ARRAY[\" . \\implode(',', $placeholders) . \"])\";\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n schemaname,\n tablename,\n indexname,\n indexdef\n FROM pg_indexes\n $whereClause\n ORDER BY tablename, indexname\n \");\n\n $stmt->execute($params);\n $results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n $indexes = [];\n foreach ($results as $row) {\n // Parse column names from index definition\n \\preg_match('/\\((.*?)\\)/', (string) $row['indexdef'], $matches);\n $columnList = $matches[1] ?? '';\n $columns = \\array_map('trim', \\explode(',', $columnList));\n\n // Clean up column names (remove function calls, etc.)\n $cleanColumns = [];\n foreach ($columns as $col) {\n // Extract just the column name if it's wrapped in functions\n if (\\preg_match('/([a-zA-Z_]\\w*)/', $col, $colMatches)) {\n $cleanColumns[] = $colMatches[1];\n }\n }\n\n $indexes[] = [\n 'table' => $row['tablename'],\n 'name' => $row['indexname'],\n 'unique' => \\str_contains((string) $row['indexdef'], 'UNIQUE'),\n 'type' => $this->extractIndexType($row['indexdef']),\n 'columns' => $cleanColumns === [] ? $columns : $cleanColumns\n ];\n }\n\n return $indexes;\n }\n\n private function extractIndexType(string $indexDef): string\n {\n if (\\str_contains($indexDef, 'USING gin')) {\n return 'GIN';\n }\n if (\\str_contains($indexDef, 'USING gist')) {\n return 'GIST';\n }\n if (\\str_contains($indexDef, 'USING hash')) {\n return 'HASH';\n }\n if (\\str_contains($indexDef, 'USING brin')) {\n return 'BRIN';\n }\n return 'BTREE';\n // Default\n\n }\n\n private function getConstraints(): array\n {\n $whereClause = \"WHERE table_schema = current_schema() AND constraint_type IN ('UNIQUE', 'CHECK')\";\n $params = [];\n\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = [];\n foreach ($this->tables as $table) {\n $placeholders[] = '?';\n $params[] = $table;\n }\n $whereClause .= \" AND table_name = ANY(ARRAY[\" . \\implode(',', $placeholders) . \"])\";\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n constraint_name,\n table_name,\n constraint_type\n FROM information_schema.table_constraints\n $whereClause\n \");\n\n $stmt->execute($params);\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n private function formatForLLM(array $structure): string\n {\n $output = \"# PostgreSQL Database Schema Analysis\\n\\n\";\n $output .= \"This PostgreSQL database contains \" . \\count($structure['tables']) . \" tables with the following structure:\\n\\n\";\n\n // Tables overview\n $output .= \"## Tables Overview\\n\";\n $tableCount = \\count($structure['tables']);\n $filteredNote = $this->tables !== null ? \" (filtered to specified tables)\" : \"\";\n $output .= \"Analyzing {$tableCount} tables{$filteredNote}:\\n\";\n\n foreach ($structure['tables'] as $table) {\n $pkColumns = empty($table['primary_key']) ? 'None' : \\implode(', ', $table['primary_key']);\n $output .= \"- **{$table['name']}**: {$table['estimated_rows']} rows, Primary Key: {$pkColumns}\";\n if ($table['comment']) {\n $output .= \" - {$table['comment']}\";\n }\n $output .= \"\\n\";\n }\n $output .= \"\\n\";\n\n // Detailed table structures\n $output .= \"## Detailed Table Structures\\n\\n\";\n foreach ($structure['tables'] as $table) {\n $output .= \"### Table: `{$table['name']}`\\n\";\n if ($table['comment']) {\n $output .= \"**Description**: {$table['comment']}\\n\";\n }\n $output .= \"**Estimated Rows**: {$table['estimated_rows']}\\n\\n\";\n\n $output .= \"**Columns**:\\n\";\n foreach ($table['columns'] as $column) {\n $nullable = $column['nullable'] ? 'NULL' : 'NOT NULL';\n $autoInc = $column['auto_increment'] ? ' (SERIAL/SEQUENCE)' : '';\n $default = $column['default'] !== null ? \" DEFAULT {$column['default']}\" : '';\n\n $output .= \"- `{$column['name']}` {$column['full_type']} {$nullable}{$default}{$autoInc}\";\n if ($column['comment']) {\n $output .= \" - {$column['comment']}\";\n }\n $output .= \"\\n\";\n }\n\n if (!empty($table['primary_key'])) {\n $output .= \"\\n**Primary Key**: \" . \\implode(', ', $table['primary_key']) . \"\\n\";\n }\n\n if (!empty($table['unique_keys'])) {\n $output .= \"**Unique Keys**: \" . \\implode(', ', $table['unique_keys']) . \"\\n\";\n }\n\n $output .= \"\\n\";\n }\n\n // Relationships\n if (!empty($structure['relationships'])) {\n $output .= \"## Foreign Key Relationships\\n\\n\";\n $output .= \"Understanding these relationships is crucial for JOIN operations:\\n\\n\";\n\n foreach ($structure['relationships'] as $rel) {\n $output .= \"- `{$rel['source_table']}.{$rel['source_column']}` → `{$rel['target_table']}.{$rel['target_column']}`\";\n $output .= \" (ON DELETE {$rel['delete_rule']}, ON UPDATE {$rel['update_rule']})\\n\";\n }\n $output .= \"\\n\";\n }\n\n // Indexes for query optimization\n if (!empty($structure['indexes'])) {\n $output .= \"## Available Indexes (for Query Optimization)\\n\\n\";\n $output .= \"These indexes can significantly improve query performance:\\n\\n\";\n\n foreach ($structure['indexes'] as $index) {\n $unique = $index['unique'] ? 'UNIQUE ' : '';\n $columns = \\implode(', ', $index['columns']);\n $output .= \"- {$unique}{$index['type']} INDEX `{$index['name']}` on `{$index['table']}` ({$columns})\\n\";\n }\n $output .= \"\\n\";\n }\n\n // PostgreSQL-specific query guidelines\n $output .= \"## PostgreSQL SQL Query Generation Guidelines\\n\\n\";\n $output .= \"**Best Practices for this PostgreSQL database**:\\n\";\n $output .= \"1. Always use table aliases for better readability\\n\";\n $output .= \"2. Prefer indexed columns in WHERE clauses for better performance\\n\";\n $output .= \"3. Use appropriate JOINs based on the foreign key relationships listed above\\n\";\n $output .= \"4. Use double quotes (\\\") for identifiers if they contain special characters or are case-sensitive\\n\";\n $output .= \"5. PostgreSQL is case-sensitive for identifiers - use exact casing as shown above\\n\";\n $output .= \"6. Use \\$1, \\$2, etc. for parameterized queries in prepared statements\\n\";\n $output .= \"7. LIMIT clause syntax: `SELECT ... LIMIT n OFFSET m`\\n\";\n $output .= \"8. String comparisons are case-sensitive by default (use ILIKE for case-insensitive)\\n\";\n $output .= \"9. Use single quotes (') for string literals, not double quotes\\n\";\n $output .= \"10. PostgreSQL supports advanced features like arrays, JSON/JSONB, and full-text search\\n\";\n $output .= \"11. Use RETURNING clause for INSERT/UPDATE/DELETE to get back modified data\\n\\n\";\n\n // Common patterns\n $output .= \"**Common PostgreSQL Query Patterns**:\\n\";\n $this->addCommonPatterns($output, $structure['tables']);\n\n return $output;\n }\n\n private function addCommonPatterns(string &$output, array $tables): void\n {\n // Find tables with timestamps for temporal queries\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['timestamp without time zone', 'timestamp with time zone', 'timestamptz', 'date', 'time']) &&\n (\\str_contains(\\strtolower((string) $column['name']), 'created') ||\n \\str_contains(\\strtolower((string) $column['name']), 'updated'))) {\n $output .= \"- For temporal queries on `{$table['name']}`, use `{$column['name']}` column\\n\";\n break;\n }\n }\n }\n\n // Find potential text search columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['character varying', 'varchar', 'text', 'character']) &&\n (\\str_contains(\\strtolower((string) $column['name']), 'name') ||\n \\str_contains(\\strtolower((string) $column['name']), 'title') ||\n \\str_contains(\\strtolower((string) $column['name']), 'description'))) {\n $output .= \"- For text searches on `{$table['name']}`, consider using `{$column['name']}` with ILIKE, ~ (regex), or full-text search\\n\";\n break;\n }\n }\n }\n\n // Find JSON/JSONB columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['json', 'jsonb'])) {\n $output .= \"- Table `{$table['name']}` has {$column['type']} column `{$column['name']}` - use JSON operators like ->, ->>, @>, ? for querying\\n\";\n }\n }\n }\n\n // Find array columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\str_contains((string) $column['full_type'], '[]')) {\n $output .= \"- Table `{$table['name']}` has array column `{$column['name']}` ({$column['full_type']}) - use array operators like ANY, ALL, @>\\n\";\n }\n }\n }\n\n // Find UUID columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if ($column['type'] === 'uuid') {\n $output .= \"- Table `{$table['name']}` uses UUID for `{$column['name']}` - use gen_random_uuid() for generating new UUIDs\\n\";\n break;\n }\n }\n }\n\n $output .= \"\\n\";\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/FileVectorStore.php", "directory)) {\n throw new VectorStoreException(\"Directory '{$this->directory}' does not exist\");\n }\n }\n\n protected function getFilePath(): string\n {\n return $this->directory . \\DIRECTORY_SEPARATOR . $this->name.$this->ext;\n }\n\n public function addDocument(Document $document): void\n {\n $this->addDocuments([$document]);\n }\n\n public function addDocuments(array $documents): void\n {\n $this->appendToFile(\n \\array_map(fn (Document $document): array => $document->jsonSerialize(), $documents)\n );\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n // Temporary file\n $tmpFile = $this->directory . \\DIRECTORY_SEPARATOR . $this->name.'_tmp'.$this->ext;\n\n // Create a temporary file handle\n $tempHandle = \\fopen($tmpFile, 'w');\n if (!$tempHandle) {\n throw new \\RuntimeException(\"Cannot create temporary file: {$tmpFile}\");\n }\n\n try {\n foreach ($this->getLine($this->getFilePath()) as $line) {\n $document = \\json_decode((string) $line, true);\n\n if ($document['sourceType'] !== $sourceType || $document['sourceName'] !== $sourceName) {\n \\fwrite($tempHandle, (string) $line);\n }\n }\n } finally {\n \\fclose($tempHandle);\n }\n\n // Replace the original file with the filtered version\n \\unlink($this->getFilePath());\n if (!\\rename($tmpFile, $this->getFilePath())) {\n throw new VectorStoreException(self::class.\" failed to replace original file.\");\n }\n }\n\n public function similaritySearch(array $embedding): array\n {\n $topItems = [];\n\n foreach ($this->getLine($this->getFilePath()) as $document) {\n $document = \\json_decode((string) $document, true);\n\n if (empty($document['embedding'])) {\n throw new VectorStoreException(\"Document with the following content has no embedding: {$document['content']}\");\n }\n $dist = VectorSimilarity::cosineDistance($embedding, $document['embedding']);\n\n $topItems[] = ['dist' => $dist, 'document' => $document];\n\n \\usort($topItems, fn (array $a, array $b): int => $a['dist'] <=> $b['dist']);\n\n if (\\count($topItems) > $this->topK) {\n $topItems = \\array_slice($topItems, 0, $this->topK, true);\n }\n }\n\n return \\array_map(function (array $item): Document {\n $itemDoc = $item['document'];\n $document = new Document($itemDoc['content']);\n $document->embedding = $itemDoc['embedding'];\n $document->sourceType = $itemDoc['sourceType'];\n $document->sourceName = $itemDoc['sourceName'];\n $document->id = $itemDoc['id'];\n $document->score = VectorSimilarity::similarityFromDistance($item['dist']);\n $document->metadata = $itemDoc['metadata'] ?? [];\n\n return $document;\n }, $topItems);\n }\n\n protected function appendToFile(array $documents): void\n {\n \\file_put_contents(\n $this->getFilePath(),\n \\implode(\\PHP_EOL, \\array_map(fn (array $vector) => \\json_encode($vector), $documents)).\\PHP_EOL,\n \\FILE_APPEND\n );\n }\n\n protected function getLine(string $filename): \\Generator\n {\n $f = \\fopen($filename, 'r');\n\n try {\n while ($line = \\fgets($f)) {\n yield $line;\n }\n } finally {\n \\fclose($f);\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/FactorialTool.php", " 'Factorial is not defined for negative numbers.'];\n }\n\n // Handle edge cases\n if ($number === 0 || $number === 1) {\n return 1;\n }\n\n // For larger numbers, use BCMath to handle arbitrary precision\n if ($number > 20) {\n return self::calculateWithBCMath($number);\n }\n\n // For smaller numbers, use regular integer calculation\n $result = 1;\n for ($i = 2; $i <= $number; $i++) {\n $result *= $i;\n }\n\n return $result;\n }\n\n /**\n * Calculate factorial using BCMath for large numbers\n */\n private function calculateWithBCMath(int $number): float\n {\n $result = '1';\n\n for ($i = 2; $i <= $number; $i++) {\n $result = \\bcmul($result, (string)$i);\n }\n\n return (float)$result;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/ModeTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|int|float $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n // Convert to float values\n $numericData = \\array_map('floatval', $numericData);\n\n // Count frequency of each value\n $frequencies = \\array_count_values($numericData);\n $maxFrequency = \\max($frequencies);\n\n // Find all values with maximum frequency\n $modes = \\array_keys($frequencies, $maxFrequency);\n\n // Convert back to numeric values and sort\n $modes = \\array_map('floatval', $modes);\n \\sort($modes);\n\n return $modes;\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/Message.php", "role->value;\n }\n\n public function setRole(MessageRole|string $role): Message\n {\n if (!$role instanceof MessageRole) {\n $role = MessageRole::from($role);\n }\n\n $this->role = $role;\n return $this;\n }\n\n public function getContent(): mixed\n {\n return $this->content;\n }\n\n public function setContent(mixed $content): Message\n {\n $this->content = $content;\n return $this;\n }\n\n /**\n * @return array\n */\n public function getAttachments(): array\n {\n return $this->attachments;\n }\n\n public function addAttachment(Attachment $attachment): Message\n {\n $this->attachments[] = $attachment;\n return $this;\n }\n\n public function getUsage(): ?Usage\n {\n return $this->usage;\n }\n\n public function setUsage(Usage $usage): static\n {\n $this->usage = $usage;\n return $this;\n }\n\n public function addMetadata(string $key, string|array|null $value): Message\n {\n $this->meta[$key] = $value;\n return $this;\n }\n\n public function jsonSerialize(): array\n {\n $data = [\n 'role' => $this->getRole(),\n 'content' => $this->getContent()\n ];\n\n if ($this->getUsage() instanceof \\NeuronAI\\Chat\\Messages\\Usage) {\n $data['usage'] = $this->getUsage()->jsonSerialize();\n }\n\n if ($this->getAttachments() !== []) {\n $data['attachments'] = \\array_map(fn (Attachment $attachment): array => $attachment->jsonSerialize(), $this->getAttachments());\n }\n\n return \\array_merge($this->meta, $data);\n }\n}\n"], ["/neuron-ai/src/Observability/HandleToolEvents.php", "inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$agent::class.'_tools_bootstrap'] = $this->inspector\n ->startSegment(\n self::SEGMENT_TYPE.'-tools',\n \"tools_bootstrap()\"\n )\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function toolsBootstrapped(AgentInterface $agent, string $event, ToolsBootstrapped $data): void\n {\n if (\\array_key_exists($agent::class.'_tools_bootstrap', $this->segments) && $data->tools !== []) {\n $segment = $this->segments[$agent::class.'_tools_bootstrap']->end();\n $segment->addContext('Tools', \\array_reduce($data->tools, function (array $carry, ToolInterface $tool): array {\n $carry[$tool->getName()] = $tool->getDescription();\n return $carry;\n }, []));\n $segment->addContext('Guidelines', $data->guidelines);\n }\n }\n\n public function toolCalling(AgentInterface $agent, string $event, ToolCalling $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$data->tool->getName()] = $this->inspector\n ->startSegment(\n self::SEGMENT_TYPE.'-tools',\n \"tool_call( {$data->tool->getName()} )\"\n )\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function toolCalled(AgentInterface $agent, string $event, ToolCalled $data): void\n {\n if (\\array_key_exists($data->tool->getName(), $this->segments)) {\n $this->segments[$data->tool->getName()]\n ->end()\n ->addContext('Properties', $data->tool->getProperties())\n ->addContext('Inputs', $data->tool->getInputs())\n ->addContext('Output', $data->tool->getResult());\n }\n }\n}\n"], ["/neuron-ai/src/RAG/DataLoader/PdfReader.php", "setBinPath($binPath);\n }\n }\n\n public function setBinPath(string $binPath): self\n {\n if (!\\is_executable($binPath)) {\n throw new DataReaderException(\"The provided path is not executable.\");\n }\n $this->binPath = $binPath;\n return $this;\n }\n\n protected function findPdfToText(): string\n {\n if (isset($this->binPath)) {\n return $this->binPath;\n }\n\n foreach ($this->commonPaths as $path) {\n if (\\is_executable($path)) {\n return $path;\n }\n }\n\n throw new DataReaderException(\"The pdftotext binary was not found or is not executable.\");\n }\n\n public function setPdf(string $pdf): self\n {\n if (!\\is_readable($pdf)) {\n throw new DataReaderException(\"Could not read `{$pdf}`\");\n }\n\n $this->pdf = $pdf;\n\n return $this;\n }\n\n public function setOptions(array $options): self\n {\n $this->options = $this->parseOptions($options);\n\n return $this;\n }\n\n public function addOptions(array $options): self\n {\n $this->options = \\array_merge(\n $this->options,\n $this->parseOptions($options)\n );\n\n return $this;\n }\n\n protected function parseOptions(array $options): array\n {\n $mapper = function (string $content): array {\n $content = \\trim($content);\n if ('-' !== ($content[0] ?? '')) {\n $content = '-' . $content;\n }\n\n return \\explode(' ', $content, 2);\n };\n\n $reducer = fn (array $carry, array $option): array => \\array_merge($carry, $option);\n\n return \\array_reduce(\\array_map($mapper, $options), $reducer, []);\n }\n\n public function setTimeout(int $timeout): self\n {\n $this->timeout = $timeout;\n return $this;\n }\n\n public function text(): string\n {\n $process = new Process(\\array_merge([$this->findPdfToText()], $this->options, [$this->pdf, '-']));\n $process->setTimeout($this->timeout);\n $process->run();\n if (!$process->isSuccessful()) {\n throw new ProcessFailedException($process);\n }\n\n return \\trim($process->getOutput(), \" \\t\\n\\r\\0\\x0B\\x0C\");\n }\n\n /**\n * @throws \\Exception\n */\n public static function getText(\n string $filePath,\n array $options = []\n ): string {\n /** @phpstan-ignore new.static */\n $instance = new static();\n $instance->setPdf($filePath);\n\n if (\\array_key_exists('binPath', $options)) {\n $instance->setBinPath($options['binPath']);\n }\n\n if (\\array_key_exists('options', $options)) {\n $instance->setOptions($options['options']);\n }\n\n if (\\array_key_exists('timeout', $options)) {\n $instance->setTimeout($options['timeout']);\n }\n\n return $instance->text();\n }\n}\n"], ["/neuron-ai/src/Tools/ToolProperty.php", " $this->name,\n 'description' => $this->description,\n 'type' => $this->type->value,\n 'enum' => $this->enum,\n 'required' => $this->required,\n ];\n }\n\n public function isRequired(): bool\n {\n return $this->required;\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n public function getType(): PropertyType\n {\n return $this->type;\n }\n\n public function getDescription(): ?string\n {\n return $this->description;\n }\n\n public function getEnum(): array\n {\n return $this->enum;\n }\n\n public function getJsonSchema(): array\n {\n $schema = [\n 'type' => $this->type->value,\n ];\n\n if (!\\is_null($this->description)) {\n $schema['description'] = $this->description;\n }\n\n if ($this->enum !== []) {\n $schema['enum'] = $this->enum;\n }\n\n return $schema;\n }\n}\n"], ["/neuron-ai/src/Providers/Deepseek/Deepseek.php", "parameters = \\array_merge($this->parameters, [\n 'response_format' => [\n 'type' => 'json_object',\n ]\n ]);\n\n $this->system .= \\PHP_EOL.\"# OUTPUT FORMAT CONSTRAINTS\".\\PHP_EOL\n .'Generate a json respecting this schema: '.\\json_encode($response_format);\n\n return $this->chat($messages);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/PGSQL/PGSQLSelectTool.php", "validateReadOnlyQuery($query)) {\n return [\n \"error\" => \"The query was rejected for security reasons.\nIt looks like you are trying to run a write query using the read-only query tool.\"\n ];\n }\n\n $statement = $this->pdo->prepare($query);\n $statement->execute();\n\n return $statement->fetchAll(PDO::FETCH_ASSOC);\n }\n\n /**\n * Validates that the query is read-only\n *\n * @throws InvalidArgumentException if query contains write operations\n */\n private function validateReadOnlyQuery(string $query): bool\n {\n if ($query === '') {\n return false;\n }\n\n // Remove comments to avoid false positives\n $cleanQuery = $this->removeComments($query);\n\n // Check if query starts with an allowed read operation\n $isAllowed = false;\n foreach ($this->allowedPatterns as $pattern) {\n if (\\preg_match($pattern, $cleanQuery)) {\n $isAllowed = true;\n break;\n }\n }\n\n if (!$isAllowed) {\n return false;\n }\n\n // Check for forbidden write operations\n foreach ($this->forbiddenPatterns as $pattern) {\n if (\\preg_match($pattern, $cleanQuery)) {\n return false;\n }\n }\n\n // Additional security checks\n return $this->performAdditionalSecurityChecks($cleanQuery);\n }\n\n private function removeComments(string $query): string\n {\n // Remove single-line comments (-- style)\n $query = \\preg_replace('/--.*$/m', '', $query);\n\n // Remove multi-line comments (/* */ style)\n $query = \\preg_replace('/\\/\\*.*?\\*\\//s', '', (string) $query);\n\n return $query;\n }\n\n private function performAdditionalSecurityChecks(string $query): bool\n {\n // Check for semicolon followed by potential write operations\n if (\\preg_match('/;\\s*(?!$)/i', $query)) {\n // Multiple statements detected - need to validate each one\n $statements = $this->splitStatements($query);\n foreach ($statements as $statement) {\n if (\\trim((string) $statement) !== '' && !$this->validateSingleStatement(\\trim((string) $statement))) {\n return false;\n }\n }\n }\n\n // Check for function calls that might modify data\n $dangerousFunctions = [\n 'pg_exec',\n 'pg_query',\n 'system',\n 'exec',\n 'shell_exec',\n 'passthru',\n 'eval',\n ];\n\n foreach ($dangerousFunctions as $func) {\n if (\\stripos($query, $func) !== false) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Split query into individual statements\n */\n private function splitStatements(string $query): array\n {\n // Simple split on semicolons (this could be enhanced for more complex cases)\n return \\array_filter(\n \\array_map('trim', \\explode(';', $query)),\n fn (string $stmt): bool => $stmt !== ''\n );\n }\n\n /**\n * Validate a single statement\n *\n * @return bool True if statement is valid read-only operation, false otherwise\n */\n private function validateSingleStatement(string $statement): bool\n {\n $isAllowed = false;\n foreach ($this->allowedPatterns as $pattern) {\n if (\\preg_match($pattern, $statement)) {\n $isAllowed = true;\n break;\n }\n }\n\n return $isAllowed;\n }\n}\n"], ["/neuron-ai/src/Observability/HandleInferenceEvents.php", "inspector->canAddSegments()) {\n return;\n }\n\n $label = $this->getBaseClassName($data->message::class);\n\n $this->segments[$this->getMessageId($data->message).'-save'] = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-chathistory', \"save_message( {$label} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function messageSaved(Agent $agent, string $event, MessageSaved $data): void\n {\n $id = $this->getMessageId($data->message).'-save';\n\n if (!\\array_key_exists($id, $this->segments)) {\n return;\n }\n\n $segment = $this->segments[$id];\n $segment->addContext('Message', \\array_merge(\n $data->message->jsonSerialize(),\n $data->message->getUsage() instanceof Usage ? [\n 'usage' => [\n 'input_tokens' => $data->message->getUsage()->inputTokens,\n 'output_tokens' => $data->message->getUsage()->outputTokens,\n ]\n ] : []\n ));\n $segment->end();\n }\n\n public function inferenceStart(Agent $agent, string $event, InferenceStart $data): void\n {\n if (!$this->inspector->canAddSegments() || $data->message === false) {\n return;\n }\n\n $label = $this->getBaseClassName($data->message::class);\n\n $this->segments[$this->getMessageId($data->message).'-inference'] = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-inference', \"inference( {$label} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function inferenceStop(Agent $agent, string $event, InferenceStop $data): void\n {\n $id = $this->getMessageId($data->message).'-inference';\n\n if (\\array_key_exists($id, $this->segments)) {\n $segment = $this->segments[$id]->end();\n $segment->addContext('Message', $data->message)\n ->addContext('Response', $data->response);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/ArrayOf.php", " 'is_bool',\n 'integer' => 'is_int',\n 'float' => 'is_float',\n 'numeric' => 'is_numeric',\n 'string' => 'is_string',\n 'scalar' => 'is_scalar',\n 'array' => 'is_array',\n 'iterable' => 'is_iterable',\n 'countable' => 'is_countable',\n 'object' => 'is_object',\n 'null' => 'is_null',\n 'alnum' => 'ctype_alnum',\n 'alpha' => 'ctype_alpha',\n 'cntrl' => 'ctype_cntrl',\n 'digit' => 'ctype_digit',\n 'graph' => 'ctype_graph',\n 'lower' => 'ctype_lower',\n 'print' => 'ctype_print',\n 'punct' => 'ctype_punct',\n 'space' => 'ctype_space',\n 'upper' => 'ctype_upper',\n 'xdigit' => 'ctype_xdigit',\n ];\n\n public function __construct(\n protected string $type,\n protected bool $allowEmpty = false,\n ) {\n }\n\n public function validate(string $name, mixed $value, array &$violations): void\n {\n if ($this->allowEmpty && empty($value)) {\n return;\n }\n\n if (!$this->allowEmpty && empty($value)) {\n $violations[] = $this->buildMessage($name, $this->message, ['type' => $this->type]);\n return;\n }\n\n if (!\\is_array($value)) {\n $violations[] = $this->buildMessage($name, $this->message);\n return;\n }\n\n $type = \\strtolower($this->type);\n\n $error = false;\n foreach ($value as $item) {\n if (isset(self::VALIDATION_FUNCTIONS[$type]) && self::VALIDATION_FUNCTIONS[$type]($item)) {\n continue;\n }\n\n // It's like a recursive call.\n if ($item instanceof $this->type && Validator::validate($item) === []) {\n continue;\n }\n\n $error = true;\n break;\n }\n\n if ($error) {\n $violations[] = $this->buildMessage($name, $this->message, ['type' => $this->type]);\n }\n }\n}\n"], ["/neuron-ai/src/Agent.php", "instructions = $instructions;\n return $this;\n }\n\n public function instructions(): string\n {\n return 'Your are a helpful and friendly AI agent built with NeuronAI PHP framework.';\n }\n\n public function resolveInstructions(): string\n {\n return $this->instructions ?? $this->instructions();\n }\n\n protected function removeDelimitedContent(string $text, string $openTag, string $closeTag): string\n {\n // Escape special regex characters in the tags\n $escapedOpenTag = \\preg_quote($openTag, '/');\n $escapedCloseTag = \\preg_quote($closeTag, '/');\n\n // Create the regex pattern to match content between tags\n $pattern = '/' . $escapedOpenTag . '.*?' . $escapedCloseTag . '/s';\n\n // Remove all occurrences of the delimited content\n return \\preg_replace($pattern, '', $text);\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/AdaptiveThresholdPostProcessor.php", "1.0: Not recommended as it tends to include almost all documents.\n *\n * @param float $multiplier multiplier for MAD (higher values = more inclusive)\n */\n public function __construct(private readonly float $multiplier = 0.6)\n {\n }\n\n /**\n * Filters documents using a threshold calculated dynamically with median and MAD\n * for greater robustness against outliers.\n */\n public function process(Message $question, array $documents): array\n {\n if (\\count($documents) < 2) {\n return $documents;\n }\n\n $scores = \\array_map(fn (Document $document): float => $document->getScore(), $documents);\n $median = $this->calculateMedian($scores);\n $mad = $this->calculateMAD($scores, $median);\n\n // If MAD is zero (many equal values), don't filter\n if ($mad <= 0.0001) {\n return $documents;\n }\n\n // Threshold: median - multiplier * MAD\n $threshold = $median - ($this->multiplier * $mad);\n\n // Ensure a threshold is not negative\n $threshold = \\max(0, $threshold);\n\n return \\array_values(\\array_filter($documents, fn (Document $document): bool => $document->getScore() >= $threshold));\n }\n\n /**\n * Calculates the median of an array of values\n *\n * @param float[] $values\n */\n protected function calculateMedian(array $values): float\n {\n \\sort($values);\n $n = \\count($values);\n $mid = (int) \\floor(($n - 1) / 2);\n\n if ($n % 2 !== 0) {\n return $values[$mid];\n }\n\n return ($values[$mid] + $values[$mid + 1]) / 2.0;\n }\n\n /**\n * Calculates the Median Absolute Deviation (MAD)\n *\n * @param float[] $values\n * @param float $median The median of the values\n */\n protected function calculateMAD(array $values, float $median): float\n {\n $deviations = \\array_map(fn (float$v): float => \\abs($v - $median), $values);\n\n // MAD is the median of deviations\n return $this->calculateMedian($deviations);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/AbstractToolkit.php", "exclude = $classes;\n return $this;\n }\n\n /**\n * @param class-string[] $classes\n */\n public function only(array $classes): ToolkitInterface\n {\n $this->only = $classes;\n return $this;\n }\n\n /**\n * @return ToolInterface[]\n */\n abstract public function provide(): array;\n\n public function tools(): array\n {\n if ($this->exclude === [] && $this->only === []) {\n return $this->provide();\n }\n\n return \\array_filter(\n $this->provide(),\n fn (ToolInterface $tool): bool => !\\in_array($tool::class, $this->exclude)\n && ($this->only === [] || \\in_array($tool::class, $this->only))\n );\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/MySQL/MySQLSelectTool.php", "validateReadOnly($query)) {\n return \"The query was rejected for security reasons.\n It looks like you are trying to run a write query using the read-only query tool.\";\n }\n\n $stmt = $this->pdo->prepare($query);\n $stmt->execute();\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n protected function validateReadOnly(string $query): bool\n {\n // Remove comments and normalize whitespace\n $cleanQuery = $this->sanitizeQuery($query);\n\n // Check if it starts with allowed statements\n $firstKeyword = $this->getFirstKeyword($cleanQuery);\n if (!\\in_array($firstKeyword, $this->allowedStatements)) {\n return false;\n }\n\n // Check for forbidden keywords that might be in subqueries\n foreach ($this->forbiddenStatements as $forbidden) {\n if (self::containsKeyword($cleanQuery, $forbidden)) {\n return false;\n }\n }\n\n return true;\n }\n\n protected function sanitizeQuery(string $query): string\n {\n // Remove SQL comments\n $query = \\preg_replace('/--.*$/m', '', $query);\n $query = \\preg_replace('/\\/\\*.*?\\*\\//s', '', (string) $query);\n\n // Normalize whitespace\n return \\preg_replace('/\\s+/', ' ', \\trim((string) $query));\n }\n\n protected function getFirstKeyword(string $query): string\n {\n if (\\preg_match('/^\\s*(\\w+)/i', $query, $matches)) {\n return \\strtoupper($matches[1]);\n }\n return '';\n }\n\n protected function containsKeyword(string $query, string $keyword): bool\n {\n // Use word boundaries to avoid false positives\n return \\preg_match('/\\b' . \\preg_quote($keyword, '/') . '\\b/i', $query) === 1;\n }\n}\n"], ["/neuron-ai/src/RAG/RAG.php", "chat($question);\n }\n\n /**\n * @deprecated Use \"stream\" instead\n */\n public function answerStream(Message $question): \\Generator\n {\n return $this->stream($question);\n }\n\n /**\n * @throws MissingCallbackParameter\n * @throws ToolCallableNotSet\n * @throws \\Throwable\n */\n public function chat(Message|array $messages): Message\n {\n $question = \\is_array($messages) ? \\end($messages) : $messages;\n\n $this->notify('chat-rag-start');\n\n $this->retrieval($question);\n\n $response = parent::chat($messages);\n\n $this->notify('chat-rag-stop');\n return $response;\n }\n\n public function stream(Message|array $messages): \\Generator\n {\n $question = \\is_array($messages) ? \\end($messages) : $messages;\n\n $this->notify('stream-rag-start');\n\n $this->retrieval($question);\n\n yield from parent::stream($messages);\n\n $this->notify('stream-rag-stop');\n }\n\n public function structured(Message|array $messages, ?string $class = null, int $maxRetries = 1): mixed\n {\n $question = \\is_array($messages) ? \\end($messages) : $messages;\n\n $this->notify('structured-rag-start');\n\n $this->retrieval($question);\n\n $structured = parent::structured($messages, $class, $maxRetries);\n\n $this->notify('structured-rag-stop');\n\n return $structured;\n }\n\n protected function retrieval(Message $question): void\n {\n $this->withDocumentsContext(\n $this->retrieveDocuments($question)\n );\n }\n\n /**\n * Set the system message based on the context.\n *\n * @param Document[] $documents\n */\n public function withDocumentsContext(array $documents): AgentInterface\n {\n $originalInstructions = $this->resolveInstructions();\n\n // Remove the old context to avoid infinite grow\n $newInstructions = $this->removeDelimitedContent($originalInstructions, '', '');\n\n $newInstructions .= '';\n foreach ($documents as $document) {\n $newInstructions .= \"Source Type: \".$document->getSourceType().\\PHP_EOL.\n \"Source Name: \".$document->getSourceName().\\PHP_EOL.\n \"Content: \".$document->getContent().\\PHP_EOL.\\PHP_EOL;\n }\n $newInstructions .= '';\n\n $this->withInstructions(\\trim($newInstructions));\n\n return $this;\n }\n\n /**\n * Retrieve relevant documents from the vector store.\n *\n * @return Document[]\n */\n public function retrieveDocuments(Message $question): array\n {\n $question = $this->applyPreProcessors($question);\n\n $this->notify('rag-retrieving', new Retrieving($question));\n\n $documents = $this->resolveVectorStore()->similaritySearch(\n $this->resolveEmbeddingsProvider()->embedText($question->getContent()),\n );\n\n $retrievedDocs = [];\n\n foreach ($documents as $document) {\n //md5 for removing duplicates\n $retrievedDocs[\\md5($document->getContent())] = $document;\n }\n\n $retrievedDocs = \\array_values($retrievedDocs);\n\n $this->notify('rag-retrieved', new Retrieved($question, $retrievedDocs));\n\n return $this->applyPostProcessors($question, $retrievedDocs);\n }\n\n /**\n * Apply a series of preprocessors to the asked question.\n *\n * @return Message The processed question.\n */\n protected function applyPreProcessors(Message $question): Message\n {\n foreach ($this->preProcessors() as $processor) {\n $this->notify('rag-preprocessing', new PreProcessing($processor::class, $question));\n $question = $processor->process($question);\n $this->notify('rag-preprocessed', new PreProcessed($processor::class, $question));\n }\n\n return $question;\n }\n\n /**\n * Apply a series of postprocessors to the retrieved documents.\n *\n * @param Document[] $documents The documents to process.\n * @return Document[] The processed documents.\n */\n protected function applyPostProcessors(Message $question, array $documents): array\n {\n foreach ($this->postProcessors() as $processor) {\n $this->notify('rag-postprocessing', new PostProcessing($processor::class, $question, $documents));\n $documents = $processor->process($question, $documents);\n $this->notify('rag-postprocessed', new PostProcessed($processor::class, $question, $documents));\n }\n\n return $documents;\n }\n\n /**\n * Feed the vector store with documents.\n *\n * @param Document[] $documents\n */\n public function addDocuments(array $documents, int $chunkSize = 50): void\n {\n foreach (\\array_chunk($documents, $chunkSize) as $chunk) {\n $this->resolveVectorStore()->addDocuments(\n $this->resolveEmbeddingsProvider()->embedDocuments($chunk)\n );\n }\n }\n\n /**\n * @param Document[] $documents\n */\n public function reindexBySource(array $documents, int $chunkSize = 50): void\n {\n $grouped = [];\n\n foreach ($documents as $document) {\n $key = $document->sourceType . ':' . $document->sourceName;\n\n if (!isset($grouped[$key])) {\n $grouped[$key] = [];\n }\n\n $grouped[$key][] = $document;\n }\n\n foreach (\\array_keys($grouped) as $key) {\n [$sourceType, $sourceName] = \\explode(':', $key);\n $this->resolveVectorStore()->deleteBySource($sourceType, $sourceName);\n $this->addDocuments($grouped[$key], $chunkSize);\n }\n }\n\n /**\n * @throws AgentException\n */\n public function setPreProcessors(array $preProcessors): RAG\n {\n foreach ($preProcessors as $processor) {\n if (! $processor instanceof PreProcessorInterface) {\n throw new AgentException($processor::class.\" must implement PreProcessorInterface\");\n }\n\n $this->preProcessors[] = $processor;\n }\n\n return $this;\n }\n\n /**\n * @throws AgentException\n */\n public function setPostProcessors(array $postProcessors): RAG\n {\n foreach ($postProcessors as $processor) {\n if (! $processor instanceof PostProcessorInterface) {\n throw new AgentException($processor::class.\" must implement PostProcessorInterface\");\n }\n\n $this->postProcessors[] = $processor;\n }\n\n return $this;\n }\n\n /**\n * @return PreProcessorInterface[]\n */\n protected function preProcessors(): array\n {\n return $this->preProcessors;\n }\n\n /**\n * @return PostProcessorInterface[]\n */\n protected function postProcessors(): array\n {\n return $this->postProcessors;\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/HandleStructured.php", "parameters = \\array_merge($this->parameters, [\n 'response_format' => [\n 'type' => 'json_schema',\n 'json_schema' => [\n \"name\" => \\end($tk),\n \"strict\" => false,\n \"schema\" => $response_format,\n ],\n ]\n ]);\n\n return $this->chat($messages);\n }\n}\n"], ["/neuron-ai/src/MCP/StdioTransport.php", " [\"pipe\", \"r\"], // stdin\n 1 => [\"pipe\", \"w\"], // stdout\n 2 => [\"pipe\", \"w\"] // stderr\n ];\n\n $command = $this->config['command'];\n $args = $this->config['args'] ?? [];\n $env = $this->config['env'] ?? [];\n\n // Merge current environment with provided environment variables\n $fullEnv = \\array_merge(\\getenv(), $env);\n\n // Build command with arguments\n $commandLine = $command;\n foreach ($args as $arg) {\n $commandLine .= ' ' . \\escapeshellarg((string) $arg);\n }\n\n // Start the process\n $this->process = \\proc_open(\n $commandLine,\n $descriptorSpec,\n $this->pipes,\n null,\n $fullEnv\n );\n\n if (!\\is_resource($this->process)) {\n throw new McpException(\"Failed to start the MCP server process\");\n }\n\n // Configure pipes for binary data\n \\stream_set_write_buffer($this->pipes[0], 0);\n \\stream_set_read_buffer($this->pipes[1], 0);\n\n // Check that the process started successfully\n $status = \\proc_get_status($this->process);\n if (!$status['running']) {\n $error = \\stream_get_contents($this->pipes[2]);\n throw new McpException(\"Process failed to start: \" . $error);\n }\n }\n\n /**\n * Send a request to the MCP server\n */\n public function send(array $data): void\n {\n if (!\\is_resource($this->process)) {\n throw new McpException(\"Process is not running\");\n }\n\n $status = \\proc_get_status($this->process);\n if (!$status['running']) {\n throw new McpException(\"MCP server process is not running\");\n }\n\n $jsonData = \\json_encode($data);\n if ($jsonData === false) {\n throw new McpException(\"Failed to encode request data to JSON\");\n }\n\n $bytesWritten = \\fwrite($this->pipes[0], $jsonData . \"\\n\");\n if ($bytesWritten === false || $bytesWritten < \\strlen($jsonData) + 1) {\n throw new McpException(\"Failed to write complete request to MCP server\");\n }\n\n \\fflush($this->pipes[0]);\n }\n\n /**\n * Receive a response from the MCP server\n */\n public function receive(): array\n {\n if (!\\is_resource($this->process)) {\n throw new McpException(\"Process is not running\");\n }\n\n // Set stream to non-blocking mode\n \\stream_set_blocking($this->pipes[1], false);\n\n $response = \"\";\n $startTime = \\time();\n $timeout = 30; // 30-second timeout\n\n // Keep reading until we get a complete JSON response or timeout\n while (\\time() - $startTime < $timeout) {\n $status = \\proc_get_status($this->process);\n\n if (!$status['running']) {\n throw new McpException(\"MCP server process has terminated unexpectedly.\");\n }\n\n $chunk = \\fread($this->pipes[1], 4096);\n if ($chunk !== false && \\strlen($chunk) > 0) {\n $response .= $chunk;\n\n // Try to parse what we have so far\n $decoded = \\json_decode($response, true);\n if ($decoded !== null) {\n // We've got a valid JSON response\n return $decoded;\n }\n }\n\n // Small delay to prevent CPU spinning\n \\usleep(10000); // 10ms\n }\n\n throw new McpException(\"Timeout waiting for response from MCP server\");\n }\n\n /**\n * Disconnect from the MCP server\n */\n public function disconnect(): void\n {\n if (\\is_resource($this->process)) {\n // Close all pipe handles\n foreach ($this->pipes as $pipe) {\n if (\\is_resource($pipe)) {\n \\fclose($pipe);\n }\n }\n\n // Try graceful termination first\n $status = \\proc_get_status($this->process);\n // On Unix systems, try sending SIGTERM\n if ($status['running'] && \\function_exists('proc_terminate')) {\n \\proc_terminate($this->process);\n // Give the process a moment to shut down gracefully\n \\usleep(500000);\n // 500ms\n }\n\n // Close the process handle\n \\proc_close($this->process);\n $this->process = null;\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/DivideTool.php", " $this->name,\n 'error' => 'Division by zero is not allowed.'\n ];\n }\n\n return $number1 / $number2;\n }\n}\n"], ["/neuron-ai/src/Observability/HandleStructuredEvents.php", "inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$data->class.'-schema'] = $this->inspector->startSegment('neuron-schema-generation', \"schema_generate( {$data->class} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n protected function schemaGenerated(AgentInterface $agent, string $event, SchemaGenerated $data): void\n {\n if (\\array_key_exists($data->class.'-schema', $this->segments)) {\n $segment = $this->segments[$data->class.'-schema']->end();\n $segment->addContext('Schema', $data->schema);\n }\n }\n\n protected function extracting(AgentInterface $agent, string $event, Extracting $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $id = $this->getMessageId($data->message).'-extract';\n\n $this->segments[$id] = $this->inspector->startSegment('neuron-structured-extract', 'extract_output')\n ->setColor(self::SEGMENT_COLOR);\n }\n\n protected function extracted(AgentInterface $agent, string $event, Extracted $data): void\n {\n $id = $this->getMessageId($data->message).'-extract';\n\n if (\\array_key_exists($id, $this->segments)) {\n $segment = $this->segments[$id]->end();\n $segment->addContext(\n 'Data',\n [\n 'response' => $data->message->jsonSerialize(),\n 'json' => $data->json,\n ]\n )->addContext(\n 'Schema',\n $data->schema\n );\n unset($this->segments[$id]);\n }\n }\n\n protected function deserializing(AgentInterface $agent, string $event, Deserializing $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$data->class.'-deserialize'] = $this->inspector->startSegment('neuron-structured-deserialize', \"deserialize( {$data->class} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n protected function deserialized(AgentInterface $agent, string $event, Deserialized $data): void\n {\n $id = $data->class.'-deserialize';\n\n if (\\array_key_exists($id, $this->segments)) {\n $this->segments[$id]->end();\n }\n }\n\n protected function validating(AgentInterface $agent, string $event, Validating $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$data->class.'-validate'] = $this->inspector->startSegment('neuron-structured-validate', \"validate( {$data->class} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n protected function validated(AgentInterface $agent, string $event, Validated $data): void\n {\n $id = $data->class.'-validate';\n\n if (\\array_key_exists($id, $this->segments)) {\n $segment = $this->segments[$id]->end();\n $segment->addContext('Json', \\json_decode($data->json));\n if ($data->violations !== []) {\n $segment->addContext('Violations', $data->violations);\n }\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/NthRootTool.php", "exporter = new MermaidExporter();\n\n if (\\is_null($persistence) && !\\is_null($workflowId)) {\n throw new WorkflowException('Persistence must be defined when workflowId is defined');\n }\n if (\\is_null($workflowId) && !\\is_null($persistence)) {\n throw new WorkflowException('WorkflowId must be defined when persistence is defined');\n }\n\n $this->persistence = $persistence ?? new InMemoryPersistence();\n $this->workflowId = $workflowId ?? \\uniqid('neuron_workflow_');\n }\n\n public function validate(): void\n {\n /*if ($this->getStartNode() === null) {\n throw new WorkflowException('Start node must be defined');\n }\n\n if ($this->getEndNode() === null) {\n throw new WorkflowException('End node must be defined');\n }*/\n\n if (!isset($this->getNodes()[$this->getStartNode()])) {\n throw new WorkflowException(\"Start node {$this->getStartNode()} does not exist\");\n }\n\n foreach ($this->getEndNodes() as $endNode) {\n if (!isset($this->getNodes()[$endNode])) {\n throw new WorkflowException(\"End node {$endNode} does not exist\");\n }\n }\n\n foreach ($this->getEdges() as $edge) {\n if (!isset($this->getNodes()[$edge->getFrom()])) {\n throw new WorkflowException(\"Edge from node {$edge->getFrom()} does not exist\");\n }\n\n if (!isset($this->getNodes()[$edge->getTo()])) {\n throw new WorkflowException(\"Edge to node {$edge->getTo()} does not exist\");\n }\n }\n }\n\n /**\n * @throws WorkflowInterrupt|WorkflowException|\\Throwable\n */\n protected function execute(\n string $currentNode,\n WorkflowState $state,\n bool $resuming = false,\n array|string|int $humanFeedback = []\n ): WorkflowState {\n $context = new WorkflowContext(\n $this->workflowId,\n $currentNode,\n $this->persistence,\n $state\n );\n\n if ($resuming) {\n $context->setResuming(true, [$currentNode => $humanFeedback]);\n }\n\n try {\n while (!\\in_array($currentNode, $this->getEndNodes())) {\n $node = $this->nodes[$currentNode];\n $node->setContext($context);\n\n $this->notify('workflow-node-start', new WorkflowNodeStart($currentNode, $state));\n try {\n $state = $node->run($state);\n } catch (WorkflowInterrupt $interrupt) {\n throw $interrupt;\n } catch (\\Throwable $exception) {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n $this->notify('workflow-node-end', new WorkflowNodeEnd($currentNode, $state));\n\n $nextNode = $this->findNextNode($currentNode, $state);\n\n if ($nextNode === null) {\n throw new WorkflowException(\"No valid edge found from node {$currentNode}\");\n }\n\n $currentNode = $nextNode;\n\n // Update the context before the next iteration or end node\n $context = new WorkflowContext(\n $this->workflowId,\n $currentNode,\n $this->persistence,\n $state\n );\n }\n\n $endNode = $this->nodes[$currentNode];\n $endNode->setContext($context);\n $result = $endNode->run($state);\n $this->persistence->delete($this->workflowId);\n return $result;\n\n } catch (WorkflowInterrupt $interrupt) {\n $this->persistence->save($this->workflowId, $interrupt);\n $this->notify('workflow-interrupt', $interrupt);\n throw $interrupt;\n }\n }\n\n /**\n * @throws WorkflowInterrupt|WorkflowException|\\Throwable\n */\n public function run(?WorkflowState $initialState = null): WorkflowState\n {\n $this->notify('workflow-start', new WorkflowStart($this->getNodes(), $this->getEdges()));\n try {\n $this->validate();\n } catch (WorkflowException $exception) {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n\n $state = $initialState ?? new WorkflowState();\n $currentNode = $this->getStartNode();\n\n $result = $this->execute($currentNode, $state);\n $this->notify('workflow-end', new WorkflowEnd($result));\n\n return $result;\n }\n\n /**\n * @throws WorkflowInterrupt|WorkflowException|\\Throwable\n */\n public function resume(array|string|int $humanFeedback): WorkflowState\n {\n $this->notify('workflow-resume', new WorkflowStart($this->getNodes(), $this->getEdges()));\n $interrupt = $this->persistence->load($this->workflowId);\n\n $state = $interrupt->getState();\n $currentNode = $interrupt->getCurrentNode();\n\n $result = $this->execute(\n $currentNode,\n $state,\n true,\n $humanFeedback\n );\n $this->notify('workflow-end', new WorkflowEnd($result));\n\n return $result;\n }\n\n /**\n * @return Node[]\n */\n protected function nodes(): array\n {\n return [];\n }\n\n /**\n * @return Edge[]\n */\n protected function edges(): array\n {\n return [];\n }\n\n public function addNode(NodeInterface $node): self\n {\n $this->nodes[$node::class] = $node;\n return $this;\n }\n\n /**\n * @param NodeInterface[] $nodes\n */\n public function addNodes(array $nodes): Workflow\n {\n foreach ($nodes as $node) {\n $this->addNode($node);\n }\n return $this;\n }\n\n /**\n * @return array\n */\n public function getNodes(): array\n {\n if ($this->nodes === []) {\n foreach ($this->nodes() as $node) {\n $this->addNode($node);\n }\n }\n\n return $this->nodes;\n }\n\n public function addEdge(Edge $edge): self\n {\n $this->edges[] = $edge;\n return $this;\n }\n\n /**\n * @param Edge[] $edges\n */\n public function addEdges(array $edges): Workflow\n {\n foreach ($edges as $edge) {\n $this->addEdge($edge);\n }\n return $this;\n }\n\n /**\n * @return Edge[]\n */\n public function getEdges(): array\n {\n if ($this->edges === []) {\n $this->edges = $this->edges();\n }\n\n return $this->edges;\n }\n\n public function setStart(string $nodeClass): Workflow\n {\n $this->startNode = $nodeClass;\n return $this;\n }\n\n public function setEnd(string $nodeClass): Workflow\n {\n $this->endNodes[] = $nodeClass;\n return $this;\n }\n\n protected function getStartNode(): string\n {\n return $this->startNode ?? $this->start();\n }\n\n protected function getEndNodes(): array\n {\n return $this->endNodes ?? $this->end();\n }\n\n protected function start(): ?string\n {\n throw new WorkflowException('Start node must be defined');\n }\n\n protected function end(): array\n {\n throw new WorkflowException('End node must be defined');\n }\n\n private function findNextNode(string $currentNode, WorkflowState $state): ?string\n {\n foreach ($this->getEdges() as $edge) {\n if ($edge->getFrom() === $currentNode && $edge->shouldExecute($state)) {\n return $edge->getTo();\n }\n }\n\n return null;\n }\n\n public function getWorkflowId(): string\n {\n return $this->workflowId;\n }\n\n public function export(): string\n {\n return $this->exporter->export($this);\n }\n\n public function setExporter(ExporterInterface $exporter): Workflow\n {\n $this->exporter = $exporter;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Providers/AIProviderInterface.php", "table = $this->sanitizeTableName($table);\n $this->load();\n }\n\n protected function load(): void\n {\n $stmt = $this->pdo->prepare(\"SELECT * FROM {$this->table} WHERE thread_id = :thread_id\");\n $stmt->execute(['thread_id' => $this->thread_id]);\n $history = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n if (empty($history)) {\n $stmt = $this->pdo->prepare(\"INSERT INTO {$this->table} (thread_id, messages) VALUES (:thread_id, :messages)\");\n $stmt->execute(['thread_id' => $this->thread_id, 'messages' => '[]']);\n } else {\n $this->history = $this->deserializeMessages(\\json_decode((string) $history[0]['messages'], true));\n }\n }\n\n public function setMessages(array $messages): ChatHistoryInterface\n {\n $stmt = $this->pdo->prepare(\"UPDATE {$this->table} SET messages = :messages WHERE thread_id = :thread_id\");\n $stmt->execute(['thread_id' => $this->thread_id, 'messages' => \\json_encode($this->jsonSerialize())]);\n return $this;\n }\n\n protected function clear(): ChatHistoryInterface\n {\n $stmt = $this->pdo->prepare(\"DELETE FROM {$this->table} WHERE thread_id = :thread_id\");\n $stmt->execute(['thread_id' => $this->thread_id]);\n return $this;\n }\n\n protected function sanitizeTableName(string $tableName): string\n {\n $tableName = \\trim($tableName);\n\n // Whitelist validation\n if (!$this->tableExists($tableName)) {\n throw new ChatHistoryException('Table not allowed');\n }\n\n // Format validation as backup\n if (\\in_array(\\preg_match('/^[a-zA-Z_]\\w*$/', $tableName), [0, false], true)) {\n throw new ChatHistoryException('Invalid table name format');\n }\n\n return $tableName;\n }\n\n protected function tableExists(string $tableName): bool\n {\n $stmt = $this->pdo->prepare(\"SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :table_name\");\n $stmt->execute(['table_name' => $tableName]);\n return $stmt->fetch() !== false;\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Count.php", "exactly && null === $this->min && null === $this->max) {\n $this->min = $this->max = $this->exactly;\n }\n\n if (null === $this->min && null === $this->max) {\n throw new StructuredOutputException('Either option \"min\" or \"max\" must be given for validation rule \"Length\"');\n }\n\n if (\\is_null($value) && ($this->min > 0 || $this->exactly > 0)) {\n $violations[] = $this->buildMessage($name, '{name} cannot be empty');\n return;\n }\n\n if (!\\is_array($value) && !$value instanceof \\Countable) {\n throw new StructuredOutputException($name. ' must be an array or a Countable object');\n }\n\n\n $count = \\count($value);\n\n if (null !== $this->max && $count > $this->max) {\n $shouldExact = $this->min == $this->max;\n\n if ($shouldExact) {\n $violations[] = $this->buildMessage($name, '{name} must be exactly {exact} items long', ['exact' => $this->min]);\n } else {\n $violations[] = $this->buildMessage($name, '{name} is too long. It must be at most {max} items', ['max' => $this->max]);\n }\n }\n\n if (null !== $this->min && $count < $this->min) {\n $shouldExact = $this->min == $this->max;\n\n if ($shouldExact) {\n $violations[] = $this->buildMessage($name, '{name} must be exactly {exact} items long', ['exact' => $this->min]);\n } else {\n $violations[] = $this->buildMessage($name, '{name} is too short. It must be at least {min} items', ['min' => $this->min]);\n }\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Validator.php", "getProperties(\\ReflectionProperty::IS_PUBLIC) as $property) {\n // Get all attributes for this property\n $attributes = $property->getAttributes();\n\n if (empty($attributes)) {\n continue;\n }\n\n // Get the value of the property\n $name = $property->getName();\n $value = $property->isInitialized($obj) ? $property->getValue($obj) : null;\n\n // Apply all the validation rules to the value\n foreach ($attributes as $attribute) {\n $instance = $attribute->newInstance();\n\n // Perform validation\n if ($instance instanceof ValidationRuleInterface) {\n $instance->validate($name, $value, $violations);\n }\n }\n }\n\n return $violations;\n }\n}\n"], ["/neuron-ai/src/Chat/Attachments/Attachment.php", " $this->type->value,\n 'content' => $this->content,\n 'content_type' => $this->contentType->value,\n 'media_type' => $this->mediaType,\n ]);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/MySQL/MySQLWriteTool.php", "pdo->prepare($query)->execute();\n\n return $result\n ? \"The query has been executed successfully.\"\n : \"I'm sorry, there was an error executing the query.\";\n }\n}\n"], ["/neuron-ai/src/RAG/Document.php", "id = \\uniqid();\n }\n\n public function getId(): string|int\n {\n return $this->id;\n }\n\n public function getContent(): string\n {\n return $this->content;\n }\n\n public function getEmbedding(): array\n {\n return $this->embedding;\n }\n\n public function getSourceType(): string\n {\n return $this->sourceType;\n }\n\n public function getSourceName(): string\n {\n return $this->sourceName;\n }\n\n public function getScore(): float\n {\n return $this->score;\n }\n\n public function setScore(float $score): Document\n {\n $this->score = $score;\n return $this;\n }\n\n public function addMetadata(string $key, string|int $value): Document\n {\n $this->metadata[$key] = $value;\n return $this;\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'id' => $this->getId(),\n 'content' => $this->getContent(),\n 'embedding' => $this->getEmbedding(),\n 'sourceType' => $this->getSourceType(),\n 'sourceName' => $this->getSourceName(),\n 'score' => $this->getScore(),\n 'metadata' => $this->metadata,\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/PGSQL/PGSQLWriteTool.php", "pdo->prepare($query)->execute();\n\n return $result\n ? \"The query has been executed successfully.\"\n : \"I'm sorry, there was an error executing the query.\";\n }\n}\n"], ["/neuron-ai/src/RAG/DataLoader/FileDataLoader.php", "\n */\n protected array $readers = [];\n\n public function __construct(protected string $path, array $readers = [])\n {\n parent::__construct();\n $this->setReaders($readers);\n }\n\n public function addReader(string $fileExtension, ReaderInterface $reader): self\n {\n $this->readers[$fileExtension] = $reader;\n return $this;\n }\n\n public function setReaders(array $readers): self\n {\n $this->readers = $readers;\n return $this;\n }\n\n public function getDocuments(): array\n {\n if (! \\file_exists($this->path)) {\n return [];\n }\n\n // If it's a directory\n if (\\is_dir($this->path)) {\n return $this->getDocumentsFromDirectory($this->path);\n }\n\n // If it's a file\n try {\n return $this->splitter->splitDocument($this->getDocument($this->getContentFromFile($this->path), $this->path));\n } catch (\\Throwable) {\n return [];\n }\n }\n\n protected function getDocumentsFromDirectory(string $directory): array\n {\n $documents = [];\n // Open the directory\n if ($handle = \\opendir($directory)) {\n // Read the directory contents\n while (($entry = \\readdir($handle)) !== false) {\n $fullPath = $directory.'/'.$entry;\n if ($entry !== '.' && $entry !== '..') {\n if (\\is_dir($fullPath)) {\n $documents = [...$documents, ...$this->getDocumentsFromDirectory($fullPath)];\n } else {\n try {\n $documents[] = $this->getDocument($this->getContentFromFile($fullPath), $entry);\n } catch (\\Throwable) {\n }\n }\n }\n }\n\n // Close the directory\n \\closedir($handle);\n }\n\n return $this->splitter->splitDocuments($documents);\n }\n\n /**\n * Transform files to plain text.\n *\n * Supported PDF and plain text files.\n *\n * @throws \\Exception\n */\n protected function getContentFromFile(string $path): string|false\n {\n $fileExtension = \\strtolower(\\pathinfo($path, \\PATHINFO_EXTENSION));\n\n if (\\array_key_exists($fileExtension, $this->readers)) {\n $reader = $this->readers[$fileExtension];\n return $reader::getText($path);\n }\n\n return TextFileReader::getText($path);\n }\n\n\n protected function getDocument(string $content, string $entry): Document\n {\n $document = new Document($content);\n $document->sourceType = 'files';\n $document->sourceName = $entry;\n\n return $document;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/MemoryVectorStore.php", "documents[] = $document;\n }\n\n public function addDocuments(array $documents): void\n {\n $this->documents = \\array_merge($this->documents, $documents);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->documents = \\array_filter($this->documents, fn (Document $document): bool => $document->getSourceType() !== $sourceType || $document->getSourceName() !== $sourceName);\n }\n\n public function similaritySearch(array $embedding): array\n {\n $distances = [];\n\n foreach ($this->documents as $index => $document) {\n if ($document->embedding === []) {\n throw new VectorStoreException(\"Document with the following content has no embedding: {$document->getContent()}\");\n }\n $dist = VectorSimilarity::cosineDistance($embedding, $document->getEmbedding());\n $distances[$index] = $dist;\n }\n\n \\asort($distances); // Sort by distance (ascending).\n\n $topKIndices = \\array_slice(\\array_keys($distances), 0, $this->topK, true);\n\n return \\array_reduce($topKIndices, function (array $carry, int $index) use ($distances): array {\n $document = $this->documents[$index];\n $document->setScore(VectorSimilarity::similarityFromDistance($distances[$index]));\n $carry[] = $document;\n return $carry;\n }, []);\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Length.php", "exactly && null === $this->min && null === $this->max) {\n $this->min = $this->max = $this->exactly;\n }\n\n if (null === $this->min && null === $this->max) {\n throw new StructuredOutputException('Either option \"min\" or \"max\" must be given for validation rule \"Length\"');\n }\n\n if (\\is_null($value) && ($this->min > 0 || $this->exactly > 0)) {\n $violations[] = $this->buildMessage($name, '{name} cannot be empty');\n return;\n }\n\n if (!\\is_scalar($value) && !$value instanceof \\Stringable) {\n $violations[] = $this->buildMessage($name, '{name} must be a scalar or a stringable object');\n return;\n }\n\n $stringValue = (string) $value;\n\n $length = \\mb_strlen($stringValue);\n\n if (null !== $this->max && $length > $this->max) {\n $shouldExact = $this->min == $this->max;\n\n if ($shouldExact) {\n $violations[] = $this->buildMessage($name, '{name} must be exactly {exact} characters long', ['exact' => $this->min]);\n } else {\n $violations[] = $this->buildMessage($name, '{name} is too long. It must be at most {max} characters', ['max' => $this->max]);\n }\n }\n\n if (null !== $this->min && $length < $this->min) {\n $shouldExact = $this->min == $this->max;\n\n if ($shouldExact) {\n $violations[] = $this->buildMessage($name, '{name} must be exactly {exact} characters long', ['exact' => $this->min]);\n } else {\n $violations[] = $this->buildMessage($name, '{name} is too short. It must be at least {min} characters', ['min' => $this->min]);\n }\n }\n }\n}\n"], ["/neuron-ai/src/Providers/HuggingFace/HuggingFace.php", "buildBaseUri();\n parent::__construct($key, $model, $parameters);\n }\n\n private function buildBaseUri(): void\n {\n $endpoint = match ($this->inferenceProvider) {\n InferenceProvider::HF_INFERENCE => \\trim($this->inferenceProvider->value, \\DIRECTORY_SEPARATOR).\\DIRECTORY_SEPARATOR.$this->model,\n default => \\trim($this->inferenceProvider->value, \\DIRECTORY_SEPARATOR),\n };\n\n $this->baseUri = \\sprintf($this->baseUri, $endpoint);\n }\n\n}\n"], ["/neuron-ai/src/Observability/HandleWorkflowEvents.php", "inspector->isRecording()) {\n return;\n }\n\n if ($this->inspector->needTransaction()) {\n $this->inspector->startTransaction($workflow::class)\n ->setType('neuron-workflow')\n ->addContext('List', [\n 'nodes' => \\array_keys($data->nodes),\n 'edges' => \\array_map(fn (Edge $edge): array => [\n 'from' => $edge->getFrom(),\n 'to' => $edge->getTo(),\n 'has_condition' => $edge->hasCondition(),\n ], $data->edges)\n ]);\n } elseif ($this->inspector->canAddSegments()) {\n $this->segments[$workflow::class] = $this->inspector->startSegment('neuron-workflow', $workflow::class)\n ->setColor(self::SEGMENT_COLOR);\n }\n }\n\n public function workflowEnd(\\SplSubject $workflow, string $event, WorkflowEnd $data): void\n {\n if (\\array_key_exists($workflow::class, $this->segments)) {\n $this->segments[$workflow::class]\n ->end()\n ->addContext('State', $data->state->all());\n } elseif ($this->inspector->canAddSegments()) {\n $transaction = $this->inspector->transaction();\n $transaction->addContext('State', $data->state->all());\n $transaction->setResult('success');\n }\n }\n\n public function workflowNodeStart(\\SplSubject $workflow, string $event, WorkflowNodeStart $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $segment = $this->inspector\n ->startSegment('workflow-node', $data->node)\n ->setColor(self::SEGMENT_COLOR);\n $segment->addContext('Before', $data->state->all());\n $this->segments[$data->node] = $segment;\n }\n\n public function workflowNodeEnd(\\SplSubject $workflow, string $event, WorkflowNodeEnd $data): void\n {\n if (\\array_key_exists($data->node, $this->segments)) {\n $segment = $this->segments[$data->node]->end();\n $segment->addContext('After', $data->state->all());\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Enum.php", "values !== null && $this->values !== [] && $this->class !== null) {\n throw new StructuredOutputException('You cannot provide both \"choices\" and \"enum\" options simultaneously. Please use only one.');\n }\n\n if (($this->values === null || $this->values === []) && $this->class === null) {\n throw new StructuredOutputException('Either option \"choices\" or \"enum\" must be given for validation rule \"Enum\"');\n }\n\n if ($this->values === null || $this->values === []) {\n $this->handleEnum();\n }\n }\n\n public function validate(string $name, mixed $value, array &$violations): void\n {\n $value = $value instanceof \\BackedEnum ? $value->value : $value;\n\n if (!\\in_array($value, $this->values, true)) {\n $violations[] = $this->buildMessage($name, $this->message, ['choices' => \\implode(\", \", $this->values)]);\n }\n }\n\n /**\n * @throws StructuredOutputException\n */\n private function handleEnum(): void\n {\n if (!\\enum_exists($this->class)) {\n throw new StructuredOutputException(\"Enum '{$this->class}' does not exist.\");\n }\n\n if (!\\is_subclass_of($this->class, \\BackedEnum::class)) {\n throw new StructuredOutputException(\"Enum '{$this->class}' must implement BackedEnum.\");\n }\n\n $this->values = \\array_map(fn (\\BackedEnum $case): int|string => $case->value, $this->class::cases());\n }\n}\n"], ["/neuron-ai/src/RAG/Splitter/SentenceTextSplitter.php", "= $maxWords) {\n throw new InvalidArgumentException('Overlap must be less than maxWords');\n }\n\n $this->maxWords = $maxWords;\n $this->overlapWords = $overlapWords;\n }\n\n /**\n * Splits text into word-based chunks, preserving sentence boundaries.\n *\n * @return Document[] Array of Document chunks\n */\n public function splitDocument(Document $document): array\n {\n // Split by paragraphs (2 or more newlines)\n $paragraphs = \\preg_split('/\\n{2,}/', $document->getContent());\n $chunks = [];\n $currentWords = [];\n\n foreach ($paragraphs as $paragraph) {\n $sentences = $this->splitSentences($paragraph);\n\n foreach ($sentences as $sentence) {\n $sentenceWords = $this->tokenizeWords($sentence);\n\n // If the sentence alone exceeds the limit, split it\n if (\\count($sentenceWords) > $this->maxWords) {\n if ($currentWords !== []) {\n $chunks[] = \\implode(' ', $currentWords);\n $currentWords = [];\n }\n $chunks = \\array_merge($chunks, $this->splitLongSentence($sentenceWords));\n continue;\n }\n\n $candidateCount = \\count($currentWords) + \\count($sentenceWords);\n\n if ($candidateCount > $this->maxWords) {\n if ($currentWords !== []) {\n $chunks[] = \\implode(' ', $currentWords);\n }\n $currentWords = $sentenceWords;\n } else {\n $currentWords = \\array_merge($currentWords, $sentenceWords);\n }\n }\n }\n\n if ($currentWords !== []) {\n $chunks[] = \\implode(' ', $currentWords);\n }\n\n // Apply overlap only if necessary\n if ($this->overlapWords > 0) {\n $chunks = $this->applyOverlap($chunks);\n }\n\n $split = [];\n foreach ($chunks as $chunk) {\n $newDocument = new Document($chunk);\n $newDocument->sourceType = $document->getSourceType();\n $newDocument->sourceName = $document->getSourceName();\n $split[] = $newDocument;\n }\n\n return $split;\n }\n\n /**\n * Robust regex for sentence splitting (handles ., !, ?, …, periods followed by quotes, etc)\n */\n private function splitSentences(string $text): array\n {\n $pattern = '/(?<=[.!?…])\\s+(?=(?:[\\\"\\'\\\"\"\\'\\'«»„\"\"]?)[A-ZÀ-Ÿ])/u';\n $sentences = \\preg_split($pattern, \\trim($text));\n return \\array_filter(\\array_map('trim', $sentences));\n }\n\n /**\n * Tokenizes text into words (simple whitespace split).\n *\n * @return string[] Array of words\n */\n private function tokenizeWords(string $text): array\n {\n return \\preg_split('/\\s+/u', \\trim($text));\n }\n\n /**\n * Applies overlap of words between consecutive chunks.\n *\n * @param string[] $chunks\n * @return string[] Array of chunks with overlap applied\n */\n private function applyOverlap(array $chunks): array\n {\n if ($chunks === []) {\n return [];\n }\n\n $result = [$chunks[0]]; // First chunk remains unchanged\n $count = \\count($chunks);\n\n for ($i = 1; $i < $count; $i++) {\n $prevWords = $this->tokenizeWords($chunks[$i - 1]);\n $curWords = $this->tokenizeWords($chunks[$i]);\n\n // Get only the words needed for overlap\n $overlap = \\array_slice($prevWords, -$this->overlapWords);\n\n // Remove duplicate words at the beginning of current chunk\n $curWords = \\array_slice($curWords, $this->overlapWords);\n\n $merged = \\array_merge($overlap, $curWords);\n $result[] = \\implode(' ', $merged);\n }\n\n return $result;\n }\n\n /**\n * Splits a long sentence into smaller chunks that respect the maxWords limit.\n *\n * @param string[] $words Array of words from the sentence\n * @return string[] Array of chunks\n */\n private function splitLongSentence(array $words): array\n {\n $chunks = [];\n $currentChunk = [];\n\n foreach ($words as $word) {\n if (\\count($currentChunk) >= $this->maxWords) {\n $chunks[] = \\implode(' ', $currentChunk);\n $currentChunk = [];\n }\n $currentChunk[] = $word;\n }\n\n if ($currentChunk !== []) {\n $chunks[] = \\implode(' ', $currentChunk);\n }\n\n return $chunks;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/DoctrineVectorStore.php", "getConnection();\n $this->doctrineVectorStoreType = SupportedDoctrineVectorStore::fromPlatform($conn->getDatabasePlatform());\n $registeredTypes = Type::getTypesMap();\n if (!\\array_key_exists(VectorType::VECTOR, $registeredTypes)) {\n Type::addType(VectorType::VECTOR, VectorType::class);\n $conn->getDatabasePlatform()->registerDoctrineTypeMapping('vector', VectorType::VECTOR);\n }\n\n $this->doctrineVectorStoreType->addCustomisationsTo($this->entityManager);\n }\n\n public function addDocument(Document $document): void\n {\n if ($document->embedding === []) {\n throw new \\RuntimeException('document embedding must be set before adding a document');\n }\n\n $this->persistDocument($document);\n $this->entityManager->flush();\n }\n\n public function addDocuments(array $documents): void\n {\n if ($documents === []) {\n return;\n }\n foreach ($documents as $document) {\n $this->persistDocument($document);\n }\n\n $this->entityManager->flush();\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n throw new VectorStoreException(\"Delete by source not implemented in \".self::class);\n }\n\n public function similaritySearch(array $embedding): array\n {\n $repository = $this->entityManager->getRepository($this->entityClassName);\n\n $qb = $repository\n ->createQueryBuilder('e')\n ->orderBy($this->doctrineVectorStoreType->l2DistanceName().'(e.embedding, :embeddingString)', 'ASC')\n ->setParameter('embeddingString', $this->doctrineVectorStoreType->getVectorAsString($embedding))\n ->setMaxResults($this->topK);\n\n foreach ($this->filters as $key => $value) {\n $paramName = 'where_'.$key;\n $qb->andWhere(\\sprintf('e.%s = :%s', $key, $paramName))\n ->setParameter($paramName, $value);\n }\n\n /** @var DoctrineEmbeddingEntityBase[] */\n return $qb->getQuery()->getResult();\n }\n\n private function persistDocument(Document $document): void\n {\n if ($document->embedding === []) {\n throw new \\RuntimeException('Trying to save a document in a vectorStore without embedding');\n }\n\n if (!$document instanceof DoctrineEmbeddingEntityBase) {\n throw new \\RuntimeException('Document needs to be an instance of DoctrineEmbeddingEntityBase');\n }\n\n $this->entityManager->persist($document);\n }\n\n /**\n * @return iterable\n */\n public function fetchDocumentsByChunkRange(string $sourceType, string $sourceName, int $leftIndex, int $rightIndex): iterable\n {\n $repository = $this->entityManager->getRepository($this->entityClassName);\n\n $query = $repository->createQueryBuilder('d')\n ->andWhere('d.sourceType = :sourceType')\n ->andWhere('d.sourceName = :sourceName')\n ->andWhere('d.chunkNumber >= :lower')\n ->andWhere('d.chunkNumber <= :upper')\n ->setParameter('sourceType', $sourceType)\n ->setParameter('sourceName', $sourceName)\n ->setParameter('lower', $leftIndex)\n ->setParameter('upper', $rightIndex)\n ->getQuery();\n\n return $query->toIterable();\n }\n\n public function withFilters(array $filters): VectorStoreInterface\n {\n $this->filters = $filters;\n return $this;\n }\n}\n"], ["/neuron-ai/src/ResolveChatHistory.php", "chatHistory = $chatHistory;\n return $this;\n }\n\n /**\n * Used extending the Agent.\n */\n protected function chatHistory(): ChatHistoryInterface\n {\n return new InMemoryChatHistory();\n }\n\n public function fillChatHistory(Message|array $messages): void\n {\n $messages = \\is_array($messages) ? $messages : [$messages];\n\n foreach ($messages as $message) {\n $this->notify('message-saving', new MessageSaving($message));\n $this->resolveChatHistory()->addMessage($message);\n $this->notify('message-saved', new MessageSaved($message));\n }\n }\n\n /**\n * Get the current instance of the chat history.\n */\n public function resolveChatHistory(): ChatHistoryInterface\n {\n if (!isset($this->chatHistory)) {\n $this->chatHistory = $this->chatHistory();\n }\n\n return $this->chatHistory;\n }\n}\n"], ["/neuron-ai/src/Observability/HandleRagEvents.php", "inspector->canAddSegments()) {\n return;\n }\n\n $id = \\md5($data->question->getContent().$data->question->getRole());\n\n $this->segments[$id] = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-retrieval', \"vector_retrieval( {$data->question->getContent()} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function ragRetrieved(AgentInterface $agent, string $event, Retrieved $data): void\n {\n $id = \\md5($data->question->getContent().$data->question->getRole());\n\n if (\\array_key_exists($id, $this->segments)) {\n $segment = $this->segments[$id];\n $segment->addContext('Data', [\n 'question' => $data->question->getContent(),\n 'documents' => \\count($data->documents)\n ]);\n $segment->end();\n }\n }\n\n public function preProcessing(AgentInterface $agent, string $event, PreProcessing $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $segment = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-preprocessing', $data->processor)\n ->setColor(self::SEGMENT_COLOR);\n\n $segment->addContext('Original', $data->original->jsonSerialize());\n\n $this->segments[$data->processor] = $segment;\n }\n\n public function preProcessed(AgentInterface $agent, string $event, PreProcessed $data): void\n {\n if (\\array_key_exists($data->processor, $this->segments)) {\n $this->segments[$data->processor]\n ->end()\n ->addContext('Processed', $data->processed->jsonSerialize());\n }\n }\n\n public function postProcessing(AgentInterface $agent, string $event, PostProcessing $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $segment = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-postprocessing', $data->processor)\n ->setColor(self::SEGMENT_COLOR);\n\n $segment->addContext('Question', $data->question->jsonSerialize())\n ->addContext('Documents', $data->documents);\n\n $this->segments[$data->processor] = $segment;\n }\n\n public function postProcessed(AgentInterface $agent, string $event, PostProcessed $data): void\n {\n if (\\array_key_exists($data->processor, $this->segments)) {\n $this->segments[$data->processor]\n ->end()\n ->addContext('PostProcess', $data->documents);\n }\n }\n}\n"], ["/neuron-ai/src/RAG/Splitter/DelimiterTextSplitter.php", "getContent();\n\n if ($text === '') {\n return [];\n }\n\n if (\\strlen($text) <= $this->maxLength) {\n return [$document];\n }\n\n $parts = \\explode($this->separator, $text);\n\n $chunks = $this->createChunksWithOverlap($parts);\n\n $split = [];\n foreach ($chunks as $chunk) {\n $newDocument = new Document($chunk);\n $newDocument->sourceType = $document->getSourceType();\n $newDocument->sourceName = $document->getSourceName();\n $split[] = $newDocument;\n }\n\n return $split;\n }\n\n /**\n * @param array $words\n * @return array\n */\n private function createChunksWithOverlap(array $words): array\n {\n $chunks = [];\n $currentChunk = [];\n $currentChunkLength = 0;\n foreach ($words as $word) {\n if ($word === '') {\n continue;\n }\n\n if ($currentChunkLength + \\strlen($this->separator.$word) <= $this->maxLength || $currentChunk === []) {\n $currentChunk[] = $word;\n $currentChunkLength = $this->calculateChunkLength($currentChunk);\n } else {\n // Add the chunk with overlap\n $chunks[] = \\implode($this->separator, $currentChunk);\n\n // Calculate overlap words\n $calculatedOverlap = \\min($this->wordOverlap, \\count($currentChunk) - 1);\n $overlapWords = $calculatedOverlap > 0 ? \\array_slice($currentChunk, -$calculatedOverlap) : [];\n\n // Start a new chunk with overlap words\n $currentChunk = [...$overlapWords, $word];\n $currentChunk[0] = \\trim($currentChunk[0]);\n $currentChunkLength = $this->calculateChunkLength($currentChunk);\n }\n }\n\n if ($currentChunk !== []) {\n $chunks[] = \\implode($this->separator, $currentChunk);\n }\n\n return $chunks;\n }\n\n /**\n * @param array $chunk\n */\n private function calculateChunkLength(array $chunk): int\n {\n return \\array_sum(\\array_map('strlen', $chunk)) + \\count($chunk) * \\strlen($this->separator) - 1;\n }\n}\n"], ["/neuron-ai/src/Observability/Observable.php", "\n */\n private array $observers = [];\n\n\n private function initEventGroup(string $event = '*'): void\n {\n /*\n * If developers attach an observer, the agent monitoring will not be attached by default.\n */\n if (!isset($this->observers['*']) && !empty($_ENV['INSPECTOR_INGESTION_KEY'])) {\n $this->observers['*'] = [\n AgentMonitoring::instance(),\n ];\n }\n\n if (!isset($this->observers[$event])) {\n $this->observers[$event] = [];\n }\n }\n\n private function getEventObservers(string $event = \"*\"): array\n {\n $this->initEventGroup($event);\n $group = $this->observers[$event];\n $all = $this->observers[\"*\"] ?? [];\n\n return \\array_merge($group, $all);\n }\n\n public function observe(SplObserver $observer, string $event = \"*\"): self\n {\n $this->attach($observer, $event);\n return $this;\n }\n\n public function attach(SplObserver $observer, string $event = \"*\"): void\n {\n $this->initEventGroup($event);\n $this->observers[$event][] = $observer;\n }\n\n public function detach(SplObserver $observer, string $event = \"*\"): void\n {\n foreach ($this->getEventObservers($event) as $key => $s) {\n if ($s === $observer) {\n unset($this->observers[$event][$key]);\n }\n }\n }\n\n public function notify(string $event = \"*\", mixed $data = null): void\n {\n // Broadcasting the '$event' event\";\n foreach ($this->getEventObservers($event) as $observer) {\n $observer->update($this, $event, $data);\n }\n }\n}\n"], ["/neuron-ai/src/ResolveProvider.php", "provider = $provider;\n return $this;\n }\n\n public function setAiProvider(AIProviderInterface $provider): AgentInterface\n {\n $this->provider = $provider;\n return $this;\n }\n\n protected function provider(): AIProviderInterface\n {\n return $this->provider;\n }\n\n /**\n * Get the current instance of the chat history.\n */\n public function resolveProvider(): AIProviderInterface\n {\n if (!isset($this->provider)) {\n $this->provider = $this->provider();\n }\n\n return $this->provider;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/SquareRootTool.php", "directory)) {\n throw new ChatHistoryException(\"Directory '{$this->directory}' does not exist\");\n }\n\n $this->load();\n }\n\n protected function load(): void\n {\n if (\\is_file($this->getFilePath())) {\n $messages = \\json_decode(\\file_get_contents($this->getFilePath()), true) ?? [];\n $this->history = $this->deserializeMessages($messages);\n }\n }\n\n protected function getFilePath(): string\n {\n return $this->directory . \\DIRECTORY_SEPARATOR . $this->prefix.$this->key.$this->ext;\n }\n\n public function setMessages(array $messages): ChatHistoryInterface\n {\n $this->updateFile();\n return $this;\n }\n\n protected function clear(): ChatHistoryInterface\n {\n if (!\\unlink($this->getFilePath())) {\n throw new ChatHistoryException(\"Unable to delete file '{$this->getFilePath()}'\");\n }\n return $this;\n }\n\n protected function updateFile(): void\n {\n \\file_put_contents($this->getFilePath(), \\json_encode($this->jsonSerialize()), \\LOCK_EX);\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/HandleStructured.php", "parameters = \\array_merge($this->parameters, [\n 'format' => $response_format,\n ]);\n\n return $this->chat($messages);\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/HandleStructured.php", "system .= \\PHP_EOL.\"# OUTPUT CONSTRAINTS\".\\PHP_EOL.\n \"Your response should be a JSON string following this schema: \".\\PHP_EOL.\n \\json_encode($response_format);\n\n return $this->chat($messages);\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/FixedThresholdPostProcessor.php", " $document->getScore() >= $this->threshold));\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/Usage.php", "inputTokens + $this->outputTokens;\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'input_tokens' => $this->inputTokens,\n 'output_tokens' => $this->outputTokens,\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/ToolInterface.php", "\n */\n public function getRequiredProperties(): array;\n\n /**\n * Define the code to be executed.\n */\n public function setCallable(callable $callback): ToolInterface;\n\n /**\n * Get the input arguments of the function call.\n */\n public function getInputs(): array;\n\n /**\n * Get the input arguments of the function call.\n */\n public function setInputs(array $inputs): ToolInterface;\n\n /**\n * The call identifier generated by the LLM.\n * @return string\n */\n public function getCallId(): ?string;\n\n\n public function setCallId(string $callId): ToolInterface;\n\n\n public function getResult(): string;\n\n /**\n * Execute the tool's logic with input parameters.\n */\n public function execute(): void;\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/SumTool.php", "data;\n }\n\n public function getCurrentNode(): string\n {\n return $this->currentNode;\n }\n\n public function getState(): WorkflowState\n {\n return $this->state;\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'data' => $this->data,\n 'currentNode' => $this->currentNode,\n 'state' => $this->state->all(),\n ];\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/VectorType.php", "getVectorAsString($value);\n }\n\n public function convertToDatabaseValueSQL(mixed $sqlExpression, AbstractPlatform $platform): string\n {\n return SupportedDoctrineVectorStore::fromPlatform($platform)->convertToDatabaseValueSQL($sqlExpression);\n }\n\n public function canRequireSQLConversion(): bool\n {\n return true;\n }\n\n public function getName(): string\n {\n return self::VECTOR;\n }\n}\n"], ["/neuron-ai/src/Workflow/Persistence/FilePersistence.php", "directory)) {\n throw new WorkflowException(\"Directory '{$this->directory}' does not exist\");\n }\n }\n\n public function save(string $workflowId, WorkflowInterrupt $interrupt): void\n {\n \\file_put_contents($this->getFilePath($workflowId), \\json_encode($interrupt));\n }\n\n public function load(string $workflowId): WorkflowInterrupt\n {\n if (!\\is_file($this->getFilePath($workflowId))) {\n throw new WorkflowException(\"No saved workflow found for ID: {$workflowId}.\");\n }\n\n $interrupt = \\json_decode(\\file_get_contents($this->getFilePath($workflowId)), true) ?? [];\n\n return new WorkflowInterrupt(\n $interrupt['data'],\n $interrupt['currentNode'],\n new WorkflowState($interrupt['state'])\n );\n }\n\n public function delete(string $workflowId): void\n {\n if (\\file_exists($this->getFilePath($workflowId))) {\n \\unlink($this->getFilePath($workflowId));\n }\n }\n\n protected function getFilePath(string $workflowId): string\n {\n return $this->directory.\\DIRECTORY_SEPARATOR.$this->prefix.$workflowId.$this->ext;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/SubtractTool.php", "embeddingsProvider = $provider;\n return $this;\n }\n\n protected function embeddings(): EmbeddingsProviderInterface\n {\n return $this->embeddingsProvider;\n }\n\n public function resolveEmbeddingsProvider(): EmbeddingsProviderInterface\n {\n if (!isset($this->embeddingsProvider)) {\n $this->embeddingsProvider = $this->embeddings();\n }\n return $this->embeddingsProvider;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/SupportedDoctrineVectorStore.php", "allowNull && $value === null) {\n return;\n }\n\n if (false === $value || (empty($value) && '0' != $value)) {\n $violations[] = $this->buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/Providers/HasGuzzleClient.php", "client = $client;\n return $this;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/VectorSimilarity.php", " $value) {\n if (isset($vector2[$key])) {\n $dotProduct += $value * $vector2[$key];\n }\n $magnitude1 += $value ** 2;\n }\n\n foreach ($vector2 as $value) {\n $magnitude2 += $value ** 2;\n }\n\n if ($magnitude1 === 0.0 || $magnitude2 === 0.0) {\n return 0.0;\n }\n\n return $dotProduct / (\\sqrt($magnitude1) * \\sqrt($magnitude2));\n }\n\n public static function cosineDistance(array $vector1, array $vector2): float|int\n {\n return 1 - self::cosineSimilarity($vector1, $vector2);\n }\n\n public static function similarityFromDistance(float|int $distance): float|int\n {\n return 1 - $distance;\n }\n}\n"], ["/neuron-ai/src/RAG/ResolveVectorStore.php", "store = $store;\n return $this;\n }\n\n protected function vectorStore(): VectorStoreInterface\n {\n return $this->store;\n }\n\n public function resolveVectorStore(): VectorStoreInterface\n {\n if (!isset($this->store)) {\n $this->store = $this->vectorStore();\n }\n return $this->store;\n }\n}\n"], ["/neuron-ai/src/Workflow/WorkflowState.php", "data[$key] = $value;\n }\n\n public function get(string $key, mixed $default = null): mixed\n {\n return $this->data[$key] ?? $default;\n }\n\n public function has(string $key): bool\n {\n return \\array_key_exists($key, $this->data);\n }\n\n /**\n * Missing keys in the state are simply ignored.\n *\n * @param string[] $keys\n */\n public function only(array $keys): array\n {\n return \\array_intersect_key($this->data, \\array_flip($keys));\n }\n\n public function all(): array\n {\n return $this->data;\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/AbstractEmbeddingsProvider.php", " $document) {\n $documents[$index] = $this->embedDocument($document);\n }\n\n return $documents;\n }\n\n public function embedDocument(Document $document): Document\n {\n $text = $document->formattedContent ?? $document->content;\n $document->embedding = $this->embedText($text);\n\n return $document;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/MySQL/MySQLToolkit.php", "pdo),\n MySQLSelectTool::make($this->pdo),\n MySQLWriteTool::make($this->pdo),\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/PGSQL/PGSQLToolkit.php", "pdo),\n PGSQLSelectTool::make($this->pdo),\n PGSQLWriteTool::make($this->pdo),\n ];\n }\n}\n"], ["/neuron-ai/src/Workflow/WorkflowContext.php", "isResuming && isset($this->feedback[$this->currentNode])) {\n return $this->feedback[$this->currentNode];\n }\n\n throw new WorkflowInterrupt($data, $this->currentNode, $this->currentState);\n }\n\n public function setResuming(bool $resuming, array $feedback = []): void\n {\n $this->isResuming = $resuming;\n $this->feedback = $feedback;\n }\n\n public function setCurrentState(WorkflowState $state): WorkflowContext\n {\n $this->currentState = $state;\n return $this;\n }\n\n public function setCurrentNode(string $node): WorkflowContext\n {\n $this->currentNode = $node;\n return $this;\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Json.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Tavily/TavilyToolkit.php", "\n */\n public function provide(): array\n {\n return [\n new TavilyExtractTool($this->key),\n new TavilySearchTool($this->key),\n new TavilyCrawlTool($this->key)\n ];\n }\n}\n"], ["/neuron-ai/src/RAG/DataLoader/AbstractDataLoader.php", "splitter = new DelimiterTextSplitter(\n maxLength: 1000,\n separator: '.',\n wordOverlap: 0\n );\n }\n\n public static function for(...$arguments): static\n {\n /** @phpstan-ignore new.static */\n return new static(...$arguments);\n }\n\n public function withSplitter(SplitterInterface $splitter): DataLoaderInterface\n {\n $this->splitter = $splitter;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Riza/RizaToolkit.php", "\n */\n public function provide(): array\n {\n return [\n new RizaCodeInterpreter($this->key),\n new RizaFunctionExecutor($this->key),\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Jina/JinaToolkit.php", "\n */\n public function provide(): array\n {\n return [\n new JinaWebSearch($this->key),\n new JinaUrlReader($this->key),\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Zep/ZepLongTermMemoryToolkit.php", "key, $this->user_id),\n ZepAddToGraphTool::make($this->key, $this->user_id),\n ];\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/EqualTo.php", "reference) {\n $violations[] = $this->buildMessage($name, 'must be equal to {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/NotEqualTo.php", "reference) {\n $violations[] = $this->buildMessage($name, 'must not be equal to {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/GreaterThan.php", "reference) || $value <= $this->reference) {\n $violations[] = $this->buildMessage($name, 'must be greater than {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/GreaterThanEqual.php", "reference) || $value < $this->reference) {\n $violations[] = $this->buildMessage($name, 'must be greater than {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/LowerThan.php", "= $this->reference) {\n $violations[] = $this->buildMessage($name, 'must be greater than {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/LowerThanEqual.php", " $this->reference) {\n $violations[] = $this->buildMessage($name, 'must be greater than {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/AbstractValidationRule.php", " $value) {\n $messageTemplate = \\str_replace('{'.$key.'}', (string) $value, $messageTemplate);\n }\n\n return \\str_replace('{name}', $name, $messageTemplate);\n }\n}\n"], ["/neuron-ai/src/SystemPrompt.php", "background);\n\n if ($this->steps !== []) {\n $prompt .= \\PHP_EOL . \\PHP_EOL . \"# INTERNAL ASSISTANT STEPS\" . \\PHP_EOL . \\implode(\\PHP_EOL, $this->steps);\n }\n\n if ($this->output !== []) {\n $prompt .= \\PHP_EOL . \\PHP_EOL . \"# OUTPUT INSTRUCTIONS\" . \\PHP_EOL . \" - \" . \\implode(\\PHP_EOL . \" - \", $this->output);\n }\n\n if ($this->toolsUsage !== []) {\n $prompt .= \\PHP_EOL . \\PHP_EOL . \"# TOOLS USAGE RULES\" . \\PHP_EOL . \" - \" . \\implode(\\PHP_EOL . \" - \", $this->toolsUsage);\n }\n\n return $prompt;\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/PostProcessorInterface.php", "splitDocument($document));\n }\n\n return $split;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/DoctrineEmbeddingEntityBase.php", "id;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/CalculatorToolkit.php", "getEdges() as $edge) {\n $from = $this->getShortClassName($edge->getFrom());\n $to = $this->getShortClassName($edge->getTo());\n\n $output .= \" {$from} --> {$to}\\n\";\n }\n\n return $output;\n }\n\n private function getShortClassName(string $class): string\n {\n $reflection = new ReflectionClass($class);\n return $reflection->getShortName();\n }\n}\n"], ["/neuron-ai/src/Workflow/Edge.php", "from;\n }\n\n public function getTo(): string\n {\n return $this->to;\n }\n\n public function hasCondition(): bool\n {\n return $this->condition instanceof \\Closure;\n }\n\n public function shouldExecute(WorkflowState $state): bool\n {\n return $this->hasCondition() ? ($this->condition)($state) : true;\n }\n}\n"], ["/neuron-ai/src/Providers/MessageMapperInterface.php", " $messages\n */\n public function map(array $messages): array;\n}\n"], ["/neuron-ai/src/Workflow/Node.php", "context = $context;\n }\n\n protected function interrupt(array $data): mixed\n {\n if (!isset($this->context)) {\n throw new WorkflowException('WorkflowContext not set on node');\n }\n\n return $this->context->interrupt($data);\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/PostgresqlVectorStoreType.php", "stringListOf($vector).']';\n }\n\n public function convertToDatabaseValueSQL(string $sqlExpression): string\n {\n return $sqlExpression;\n }\n\n public function addCustomisationsTo(EntityManagerInterface $entityManager): void\n {\n $entityManager->getConfiguration()->addCustomStringFunction($this->l2DistanceName(), PostgresqlVectorL2OperatorDql::class);\n }\n\n public function l2DistanceName(): string\n {\n return 'VEC_DISTANCE_EUCLIDEAN';\n }\n}\n"], ["/neuron-ai/src/RAG/PreProcessor/PreProcessorInterface.php", "storage[$workflowId] = $interrupt;\n }\n\n public function load(string $workflowId): WorkflowInterrupt\n {\n return $this->storage[$workflowId] ?? throw new WorkflowException(\"No saved workflow found for ID: {$workflowId}\");\n }\n\n public function delete(string $workflowId): void\n {\n unset($this->storage[$workflowId]);\n }\n}\n"], ["/neuron-ai/src/Chat/History/InMemoryChatHistory.php", "stringListOf($vector).']';\n }\n\n public function convertToDatabaseValueSQL(string $sqlExpression): string\n {\n return \\sprintf('Vec_FromText(%s)', $sqlExpression);\n }\n\n public function addCustomisationsTo(EntityManagerInterface $entityManager): void\n {\n $entityManager->getConfiguration()->addCustomStringFunction($this->l2DistanceName(), MariaDBVectorL2OperatorDql::class);\n }\n\n public function l2DistanceName(): string\n {\n return 'VEC_DISTANCE_EUCLIDEAN';\n }\n}\n"], ["/neuron-ai/src/Chat/History/ChatHistoryInterface.php", "\n */\n public function getMessages(): array;\n\n public function getLastMessage(): Message|false;\n\n public function setMessages(array $messages): ChatHistoryInterface;\n\n public function flushAll(): ChatHistoryInterface;\n\n public function calculateTotalUsage(): int;\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/MariaDBVectorL2OperatorDql.php", "vectorOne->dispatch($sqlWalker).', '.\n 'VEC_FROMTEXT('.\n $this->vectorTwo->dispatch($sqlWalker).\n ')'.\n ')';\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Url.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/PostgresqlVectorL2OperatorDql.php", "vectorOne->dispatch($sqlWalker).', '.\n $this->vectorTwo->dispatch($sqlWalker).\n ')';\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IsNull.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IsNotNull.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/UserMessage.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IPAddress.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/ToolkitInterface.php", "match(\\Doctrine\\ORM\\Query\\TokenType::T_IDENTIFIER);\n $parser->match(\\Doctrine\\ORM\\Query\\TokenType::T_OPEN_PARENTHESIS);\n } else {\n $parser->match(\\Doctrine\\ORM\\Query\\Lexer::T_IDENTIFIER);\n $parser->match(\\Doctrine\\ORM\\Query\\Lexer::T_OPEN_PARENTHESIS);\n }\n\n $this->vectorOne = $parser->ArithmeticFactor(); // Fix that, should be vector\n\n if (\\class_exists(\\Doctrine\\ORM\\Query\\TokenType::class)) {\n $parser->match(\\Doctrine\\ORM\\Query\\TokenType::T_COMMA);\n } else {\n $parser->match(\\Doctrine\\ORM\\Query\\Lexer::T_COMMA);\n }\n\n $this->vectorTwo = $parser->ArithmeticFactor(); // Fix that, should be vector\n\n if (\\class_exists(\\Doctrine\\ORM\\Query\\TokenType::class)) {\n $parser->match(\\Doctrine\\ORM\\Query\\TokenType::T_CLOSE_PARENTHESIS);\n } else {\n $parser->match(\\Doctrine\\ORM\\Query\\Lexer::T_CLOSE_PARENTHESIS);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IsFalse.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IsTrue.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/Chat/Attachments/Document.php", "splitter->splitDocument(new Document($this->content));\n }\n}\n"], ["/neuron-ai/src/Chat/History/TokenCounterInterface.php", " $violations\n */\n public function __construct(\n public string $class,\n public string $json,\n public array $violations = []\n ) {\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/EmbeddingsProviderInterface.php", "withPaths([\n __DIR__ . '/src',\n __DIR__ . '/tests',\n ])\n ->withPhpSets(php81: true)\n ->withPreparedSets(\n codeQuality: true,\n deadCode: true,\n typeDeclarations: true,\n earlyReturn: true,\n strictBooleans: true,\n )\n ->withRules([\n AddReturnTypeDeclarationRector::class\n ]);\n"], ["/neuron-ai/src/Observability/Events/PreProcessed.php", " array_map(function (ToolInterface $tool) {\n return [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'input_schema' => $tool->getSchema(),\n ];\n }, $this->getTools()),\n ];\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 21-28-09"}, "editdistance_info": {"edit_distance": 34.6405, "calculate_time": "2025-08-20 21:28:09", "true_code_clean": "protected function generateToolsPayload(): array\n {\n return \\array_map(function (ToolInterface $tool): array {\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n return [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'input_schema' => [\n 'type' => 'object',\n 'properties' => empty($properties) ? null : $properties,\n 'required' => $tool->getRequiredProperties(),\n ],\n ];\n }, $this->tools);\n }", "predict_code_clean": "protected function generateToolsPayload(): array\n {\n return [\n 'tools' => array_map(function (ToolInterface $tool) {\n return [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'input_schema' => $tool->getSchema(),\n ];\n }, $this->getTools()),\n ];\n }"}} {"repo_name": "neuron-ai", "file_name": "/neuron-ai/src/Providers/Deepseek/Deepseek.php", "inference_info": {"prefix_code": "parameters = \\array_merge($this->parameters, [\n 'response_format' => [\n 'type' => 'json_object',\n ]\n ]);\n $this->system .= \\PHP_EOL.\"\n .'Generate a json respecting this schema: '.\\json_encode($response_format);\n return $this->chat($messages);\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/neuron-ai/src/Providers/OpenAI/HandleStructured.php", "parameters = \\array_merge($this->parameters, [\n 'response_format' => [\n 'type' => 'json_schema',\n 'json_schema' => [\n \"name\" => \\end($tk),\n \"strict\" => false,\n \"schema\" => $response_format,\n ],\n ]\n ]);\n\n return $this->chat($messages);\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/HandleStructured.php", "system .= \\PHP_EOL.\"# OUTPUT CONSTRAINTS\".\\PHP_EOL.\n \"Your response should be a JSON string following this schema: \".\\PHP_EOL.\n \\json_encode($response_format);\n\n return $this->chat($messages);\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/HandleStructured.php", "parameters)) {\n $this->parameters['generationConfig'] = [\n 'temperature' => 0,\n ];\n }\n\n // Gemini does not support structured output in combination with tools.\n // So we try to work with a JSON mode in case the agent has some tools defined.\n if (!empty($this->tools)) {\n $last_message = \\end($messages);\n if ($last_message instanceof Message && $last_message->getRole() === MessageRole::USER->value) {\n $last_message->setContent(\n $last_message->getContent() . ' Respond using this JSON schema: '.\\json_encode($response_format)\n );\n }\n } else {\n // If there are no tools, we can enforce the structured output.\n $this->parameters['generationConfig']['response_schema'] = $this->adaptSchema($response_format);\n $this->parameters['generationConfig']['response_mime_type'] = 'application/json';\n }\n\n return $this->chat($messages);\n }\n\n /**\n * Gemini does not support additionalProperties attribute.\n */\n protected function adaptSchema(array $schema): array\n {\n if (\\array_key_exists('additionalProperties', $schema)) {\n unset($schema['additionalProperties']);\n }\n\n foreach ($schema as $key => $value) {\n if (\\is_array($value)) {\n $schema[$key] = $this->adaptSchema($value);\n }\n }\n\n return $schema;\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/HandleStructured.php", "parameters = \\array_merge($this->parameters, [\n 'format' => $response_format,\n ]);\n\n return $this->chat($messages);\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/OpenAIEmbeddingsProvider.php", "client = new Client([\n 'base_uri' => $this->baseUri,\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer ' . $this->key,\n ]\n ]);\n }\n\n public function embedText(string $text): array\n {\n $response = $this->client->post('', [\n 'json' => [\n 'model' => $this->model,\n 'input' => $text,\n 'encoding_format' => 'float',\n 'dimensions' => $this->dimensions,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['data'][0]['embedding'];\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/OpenAI.php", "client = new Client([\n 'base_uri' => \\trim($this->baseUri, '/').'/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer ' . $this->key,\n ]\n ]);\n }\n\n public function systemPrompt(?string $prompt): AIProviderInterface\n {\n $this->system = $prompt;\n return $this;\n }\n\n public function messageMapper(): MessageMapperInterface\n {\n return new MessageMapper();\n }\n\n protected function generateToolsPayload(): array\n {\n return \\array_map(function (ToolInterface $tool): array {\n $payload = [\n 'type' => 'function',\n 'function' => [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'parameters' => [\n 'type' => 'object',\n 'properties' => new \\stdClass(),\n 'required' => [],\n ],\n ]\n ];\n\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n\n if (!empty($properties)) {\n $payload['function']['parameters'] = [\n 'type' => 'object',\n 'properties' => $properties,\n 'required' => $tool->getRequiredProperties(),\n ];\n }\n\n return $payload;\n }, $this->tools);\n }\n\n protected function createToolCallMessage(array $message): Message\n {\n $tools = \\array_map(\n fn (array $item): ToolInterface => $this->findTool($item['function']['name'])\n ->setInputs(\n \\json_decode((string) $item['function']['arguments'], true)\n )\n ->setCallId($item['id']),\n $message['tool_calls']\n );\n\n $result = new ToolCallMessage(\n $message['content'],\n $tools\n );\n\n return $result->addMetadata('tool_calls', $message['tool_calls']);\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/AzureOpenAI.php", "setBaseUrl();\n\n $this->client = new Client([\n 'base_uri' => $this->baseUri,\n 'query' => [\n 'api-version' => $this->version,\n ],\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n ],\n ]);\n }\n\n private function setBaseUrl(): void\n {\n $this->endpoint = \\preg_replace('/^https?:\\/\\/([^\\/]*)\\/?$/', '$1', $this->endpoint);\n $this->baseUri = \\sprintf($this->baseUri, $this->endpoint, $this->model);\n $this->baseUri = \\trim($this->baseUri, '/').'/';\n }\n}\n"], ["/neuron-ai/src/Providers/Mistral/Mistral.php", "system !== null) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'stream' => true,\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n // Attach tools\n if ($this->tools !== []) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n $stream = $this->client->post('chat/completions', [\n 'stream' => true,\n ...['json' => $json]\n ])->getBody();\n\n $text = '';\n $toolCalls = [];\n\n while (! $stream->eof()) {\n if (($line = $this->parseNextDataLine($stream)) === null) {\n continue;\n }\n\n // Inform the agent about usage when stream\n if (empty($line['choices']) && !empty($line['usage'])) {\n yield \\json_encode(['usage' => [\n 'input_tokens' => $line['usage']['prompt_tokens'],\n 'output_tokens' => $line['usage']['completion_tokens'],\n ]]);\n continue;\n }\n\n if (empty($line['choices'])) {\n continue;\n }\n\n // Compile tool calls\n if ($this->isToolCallPart($line)) {\n $toolCalls = $this->composeToolCalls($line, $toolCalls);\n\n // Handle tool calls\n if ($line['choices'][0]['finish_reason'] === 'tool_calls') {\n yield from $executeToolsCallback(\n $this->createToolCallMessage([\n 'content' => $text,\n 'tool_calls' => $toolCalls\n ])\n );\n }\n\n continue;\n }\n\n // Process regular content\n $content = $line['choices'][0]['delta']['content'] ?? '';\n $text .= $content;\n\n yield $content;\n }\n }\n\n protected function isToolCallPart(array $line): bool\n {\n $calls = $line['choices'][0]['delta']['tool_calls'] ?? [];\n\n foreach ($calls as $call) {\n if (isset($call['function'])) {\n return true;\n }\n }\n\n return false;\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(array $messages): PromiseInterface\n {\n // Include the system prompt\n if (isset($this->system)) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters\n ];\n\n // Attach tools\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n return $this->client->postAsync('chat/completions', ['json' => $json])\n ->then(function (ResponseInterface $response) {\n $result = \\json_decode($response->getBody()->getContents(), true);\n\n if ($result['choices'][0]['finish_reason'] === 'tool_calls') {\n $response = $this->createToolCallMessage($result['choices'][0]['message']);\n } else {\n $response = new AssistantMessage($result['choices'][0]['message']['content']);\n }\n\n if (\\array_key_exists('usage', $result)) {\n $response->setUsage(\n new Usage($result['usage']['prompt_tokens'], $result['usage']['completion_tokens'])\n );\n }\n\n return $response;\n });\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/VoyageEmbeddingsProvider.php", "client = new Client([\n 'base_uri' => $this->baseUri,\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer ' . $key,\n ],\n ]);\n }\n\n public function embedText(string $text): array\n {\n $response = $this->client->post('', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'input' => $text,\n 'output_dimension' => $this->dimensions,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['data'][0]['embedding'];\n }\n\n public function embedDocuments(array $documents): array\n {\n $chunks = \\array_chunk($documents, 100);\n\n foreach ($chunks as $chunk) {\n $response = $this->client->post('', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'input' => \\array_map(fn (Document $document): string => $document->getContent(), $chunk),\n 'output_dimension' => $this->dimensions,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n foreach ($response['data'] as $index => $item) {\n $chunk[$index]->embedding = $item['embedding'];\n }\n }\n\n return \\array_merge(...$chunks);\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(array $messages): PromiseInterface\n {\n // Include the system prompt\n if (isset($this->system)) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'stream' => false,\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n if (! empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n return $this->client->postAsync('chat', ['json' => $json])\n ->then(function (ResponseInterface $response): Message {\n if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) {\n throw new ProviderException(\"Ollama chat error: {$response->getBody()->getContents()}\");\n }\n\n $response = \\json_decode($response->getBody()->getContents(), true);\n $message = $response['message'];\n\n if (\\array_key_exists('tool_calls', $message)) {\n $message = $this->createToolCallMessage($message);\n } else {\n $message = new AssistantMessage($message['content']);\n }\n\n if (\\array_key_exists('prompt_eval_count', $response) && \\array_key_exists('eval_count', $response)) {\n $message->setUsage(\n new Usage($response['prompt_eval_count'], $response['eval_count'])\n );\n }\n\n return $message;\n });\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(array $messages): PromiseInterface\n {\n $json = [\n 'model' => $this->model,\n 'max_tokens' => $this->max_tokens,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n if (isset($this->system)) {\n $json['system'] = $this->system;\n }\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n\n return $this->client->postAsync('messages', ['json' => $json])\n ->then(function (ResponseInterface $response) {\n $result = \\json_decode($response->getBody()->getContents(), true);\n\n $content = \\end($result['content']);\n\n if ($content['type'] === 'tool_use') {\n $response = $this->createToolCallMessage($content);\n } else {\n $response = new AssistantMessage($content['text']);\n }\n\n // Attach the usage for the current interaction\n if (\\array_key_exists('usage', $result)) {\n $response->setUsage(\n new Usage(\n $result['usage']['input_tokens'],\n $result['usage']['output_tokens']\n )\n );\n }\n\n return $response;\n });\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/Anthropic.php", "client = new Client([\n 'base_uri' => \\trim($this->baseUri, '/').'/',\n 'headers' => [\n 'Content-Type' => 'application/json',\n 'x-api-key' => $this->key,\n 'anthropic-version' => $version,\n ]\n ]);\n }\n\n public function systemPrompt(?string $prompt): AIProviderInterface\n {\n $this->system = $prompt;\n return $this;\n }\n\n public function messageMapper(): MessageMapperInterface\n {\n return new MessageMapper();\n }\n\n protected function generateToolsPayload(): array\n {\n return \\array_map(function (ToolInterface $tool): array {\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n\n return [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'input_schema' => [\n 'type' => 'object',\n 'properties' => empty($properties) ? null : $properties,\n 'required' => $tool->getRequiredProperties(),\n ],\n ];\n }, $this->tools);\n }\n\n public function createToolCallMessage(array $content): Message\n {\n $tool = $this->findTool($content['name'])\n ->setInputs($content['input'])\n ->setCallId($content['id']);\n\n // During serialization and deserialization PHP convert the original empty object {} to empty array []\n // causing an error on the Anthropic API. If there are no inputs, we need to restore the empty JSON object.\n if (empty($content['input'])) {\n $content['input'] = new \\stdClass();\n }\n\n return new ToolCallMessage(\n [$content],\n [$tool] // Anthropic call one tool at a time. So we pass an array with one element.\n );\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/Gemini.php", "client = new Client([\n // Since Gemini use colon \":\" into the URL guzzle fire an exception using base_uri configuration.\n //'base_uri' => trim($this->baseUri, '/').'/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'x-goog-api-key' => $this->key,\n ]\n ]);\n }\n\n public function systemPrompt(?string $prompt): AIProviderInterface\n {\n $this->system = $prompt;\n return $this;\n }\n\n public function messageMapper(): MessageMapperInterface\n {\n return new MessageMapper();\n }\n\n protected function generateToolsPayload(): array\n {\n $tools = \\array_map(function (ToolInterface $tool): array {\n $payload = [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'parameters' => [\n 'type' => 'object',\n 'properties' => new \\stdClass(),\n 'required' => [],\n ],\n ];\n\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property) {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n\n if (!empty($properties)) {\n $payload['parameters'] = [\n 'type' => 'object',\n 'properties' => $properties,\n 'required' => $tool->getRequiredProperties(),\n ];\n }\n\n return $payload;\n }, $this->tools);\n\n return [\n 'functionDeclarations' => $tools\n ];\n }\n\n protected function createToolCallMessage(array $message): Message\n {\n $tools = \\array_map(function (array $item): ?\\NeuronAI\\Tools\\ToolInterface {\n if (!isset($item['functionCall'])) {\n return null;\n }\n\n // Gemini does not use ID. It uses the tool's name as a unique identifier.\n return $this->findTool($item['functionCall']['name'])\n ->setInputs($item['functionCall']['args'])\n ->setCallId($item['functionCall']['name']);\n }, $message['parts']);\n\n $result = new ToolCallMessage(\n $message['content'] ?? null,\n \\array_filter($tools)\n );\n $result->setRole(MessageRole::MODEL);\n\n return $result;\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(array $messages): PromiseInterface\n {\n $json = [\n 'contents' => $this->messageMapper()->map($messages),\n ...$this->parameters\n ];\n\n if (isset($this->system)) {\n $json['system_instruction'] = [\n 'parts' => [\n ['text' => $this->system]\n ]\n ];\n }\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n return $this->client->postAsync(\\trim($this->baseUri, '/').\"/{$this->model}:generateContent\", [RequestOptions::JSON => $json])\n ->then(function (ResponseInterface $response): Message {\n $result = \\json_decode($response->getBody()->getContents(), true);\n\n $content = $result['candidates'][0]['content'];\n\n if (!isset($content['parts']) && isset($result['candidates'][0]['finishReason']) && $result['candidates'][0]['finishReason'] === 'MAX_TOKENS') {\n return new Message(MessageRole::from($content['role']), '');\n }\n\n $parts = $content['parts'];\n\n if (\\array_key_exists('functionCall', $parts[0]) && !empty($parts[0]['functionCall'])) {\n $response = $this->createToolCallMessage($content);\n } else {\n $response = new Message(MessageRole::from($content['role']), $parts[0]['text'] ?? '');\n }\n\n // Attach the usage for the current interaction\n if (\\array_key_exists('usageMetadata', $result)) {\n $response->setUsage(\n new Usage(\n $result['usageMetadata']['promptTokenCount'],\n $result['usageMetadata']['candidatesTokenCount'] ?? 0\n )\n );\n }\n\n return $response;\n });\n }\n}\n"], ["/neuron-ai/src/HandleStructured.php", "notify('structured-start');\n\n $this->fillChatHistory($messages);\n\n $tools = $this->bootstrapTools();\n\n // Get the JSON schema from the response model\n $class ??= $this->getOutputClass();\n $this->notify('schema-generation', new SchemaGeneration($class));\n $schema = (new JsonSchema())->generate($class);\n $this->notify('schema-generated', new SchemaGenerated($class, $schema));\n\n $error = '';\n do {\n try {\n // If something goes wrong, retry informing the model about the error\n if (\\trim($error) !== '') {\n $correctionMessage = new UserMessage(\n \"There was a problem in your previous response that generated the following errors\".\n \\PHP_EOL.\\PHP_EOL.'- '.$error.\\PHP_EOL.\\PHP_EOL.\n \"Try to generate the correct JSON structure based on the provided schema.\"\n );\n $this->fillChatHistory($correctionMessage);\n }\n\n $messages = $this->resolveChatHistory()->getMessages();\n\n $last = clone $this->resolveChatHistory()->getLastMessage();\n $this->notify(\n 'inference-start',\n new InferenceStart($last)\n );\n $response = $this->resolveProvider()\n ->systemPrompt($this->resolveInstructions())\n ->setTools($tools)\n ->structured($messages, $class, $schema);\n $this->notify(\n 'inference-stop',\n new InferenceStop($last, $response)\n );\n\n $this->fillChatHistory($response);\n\n if ($response instanceof ToolCallMessage) {\n $toolCallResult = $this->executeTools($response);\n return self::structured($toolCallResult, $class, $maxRetries);\n }\n\n $output = $this->processResponse($response, $schema, $class);\n $this->notify('structured-stop');\n return $output;\n } catch (RequestException $exception) {\n $error = $exception->getResponse()?->getBody()->getContents() ?? $exception->getMessage();\n $this->notify('error', new AgentError($exception, false));\n } catch (\\Exception $exception) {\n $error = $exception->getMessage();\n $this->notify('error', new AgentError($exception, false));\n }\n\n $maxRetries--;\n } while ($maxRetries >= 0);\n\n $exception = new AgentException(\n \"Impossible to generate a structured response for the class {$class}: {$error}\"\n );\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n\n protected function processResponse(\n Message $response,\n array $schema,\n string $class,\n ): mixed {\n // Try to extract a valid JSON object from the LLM response\n $this->notify('structured-extracting', new Extracting($response));\n $json = (new JsonExtractor())->getJson($response->getContent());\n $this->notify('structured-extracted', new Extracted($response, $schema, $json));\n if ($json === null || $json === '') {\n throw new AgentException(\"The response does not contains a valid JSON Object.\");\n }\n\n // Deserialize the JSON response from the LLM into an instance of the response model\n $this->notify('structured-deserializing', new Deserializing($class));\n $obj = Deserializer::fromJson($json, $class);\n $this->notify('structured-deserialized', new Deserialized($class));\n\n // Validate if the object fields respect the validation attributes\n // https://symfony.com/doc/current/validation.html#constraints\n $this->notify('structured-validating', new Validating($class, $json));\n\n $violations = Validator::validate($obj);\n\n if (\\count($violations) > 0) {\n $this->notify('structured-validated', new Validated($class, $json, $violations));\n throw new AgentException(\\PHP_EOL.'- '.\\implode(\\PHP_EOL.'- ', $violations));\n }\n $this->notify('structured-validated', new Validated($class, $json));\n\n return $obj;\n }\n\n protected function getOutputClass(): string\n {\n throw new AgentException('You need to specify an output class.');\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/Ollama.php", "client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n ]);\n }\n\n public function systemPrompt(?string $prompt): AIProviderInterface\n {\n $this->system = $prompt;\n\n return $this;\n }\n\n public function messageMapper(): MessageMapperInterface\n {\n return new MessageMapper();\n }\n\n protected function generateToolsPayload(): array\n {\n return \\array_map(function (ToolInterface $tool): array {\n $payload = [\n 'type' => 'function',\n 'function' => [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'parameters' => [\n 'type' => 'object',\n 'properties' => new \\stdClass(),\n 'required' => [],\n ]\n ],\n ];\n\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n $carry[$property->getName()] = [\n 'type' => $property->getType()->value,\n 'description' => $property->getDescription(),\n ];\n\n return $carry;\n }, []);\n\n if (! empty($properties)) {\n $payload['function']['parameters'] = [\n 'type' => 'object',\n 'properties' => $properties,\n 'required' => $tool->getRequiredProperties(),\n ];\n }\n\n return $payload;\n }, $this->tools);\n }\n\n protected function createToolCallMessage(array $message): Message\n {\n $tools = \\array_map(fn (array $item): ToolInterface => $this->findTool($item['function']['name'])\n ->setInputs($item['function']['arguments']), $message['tool_calls']);\n\n $result = new ToolCallMessage(\n $message['content'],\n $tools\n );\n\n return $result->addMetadata('tool_calls', $message['tool_calls']);\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/GeminiEmbeddingsProvider.php", "client = new Client([\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'x-goog-api-key' => $this->key,\n ]\n ]);\n }\n\n public function embedText(string $text): array\n {\n $response = $this->client->post(\\trim($this->baseUri, '/').\"/{$this->model}:embedContent\", [\n RequestOptions::JSON => [\n 'content' => [\n 'parts' => [['text' => $text]]\n ],\n ...($this->config !== [] ? ['embedding_config' => $this->config] : []),\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['embedding']['values'];\n }\n}\n"], ["/neuron-ai/src/Providers/HuggingFace/HuggingFace.php", "buildBaseUri();\n parent::__construct($key, $model, $parameters);\n }\n\n private function buildBaseUri(): void\n {\n $endpoint = match ($this->inferenceProvider) {\n InferenceProvider::HF_INFERENCE => \\trim($this->inferenceProvider->value, \\DIRECTORY_SEPARATOR).\\DIRECTORY_SEPARATOR.$this->model,\n default => \\trim($this->inferenceProvider->value, \\DIRECTORY_SEPARATOR),\n };\n\n $this->baseUri = \\sprintf($this->baseUri, $endpoint);\n }\n\n}\n"], ["/neuron-ai/src/Providers/OpenAI/HandleStream.php", "system)) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'stream' => true,\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n 'stream_options' => ['include_usage' => true],\n ...$this->parameters,\n ];\n\n // Attach tools\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n $stream = $this->client->post('chat/completions', [\n 'stream' => true,\n ...['json' => $json]\n ])->getBody();\n\n $text = '';\n $toolCalls = [];\n\n while (! $stream->eof()) {\n if (!$line = $this->parseNextDataLine($stream)) {\n continue;\n }\n\n // Inform the agent about usage when stream\n if (!empty($line['usage'])) {\n yield \\json_encode(['usage' => [\n 'input_tokens' => $line['usage']['prompt_tokens'],\n 'output_tokens' => $line['usage']['completion_tokens'],\n ]]);\n }\n\n if (empty($line['choices'])) {\n continue;\n }\n\n // Compile tool calls\n if (isset($line['choices'][0]['delta']['tool_calls'])) {\n $toolCalls = $this->composeToolCalls($line, $toolCalls);\n continue;\n }\n\n // Handle tool calls\n if (isset($line['choices'][0]['finish_reason']) && $line['choices'][0]['finish_reason'] === 'tool_calls') {\n yield from $executeToolsCallback(\n $this->createToolCallMessage([\n 'content' => $text,\n 'tool_calls' => $toolCalls\n ])\n );\n\n return;\n }\n\n // Process regular content\n $content = $line['choices'][0]['delta']['content'] ?? '';\n $text .= $content;\n\n yield $content;\n }\n }\n\n /**\n * Recreate the tool_calls format from streaming OpenAI API.\n *\n * @param array $line\n * @param array> $toolCalls\n * @return array>\n */\n protected function composeToolCalls(array $line, array $toolCalls): array\n {\n foreach ($line['choices'][0]['delta']['tool_calls'] as $call) {\n $index = $call['index'];\n\n if (!\\array_key_exists($index, $toolCalls)) {\n if ($name = $call['function']['name'] ?? null) {\n $toolCalls[$index]['function'] = ['name' => $name, 'arguments' => $call['function']['arguments'] ?? ''];\n $toolCalls[$index]['id'] = $call['id'];\n $toolCalls[$index]['type'] = 'function';\n }\n } else {\n $arguments = $call['function']['arguments'] ?? null;\n if ($arguments !== null) {\n $toolCalls[$index]['function']['arguments'] .= $arguments;\n }\n }\n }\n\n return $toolCalls;\n }\n\n protected function parseNextDataLine(StreamInterface $stream): ?array\n {\n $line = $this->readLine($stream);\n\n if (! \\str_starts_with((string) $line, 'data:')) {\n return null;\n }\n\n $line = \\trim(\\substr((string) $line, \\strlen('data: ')));\n\n if (\\str_contains($line, 'DONE')) {\n return null;\n }\n\n try {\n return \\json_decode($line, true, flags: \\JSON_THROW_ON_ERROR);\n } catch (\\Throwable $exception) {\n throw new ProviderException('OpenAI streaming error - '.$exception->getMessage());\n }\n }\n\n protected function readLine(StreamInterface $stream): string\n {\n $buffer = '';\n\n while (! $stream->eof()) {\n $byte = $stream->read(1);\n\n if ($byte === '') {\n return $buffer;\n }\n\n $buffer .= $byte;\n\n if ($byte === \"\\n\") {\n break;\n }\n }\n\n return $buffer;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Riza/RizaCodeInterpreter.php", "client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json; charset=utf-8',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function __invoke(\n string $code,\n array $args = [],\n array $env = [],\n ): mixed {\n $result = $this->getClient()->post('execute', [\n RequestOptions::JSON => [\n 'language' => $this->language,\n 'code' => $code,\n 'args' => $args,\n 'env' => $env,\n ]\n ])->getBody()->getContents();\n\n return \\json_decode($result, true);\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/CohereRerankerPostProcessor.php", "client ?? $this->client = new Client([\n 'base_uri' => 'https://api.cohere.com/v2/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer '.$this->key,\n ],\n ]);\n }\n\n public function process(Message $question, array $documents): array\n {\n $response = $this->getClient()->post('rerank', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'query' => $question->getContent(),\n 'top_n' => $this->topN,\n 'documents' => \\array_map(fn (Document $document): string => $document->getContent(), $documents),\n ],\n ])->getBody()->getContents();\n\n $result = \\json_decode($response, true);\n\n return \\array_map(function (array $item) use ($documents): Document {\n $document = $documents[$item['index']];\n $document->setScore($item['relevance_score']);\n return $document;\n }, $result['results']);\n }\n\n public function setClient(Client $client): PostProcessorInterface\n {\n $this->client = $client;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/HandleStream.php", " true,\n 'model' => $this->model,\n 'max_tokens' => $this->max_tokens,\n 'system' => $this->system ?? null,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n // https://docs.anthropic.com/claude/reference/messages_post\n $stream = $this->client->post('messages', [\n 'stream' => true,\n ...['json' => $json]\n ])->getBody();\n\n $toolCalls = [];\n\n while (! $stream->eof()) {\n if (!$line = $this->parseNextDataLine($stream)) {\n continue;\n }\n\n // https://docs.anthropic.com/en/api/messages-streaming\n if ($line['type'] === 'message_start') {\n yield \\json_encode(['usage' => $line['message']['usage']]);\n continue;\n }\n\n if ($line['type'] === 'message_delta') {\n yield \\json_encode(['usage' => $line['usage']]);\n continue;\n }\n\n // Tool calls detection (https://docs.anthropic.com/en/api/messages-streaming#streaming-request-with-tool-use)\n if (\n (isset($line['content_block']['type']) && $line['content_block']['type'] === 'tool_use') ||\n (isset($line['delta']['type']) && $line['delta']['type'] === 'input_json_delta')\n ) {\n $toolCalls = $this->composeToolCalls($line, $toolCalls);\n continue;\n }\n\n // Handle tool call\n if ($line['type'] === 'content_block_stop' && !empty($toolCalls)) {\n // Restore the input field as an array\n $toolCalls = \\array_map(function (array $call) {\n $call['input'] = \\json_decode((string) $call['input'], true);\n return $call;\n }, $toolCalls);\n\n yield from $executeToolsCallback(\n $this->createToolCallMessage(\\end($toolCalls))\n );\n }\n\n // Process regular content\n $content = $line['delta']['text'] ?? '';\n\n yield $content;\n }\n }\n\n /**\n * Recreate the tool_call format of anthropic API from streaming.\n *\n * @param array $line\n * @param array> $toolCalls\n * @return array>\n */\n protected function composeToolCalls(array $line, array $toolCalls): array\n {\n if (!\\array_key_exists($line['index'], $toolCalls)) {\n $toolCalls[$line['index']] = [\n 'type' => 'tool_use',\n 'id' => $line['content_block']['id'],\n 'name' => $line['content_block']['name'],\n 'input' => '',\n ];\n } elseif ($input = $line['delta']['partial_json'] ?? null) {\n $toolCalls[$line['index']]['input'] .= $input;\n }\n\n return $toolCalls;\n }\n\n protected function parseNextDataLine(StreamInterface $stream): ?array\n {\n $line = $this->readLine($stream);\n\n if (! \\str_starts_with((string) $line, 'data:')) {\n return null;\n }\n\n $line = \\trim(\\substr((string) $line, \\strlen('data: ')));\n\n try {\n return \\json_decode($line, true, flags: \\JSON_THROW_ON_ERROR);\n } catch (\\Throwable $exception) {\n throw new ProviderException('Anthropic streaming error - '.$exception->getMessage());\n }\n }\n\n protected function readLine(StreamInterface $stream): string\n {\n $buffer = '';\n\n while (! $stream->eof()) {\n $byte = $stream->read(1);\n\n if ($byte === '') {\n return $buffer;\n }\n\n $buffer .= $byte;\n\n if ($byte === \"\\n\") {\n break;\n }\n }\n\n return $buffer;\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/HandleStream.php", "system)) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'stream' => true,\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n $stream = $this->client->post('chat', [\n 'stream' => true,\n ...['json' => $json]\n ])->getBody();\n\n while (! $stream->eof()) {\n if (!$line = $this->parseNextJson($stream)) {\n continue;\n }\n\n // Last chunk will contain the usage information.\n if ($line['done'] === true) {\n yield \\json_encode(['usage' => [\n 'input_tokens' => $line['prompt_eval_count'],\n 'output_tokens' => $line['eval_count'],\n ]]);\n continue;\n }\n\n // Process tool calls\n if (isset($line['message']['tool_calls'])) {\n yield from $executeToolsCallback(\n $this->createToolCallMessage($line['message'])\n );\n }\n\n // Process regular content\n $content = $line['message']['content'] ?? '';\n\n yield $content;\n }\n }\n\n protected function parseNextJson(StreamInterface $stream): ?array\n {\n $line = $this->readLine($stream);\n\n if (empty($line)) {\n return null;\n }\n\n $json = \\json_decode((string) $line, true);\n\n if ($json['done']) {\n return null;\n }\n\n if (! isset($json['message']) || $json['message']['role'] !== 'assistant') {\n return null;\n }\n\n return $json;\n }\n\n protected function readLine(StreamInterface $stream): string\n {\n $buffer = '';\n\n while (! $stream->eof()) {\n if ('' === ($byte = $stream->read(1))) {\n return $buffer;\n }\n $buffer .= $byte;\n if ($byte === \"\\n\") {\n break;\n }\n }\n\n return $buffer;\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/OllamaEmbeddingsProvider.php", "client = new Client(['base_uri' => \\trim($this->url, '/').'/']);\n }\n\n public function embedText(string $text): array\n {\n $response = $this->client->post('embed', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'input' => $text,\n ...$this->parameters,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['embeddings'][0];\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/MessageMapper.php", "mapping = [];\n\n foreach ($messages as $message) {\n match ($message::class) {\n Message::class,\n UserMessage::class,\n AssistantMessage::class => $this->mapMessage($message),\n ToolCallMessage::class => $this->mapToolCall($message),\n ToolCallResultMessage::class => $this->mapToolsResult($message),\n default => throw new ProviderException('Could not map message type '.$message::class),\n };\n }\n\n return $this->mapping;\n }\n\n protected function mapMessage(Message $message): void\n {\n $payload = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $payload)) {\n unset($payload['usage']);\n }\n\n $attachments = $message->getAttachments();\n\n if (\\is_string($payload['content']) && $attachments) {\n $payload['content'] = [\n [\n 'type' => 'text',\n 'text' => $payload['content'],\n ],\n ];\n }\n\n foreach ($attachments as $attachment) {\n if ($attachment->type === AttachmentType::DOCUMENT) {\n throw new ProviderException('This provider does not support document attachments.');\n }\n\n $payload['content'][] = $this->mapAttachment($attachment);\n }\n\n unset($payload['attachments']);\n\n $this->mapping[] = $payload;\n }\n\n protected function mapAttachment(Attachment $attachment): array\n {\n return match($attachment->contentType) {\n AttachmentContentType::URL => [\n 'type' => 'image_url',\n 'image_url' => [\n 'url' => $attachment->content,\n ],\n ],\n AttachmentContentType::BASE64 => [\n 'type' => 'image_url',\n 'image_url' => [\n 'url' => 'data:'.$attachment->mediaType.';base64,'.$attachment->content,\n ],\n ]\n };\n }\n\n protected function mapToolCall(ToolCallMessage $message): void\n {\n $message = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $message)) {\n unset($message['usage']);\n }\n\n unset($message['type']);\n unset($message['tools']);\n\n $this->mapping[] = $message;\n }\n\n protected function mapToolsResult(ToolCallResultMessage $message): void\n {\n foreach ($message->getTools() as $tool) {\n $this->mapping[] = [\n 'role' => MessageRole::TOOL->value,\n 'tool_call_id' => $tool->getCallId(),\n 'content' => $tool->getResult()\n ];\n }\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/JinaRerankerPostProcessor.php", "client ?? $this->client = new Client([\n 'base_uri' => 'https://api.jina.ai/v1/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer '.$this->key,\n ],\n ]);\n }\n\n public function process(Message $question, array $documents): array\n {\n $response = $this->getClient()->post('rerank', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'query' => $question->getContent(),\n 'top_n' => $this->topN,\n 'documents' => \\array_map(fn (Document $document): array => ['text' => $document->getContent()], $documents),\n 'return_documents' => false,\n ],\n ])->getBody()->getContents();\n\n $result = \\json_decode($response, true);\n\n return \\array_map(function (array $item) use ($documents): Document {\n $document = $documents[$item['index']];\n $document->setScore($item['relevance_score']);\n return $document;\n }, $result['results']);\n }\n\n public function setClient(Client $client): PostProcessorInterface\n {\n $this->client = $client;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Riza/RizaFunctionExecutor.php", "client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json; charset=utf-8',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function __invoke(\n string $code,\n array $input = [],\n array $env = [],\n ): mixed {\n $result = $this->getClient()->post('execute-function', [\n RequestOptions::JSON => [\n 'language' => $this->language,\n 'code' => $code,\n 'input' => $input,\n 'env' => $env,\n ]\n ])->getBody()->getContents();\n\n return \\json_decode($result, true);\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/MessageMapper.php", "mapping = [];\n\n foreach ($messages as $message) {\n match ($message::class) {\n Message::class,\n UserMessage::class,\n AssistantMessage::class => $this->mapMessage($message),\n ToolCallMessage::class => $this->mapToolCall($message),\n ToolCallResultMessage::class => $this->mapToolsResult($message),\n default => throw new ProviderException('Could not map message type '.$message::class),\n };\n }\n\n return $this->mapping;\n }\n\n protected function mapMessage(Message $message): void\n {\n $payload = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $payload)) {\n unset($payload['usage']);\n }\n\n $attachments = $message->getAttachments();\n\n if (\\is_string($payload['content']) && $attachments) {\n $payload['content'] = [\n [\n 'type' => 'text',\n 'text' => $payload['content'],\n ],\n ];\n }\n\n foreach ($attachments as $attachment) {\n $payload['content'][] = $this->mapAttachment($attachment);\n }\n\n unset($payload['attachments']);\n\n $this->mapping[] = $payload;\n }\n\n protected function mapAttachment(Attachment $attachment): array\n {\n return match($attachment->contentType) {\n AttachmentContentType::URL => [\n 'type' => $attachment->type->value,\n 'source' => [\n 'type' => 'url',\n 'url' => $attachment->content,\n ],\n ],\n AttachmentContentType::BASE64 => [\n 'type' => $attachment->type->value,\n 'source' => [\n 'type' => 'base64',\n 'media_type' => $attachment->mediaType,\n 'data' => $attachment->content,\n ],\n ],\n };\n }\n\n protected function mapToolCall(ToolCallMessage $message): void\n {\n $message = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $message)) {\n unset($message['usage']);\n }\n\n unset($message['type']);\n unset($message['tools']);\n\n $this->mapping[] = $message;\n }\n\n protected function mapToolsResult(ToolCallResultMessage $message): void\n {\n $this->mapping[] = [\n 'role' => MessageRole::USER,\n 'content' => \\array_map(fn (ToolInterface $tool): array => [\n 'type' => 'tool_result',\n 'tool_use_id' => $tool->getCallId(),\n 'content' => $tool->getResult(),\n ], $message->getTools())\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Zep/ZepSearchGraphTool.php", "createUser();\n }\n\n protected function properties(): array\n {\n return [\n new ToolProperty(\n 'query',\n PropertyType::STRING,\n 'The search term to find relevant facts or nodes',\n true\n ),\n new ToolProperty(\n 'search_scope',\n PropertyType::STRING,\n 'The scope of the search to perform. Can be \"facts\" or \"nodes\"',\n false,\n ['facts', 'nodes']\n )\n ];\n }\n\n public function __invoke(string $query, string $search_scope = 'facts', int $limit = 5): array\n {\n $response = $this->getClient()->post('graph/search', [\n RequestOptions::JSON => [\n 'user_id' => $this->user_id,\n 'query' => $query,\n 'scope' => $search_scope === 'facts' ? 'edges' : 'nodes',\n 'limit' => $limit,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return match ($search_scope) {\n 'nodes' => $this->mapNodes($response['nodes']),\n default => $this->mapEdges($response['edges']),\n };\n }\n\n protected function mapEdges(array $edges): array\n {\n return \\array_map(fn (array $edge): array => [\n 'fact' => $edge['fact'],\n 'created_at' => $edge['created_at'],\n ], $edges);\n }\n\n protected function mapNodes(array $nodes): array\n {\n return \\array_map(fn (array $node): array => [\n 'name' => $node['name'],\n 'summary' => $node['summary'],\n ], $nodes);\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/MessageMapper.php", "mapping = [];\n\n foreach ($messages as $message) {\n match ($message::class) {\n Message::class,\n UserMessage::class,\n AssistantMessage::class => $this->mapMessage($message),\n ToolCallMessage::class => $this->mapToolCall($message),\n ToolCallResultMessage::class => $this->mapToolsResult($message),\n default => throw new ProviderException('Could not map message type '.$message::class),\n };\n }\n\n return $this->mapping;\n }\n\n protected function mapMessage(Message $message): void\n {\n $payload = [\n 'role' => $message->getRole(),\n 'parts' => [\n ['text' => $message->getContent()]\n ],\n ];\n\n $attachments = $message->getAttachments();\n\n foreach ($attachments as $attachment) {\n $payload['parts'][] = $this->mapAttachment($attachment);\n }\n\n $this->mapping[] = $payload;\n }\n\n protected function mapAttachment(Attachment $attachment): array\n {\n return match($attachment->contentType) {\n AttachmentContentType::URL => [\n 'file_data' => [\n 'file_uri' => $attachment->content,\n 'mime_type' => $attachment->mediaType,\n ],\n ],\n AttachmentContentType::BASE64 => [\n 'inline_data' => [\n 'data' => $attachment->content,\n 'mime_type' => $attachment->mediaType,\n ]\n ]\n };\n }\n\n protected function mapToolCall(ToolCallMessage $message): void\n {\n $this->mapping[] = [\n 'role' => MessageRole::MODEL->value,\n 'parts' => [\n ...\\array_map(fn (ToolInterface $tool): array => [\n 'functionCall' => [\n 'name' => $tool->getName(),\n 'args' => $tool->getInputs() !== [] ? $tool->getInputs() : new \\stdClass(),\n ]\n ], $message->getTools())\n ]\n ];\n }\n\n protected function mapToolsResult(ToolCallResultMessage $message): void\n {\n $this->mapping[] = [\n 'role' => MessageRole::USER->value,\n 'parts' => \\array_map(fn (ToolInterface $tool): array => [\n 'functionResponse' => [\n 'name' => $tool->getName(),\n 'response' => [\n 'name' => $tool->getName(),\n 'content' => $tool->getResult(),\n ],\n ],\n ], $message->getTools()),\n ];\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/ChromaVectorStore.php", "client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->host, '/').\"/api/v1/collections/{$this->collection}/\",\n 'headers' => [\n 'Content-Type' => 'application/json',\n ]\n ]);\n }\n\n public function addDocument(Document $document): void\n {\n $this->addDocuments([$document]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->getClient()->post('delete', [\n RequestOptions::JSON => [\n 'where' => [\n 'sourceType' => $sourceType,\n 'sourceName' => $sourceName,\n ]\n ]\n ]);\n }\n\n public function addDocuments(array $documents): void\n {\n $this->getClient()->post('upsert', [\n RequestOptions::JSON => $this->mapDocuments($documents),\n ])->getBody()->getContents();\n }\n\n public function similaritySearch(array $embedding): iterable\n {\n $response = $this->getClient()->post('query', [\n RequestOptions::JSON => [\n 'queryEmbeddings' => $embedding,\n 'nResults' => $this->topK,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n // Map the result\n $size = \\count($response['distances']);\n $result = [];\n for ($i = 0; $i < $size; $i++) {\n $document = new Document();\n $document->id = $response['ids'][$i] ?? \\uniqid();\n $document->embedding = $response['embeddings'][$i];\n $document->content = $response['documents'][$i];\n $document->sourceType = $response['metadatas'][$i]['sourceType'] ?? null;\n $document->sourceName = $response['metadatas'][$i]['sourceName'] ?? null;\n $document->score = VectorSimilarity::similarityFromDistance($response['distances'][$i]);\n\n foreach ($response['metadatas'][$i] as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName', 'score', 'embedding', 'id'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n $result[] = $document;\n }\n\n return $result;\n }\n\n /**\n * @param Document[] $documents\n */\n protected function mapDocuments(array $documents): array\n {\n $payload = [\n 'ids' => [],\n 'documents' => [],\n 'embeddings' => [],\n 'metadatas' => [],\n ];\n\n foreach ($documents as $document) {\n $payload['ids'][] = $document->getId();\n $payload['documents'][] = $document->getContent();\n $payload['embeddings'][] = $document->getEmbedding();\n $payload['metadatas'][] = [\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ];\n }\n\n return $payload;\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/HandleStream.php", " $this->messageMapper()->map($messages),\n ...$this->parameters\n ];\n\n if (isset($this->system)) {\n $json['system_instruction'] = [\n 'parts' => [\n ['text' => $this->system]\n ]\n ];\n }\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n $stream = $this->client->post(\\trim($this->baseUri, '/').\"/{$this->model}:streamGenerateContent\", [\n 'stream' => true,\n ...[RequestOptions::JSON => $json]\n ])->getBody();\n\n $text = '';\n $toolCalls = [];\n\n while (! $stream->eof()) {\n $line = $this->readLine($stream);\n\n if (($line = \\json_decode((string) $line, true)) === null) {\n continue;\n }\n\n // Inform the agent about usage when stream\n if (\\array_key_exists('usageMetadata', $line)) {\n yield \\json_encode(['usage' => [\n 'input_tokens' => $line['usageMetadata']['promptTokenCount'],\n 'output_tokens' => $line['usageMetadata']['candidatesTokenCount'] ?? 0,\n ]]);\n }\n\n // Process tool calls\n if ($this->hasToolCalls($line)) {\n $toolCalls = $this->composeToolCalls($line, $toolCalls);\n\n // Handle tool calls\n if (isset($line['candidates'][0]['finishReason']) && $line['candidates'][0]['finishReason'] === 'STOP') {\n yield from $executeToolsCallback(\n $this->createToolCallMessage([\n 'content' => $text,\n 'parts' => $toolCalls\n ])\n );\n\n return;\n }\n\n continue;\n }\n\n // Process regular content\n $content = $line['candidates'][0]['content']['parts'][0]['text'] ?? '';\n $text .= $content;\n\n yield $content;\n }\n }\n\n /**\n * Recreate the tool_calls format from streaming Gemini API.\n */\n protected function composeToolCalls(array $line, array $toolCalls): array\n {\n $parts = $line['candidates'][0]['content']['parts'] ?? [];\n\n foreach ($parts as $index => $part) {\n if (isset($part['functionCall'])) {\n $toolCalls[$index]['functionCall'] = $part['functionCall'];\n }\n }\n\n return $toolCalls;\n }\n\n /**\n * Determines if the given line contains tool function calls.\n *\n * @param array $line The data line to check for tool function calls.\n * @return bool Returns true if the line contains tool function calls, otherwise false.\n */\n protected function hasToolCalls(array $line): bool\n {\n $parts = $line['candidates'][0]['content']['parts'] ?? [];\n\n foreach ($parts as $part) {\n if (isset($part['functionCall'])) {\n return true;\n }\n }\n\n return false;\n }\n\n private function readLine(StreamInterface $stream): string\n {\n $buffer = '';\n\n while (! $stream->eof()) {\n $buffer .= $stream->read(1);\n\n if (\\strlen($buffer) === 1 && $buffer !== '{') {\n $buffer = '';\n }\n\n if (\\json_decode($buffer) !== null) {\n return $buffer;\n }\n }\n\n return \\rtrim($buffer, ']');\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Tavily/TavilySearchTool.php", " 'basic',\n 'chunks_per_source' => 3,\n 'max_results' => 1,\n ];\n\n /**\n * @param string $key Tavily API key.\n * @param array $topics Explicit the topics you want to force the Agent to perform web search.\n */\n public function __construct(\n protected string $key,\n protected array $topics = [],\n ) {\n\n parent::__construct(\n 'web_search',\n 'Use this tool to search the web for additional information '.\n ($this->topics === [] ? '' : 'about '.\\implode(', ', $this->topics).', or ').\n 'if the question is outside the scope of the context you have.'\n );\n\n }\n\n protected function properties(): array\n {\n return [\n new ToolProperty(\n 'search_query',\n PropertyType::STRING,\n 'The search query to perform web search.',\n true\n ),\n new ToolProperty(\n 'topic',\n PropertyType::STRING,\n 'Explicit the topic you want to perform the web search on.',\n false,\n ['general', 'news']\n ),\n new ToolProperty(\n 'time_range',\n PropertyType::STRING,\n '',\n false,\n ['day, week, month, year']\n ),\n new ToolProperty(\n 'days',\n PropertyType::INTEGER,\n 'Filter search results for a certain range of days up to today.',\n false,\n )\n ];\n }\n\n protected function getClient(): Client\n {\n return $this->client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function __invoke(\n string $search_query,\n ?string $topic = null,\n ?string $time_range = null,\n ?int $days = null,\n ): array {\n $topic ??= 'general';\n $time_range ??= 'day';\n $days ??= 7;\n\n $result = $this->getClient()->post('search', [\n RequestOptions::JSON => \\array_merge(\n ['topic' => $topic, 'time_range' => $time_range, 'days' => $days],\n $this->options,\n [\n 'query' => $search_query,\n ]\n )\n ])->getBody()->getContents();\n\n $result = \\json_decode($result, true);\n\n return [\n 'answer' => $result['answer'],\n 'results' => \\array_map(fn (array $item): array => [\n 'title' => $item['title'],\n 'url' => $item['url'],\n 'content' => $item['content'],\n ], $result['results']),\n ];\n }\n\n public function withOptions(array $options): self\n {\n $this->options = $options;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Tavily/TavilyCrawlTool.php", " false,\n 'allow_external' => false\n ];\n\n /**\n * @param string $key Tavily API key.\n */\n public function __construct(\n protected string $key,\n ) {\n parent::__construct(\n 'url_crawl',\n 'Get the entire website in markdown format.'\n );\n }\n\n protected function properties(): array\n {\n return [\n new ToolProperty(\n 'url',\n PropertyType::STRING,\n 'The URL to crawl.',\n true\n ),\n ];\n }\n\n public function __invoke(string $url): array\n {\n if (!\\filter_var($url, \\FILTER_VALIDATE_URL)) {\n throw new ToolException('Invalid URL.');\n }\n\n $result = $this->getClient()->post('crawl', [\n RequestOptions::JSON => \\array_merge(\n $this->options,\n ['url' => $url]\n )\n ])->getBody()->getContents();\n\n return \\json_decode($result, true);\n }\n\n\n protected function getClient(): Client\n {\n return $this->client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function withOptions(array $options): self\n {\n $this->options = $options;\n return $this;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/QdrantVectorStore.php", "client = new Client([\n 'base_uri' => \\trim($this->collectionUrl, '/').'/',\n 'headers' => [\n 'Content-Type' => 'application/json',\n 'api-key' => $this->key,\n ]\n ]);\n }\n\n public function addDocument(Document $document): void\n {\n $this->client->put('points', [\n RequestOptions::JSON => [\n 'points' => [\n [\n 'id' => $document->getId(),\n 'payload' => [\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n 'metadata' => $document->metadata,\n ],\n 'vector' => $document->getEmbedding(),\n ]\n ]\n ]\n ]);\n }\n\n /**\n * Bulk save documents.\n *\n * @param Document[] $documents\n * @throws GuzzleException\n */\n public function addDocuments(array $documents): void\n {\n $points = \\array_map(fn (Document $document): array => [\n 'id' => $document->getId(),\n 'payload' => [\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ],\n 'vector' => $document->getEmbedding(),\n ], $documents);\n\n $this->client->put('points', [\n RequestOptions::JSON => ['points' => $points]\n ]);\n }\n\n /**\n * @throws GuzzleException\n */\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->post('points/delete', [\n RequestOptions::JSON => [\n 'wait' => true,\n 'filter' => [\n 'must' => [\n [\n 'key' => 'sourceType',\n 'match' => [\n 'value' => $sourceType,\n ]\n ],\n [\n 'key' => 'sourceName',\n 'match' => [\n 'value' => $sourceName,\n ]\n ]\n ]\n ]\n ]\n ]);\n }\n\n public function similaritySearch(array $embedding): iterable\n {\n $response = $this->client->post('points/search', [\n RequestOptions::JSON => [\n 'vector' => $embedding,\n 'limit' => $this->topK,\n 'with_payload' => true,\n 'with_vector' => true,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return \\array_map(function (array $item): Document {\n $document = new Document($item['payload']['content']);\n $document->id = $item['id'];\n $document->embedding = $item['vector'];\n $document->sourceType = $item['payload']['sourceType'];\n $document->sourceName = $item['payload']['sourceName'];\n $document->score = $item['score'];\n\n foreach ($item['payload'] as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName', 'score', 'embedding', 'id'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $response['result']);\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/MeilisearchVectorStore.php", "client = new Client([\n 'base_uri' => \\trim($host, '/').'/indexes/'.$indexUid.'/',\n 'headers' => [\n 'Content-Type' => 'application/json',\n ...(\\is_null($key) ? [] : ['Authorization' => \"Bearer {$key}\"])\n ]\n ]);\n\n try {\n $this->client->get('');\n } catch (\\Exception) {\n throw new VectorStoreException(\"Index {$indexUid} doesn't exists. Remember to attach a custom embedder to the index in order to process vectors.\");\n }\n }\n\n public function addDocument(Document $document): void\n {\n $this->addDocuments([$document]);\n }\n\n public function addDocuments(array $documents): void\n {\n $this->client->put('documents', [\n RequestOptions::JSON => \\array_map(fn (Document $document) => [\n 'id' => $document->getId(),\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n '_vectors' => [\n 'default' => [\n 'embeddings' => $document->getEmbedding(),\n 'regenerate' => false,\n ],\n ]\n ], $documents),\n ]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->post('documents/delete', [\n RequestOptions::JSON => [\n 'filter' => \"sourceType = {$sourceType} AND sourceName = {$sourceName}\",\n ]\n ]);\n }\n\n public function similaritySearch(array $embedding): iterable\n {\n $response = $this->client->post('search', [\n RequestOptions::JSON => [\n 'vector' => $embedding,\n 'limit' => \\min($this->topK, 20),\n 'retrieveVectors' => true,\n 'showRankingScore' => true,\n 'hybrid' => [\n 'semanticRatio' => 1.0,\n 'embedder' => $this->embedder,\n ],\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return \\array_map(function (array $item): Document {\n $document = new Document($item['content']);\n $document->id = $item['id'] ?? \\uniqid();\n $document->sourceType = $item['sourceType'] ?? null;\n $document->sourceName = $item['sourceName'] ?? null;\n $document->embedding = $item['_vectors']['default']['embeddings'];\n $document->score = $item['_rankingScore'];\n\n foreach ($item as $name => $value) {\n if (!\\in_array($name, ['_vectors', '_rankingScore', 'content', 'sourceType', 'sourceName', 'score', 'embedding', 'id'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $response['hits']);\n }\n}\n"], ["/neuron-ai/src/MCP/McpClient.php", "transport = new StdioTransport($config);\n $this->transport->connect();\n $this->initialize();\n } else {\n // todo: implement support for SSE with URL config property\n throw new McpException('Transport not supported!');\n }\n }\n\n protected function initialize(): void\n {\n $request = [\n \"jsonrpc\" => \"2.0\",\n \"id\" => ++$this->requestId,\n \"method\" => \"initialize\",\n \"params\" => [\n 'protocolVersion' => '2024-11-05',\n 'capabilities' => (object)[\n 'sampling' => new \\stdClass(),\n ],\n 'clientInfo' => (object)[\n 'name' => 'neuron-ai',\n 'version' => '1.0.0',\n ],\n ],\n ];\n $this->transport->send($request);\n $response = $this->transport->receive();\n\n if ($response['id'] !== $this->requestId) {\n throw new McpException('Invalid response ID');\n }\n\n $request = [\n \"jsonrpc\" => \"2.0\",\n \"method\" => \"notifications/initialized\",\n ];\n $this->transport->send($request);\n }\n\n /**\n * List all available tools from the MCP server\n *\n * @throws \\Exception\n */\n public function listTools(): array\n {\n $tools = [];\n\n do {\n $request = [\n \"jsonrpc\" => \"2.0\",\n \"id\" => ++$this->requestId,\n \"method\" => \"tools/list\",\n ];\n\n // Eventually add pagination\n if (isset($response['result']['nextCursor'])) {\n $request['params'] = ['cursor' => $response['result']['nextCursor']];\n }\n\n $this->transport->send($request);\n $response = $this->transport->receive();\n\n if ($response['id'] !== $this->requestId) {\n throw new McpException('Invalid response ID');\n }\n\n $tools = \\array_merge($tools, $response['result']['tools']);\n } while (isset($response['result']['nextCursor']));\n\n return $tools;\n }\n\n /**\n * Call a tool on the MCP server\n *\n * @throws \\Exception\n */\n public function callTool(string $toolName, array $arguments = []): array\n {\n $request = [\n \"jsonrpc\" => \"2.0\",\n \"id\" => ++$this->requestId,\n \"method\" => \"tools/call\",\n \"params\" => [\n \"name\" => $toolName,\n \"arguments\" => $arguments\n ]\n ];\n\n $this->transport->send($request);\n return $this->transport->receive();\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/TypesenseVectorStore.php", "client->collections[$this->collection]->retrieve();\n $this->checkVectorDimension(\\count($document->getEmbedding()));\n return;\n } catch (ObjectNotFound) {\n $fields = [\n [\n 'name' => 'content',\n 'type' => 'string',\n ],\n [\n 'name' => 'sourceType',\n 'type' => 'string',\n 'facet' => true,\n ],\n [\n 'name' => 'sourceName',\n 'type' => 'string',\n 'facet' => true,\n ],\n [\n 'name' => 'embedding',\n 'type' => 'float[]',\n 'num_dim' => $this->vectorDimension,\n ],\n ];\n\n // Map custom fields\n foreach ($document->metadata as $name => $value) {\n $fields[] = [\n 'name' => $name,\n 'type' => \\gettype($value),\n 'facet' => true,\n ];\n }\n\n $this->client->collections->create([\n 'name' => $this->collection,\n 'fields' => $fields,\n ]);\n }\n }\n\n public function addDocument(Document $document): void\n {\n if ($document->getEmbedding() === []) {\n throw new \\Exception('document embedding must be set before adding a document');\n }\n\n $this->checkIndexStatus($document);\n\n $this->client->collections[$this->collection]->documents->create([\n 'id' => $document->getId(), // Unique ID is required\n 'content' => $document->getContent(),\n 'embedding' => $document->getEmbedding(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->collections[$this->collection]->documents->delete([\n \"filter_by\" => \"sourceType:={$sourceType} && sourceName:={$sourceName}\",\n ]);\n }\n\n /**\n * Bulk save.\n *\n * @param Document[] $documents\n * @throws Exception\n * @throws \\JsonException\n * @throws TypesenseClientError\n */\n public function addDocuments(array $documents): void\n {\n if ($documents === []) {\n return;\n }\n\n if (empty($documents[0]->getEmbedding())) {\n throw new \\Exception('document embedding must be set before adding a document');\n }\n\n $this->checkIndexStatus($documents[0]);\n\n $lines = [];\n foreach ($documents as $document) {\n $lines[] = \\json_encode([\n 'id' => $document->getId(), // Unique ID is required\n 'embedding' => $document->getEmbedding(),\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ]);\n }\n\n $ndjson = \\implode(\"\\n\", $lines);\n\n $this->client->collections[$this->collection]->documents->import($ndjson);\n }\n\n public function similaritySearch(array $embedding): array\n {\n $params = [\n 'collection' => $this->collection,\n 'q' => '*',\n 'vector_query' => 'embedding:(' . \\json_encode($embedding) . ')',\n 'exclude_fields' => 'embedding',\n 'per_page' => $this->topK,\n 'num_candidates' => \\max(50, \\intval($this->topK) * 4),\n ];\n\n $searchRequests = ['searches' => [$params]];\n\n $response = $this->client->multiSearch->perform($searchRequests);\n return \\array_map(function (array $hit): Document {\n $item = $hit['document'];\n $document = new Document($item['content']);\n //$document->embedding = $item['embedding']; // avoid carrying large data\n $document->sourceType = $item['sourceType'];\n $document->sourceName = $item['sourceName'];\n $document->score = VectorSimilarity::similarityFromDistance($hit['vector_distance']);\n\n foreach ($item as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName', 'score', 'embedding', 'id', 'vector_distance'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $response['results'][0]['hits']);\n }\n\n private function checkVectorDimension(int $dimension): void\n {\n $schema = $this->client->collections[$this->collection]->retrieve();\n\n $embeddingField = null;\n\n foreach ($schema['fields'] as $field) {\n if ($field['name'] === 'embedding') {\n $embeddingField = $field;\n break;\n }\n }\n\n if (\n \\array_key_exists('num_dim', $embeddingField)\n && $embeddingField['num_dim'] === $dimension\n ) {\n return;\n }\n\n throw new \\Exception(\n \"Vector embeddings dimension {$dimension} must be the same as the initial setup {$this->vectorDimension} - \".\n \\json_encode($embeddingField)\n );\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Tavily/TavilyExtractTool.php", "getClient()->post('extract', [\n RequestOptions::JSON => \\array_merge(\n $this->options,\n ['urls' => [$url]]\n )\n ])->getBody()->getContents();\n\n $result = \\json_decode($result, true);\n\n return $result['results'][0];\n }\n\n\n protected function getClient(): Client\n {\n return $this->client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function withOptions(array $options): self\n {\n $this->options = $options;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Zep/ZepAddToGraphTool.php", "createUser();\n }\n\n protected function properties(): array\n {\n return [\n new ToolProperty(\n 'data',\n PropertyType::STRING,\n 'The search term to find relevant facts or nodes',\n true\n ),\n new ToolProperty(\n 'type',\n PropertyType::STRING,\n 'The scope of the search to perform. Can be \"facts\" or \"nodes\"',\n true,\n ['text', 'json', 'message']\n )\n ];\n }\n\n public function __invoke(string $data, string $type): string\n {\n $response = $this->getClient()->post('graph', [\n RequestOptions::JSON => [\n 'user_id' => $this->user_id,\n 'data' => $data,\n 'type' => $type,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['content'];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Zep/HandleZepClient.php", "client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => \"Api-Key {$this->key}\",\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n protected function createUser(): self\n {\n // Create the user if it doesn't exist\n try {\n $this->getClient()->get('users/'.$this->user_id);\n } catch (\\Exception) {\n $this->getClient()->post('users', [\n RequestOptions::JSON => ['user_id' => $this->user_id]\n ]);\n }\n\n return $this;\n }\n}\n"], ["/neuron-ai/src/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(Message|array $messages): PromiseInterface\n {\n $this->notify('chat-start');\n\n $this->fillChatHistory($messages);\n\n $tools = $this->bootstrapTools();\n\n $this->notify(\n 'inference-start',\n new InferenceStart($this->resolveChatHistory()->getLastMessage())\n );\n\n return $this->resolveProvider()\n ->systemPrompt($this->resolveInstructions())\n ->setTools($tools)\n ->chatAsync(\n $this->resolveChatHistory()->getMessages()\n )->then(function (Message $response): Message|PromiseInterface {\n $this->notify(\n 'inference-stop',\n new InferenceStop($this->resolveChatHistory()->getLastMessage(), $response)\n );\n\n $this->fillChatHistory($response);\n\n if ($response instanceof ToolCallMessage) {\n $toolCallResult = $this->executeTools($response);\n return self::chatAsync($toolCallResult);\n }\n\n $this->notify('chat-stop');\n return $response;\n }, function (\\Throwable $exception): void {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n });\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/ToolCallMessage.php", " $tools\n */\n public function __construct(\n protected array|string|int|float|null $content,\n protected array $tools\n ) {\n parent::__construct($this->content);\n }\n\n /**\n * @return array\n */\n public function getTools(): array\n {\n return $this->tools;\n }\n\n public function jsonSerialize(): array\n {\n return \\array_merge(\n parent::jsonSerialize(),\n [\n 'type' => 'tool_call',\n 'tools' => \\array_map(fn (ToolInterface $tool): array => $tool->jsonSerialize(), $this->tools)\n ]\n );\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/MessageMapper.php", "mapping = [];\n\n foreach ($messages as $message) {\n match ($message::class) {\n Message::class,\n UserMessage::class,\n AssistantMessage::class => $this->mapMessage($message),\n ToolCallMessage::class => $this->mapToolCall($message),\n ToolCallResultMessage::class => $this->mapToolsResult($message),\n default => throw new ProviderException('Could not map message type '.$message::class),\n };\n }\n\n return $this->mapping;\n }\n\n public function mapMessage(Message $message): void\n {\n $payload = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $payload)) {\n unset($payload['usage']);\n }\n\n $attachments = $message->getAttachments();\n\n foreach ($attachments as $attachment) {\n if ($attachment->type === AttachmentType::DOCUMENT) {\n throw new ProviderException('This provider does not support document attachments.');\n }\n\n $payload['images'][] = $this->mapAttachment($attachment);\n }\n\n unset($payload['attachments']);\n\n $this->mapping[] = $payload;\n }\n\n protected function mapAttachment(Attachment $attachment): string\n {\n return match ($attachment->contentType) {\n AttachmentContentType::BASE64 => $attachment->content,\n AttachmentContentType::URL => throw new ProviderException('Ollama support only base64 attachment type.'),\n };\n }\n\n protected function mapToolCall(ToolCallMessage $message): void\n {\n $message = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $message)) {\n unset($message['usage']);\n }\n\n if (\\array_key_exists('tool_calls', $message)) {\n $message['tool_calls'] = \\array_map(function (array $toolCall) {\n if (empty($toolCall['function']['arguments'])) {\n $toolCall['function']['arguments'] = new \\stdClass();\n }\n return $toolCall;\n }, $message['tool_calls']);\n }\n\n unset($message['type']);\n unset($message['tools']);\n\n $this->mapping[] = $message;\n }\n\n public function mapToolsResult(ToolCallResultMessage $message): void\n {\n foreach ($message->getTools() as $tool) {\n $this->mapping[] = [\n 'role' => MessageRole::TOOL->value,\n 'content' => $tool->getResult()\n ];\n }\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/ElasticsearchVectorStore.php", "client->indices()->exists(['index' => $this->index]);\n $existStatusCode = $existResponse->getStatusCode();\n\n if ($existStatusCode === 200) {\n // Map vector embeddings dimension on the fly adding a document.\n $this->mapVectorDimension(\\count($document->getEmbedding()));\n return;\n }\n\n $properties = [\n 'content' => [\n 'type' => 'text',\n ],\n 'sourceType' => [\n 'type' => 'keyword',\n ],\n 'sourceName' => [\n 'type' => 'keyword',\n ]\n ];\n\n // Map metadata\n foreach (\\array_keys($document->metadata) as $name) {\n $properties[$name] = [\n 'type' => 'keyword',\n ];\n }\n\n $this->client->indices()->create([\n 'index' => $this->index,\n 'body' => [\n 'mappings' => [\n 'properties' => $properties,\n ],\n ],\n ]);\n }\n\n /**\n * @throws \\Exception\n */\n public function addDocument(Document $document): void\n {\n if ($document->embedding === []) {\n throw new \\Exception('Document embedding must be set before adding a document');\n }\n\n $this->checkIndexStatus($document);\n\n $this->client->index([\n 'index' => $this->index,\n 'body' => [\n 'embedding' => $document->getEmbedding(),\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ],\n ]);\n\n $this->client->indices()->refresh(['index' => $this->index]);\n }\n\n /**\n * @param Document[] $documents\n *\n * @throws \\Exception\n */\n public function addDocuments(array $documents): void\n {\n if ($documents === []) {\n return;\n }\n\n if (empty($documents[0]->getEmbedding())) {\n throw new \\Exception('Document embedding must be set before adding a document');\n }\n\n $this->checkIndexStatus($documents[0]);\n\n /*\n * Generate a bulk payload\n */\n $params = ['body' => []];\n foreach ($documents as $document) {\n $params['body'][] = [\n 'index' => [\n '_index' => $this->index,\n ],\n ];\n $params['body'][] = [\n 'embedding' => $document->getEmbedding(),\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ];\n }\n $this->client->bulk($params);\n $this->client->indices()->refresh(['index' => $this->index]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->deleteByQuery([\n 'index' => $this->index,\n 'q' => \"sourceType:{$sourceType} AND sourceName:{$sourceName}\",\n 'body' => []\n ]);\n $this->client->indices()->refresh(['index' => $this->index]);\n }\n\n /**\n * {@inheritDoc}\n *\n * num_candidates are used to tune approximate kNN for speed or accuracy (see : https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy)\n * @return Document[]\n * @throws ClientResponseException\n * @throws ServerResponseException\n */\n public function similaritySearch(array $embedding): array\n {\n $searchParams = [\n 'index' => $this->index,\n 'body' => [\n 'knn' => [\n 'field' => 'embedding',\n 'query_vector' => $embedding,\n 'k' => $this->topK,\n 'num_candidates' => \\max(50, $this->topK * 4),\n ],\n 'sort' => [\n '_score' => [\n 'order' => 'desc',\n ],\n ],\n ],\n ];\n\n // Hybrid search\n if ($this->filters !== []) {\n $searchParams['body']['knn']['filter'] = $this->filters;\n }\n\n $response = $this->client->search($searchParams);\n\n return \\array_map(function (array $item): Document {\n $document = new Document($item['_source']['content']);\n //$document->embedding = $item['_source']['embedding']; // avoid carrying large data\n $document->sourceType = $item['_source']['sourceType'];\n $document->sourceName = $item['_source']['sourceName'];\n $document->score = $item['_score'];\n\n foreach ($item['_source'] as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName', 'score', 'embedding', 'id'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $response['hits']['hits']);\n }\n\n /**\n * Map vector embeddings dimension on the fly.\n */\n private function mapVectorDimension(int $dimension): void\n {\n if ($this->vectorDimSet) {\n return;\n }\n\n $response = $this->client->indices()->getFieldMapping([\n 'index' => $this->index,\n 'fields' => 'embedding',\n ]);\n\n $mappings = $response[$this->index]['mappings'];\n if (\n \\array_key_exists('embedding', $mappings)\n && $mappings['embedding']['mapping']['embedding']['dims'] === $dimension\n ) {\n return;\n }\n\n $this->client->indices()->putMapping([\n 'index' => $this->index,\n 'body' => [\n 'properties' => [\n 'embedding' => [\n 'type' => 'dense_vector',\n //'element_type' => 'float', // it's float by default\n 'dims' => $dimension,\n 'index' => true,\n 'similarity' => 'cosine',\n ],\n ],\n ],\n ]);\n\n $this->vectorDimSet = true;\n }\n\n public function withFilters(array $filters): self\n {\n $this->filters = $filters;\n return $this;\n }\n}\n"], ["/neuron-ai/src/RAG/RAG.php", "chat($question);\n }\n\n /**\n * @deprecated Use \"stream\" instead\n */\n public function answerStream(Message $question): \\Generator\n {\n return $this->stream($question);\n }\n\n /**\n * @throws MissingCallbackParameter\n * @throws ToolCallableNotSet\n * @throws \\Throwable\n */\n public function chat(Message|array $messages): Message\n {\n $question = \\is_array($messages) ? \\end($messages) : $messages;\n\n $this->notify('chat-rag-start');\n\n $this->retrieval($question);\n\n $response = parent::chat($messages);\n\n $this->notify('chat-rag-stop');\n return $response;\n }\n\n public function stream(Message|array $messages): \\Generator\n {\n $question = \\is_array($messages) ? \\end($messages) : $messages;\n\n $this->notify('stream-rag-start');\n\n $this->retrieval($question);\n\n yield from parent::stream($messages);\n\n $this->notify('stream-rag-stop');\n }\n\n public function structured(Message|array $messages, ?string $class = null, int $maxRetries = 1): mixed\n {\n $question = \\is_array($messages) ? \\end($messages) : $messages;\n\n $this->notify('structured-rag-start');\n\n $this->retrieval($question);\n\n $structured = parent::structured($messages, $class, $maxRetries);\n\n $this->notify('structured-rag-stop');\n\n return $structured;\n }\n\n protected function retrieval(Message $question): void\n {\n $this->withDocumentsContext(\n $this->retrieveDocuments($question)\n );\n }\n\n /**\n * Set the system message based on the context.\n *\n * @param Document[] $documents\n */\n public function withDocumentsContext(array $documents): AgentInterface\n {\n $originalInstructions = $this->resolveInstructions();\n\n // Remove the old context to avoid infinite grow\n $newInstructions = $this->removeDelimitedContent($originalInstructions, '', '');\n\n $newInstructions .= '';\n foreach ($documents as $document) {\n $newInstructions .= \"Source Type: \".$document->getSourceType().\\PHP_EOL.\n \"Source Name: \".$document->getSourceName().\\PHP_EOL.\n \"Content: \".$document->getContent().\\PHP_EOL.\\PHP_EOL;\n }\n $newInstructions .= '';\n\n $this->withInstructions(\\trim($newInstructions));\n\n return $this;\n }\n\n /**\n * Retrieve relevant documents from the vector store.\n *\n * @return Document[]\n */\n public function retrieveDocuments(Message $question): array\n {\n $question = $this->applyPreProcessors($question);\n\n $this->notify('rag-retrieving', new Retrieving($question));\n\n $documents = $this->resolveVectorStore()->similaritySearch(\n $this->resolveEmbeddingsProvider()->embedText($question->getContent()),\n );\n\n $retrievedDocs = [];\n\n foreach ($documents as $document) {\n //md5 for removing duplicates\n $retrievedDocs[\\md5($document->getContent())] = $document;\n }\n\n $retrievedDocs = \\array_values($retrievedDocs);\n\n $this->notify('rag-retrieved', new Retrieved($question, $retrievedDocs));\n\n return $this->applyPostProcessors($question, $retrievedDocs);\n }\n\n /**\n * Apply a series of preprocessors to the asked question.\n *\n * @return Message The processed question.\n */\n protected function applyPreProcessors(Message $question): Message\n {\n foreach ($this->preProcessors() as $processor) {\n $this->notify('rag-preprocessing', new PreProcessing($processor::class, $question));\n $question = $processor->process($question);\n $this->notify('rag-preprocessed', new PreProcessed($processor::class, $question));\n }\n\n return $question;\n }\n\n /**\n * Apply a series of postprocessors to the retrieved documents.\n *\n * @param Document[] $documents The documents to process.\n * @return Document[] The processed documents.\n */\n protected function applyPostProcessors(Message $question, array $documents): array\n {\n foreach ($this->postProcessors() as $processor) {\n $this->notify('rag-postprocessing', new PostProcessing($processor::class, $question, $documents));\n $documents = $processor->process($question, $documents);\n $this->notify('rag-postprocessed', new PostProcessed($processor::class, $question, $documents));\n }\n\n return $documents;\n }\n\n /**\n * Feed the vector store with documents.\n *\n * @param Document[] $documents\n */\n public function addDocuments(array $documents, int $chunkSize = 50): void\n {\n foreach (\\array_chunk($documents, $chunkSize) as $chunk) {\n $this->resolveVectorStore()->addDocuments(\n $this->resolveEmbeddingsProvider()->embedDocuments($chunk)\n );\n }\n }\n\n /**\n * @param Document[] $documents\n */\n public function reindexBySource(array $documents, int $chunkSize = 50): void\n {\n $grouped = [];\n\n foreach ($documents as $document) {\n $key = $document->sourceType . ':' . $document->sourceName;\n\n if (!isset($grouped[$key])) {\n $grouped[$key] = [];\n }\n\n $grouped[$key][] = $document;\n }\n\n foreach (\\array_keys($grouped) as $key) {\n [$sourceType, $sourceName] = \\explode(':', $key);\n $this->resolveVectorStore()->deleteBySource($sourceType, $sourceName);\n $this->addDocuments($grouped[$key], $chunkSize);\n }\n }\n\n /**\n * @throws AgentException\n */\n public function setPreProcessors(array $preProcessors): RAG\n {\n foreach ($preProcessors as $processor) {\n if (! $processor instanceof PreProcessorInterface) {\n throw new AgentException($processor::class.\" must implement PreProcessorInterface\");\n }\n\n $this->preProcessors[] = $processor;\n }\n\n return $this;\n }\n\n /**\n * @throws AgentException\n */\n public function setPostProcessors(array $postProcessors): RAG\n {\n foreach ($postProcessors as $processor) {\n if (! $processor instanceof PostProcessorInterface) {\n throw new AgentException($processor::class.\" must implement PostProcessorInterface\");\n }\n\n $this->postProcessors[] = $processor;\n }\n\n return $this;\n }\n\n /**\n * @return PreProcessorInterface[]\n */\n protected function preProcessors(): array\n {\n return $this->preProcessors;\n }\n\n /**\n * @return PostProcessorInterface[]\n */\n protected function postProcessors(): array\n {\n return $this->postProcessors;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/AWS/SESTool.php", "validateRecipients($to);\n\n $result = $this->sesClient->sendEmail([\n 'Source' => $this->fromEmail,\n 'Destination' => $this->buildDestinations($to, $cc, $bcc),\n 'Message' => $this->buildMessage($subject, $body),\n ]);\n\n return [\n 'success' => true,\n 'message_id' => $result['MessageId'] ?? null,\n 'status' => 'sent',\n 'recipients_count' => \\count($to),\n 'aws_request_id' => $result['@metadata']['requestId'] ?? null\n ];\n } catch (\\Exception $e) {\n return [\n 'success' => false,\n 'error' => $e->getMessage(),\n 'error_type' => $e::class,\n 'status' => 'failed'\n ];\n }\n }\n\n /**\n * @param array $to\n * @throws ToolException\n */\n protected function validateRecipients(array $to): void\n {\n foreach ($to as $recipient) {\n if (\\filter_var($recipient, \\FILTER_VALIDATE_EMAIL) === false) {\n throw new ToolException('Invalid email address: ' . $recipient . '.');\n }\n }\n }\n\n protected function buildDestinations(array $to, ?array $cc = null, ?array $bcc = null): array\n {\n $destinations = [\n 'ToAddresses' => $to,\n ];\n\n if ($cc !== null && $cc !== []) {\n $destinations['CcAddresses'] = $cc;\n }\n\n if ($bcc !== null && $bcc !== []) {\n $destinations['BccAddresses'] = $bcc;\n }\n\n return $destinations;\n }\n\n protected function buildMessage(string $subject, string $body): array\n {\n return [\n 'Subject' => [\n 'Data' => $subject,\n 'Charset' => 'UTF-8'\n ],\n 'Body' => [\n 'Html' => [\n 'Data' => $body,\n 'Charset' => 'UTF-8'\n ],\n 'Text' => [\n 'Data' => \\strip_tags($body),\n 'Charset' => 'UTF-8'\n ]\n ]\n ];\n }\n}\n"], ["/neuron-ai/src/Observability/AgentMonitoring.php", "\n */\n protected array $segments = [];\n\n\n /**\n * @var array\n */\n protected array $methodsMap = [\n 'error' => 'reportError',\n 'chat-start' => 'start',\n 'chat-stop' => 'stop',\n 'stream-start' => 'start',\n 'stream-stop' => 'stop',\n 'structured-start' => 'start',\n 'structured-stop' => 'stop',\n 'chat-rag-start' => 'start',\n 'chat-rag-stop' => 'stop',\n 'stream-rag-start' => 'start',\n 'stream-rag-stop' => 'stop',\n 'structured-rag-start' => 'start',\n 'structured-rag-stop' => 'stop',\n\n 'message-saving' => 'messageSaving',\n 'message-saved' => 'messageSaved',\n 'tools-bootstrapping' => 'toolsBootstrapping',\n 'tools-bootstrapped' => 'toolsBootstrapped',\n 'inference-start' => 'inferenceStart',\n 'inference-stop' => 'inferenceStop',\n 'tool-calling' => 'toolCalling',\n 'tool-called' => 'toolCalled',\n 'schema-generation' => 'schemaGeneration',\n 'schema-generated' => 'schemaGenerated',\n 'structured-extracting' => 'extracting',\n 'structured-extracted' => 'extracted',\n 'structured-deserializing' => 'deserializing',\n 'structured-deserialized' => 'deserialized',\n 'structured-validating' => 'validating',\n 'structured-validated' => 'validated',\n 'rag-retrieving' => 'ragRetrieving',\n 'rag-retrieved' => 'ragRetrieved',\n 'rag-preprocessing' => 'preProcessing',\n 'rag-preprocessed' => 'preProcessed',\n 'rag-postprocessing' => 'postProcessing',\n 'rag-postprocessed' => 'postProcessed',\n 'workflow-start' => 'workflowStart',\n 'workflow-end' => 'workflowEnd',\n 'workflow-node-start' => 'workflowNodeStart',\n 'workflow-node-end' => 'workflowNodeEnd',\n ];\n\n protected static ?AgentMonitoring $instance = null;\n\n /**\n * @param Inspector $inspector The monitoring instance\n */\n public function __construct(\n protected Inspector $inspector,\n protected bool $autoFlush = false,\n ) {\n }\n\n\n public static function instance(): AgentMonitoring\n {\n $configuration = new Configuration($_ENV['INSPECTOR_INGESTION_KEY']);\n $configuration->setTransport($_ENV['INSPECTOR_TRANSPORT'] ?? 'async');\n $configuration->setVersion($_ENV['INSPECTOR_VERSION'] ?? $configuration->getVersion());\n\n // Split monitoring between agents and workflows.\n if (isset($_ENV['NEURON_SPLIT_MONITORING'])) {\n return new self(new Inspector($configuration), $_ENV['NEURON_AUTOFLUSH'] ?? false);\n }\n\n if (!self::$instance instanceof AgentMonitoring) {\n self::$instance = new self(new Inspector($configuration), $_ENV['NEURON_AUTOFLUSH'] ?? false);\n }\n return self::$instance;\n }\n\n public function update(\\SplSubject $subject, ?string $event = null, mixed $data = null): void\n {\n if (!\\is_null($event) && \\array_key_exists($event, $this->methodsMap)) {\n $method = $this->methodsMap[$event];\n $this->$method($subject, $event, $data);\n }\n }\n\n public function start(Agent $agent, string $event, mixed $data = null): void\n {\n if (!$this->inspector->isRecording()) {\n return;\n }\n\n $method = $this->getPrefix($event);\n $class = $agent::class;\n\n if ($this->inspector->needTransaction()) {\n $this->inspector->startTransaction($class.'::'.$method)\n ->setType('ai-agent')\n ->setContext($this->getContext($agent));\n } elseif ($this->inspector->canAddSegments() && !$agent instanceof RAG) { // do not add \"parent\" agent segments on RAG\n $key = $class.$method;\n\n if (\\array_key_exists($key, $this->segments)) {\n $key .= '-'.\\uniqid();\n }\n\n $segment = $this->inspector->startSegment(self::SEGMENT_TYPE.'-'.$method, \"{$class}::{$method}\")\n ->setColor(self::SEGMENT_COLOR);\n $segment->setContext($this->getContext($agent));\n $this->segments[$key] = $segment;\n }\n }\n\n /**\n * @throws \\Exception\n */\n public function stop(Agent $agent, string $event, mixed $data = null): void\n {\n $method = $this->getPrefix($event);\n $class = $agent::class;\n\n if (\\array_key_exists($class.$method, $this->segments)) {\n // End the last segment for the given method and agent class\n foreach (\\array_reverse($this->segments, true) as $key => $segment) {\n if ($key === $class.$method) {\n $segment->setContext($this->getContext($agent));\n $segment->end();\n unset($this->segments[$key]);\n break;\n }\n }\n } elseif ($this->inspector->canAddSegments()) {\n $transaction = $this->inspector->transaction()->setResult('success');\n $transaction->setContext($this->getContext($agent));\n\n if ($this->autoFlush) {\n $this->inspector->flush();\n }\n }\n }\n\n public function reportError(\\SplSubject $subject, string $event, AgentError $data): void\n {\n $this->inspector->reportException($data->exception, !$data->unhandled);\n\n if ($data->unhandled) {\n $this->inspector->transaction()->setResult('error');\n if ($subject instanceof Agent) {\n $this->inspector->transaction()->setContext($this->getContext($subject));\n }\n }\n }\n\n public function getPrefix(string $event): string\n {\n return \\explode('-', $event)[0];\n }\n\n protected function getContext(Agent $agent): array\n {\n $mapTool = fn (ToolInterface $tool) => [\n $tool->getName() => [\n 'description' => $tool->getDescription(),\n 'properties' => \\array_map(\n fn (ToolPropertyInterface $property) => $property->jsonSerialize(),\n $tool->getProperties()\n )\n ]\n ];\n\n return [\n 'Agent' => [\n 'provider' => $agent->resolveProvider()::class,\n 'instructions' => $agent->resolveInstructions(),\n ],\n 'Tools' => \\array_map(\n fn (ToolInterface|ToolkitInterface $tool) => $tool instanceof ToolInterface\n ? $mapTool($tool)\n : [$tool::class => \\array_map($mapTool, $tool->tools())],\n $agent->getTools()\n ),\n //'Messages' => $agent->resolveChatHistory()->getMessages(),\n ];\n }\n\n public function getMessageId(Message $message): string\n {\n $content = $message->getContent();\n\n if (!\\is_string($content)) {\n $content = \\json_encode($content, \\JSON_UNESCAPED_UNICODE);\n }\n\n return \\md5($content.$message->getRole());\n }\n\n protected function getBaseClassName(string $class): string\n {\n return \\substr(\\strrchr($class, '\\\\'), 1);\n }\n}\n"], ["/neuron-ai/src/Observability/HandleInferenceEvents.php", "inspector->canAddSegments()) {\n return;\n }\n\n $label = $this->getBaseClassName($data->message::class);\n\n $this->segments[$this->getMessageId($data->message).'-save'] = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-chathistory', \"save_message( {$label} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function messageSaved(Agent $agent, string $event, MessageSaved $data): void\n {\n $id = $this->getMessageId($data->message).'-save';\n\n if (!\\array_key_exists($id, $this->segments)) {\n return;\n }\n\n $segment = $this->segments[$id];\n $segment->addContext('Message', \\array_merge(\n $data->message->jsonSerialize(),\n $data->message->getUsage() instanceof Usage ? [\n 'usage' => [\n 'input_tokens' => $data->message->getUsage()->inputTokens,\n 'output_tokens' => $data->message->getUsage()->outputTokens,\n ]\n ] : []\n ));\n $segment->end();\n }\n\n public function inferenceStart(Agent $agent, string $event, InferenceStart $data): void\n {\n if (!$this->inspector->canAddSegments() || $data->message === false) {\n return;\n }\n\n $label = $this->getBaseClassName($data->message::class);\n\n $this->segments[$this->getMessageId($data->message).'-inference'] = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-inference', \"inference( {$label} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function inferenceStop(Agent $agent, string $event, InferenceStop $data): void\n {\n $id = $this->getMessageId($data->message).'-inference';\n\n if (\\array_key_exists($id, $this->segments)) {\n $segment = $this->segments[$id]->end();\n $segment->addContext('Message', $data->message)\n ->addContext('Response', $data->response);\n }\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/PineconeVectorStore.php", "client = new Client([\n 'base_uri' => \\trim($this->indexUrl, '/').'/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Api-Key' => $key,\n 'X-Pinecone-API-Version' => $version,\n ]\n ]);\n }\n\n public function addDocument(Document $document): void\n {\n $this->addDocuments([$document]);\n }\n\n public function addDocuments(array $documents): void\n {\n $this->client->post(\"vectors/upsert\", [\n RequestOptions::JSON => [\n 'namespace' => $this->namespace,\n 'vectors' => \\array_map(fn (Document $document): array => [\n 'id' => $document->getId(),\n 'values' => $document->getEmbedding(),\n 'metadata' => [\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ],\n ], $documents)\n ]\n ]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->post(\"vectors/delete\", [\n RequestOptions::JSON => [\n 'namespace' => $this->namespace,\n 'filter' => [\n 'sourceType' => ['$eq' => $sourceType],\n 'sourceName' => ['$eq' => $sourceName],\n ]\n ]\n ]);\n }\n\n public function similaritySearch(array $embedding): iterable\n {\n $result = $this->client->post(\"query\", [\n RequestOptions::JSON => [\n 'namespace' => $this->namespace,\n 'includeMetadata' => true,\n 'includeValues' => true,\n 'vector' => $embedding,\n 'topK' => $this->topK,\n 'filters' => $this->filters, // Hybrid search\n ]\n ])->getBody()->getContents();\n\n $result = \\json_decode($result, true);\n\n return \\array_map(function (array $item): Document {\n $document = new Document();\n $document->id = $item['id'];\n $document->embedding = $item['values'];\n $document->content = $item['metadata']['content'];\n $document->sourceType = $item['metadata']['sourceType'];\n $document->sourceName = $item['metadata']['sourceName'];\n $document->score = $item['score'];\n\n foreach ($item['metadata'] as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $result['matches']);\n }\n\n public function withFilters(array $filters): self\n {\n $this->filters = $filters;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/ToolCallResultMessage.php", " $tools\n */\n public function __construct(protected array $tools)\n {\n parent::__construct(null);\n }\n\n /**\n * @return array\n */\n public function getTools(): array\n {\n return $this->tools;\n }\n\n public function jsonSerialize(): array\n {\n return \\array_merge(\n parent::jsonSerialize(),\n [\n 'type' => 'tool_call_result',\n 'tools' => \\array_map(fn (ToolInterface $tool): array => $tool->jsonSerialize(), $this->tools)\n ]\n );\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/FileVectorStore.php", "directory)) {\n throw new VectorStoreException(\"Directory '{$this->directory}' does not exist\");\n }\n }\n\n protected function getFilePath(): string\n {\n return $this->directory . \\DIRECTORY_SEPARATOR . $this->name.$this->ext;\n }\n\n public function addDocument(Document $document): void\n {\n $this->addDocuments([$document]);\n }\n\n public function addDocuments(array $documents): void\n {\n $this->appendToFile(\n \\array_map(fn (Document $document): array => $document->jsonSerialize(), $documents)\n );\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n // Temporary file\n $tmpFile = $this->directory . \\DIRECTORY_SEPARATOR . $this->name.'_tmp'.$this->ext;\n\n // Create a temporary file handle\n $tempHandle = \\fopen($tmpFile, 'w');\n if (!$tempHandle) {\n throw new \\RuntimeException(\"Cannot create temporary file: {$tmpFile}\");\n }\n\n try {\n foreach ($this->getLine($this->getFilePath()) as $line) {\n $document = \\json_decode((string) $line, true);\n\n if ($document['sourceType'] !== $sourceType || $document['sourceName'] !== $sourceName) {\n \\fwrite($tempHandle, (string) $line);\n }\n }\n } finally {\n \\fclose($tempHandle);\n }\n\n // Replace the original file with the filtered version\n \\unlink($this->getFilePath());\n if (!\\rename($tmpFile, $this->getFilePath())) {\n throw new VectorStoreException(self::class.\" failed to replace original file.\");\n }\n }\n\n public function similaritySearch(array $embedding): array\n {\n $topItems = [];\n\n foreach ($this->getLine($this->getFilePath()) as $document) {\n $document = \\json_decode((string) $document, true);\n\n if (empty($document['embedding'])) {\n throw new VectorStoreException(\"Document with the following content has no embedding: {$document['content']}\");\n }\n $dist = VectorSimilarity::cosineDistance($embedding, $document['embedding']);\n\n $topItems[] = ['dist' => $dist, 'document' => $document];\n\n \\usort($topItems, fn (array $a, array $b): int => $a['dist'] <=> $b['dist']);\n\n if (\\count($topItems) > $this->topK) {\n $topItems = \\array_slice($topItems, 0, $this->topK, true);\n }\n }\n\n return \\array_map(function (array $item): Document {\n $itemDoc = $item['document'];\n $document = new Document($itemDoc['content']);\n $document->embedding = $itemDoc['embedding'];\n $document->sourceType = $itemDoc['sourceType'];\n $document->sourceName = $itemDoc['sourceName'];\n $document->id = $itemDoc['id'];\n $document->score = VectorSimilarity::similarityFromDistance($item['dist']);\n $document->metadata = $itemDoc['metadata'] ?? [];\n\n return $document;\n }, $topItems);\n }\n\n protected function appendToFile(array $documents): void\n {\n \\file_put_contents(\n $this->getFilePath(),\n \\implode(\\PHP_EOL, \\array_map(fn (array $vector) => \\json_encode($vector), $documents)).\\PHP_EOL,\n \\FILE_APPEND\n );\n }\n\n protected function getLine(string $filename): \\Generator\n {\n $f = \\fopen($filename, 'r');\n\n try {\n while ($line = \\fgets($f)) {\n yield $line;\n }\n } finally {\n \\fclose($f);\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/MySQL/MySQLSchemaTool.php", "formatForLLM([\n 'tables' => $this->getTables(),\n 'relationships' => $this->getRelationships(),\n 'indexes' => $this->getIndexes(),\n 'constraints' => $this->getConstraints()\n ]);\n }\n\n protected function formatForLLM(array $structure): string\n {\n $output = \"# MySQL Database Schema Analysis\\n\\n\";\n $output .= \"This database contains \" . \\count($structure['tables']) . \" tables with the following structure:\\n\\n\";\n\n // Tables overview\n $output .= \"## Tables Overview\\n\";\n foreach ($structure['tables'] as $table) {\n $pkColumns = empty($table['primary_key']) ? 'None' : \\implode(', ', $table['primary_key']);\n $output .= \"- **{$table['name']}**: {$table['estimated_rows']} rows, Primary Key: {$pkColumns}\";\n if ($table['comment']) {\n $output .= \" - {$table['comment']}\";\n }\n $output .= \"\\n\";\n }\n $output .= \"\\n\";\n\n // Detailed table structures\n $output .= \"## Detailed Table Structures\\n\\n\";\n foreach ($structure['tables'] as $table) {\n $output .= \"### Table: `{$table['name']}`\\n\";\n if ($table['comment']) {\n $output .= \"**Description**: {$table['comment']}\\n\";\n }\n $output .= \"**Estimated Rows**: {$table['estimated_rows']}\\n\\n\";\n\n $output .= \"**Columns**:\\n\";\n foreach ($table['columns'] as $column) {\n $nullable = $column['nullable'] ? 'NULL' : 'NOT NULL';\n $autoInc = $column['auto_increment'] ? ' AUTO_INCREMENT' : '';\n $default = $column['default'] !== null ? \" DEFAULT '{$column['default']}'\" : '';\n\n $output .= \"- `{$column['name']}` {$column['full_type']} {$nullable}{$default}{$autoInc}\";\n if ($column['comment']) {\n $output .= \" - {$column['comment']}\";\n }\n $output .= \"\\n\";\n }\n\n if (!empty($table['primary_key'])) {\n $output .= \"\\n**Primary Key**: \" . \\implode(', ', $table['primary_key']) . \"\\n\";\n }\n\n if (!empty($table['unique_keys'])) {\n $output .= \"**Unique Keys**: \" . \\implode(', ', $table['unique_keys']) . \"\\n\";\n }\n\n $output .= \"\\n\";\n }\n\n // Relationships\n if (!empty($structure['relationships'])) {\n $output .= \"## Foreign Key Relationships\\n\\n\";\n $output .= \"Understanding these relationships is crucial for JOIN operations:\\n\\n\";\n\n foreach ($structure['relationships'] as $rel) {\n $output .= \"- `{$rel['source_table']}.{$rel['source_column']}` → `{$rel['target_table']}.{$rel['target_column']}`\";\n $output .= \" (ON DELETE {$rel['DELETE_RULE']}, ON UPDATE {$rel['UPDATE_RULE']})\\n\";\n }\n $output .= \"\\n\";\n }\n\n // Indexes for query optimization\n if (!empty($structure['indexes'])) {\n $output .= \"## Available Indexes (for Query Optimization)\\n\\n\";\n $output .= \"These indexes can significantly improve query performance:\\n\\n\";\n\n foreach ($structure['indexes'] as $index) {\n $unique = $index['unique'] ? 'UNIQUE ' : '';\n $columns = \\implode(', ', $index['columns']);\n $output .= \"- {$unique}INDEX `{$index['name']}` on `{$index['table']}` ({$columns})\\n\";\n }\n $output .= \"\\n\";\n }\n\n // Query generation guidelines\n $output .= \"## MySQL Query Generation Guidelines\\n\\n\";\n $output .= \"**Best Practices for this database**:\\n\";\n $output .= \"1. Always use table aliases for better readability\\n\";\n $output .= \"2. Prefer indexed columns in WHERE clauses for better performance\\n\";\n $output .= \"3. Use appropriate JOINs based on the foreign key relationships listed above\\n\";\n $output .= \"4. Consider the estimated row counts when writing queries - larger tables may need LIMIT clauses\\n\";\n $output .= \"5. Pay attention to nullable columns when using comparison operators\\n\\n\";\n\n // Common patterns\n $output .= \"**Common Query Patterns**:\\n\";\n $this->addCommonPatterns($output, $structure['tables']);\n\n return $output;\n }\n\n protected function getTables(): array\n {\n $whereClause = \"WHERE t.TABLE_SCHEMA = DATABASE() AND t.TABLE_TYPE = 'BASE TABLE'\";\n $params = [];\n\n // Add table filtering if specific tables are requested\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = \\str_repeat('?,', \\count($this->tables) - 1) . '?';\n $whereClause .= \" AND t.TABLE_NAME IN ($placeholders)\";\n $params = $this->tables;\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n t.TABLE_NAME,\n t.ENGINE,\n t.TABLE_ROWS,\n t.TABLE_COMMENT,\n c.COLUMN_NAME,\n c.ORDINAL_POSITION,\n c.COLUMN_DEFAULT,\n c.IS_NULLABLE,\n c.DATA_TYPE,\n c.CHARACTER_MAXIMUM_LENGTH,\n c.NUMERIC_PRECISION,\n c.NUMERIC_SCALE,\n c.COLUMN_TYPE,\n c.COLUMN_KEY,\n c.EXTRA,\n c.COLUMN_COMMENT\n FROM INFORMATION_SCHEMA.TABLES t\n LEFT JOIN INFORMATION_SCHEMA.COLUMNS c ON t.TABLE_NAME = c.TABLE_NAME\n AND t.TABLE_SCHEMA = c.TABLE_SCHEMA\n $whereClause\n ORDER BY t.TABLE_NAME, c.ORDINAL_POSITION\n \");\n\n $stmt->execute($params);\n $results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n $tables = [];\n foreach ($results as $row) {\n $tableName = $row['TABLE_NAME'];\n\n if (!isset($tables[$tableName])) {\n $tables[$tableName] = [\n 'name' => $tableName,\n 'engine' => $row['ENGINE'],\n 'estimated_rows' => $row['TABLE_ROWS'],\n 'comment' => $row['TABLE_COMMENT'],\n 'columns' => [],\n 'primary_key' => [],\n 'unique_keys' => [],\n 'indexes' => []\n ];\n }\n\n if ($row['COLUMN_NAME']) {\n $column = [\n 'name' => $row['COLUMN_NAME'],\n 'type' => $row['DATA_TYPE'],\n 'full_type' => $row['COLUMN_TYPE'],\n 'nullable' => $row['IS_NULLABLE'] === 'YES',\n 'default' => $row['COLUMN_DEFAULT'],\n 'auto_increment' => \\str_contains((string) $row['EXTRA'], 'auto_increment'),\n 'comment' => $row['COLUMN_COMMENT']\n ];\n\n // Add length/precision info for better LLM understanding\n if ($row['CHARACTER_MAXIMUM_LENGTH']) {\n $column['max_length'] = $row['CHARACTER_MAXIMUM_LENGTH'];\n }\n if ($row['NUMERIC_PRECISION']) {\n $column['precision'] = $row['NUMERIC_PRECISION'];\n $column['scale'] = $row['NUMERIC_SCALE'];\n }\n\n $tables[$tableName]['columns'][] = $column;\n\n // Track key information\n if ($row['COLUMN_KEY'] === 'PRI') {\n $tables[$tableName]['primary_key'][] = $row['COLUMN_NAME'];\n } elseif ($row['COLUMN_KEY'] === 'UNI') {\n $tables[$tableName]['unique_keys'][] = $row['COLUMN_NAME'];\n } elseif ($row['COLUMN_KEY'] === 'MUL') {\n $tables[$tableName]['indexes'][] = $row['COLUMN_NAME'];\n }\n }\n }\n\n return $tables;\n }\n\n protected function getRelationships(): array\n {\n $whereClause = \"WHERE kcu.TABLE_SCHEMA = DATABASE() AND kcu.REFERENCED_TABLE_NAME IS NOT NULL\";\n $params = [];\n\n // Add table filtering if specific tables are requested\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = \\str_repeat('?,', \\count($this->tables) - 1) . '?';\n $whereClause .= \" AND (kcu.TABLE_NAME IN ($placeholders) OR kcu.REFERENCED_TABLE_NAME IN ($placeholders))\";\n $params = \\array_merge($this->tables, $this->tables);\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n kcu.CONSTRAINT_NAME,\n kcu.TABLE_NAME as source_table,\n kcu.COLUMN_NAME as source_column,\n kcu.REFERENCED_TABLE_NAME as target_table,\n kcu.REFERENCED_COLUMN_NAME as target_column,\n rc.UPDATE_RULE,\n rc.DELETE_RULE\n FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu\n JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc\n ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME\n AND kcu.CONSTRAINT_SCHEMA = rc.CONSTRAINT_SCHEMA\n $whereClause\n ORDER BY kcu.TABLE_NAME, kcu.ORDINAL_POSITION\n \");\n\n $stmt->execute($params);\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n protected function getIndexes(): array\n {\n $stmt = $this->pdo->prepare(\"\n SELECT\n TABLE_NAME,\n INDEX_NAME,\n COLUMN_NAME,\n SEQ_IN_INDEX,\n NON_UNIQUE,\n INDEX_TYPE,\n CARDINALITY\n FROM INFORMATION_SCHEMA.STATISTICS\n WHERE TABLE_SCHEMA = DATABASE()\n AND INDEX_NAME != 'PRIMARY'\n ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX\n \");\n\n $stmt->execute();\n $results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n $indexes = [];\n foreach ($results as $row) {\n $key = $row['TABLE_NAME'] . '.' . $row['INDEX_NAME'];\n if (!isset($indexes[$key])) {\n $indexes[$key] = [\n 'table' => $row['TABLE_NAME'],\n 'name' => $row['INDEX_NAME'],\n 'unique' => $row['NON_UNIQUE'] == 0,\n 'type' => $row['INDEX_TYPE'],\n 'columns' => []\n ];\n }\n $indexes[$key]['columns'][] = $row['COLUMN_NAME'];\n }\n\n return \\array_values($indexes);\n }\n\n protected function getConstraints(): array\n {\n $whereClause = \"WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_TYPE IN ('UNIQUE')\";\n $params = [];\n\n // Add table filtering if specific tables are requested\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = \\str_repeat('?,', \\count($this->tables) - 1) . '?';\n $whereClause .= \" AND TABLE_NAME IN ($placeholders)\";\n $params = $this->tables;\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n CONSTRAINT_NAME,\n TABLE_NAME,\n CONSTRAINT_TYPE\n FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS\n $whereClause\n \");\n\n $stmt->execute($params);\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n protected function addCommonPatterns(string &$output, array $tables): void\n {\n // Find tables with timestamps for temporal queries\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['timestamp', 'datetime', 'date']) &&\n (\\str_contains(\\strtolower((string) $column['name']), 'created') ||\n \\str_contains(\\strtolower((string) $column['name']), 'updated'))) {\n $output .= \"- For temporal queries on `{$table['name']}`, use `{$column['name']}` column\\n\";\n break;\n }\n }\n }\n\n // Find potential text search columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['varchar', 'text', 'longtext']) &&\n (\\str_contains(\\strtolower((string) $column['name']), 'name') ||\n \\str_contains(\\strtolower((string) $column['name']), 'title') ||\n \\str_contains(\\strtolower((string) $column['name']), 'description'))) {\n $output .= \"- For text searches on `{$table['name']}`, consider using `{$column['name']}` with LIKE or FULLTEXT\\n\";\n break;\n }\n }\n }\n\n $output .= \"\\n\";\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/JsonSchema.php", "processedClasses = [];\n\n // Generate the main schema\n return [\n ...$this->generateClassSchema($class),\n 'additionalProperties' => false,\n ];\n }\n\n /**\n * Generate schema for a class\n *\n * @param string $class Class name\n * @return array The schema\n * @throws ReflectionException\n */\n private function generateClassSchema(string $class): array\n {\n $reflection = new ReflectionClass($class);\n\n // Check for circular reference\n if (\\in_array($class, $this->processedClasses)) {\n // For circular references, return a simple object schema to break the cycle\n return ['type' => 'object'];\n }\n\n $this->processedClasses[] = $class;\n\n // Handle enum types differently\n if ($reflection->isEnum()) {\n $result = $this->processEnum(new ReflectionEnum($class));\n // Remove the class from the processed list after processing\n \\array_pop($this->processedClasses);\n return $result;\n }\n\n // Create a basic object schema\n $schema = [\n 'type' => 'object',\n 'properties' => [],\n ];\n\n $requiredProperties = [];\n\n // Process all public properties\n $properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);\n\n // Process each property\n foreach ($properties as $property) {\n $propertyName = $property->getName();\n\n $schema['properties'][$propertyName] = $this->processProperty($property);\n\n $attribute = $this->getPropertyAttribute($property);\n if ($attribute instanceof SchemaProperty && $attribute->required !== null) {\n if ($attribute->required) {\n $requiredProperties[] = $propertyName;\n }\n } else {\n // If the attribute is not available,\n // use the default logic for required properties\n $type = $property->getType();\n\n $isNullable = $type ? $type->allowsNull() : true;\n\n if (!$isNullable && !$property->hasDefaultValue()) {\n $requiredProperties[] = $propertyName;\n }\n }\n }\n\n // Add required properties\n if ($requiredProperties !== []) {\n $schema['required'] = $requiredProperties;\n }\n\n // Remove the class from the processed list after processing\n \\array_pop($this->processedClasses);\n\n return $schema;\n }\n\n /**\n * Process a single property to generate its schema\n *\n * @return array Property schema\n * @throws ReflectionException\n */\n private function processProperty(ReflectionProperty $property): array\n {\n $schema = [];\n\n // Process Property attribute if present\n $attribute = $this->getPropertyAttribute($property);\n if ($attribute instanceof SchemaProperty) {\n if ($attribute->title !== null) {\n $schema['title'] = $attribute->title;\n }\n\n if ($attribute->description !== null) {\n $schema['description'] = $attribute->description;\n }\n }\n\n /** @var ?ReflectionNamedType $type */\n $type = $property->getType();\n $typeName = $type?->getName();\n\n // Handle default values\n if ($property->hasDefaultValue()) {\n $schema['default'] = $property->getDefaultValue();\n }\n\n // Process different types\n if ($typeName === 'array') {\n $schema['type'] = 'array';\n\n // Parse PHPDoc for the array item type\n $docComment = $property->getDocComment();\n if ($docComment) {\n // Extract type from both \"@var \\App\\Type[]\" and \"@var array<\\App\\Type>\"\n \\preg_match('/@var\\s+(?:([a-zA-Z0-9_\\\\\\\\]+)\\[\\]|array<([a-zA-Z0-9_\\\\\\\\]+)>)/', $docComment, $matches);\n\n if (isset($matches[1]) || isset($matches[2])) {\n $itemType = empty($matches[1]) ? ((isset($matches[2]) && $matches[2] !== '0') ? $matches[2] : null) : ($matches[1]);\n\n // Handle class type for array items\n if (\\class_exists($itemType) || \\enum_exists($itemType)) {\n $schema['items'] = $this->generateClassSchema($itemType);\n } else {\n // Basic type\n $schema['items'] = $this->getBasicTypeSchema($itemType);\n }\n } else {\n // Default to string if no specific type found\n $schema['items'] = ['type' => 'string'];\n }\n } else {\n // Default to string if no doc comment\n $schema['items'] = ['type' => 'string'];\n }\n }\n // Handle enum types\n elseif ($typeName && \\enum_exists($typeName)) {\n $enumReflection = new ReflectionEnum($typeName);\n $schema = \\array_merge($schema, $this->processEnum($enumReflection));\n }\n // Handle class types\n elseif ($typeName && \\class_exists($typeName)) {\n $classSchema = $this->generateClassSchema($typeName);\n $schema = \\array_merge($schema, $classSchema);\n }\n // Handle basic types\n elseif ($typeName) {\n $typeSchema = $this->getBasicTypeSchema($typeName);\n $schema = \\array_merge($schema, $typeSchema);\n } else {\n // Default to string if no type hint\n $schema['type'] = 'string';\n }\n\n // Handle nullable types - for basic types only\n if ($type && $type->allowsNull() && isset($schema['type']) && !isset($schema['$ref']) && !isset($schema['allOf'])) {\n if (\\is_array($schema['type'])) {\n if (!\\in_array('null', $schema['type'])) {\n $schema['type'][] = 'null';\n }\n } else {\n $schema['type'] = [$schema['type'], 'null'];\n }\n }\n\n return $schema;\n }\n\n /**\n * Process an enum to generate its schema\n */\n private function processEnum(ReflectionEnum $enum): array\n {\n // Create enum schema\n $schema = [\n 'type' => 'string',\n 'enum' => [],\n ];\n\n // Extract enum values\n foreach ($enum->getCases() as $case) {\n if ($enum->isBacked()) {\n /** @var ReflectionEnumBackedCase $case */\n // For backed enums, use the backing value\n $schema['enum'][] = $case->getBackingValue();\n } else {\n // For non-backed enums, use case name\n $schema['enum'][] = $case->getName();\n }\n }\n\n return $schema;\n }\n\n /**\n * Get the Property attribute if it exists on a property\n */\n private function getPropertyAttribute(ReflectionProperty $property): ?SchemaProperty\n {\n $attributes = $property->getAttributes(SchemaProperty::class);\n if ($attributes !== []) {\n return $attributes[0]->newInstance();\n }\n return null;\n }\n\n /**\n * Get schema for a basic PHP type\n *\n * @param string $type PHP type name\n * @return array Schema for the type\n * @throws ReflectionException\n */\n private function getBasicTypeSchema(string $type): array\n {\n switch ($type) {\n case 'string':\n return ['type' => 'string'];\n\n case 'int':\n case 'integer':\n return ['type' => 'integer'];\n\n case 'float':\n case 'double':\n return ['type' => 'number'];\n\n case 'bool':\n case 'boolean':\n return ['type' => 'boolean'];\n\n case 'array':\n return [\n 'type' => 'array',\n 'items' => ['type' => 'string'],\n ];\n\n default:\n // Check if it's a class or enum\n if (\\class_exists($type)) {\n return $this->generateClassSchema($type);\n }\n // Check if it's a class or enum\n if (\\enum_exists($type)) {\n return $this->processEnum(new ReflectionEnum($type));\n }\n\n // Default to string for unknown types\n return ['type' => 'string'];\n }\n }\n}\n"], ["/neuron-ai/src/MCP/McpConnector.php", "client = new McpClient($config);\n }\n\n /**\n * @param string[] $tools\n */\n public function exclude(array $tools): McpConnector\n {\n $this->exclude = $tools;\n return $this;\n }\n\n /**\n * @param string[] $tools\n */\n public function only(array $tools): McpConnector\n {\n $this->only = $tools;\n return $this;\n }\n\n /**\n * Get the list of available Tools from the server.\n *\n * @return ToolInterface[]\n * @throws \\Exception\n */\n public function tools(): array\n {\n // Filter by the only and exclude preferences.\n $tools = \\array_filter(\n $this->client->listTools(),\n fn (array $tool): bool =>\n !\\in_array($tool['name'], $this->exclude) &&\n ($this->only === [] || \\in_array($tool['name'], $this->only)),\n );\n\n return \\array_map(fn (array $tool): ToolInterface => $this->createTool($tool), $tools);\n }\n\n /**\n * Convert the list of tools from the MCP server to Neuron compatible entities.\n * @throws ArrayPropertyException\n * @throws \\ReflectionException\n * @throws ToolException\n */\n protected function createTool(array $item): ToolInterface\n {\n $tool = Tool::make(\n name: $item['name'],\n description: $item['description'] ?? null\n )->setCallable(function (...$arguments) use ($item) {\n $response = \\call_user_func($this->client->callTool(...), $item['name'], $arguments);\n\n if (\\array_key_exists('error', $response)) {\n throw new McpException($response['error']['message']);\n }\n\n $response = $response['result']['content'][0];\n\n if ($response['type'] === 'text') {\n return $response['text'];\n }\n\n if ($response['type'] === 'image') {\n return $response;\n }\n\n throw new McpException(\"Tool response format not supported: {$response['type']}\");\n });\n\n foreach ($item['inputSchema']['properties'] as $name => $prop) {\n $required = \\in_array($name, $item['inputSchema']['required'] ?? []);\n\n $type = PropertyType::fromSchema($prop['type']);\n\n $property = match ($type) {\n PropertyType::ARRAY => $this->createArrayProperty($name, $required, $prop),\n PropertyType::OBJECT => $this->createObjectProperty($name, $required, $prop),\n default => $this->createToolProperty($name, $type, $required, $prop),\n };\n\n $tool->addProperty($property);\n }\n\n return $tool;\n }\n\n protected function createToolProperty(string $name, PropertyType $type, bool $required, array $prop): ToolProperty\n {\n return new ToolProperty(\n name: $name,\n type: $type,\n description: $prop['description'] ?? null,\n required: $required,\n enum: $prop['items']['enum'] ?? []\n );\n }\n\n /**\n * @throws ArrayPropertyException\n */\n protected function createArrayProperty(string $name, bool $required, array $prop): ArrayProperty\n {\n return new ArrayProperty(\n name: $name,\n description: $prop['description'] ?? null,\n required: $required,\n items: new ToolProperty(\n name: 'type',\n type: PropertyType::from($prop['items']['type'] ?? 'string'),\n )\n );\n }\n\n /**\n * @throws \\ReflectionException\n */\n protected function createObjectProperty(string $name, bool $required, array $prop): ObjectProperty\n {\n return new ObjectProperty(\n name: $name,\n description: $prop['description'] ?? null,\n required: $required,\n );\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/JsonExtractor.php", "extractors = [\n fn (string $text): array => [$text], // Try as it is\n fn (string $text): array => $this->findByMarkdown($text),\n fn (string $text): ?string => $this->findByBrackets($text),\n fn (string $text): array => $this->findJSONLikeStrings($text),\n ];\n }\n\n /**\n * Attempt to find and parse a complete valid JSON string in the input.\n * Returns a JSON-encoded string on success or an empty string on failure.\n */\n public function getJson(string $input): ?string\n {\n foreach ($this->extractors as $extractor) {\n $candidates = $extractor($input);\n if (empty($candidates)) {\n continue;\n }\n if (\\is_string($candidates)) {\n $candidates = [$candidates];\n }\n\n foreach ($candidates as $candidate) {\n if (!\\is_string($candidate)) {\n continue;\n }\n if (\\trim($candidate) === '') {\n continue;\n }\n try {\n $data = $this->tryParse($candidate);\n } catch (\\Throwable) {\n continue;\n }\n\n if ($data !== null) {\n // Re-encode in canonical JSON form\n $result = \\json_encode($data);\n if ($result !== false) {\n return $result;\n }\n }\n }\n }\n\n return null;\n }\n\n /**\n * Returns an associative array on success, or null if the parsing fails.\n *\n * @throws \\JsonException\n */\n private function tryParse(string $maybeJson): ?array\n {\n $data = \\json_decode($maybeJson, true, 512, \\JSON_THROW_ON_ERROR);\n\n if ($data === false || $data === null || $data === '') {\n return null;\n }\n\n return $data;\n }\n\n /**\n * Find ALL fenced code blocks that start with ```json, and extract\n * the portion between the first '{' and the matching last '}' inside\n * that block. Return an array of candidates.\n */\n private function findByMarkdown(string $text): array\n {\n if (\\trim($text) === '') {\n return [];\n }\n\n $candidates = [];\n $offset = 0;\n $fenceTag = '```json';\n\n while (($startFence = \\strpos($text, $fenceTag, $offset)) !== false) {\n // Find the next triple-backtick fence AFTER the \"```json\"\n $closeFence = \\strpos($text, '```', $startFence + \\strlen($fenceTag));\n if ($closeFence === false) {\n // No closing fence found, stop scanning\n break;\n }\n\n // Substring that represents the code block between \"```json\" and \"```\"\n $codeBlock = \\substr(\n $text,\n $startFence + \\strlen($fenceTag),\n $closeFence - ($startFence + \\strlen($fenceTag))\n );\n\n // Now find the first '{' and last '}' within this code block\n $firstBrace = \\strpos($codeBlock, '{');\n $lastBrace = \\strrpos($codeBlock, '}');\n if ($firstBrace !== false && $lastBrace !== false && $firstBrace < $lastBrace) {\n $jsonCandidate = \\substr($codeBlock, $firstBrace, $lastBrace - $firstBrace + 1);\n $candidates[] = $jsonCandidate;\n }\n\n // Advance offset past the closing fence, so we can find subsequent code blocks\n $offset = $closeFence + 3; // skip '```'\n }\n\n return $candidates;\n }\n\n /**\n * Find a substring from the first '{' to the last '}'.\n */\n private function findByBrackets(string $text): ?string\n {\n $trimmed = \\trim($text);\n if ($trimmed === '') {\n return null;\n }\n $firstOpen = \\strpos($trimmed, '{');\n if ($firstOpen === 0 || $firstOpen === false) {\n return null;\n }\n\n $lastClose = \\strrpos($trimmed, '}');\n if ($lastClose === false || $lastClose < $firstOpen) {\n return null;\n }\n\n return \\substr($trimmed, $firstOpen, $lastClose - $firstOpen + 1);\n }\n\n /**\n * Scan through the text, capturing any substring that begins at '{'\n * and ends at its matching '}'—accounting for nested braces and strings.\n * Returns an array of all such candidates found.\n */\n private function findJSONLikeStrings(string $text): array\n {\n $text = \\trim($text);\n if ($text === '') {\n return [];\n }\n\n $candidates = [];\n $currentCandidate = '';\n $bracketCount = 0;\n $inString = false;\n $escape = false;\n $len = \\strlen($text);\n\n for ($i = 0; $i < $len; $i++) {\n $char = $text[$i];\n\n if (!$inString) {\n if ($char === '{') {\n if ($bracketCount === 0) {\n $currentCandidate = '';\n }\n $bracketCount++;\n } elseif ($char === '}') {\n $bracketCount--;\n }\n }\n\n // Toggle inString if we encounter an unescaped quote\n if ($char === '\"' && !$escape) {\n $inString = !$inString;\n }\n\n // Determine if current char is a backslash for next iteration\n $escape = ($char === '\\\\' && !$escape);\n\n if ($bracketCount > 0) {\n $currentCandidate .= $char;\n }\n\n // If bracketCount just went back to 0, we’ve closed a JSON-like block\n if ($bracketCount === 0 && $currentCandidate !== '') {\n $currentCandidate .= $char; // include the closing '}'\n $candidates[] = $currentCandidate;\n $currentCandidate = '';\n }\n }\n\n return $candidates;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Jina/JinaWebSearch.php", "client ?? $this->client = new Client([\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'X-Respond-With' => 'no-content',\n ]\n ]);\n }\n\n public function __invoke(string $search_query): string\n {\n return $this->getClient()->post('https://s.jina.ai/', [\n RequestOptions::JSON => [\n 'q' => $search_query,\n ]\n ])->getBody()->getContents();\n }\n}\n"], ["/neuron-ai/src/Tools/Tool.php", "properties = $properties;\n }\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n public function getDescription(): ?string\n {\n return $this->description;\n }\n\n public function addProperty(ToolPropertyInterface $property): ToolInterface\n {\n $this->properties[] = $property;\n return $this;\n }\n\n /**\n * @return ToolPropertyInterface[]\n */\n protected function properties(): array\n {\n return [];\n }\n\n /**\n * @return ToolPropertyInterface[]\n */\n public function getProperties(): array\n {\n if ($this->properties === []) {\n foreach ($this->properties() as $property) {\n $this->addProperty($property);\n }\n }\n\n return $this->properties;\n }\n\n public function getRequiredProperties(): array\n {\n return \\array_reduce($this->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n if ($property->isRequired()) {\n $carry[] = $property->getName();\n }\n\n return $carry;\n }, []);\n }\n\n public function setCallable(callable $callback): self\n {\n $this->callback = $callback;\n return $this;\n }\n\n public function getInputs(): array\n {\n return $this->inputs ?? [];\n }\n\n public function setInputs(?array $inputs): self\n {\n $this->inputs = $inputs ?? [];\n return $this;\n }\n\n public function getCallId(): ?string\n {\n return $this->callId;\n }\n\n public function setCallId(?string $callId): self\n {\n $this->callId = $callId;\n return $this;\n }\n\n public function getResult(): string\n {\n return $this->result;\n }\n\n public function setResult(mixed $result): self\n {\n $this->result = \\is_array($result) ? \\json_encode($result) : (string) $result;\n\n return $this;\n }\n\n /**\n * Execute the client side function.\n *\n * @throws MissingCallbackParameter\n * @throws ToolCallableNotSet\n * @throws DeserializerException\n * @throws \\ReflectionException\n */\n public function execute(): void\n {\n if (!\\is_callable($this->callback) && !\\method_exists($this, '__invoke')) {\n throw new ToolCallableNotSet('No function defined for tool execution.');\n }\n\n // Validate required parameters\n foreach ($this->getProperties() as $property) {\n if ($property->isRequired() && !\\array_key_exists($property->getName(), $this->getInputs())) {\n throw new MissingCallbackParameter(\"Missing required parameter: {$property->getName()}\");\n }\n }\n\n $parameters = \\array_reduce($this->getProperties(), function (array $carry, ToolPropertyInterface $property) {\n $propertyName = $property->getName();\n $inputs = $this->getInputs();\n\n // Normalize missing optional properties by assigning them a null value\n // Treat it as explicitly null to ensure a consistent structure\n if (!\\array_key_exists($propertyName, $inputs)) {\n $carry[$propertyName] = null;\n return $carry;\n }\n\n // Find the corresponding input value\n $inputValue = $inputs[$propertyName];\n\n // If there is an object property with a class definition,\n // deserialize the tool input into an instance of that class\n if ($property instanceof ObjectProperty && $property->getClass()) {\n $carry[$propertyName] = Deserializer::fromJson(\\json_encode($inputValue), $property->getClass());\n return $carry;\n }\n\n // If a property is an array of objects and each item matches a class definition,\n // deserialize each item into an instance of that class\n if ($property instanceof ArrayProperty) {\n $items = $property->getItems();\n if ($items instanceof ObjectProperty && $items->getClass()) {\n $class = $items->getClass();\n $carry[$propertyName] = \\array_map(fn (array|object $input): object => Deserializer::fromJson(\\json_encode($input), $class), $inputValue);\n return $carry;\n }\n }\n\n // No extra treatments for basic property types\n $carry[$propertyName] = $inputValue;\n return $carry;\n\n }, []);\n\n $this->setResult(\n \\method_exists($this, '__invoke') ? $this->__invoke(...$parameters)\n : \\call_user_func($this->callback, ...$parameters)\n );\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'name' => $this->name,\n 'description' => $this->description,\n 'inputs' => $this->inputs === [] ? new \\stdClass() : $this->inputs,\n 'callId' => $this->callId,\n 'result' => $this->result,\n ];\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/Message.php", "role->value;\n }\n\n public function setRole(MessageRole|string $role): Message\n {\n if (!$role instanceof MessageRole) {\n $role = MessageRole::from($role);\n }\n\n $this->role = $role;\n return $this;\n }\n\n public function getContent(): mixed\n {\n return $this->content;\n }\n\n public function setContent(mixed $content): Message\n {\n $this->content = $content;\n return $this;\n }\n\n /**\n * @return array\n */\n public function getAttachments(): array\n {\n return $this->attachments;\n }\n\n public function addAttachment(Attachment $attachment): Message\n {\n $this->attachments[] = $attachment;\n return $this;\n }\n\n public function getUsage(): ?Usage\n {\n return $this->usage;\n }\n\n public function setUsage(Usage $usage): static\n {\n $this->usage = $usage;\n return $this;\n }\n\n public function addMetadata(string $key, string|array|null $value): Message\n {\n $this->meta[$key] = $value;\n return $this;\n }\n\n public function jsonSerialize(): array\n {\n $data = [\n 'role' => $this->getRole(),\n 'content' => $this->getContent()\n ];\n\n if ($this->getUsage() instanceof \\NeuronAI\\Chat\\Messages\\Usage) {\n $data['usage'] = $this->getUsage()->jsonSerialize();\n }\n\n if ($this->getAttachments() !== []) {\n $data['attachments'] = \\array_map(fn (Attachment $attachment): array => $attachment->jsonSerialize(), $this->getAttachments());\n }\n\n return \\array_merge($this->meta, $data);\n }\n}\n"], ["/neuron-ai/src/HandleStream.php", "notify('stream-start');\n\n $this->fillChatHistory($messages);\n\n $tools = $this->bootstrapTools();\n\n $stream = $this->resolveProvider()\n ->systemPrompt($this->resolveInstructions())\n ->setTools($tools)\n ->stream(\n $this->resolveChatHistory()->getMessages(),\n function (ToolCallMessage $toolCallMessage) {\n $toolCallResult = $this->executeTools($toolCallMessage);\n yield from self::stream([$toolCallMessage, $toolCallResult]);\n }\n );\n\n $content = '';\n $usage = new Usage(0, 0);\n foreach ($stream as $text) {\n // Catch usage when streaming\n $decoded = \\json_decode((string) $text, true);\n if (\\is_array($decoded) && \\array_key_exists('usage', $decoded)) {\n $usage->inputTokens += $decoded['usage']['input_tokens'] ?? 0;\n $usage->outputTokens += $decoded['usage']['output_tokens'] ?? 0;\n continue;\n }\n\n $content .= $text;\n yield $text;\n }\n\n $response = new AssistantMessage($content);\n $response->setUsage($usage);\n\n // Avoid double saving due to the recursive call.\n $last = $this->resolveChatHistory()->getLastMessage();\n if ($response->getRole() !== $last->getRole()) {\n $this->fillChatHistory($response);\n }\n\n $this->notify('stream-stop');\n } catch (\\Throwable $exception) {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/ArrayOf.php", " 'is_bool',\n 'integer' => 'is_int',\n 'float' => 'is_float',\n 'numeric' => 'is_numeric',\n 'string' => 'is_string',\n 'scalar' => 'is_scalar',\n 'array' => 'is_array',\n 'iterable' => 'is_iterable',\n 'countable' => 'is_countable',\n 'object' => 'is_object',\n 'null' => 'is_null',\n 'alnum' => 'ctype_alnum',\n 'alpha' => 'ctype_alpha',\n 'cntrl' => 'ctype_cntrl',\n 'digit' => 'ctype_digit',\n 'graph' => 'ctype_graph',\n 'lower' => 'ctype_lower',\n 'print' => 'ctype_print',\n 'punct' => 'ctype_punct',\n 'space' => 'ctype_space',\n 'upper' => 'ctype_upper',\n 'xdigit' => 'ctype_xdigit',\n ];\n\n public function __construct(\n protected string $type,\n protected bool $allowEmpty = false,\n ) {\n }\n\n public function validate(string $name, mixed $value, array &$violations): void\n {\n if ($this->allowEmpty && empty($value)) {\n return;\n }\n\n if (!$this->allowEmpty && empty($value)) {\n $violations[] = $this->buildMessage($name, $this->message, ['type' => $this->type]);\n return;\n }\n\n if (!\\is_array($value)) {\n $violations[] = $this->buildMessage($name, $this->message);\n return;\n }\n\n $type = \\strtolower($this->type);\n\n $error = false;\n foreach ($value as $item) {\n if (isset(self::VALIDATION_FUNCTIONS[$type]) && self::VALIDATION_FUNCTIONS[$type]($item)) {\n continue;\n }\n\n // It's like a recursive call.\n if ($item instanceof $this->type && Validator::validate($item) === []) {\n continue;\n }\n\n $error = true;\n break;\n }\n\n if ($error) {\n $violations[] = $this->buildMessage($name, $this->message, ['type' => $this->type]);\n }\n }\n}\n"], ["/neuron-ai/src/Chat/History/FileChatHistory.php", "directory)) {\n throw new ChatHistoryException(\"Directory '{$this->directory}' does not exist\");\n }\n\n $this->load();\n }\n\n protected function load(): void\n {\n if (\\is_file($this->getFilePath())) {\n $messages = \\json_decode(\\file_get_contents($this->getFilePath()), true) ?? [];\n $this->history = $this->deserializeMessages($messages);\n }\n }\n\n protected function getFilePath(): string\n {\n return $this->directory . \\DIRECTORY_SEPARATOR . $this->prefix.$this->key.$this->ext;\n }\n\n public function setMessages(array $messages): ChatHistoryInterface\n {\n $this->updateFile();\n return $this;\n }\n\n protected function clear(): ChatHistoryInterface\n {\n if (!\\unlink($this->getFilePath())) {\n throw new ChatHistoryException(\"Unable to delete file '{$this->getFilePath()}'\");\n }\n return $this;\n }\n\n protected function updateFile(): void\n {\n \\file_put_contents($this->getFilePath(), \\json_encode($this->jsonSerialize()), \\LOCK_EX);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/PGSQL/PGSQLSchemaTool.php", "formatForLLM([\n 'tables' => $this->getTables(),\n 'relationships' => $this->getRelationships(),\n 'indexes' => $this->getIndexes(),\n 'constraints' => $this->getConstraints()\n ]);\n }\n\n private function getTables(): array\n {\n $whereClause = \"WHERE t.table_schema = current_schema() AND t.table_type = 'BASE TABLE'\";\n $params = [];\n\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = [];\n foreach ($this->tables as $table) {\n $placeholders[] = '?';\n $params[] = $table;\n }\n $whereClause .= \" AND t.table_name = ANY(ARRAY[\" . \\implode(',', $placeholders) . \"])\";\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n t.table_name,\n obj_description(pgc.oid) as table_comment,\n c.column_name,\n c.ordinal_position,\n c.column_default,\n c.is_nullable,\n c.data_type,\n c.character_maximum_length,\n c.numeric_precision,\n c.numeric_scale,\n c.udt_name,\n CASE\n WHEN pk.column_name IS NOT NULL THEN 'PRI'\n WHEN uk.column_name IS NOT NULL THEN 'UNI'\n WHEN idx.column_name IS NOT NULL THEN 'MUL'\n ELSE ''\n END as column_key,\n CASE\n WHEN c.column_default LIKE 'nextval%' THEN 'auto_increment'\n ELSE ''\n END as extra,\n col_description(pgc.oid, c.ordinal_position) as column_comment\n FROM information_schema.tables t\n LEFT JOIN information_schema.columns c ON t.table_name = c.table_name\n AND t.table_schema = c.table_schema\n LEFT JOIN pg_class pgc ON pgc.relname = t.table_name AND pgc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = current_schema())\n LEFT JOIN (\n SELECT ku.table_name, ku.column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage ku ON tc.constraint_name = ku.constraint_name\n WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = current_schema()\n ) pk ON pk.table_name = c.table_name AND pk.column_name = c.column_name\n LEFT JOIN (\n SELECT ku.table_name, ku.column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage ku ON tc.constraint_name = ku.constraint_name\n WHERE tc.constraint_type = 'UNIQUE' AND tc.table_schema = current_schema()\n ) uk ON uk.table_name = c.table_name AND uk.column_name = c.column_name\n LEFT JOIN (\n SELECT\n t.relname as table_name,\n a.attname as column_name\n FROM pg_index i\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(i.indkey)\n JOIN pg_namespace n ON n.oid = t.relnamespace\n WHERE i.indisprimary = false AND i.indisunique = false AND n.nspname = current_schema()\n ) idx ON idx.table_name = c.table_name AND idx.column_name = c.column_name\n $whereClause\n ORDER BY t.table_name, c.ordinal_position\n \");\n\n $stmt->execute($params);\n $results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n $tables = [];\n foreach ($results as $row) {\n $tableName = $row['table_name'];\n\n if (!isset($tables[$tableName])) {\n $tables[$tableName] = [\n 'name' => $tableName,\n 'engine' => 'PostgreSQL',\n 'estimated_rows' => $this->getTableRowCount($tableName),\n 'comment' => $row['table_comment'],\n 'columns' => [],\n 'primary_key' => [],\n 'unique_keys' => [],\n 'indexes' => []\n ];\n }\n\n if ($row['column_name']) {\n // Map PostgreSQL types to a more readable format\n $fullType = $this->formatPostgreSQLType($row);\n\n $column = [\n 'name' => $row['column_name'],\n 'type' => $row['data_type'],\n 'full_type' => $fullType,\n 'nullable' => $row['is_nullable'] === 'YES',\n 'default' => $row['column_default'],\n 'auto_increment' => \\str_contains((string) $row['extra'], 'auto_increment'),\n 'comment' => $row['column_comment']\n ];\n\n if ($row['character_maximum_length']) {\n $column['max_length'] = $row['character_maximum_length'];\n }\n if ($row['numeric_precision']) {\n $column['precision'] = $row['numeric_precision'];\n $column['scale'] = $row['numeric_scale'];\n }\n\n $tables[$tableName]['columns'][] = $column;\n\n if ($row['column_key'] === 'PRI') {\n $tables[$tableName]['primary_key'][] = $row['column_name'];\n } elseif ($row['column_key'] === 'UNI') {\n $tables[$tableName]['unique_keys'][] = $row['column_name'];\n } elseif ($row['column_key'] === 'MUL') {\n $tables[$tableName]['indexes'][] = $row['column_name'];\n }\n }\n }\n\n return $tables;\n }\n\n private function getTableRowCount(string $tableName): string\n {\n try {\n $stmt = $this->pdo->prepare(\"\n SELECT n_tup_ins - n_tup_del as estimate\n FROM pg_stat_user_tables\n WHERE relname = $1\n \");\n $stmt->execute([$tableName]);\n $result = $stmt->fetchColumn();\n return $result !== false ? (string)$result : 'N/A';\n } catch (\\Exception) {\n return 'N/A';\n }\n }\n\n private function formatPostgreSQLType(array $row): string\n {\n $type = $row['udt_name'] ?? $row['data_type'];\n\n // Handle specific PostgreSQL types\n if ($type === 'varchar' || $type === 'character varying') {\n $type = 'character varying';\n }\n if ($row['character_maximum_length']) {\n return \"{$type}({$row['character_maximum_length']})\";\n }\n if ($row['numeric_precision'] && $row['numeric_scale']) {\n return \"{$type}({$row['numeric_precision']},{$row['numeric_scale']})\";\n }\n\n if ($row['numeric_precision']) {\n return \"{$type}({$row['numeric_precision']})\";\n }\n\n return $type;\n }\n\n private function getRelationships(): array\n {\n $whereClause = \"WHERE tc.table_schema = current_schema()\";\n $paramIndex = 1;\n $params = [];\n\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = [];\n foreach ($this->tables as $table) {\n $placeholders[] = '?';\n $params[] = $table;\n }\n $additionalPlaceholders = [];\n foreach ($this->tables as $table) {\n $additionalPlaceholders[] = '$' . $paramIndex++;\n $params[] = $table;\n }\n $whereClause .= \" AND (tc.table_name = ANY(ARRAY[\" . \\implode(',', $placeholders) . \"]) OR ccu.table_name = ANY(ARRAY[\" . \\implode(',', $additionalPlaceholders) . \"]))\";\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n tc.constraint_name,\n tc.table_name as source_table,\n kcu.column_name as source_column,\n ccu.table_name as target_table,\n ccu.column_name as target_column,\n rc.update_rule,\n rc.delete_rule\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n JOIN information_schema.constraint_column_usage ccu\n ON ccu.constraint_name = tc.constraint_name\n AND ccu.table_schema = tc.table_schema\n JOIN information_schema.referential_constraints rc\n ON tc.constraint_name = rc.constraint_name\n AND tc.table_schema = rc.constraint_schema\n $whereClause\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.table_name\n \");\n\n $stmt->execute($params);\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n private function getIndexes(): array\n {\n $whereClause = \"WHERE schemaname = current_schema() AND indexname NOT LIKE '%_pkey'\";\n $params = [];\n\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = [];\n foreach ($this->tables as $table) {\n $placeholders[] = '?';\n $params[] = $table;\n }\n $whereClause .= \" AND tablename = ANY(ARRAY[\" . \\implode(',', $placeholders) . \"])\";\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n schemaname,\n tablename,\n indexname,\n indexdef\n FROM pg_indexes\n $whereClause\n ORDER BY tablename, indexname\n \");\n\n $stmt->execute($params);\n $results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n $indexes = [];\n foreach ($results as $row) {\n // Parse column names from index definition\n \\preg_match('/\\((.*?)\\)/', (string) $row['indexdef'], $matches);\n $columnList = $matches[1] ?? '';\n $columns = \\array_map('trim', \\explode(',', $columnList));\n\n // Clean up column names (remove function calls, etc.)\n $cleanColumns = [];\n foreach ($columns as $col) {\n // Extract just the column name if it's wrapped in functions\n if (\\preg_match('/([a-zA-Z_]\\w*)/', $col, $colMatches)) {\n $cleanColumns[] = $colMatches[1];\n }\n }\n\n $indexes[] = [\n 'table' => $row['tablename'],\n 'name' => $row['indexname'],\n 'unique' => \\str_contains((string) $row['indexdef'], 'UNIQUE'),\n 'type' => $this->extractIndexType($row['indexdef']),\n 'columns' => $cleanColumns === [] ? $columns : $cleanColumns\n ];\n }\n\n return $indexes;\n }\n\n private function extractIndexType(string $indexDef): string\n {\n if (\\str_contains($indexDef, 'USING gin')) {\n return 'GIN';\n }\n if (\\str_contains($indexDef, 'USING gist')) {\n return 'GIST';\n }\n if (\\str_contains($indexDef, 'USING hash')) {\n return 'HASH';\n }\n if (\\str_contains($indexDef, 'USING brin')) {\n return 'BRIN';\n }\n return 'BTREE';\n // Default\n\n }\n\n private function getConstraints(): array\n {\n $whereClause = \"WHERE table_schema = current_schema() AND constraint_type IN ('UNIQUE', 'CHECK')\";\n $params = [];\n\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = [];\n foreach ($this->tables as $table) {\n $placeholders[] = '?';\n $params[] = $table;\n }\n $whereClause .= \" AND table_name = ANY(ARRAY[\" . \\implode(',', $placeholders) . \"])\";\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n constraint_name,\n table_name,\n constraint_type\n FROM information_schema.table_constraints\n $whereClause\n \");\n\n $stmt->execute($params);\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n private function formatForLLM(array $structure): string\n {\n $output = \"# PostgreSQL Database Schema Analysis\\n\\n\";\n $output .= \"This PostgreSQL database contains \" . \\count($structure['tables']) . \" tables with the following structure:\\n\\n\";\n\n // Tables overview\n $output .= \"## Tables Overview\\n\";\n $tableCount = \\count($structure['tables']);\n $filteredNote = $this->tables !== null ? \" (filtered to specified tables)\" : \"\";\n $output .= \"Analyzing {$tableCount} tables{$filteredNote}:\\n\";\n\n foreach ($structure['tables'] as $table) {\n $pkColumns = empty($table['primary_key']) ? 'None' : \\implode(', ', $table['primary_key']);\n $output .= \"- **{$table['name']}**: {$table['estimated_rows']} rows, Primary Key: {$pkColumns}\";\n if ($table['comment']) {\n $output .= \" - {$table['comment']}\";\n }\n $output .= \"\\n\";\n }\n $output .= \"\\n\";\n\n // Detailed table structures\n $output .= \"## Detailed Table Structures\\n\\n\";\n foreach ($structure['tables'] as $table) {\n $output .= \"### Table: `{$table['name']}`\\n\";\n if ($table['comment']) {\n $output .= \"**Description**: {$table['comment']}\\n\";\n }\n $output .= \"**Estimated Rows**: {$table['estimated_rows']}\\n\\n\";\n\n $output .= \"**Columns**:\\n\";\n foreach ($table['columns'] as $column) {\n $nullable = $column['nullable'] ? 'NULL' : 'NOT NULL';\n $autoInc = $column['auto_increment'] ? ' (SERIAL/SEQUENCE)' : '';\n $default = $column['default'] !== null ? \" DEFAULT {$column['default']}\" : '';\n\n $output .= \"- `{$column['name']}` {$column['full_type']} {$nullable}{$default}{$autoInc}\";\n if ($column['comment']) {\n $output .= \" - {$column['comment']}\";\n }\n $output .= \"\\n\";\n }\n\n if (!empty($table['primary_key'])) {\n $output .= \"\\n**Primary Key**: \" . \\implode(', ', $table['primary_key']) . \"\\n\";\n }\n\n if (!empty($table['unique_keys'])) {\n $output .= \"**Unique Keys**: \" . \\implode(', ', $table['unique_keys']) . \"\\n\";\n }\n\n $output .= \"\\n\";\n }\n\n // Relationships\n if (!empty($structure['relationships'])) {\n $output .= \"## Foreign Key Relationships\\n\\n\";\n $output .= \"Understanding these relationships is crucial for JOIN operations:\\n\\n\";\n\n foreach ($structure['relationships'] as $rel) {\n $output .= \"- `{$rel['source_table']}.{$rel['source_column']}` → `{$rel['target_table']}.{$rel['target_column']}`\";\n $output .= \" (ON DELETE {$rel['delete_rule']}, ON UPDATE {$rel['update_rule']})\\n\";\n }\n $output .= \"\\n\";\n }\n\n // Indexes for query optimization\n if (!empty($structure['indexes'])) {\n $output .= \"## Available Indexes (for Query Optimization)\\n\\n\";\n $output .= \"These indexes can significantly improve query performance:\\n\\n\";\n\n foreach ($structure['indexes'] as $index) {\n $unique = $index['unique'] ? 'UNIQUE ' : '';\n $columns = \\implode(', ', $index['columns']);\n $output .= \"- {$unique}{$index['type']} INDEX `{$index['name']}` on `{$index['table']}` ({$columns})\\n\";\n }\n $output .= \"\\n\";\n }\n\n // PostgreSQL-specific query guidelines\n $output .= \"## PostgreSQL SQL Query Generation Guidelines\\n\\n\";\n $output .= \"**Best Practices for this PostgreSQL database**:\\n\";\n $output .= \"1. Always use table aliases for better readability\\n\";\n $output .= \"2. Prefer indexed columns in WHERE clauses for better performance\\n\";\n $output .= \"3. Use appropriate JOINs based on the foreign key relationships listed above\\n\";\n $output .= \"4. Use double quotes (\\\") for identifiers if they contain special characters or are case-sensitive\\n\";\n $output .= \"5. PostgreSQL is case-sensitive for identifiers - use exact casing as shown above\\n\";\n $output .= \"6. Use \\$1, \\$2, etc. for parameterized queries in prepared statements\\n\";\n $output .= \"7. LIMIT clause syntax: `SELECT ... LIMIT n OFFSET m`\\n\";\n $output .= \"8. String comparisons are case-sensitive by default (use ILIKE for case-insensitive)\\n\";\n $output .= \"9. Use single quotes (') for string literals, not double quotes\\n\";\n $output .= \"10. PostgreSQL supports advanced features like arrays, JSON/JSONB, and full-text search\\n\";\n $output .= \"11. Use RETURNING clause for INSERT/UPDATE/DELETE to get back modified data\\n\\n\";\n\n // Common patterns\n $output .= \"**Common PostgreSQL Query Patterns**:\\n\";\n $this->addCommonPatterns($output, $structure['tables']);\n\n return $output;\n }\n\n private function addCommonPatterns(string &$output, array $tables): void\n {\n // Find tables with timestamps for temporal queries\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['timestamp without time zone', 'timestamp with time zone', 'timestamptz', 'date', 'time']) &&\n (\\str_contains(\\strtolower((string) $column['name']), 'created') ||\n \\str_contains(\\strtolower((string) $column['name']), 'updated'))) {\n $output .= \"- For temporal queries on `{$table['name']}`, use `{$column['name']}` column\\n\";\n break;\n }\n }\n }\n\n // Find potential text search columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['character varying', 'varchar', 'text', 'character']) &&\n (\\str_contains(\\strtolower((string) $column['name']), 'name') ||\n \\str_contains(\\strtolower((string) $column['name']), 'title') ||\n \\str_contains(\\strtolower((string) $column['name']), 'description'))) {\n $output .= \"- For text searches on `{$table['name']}`, consider using `{$column['name']}` with ILIKE, ~ (regex), or full-text search\\n\";\n break;\n }\n }\n }\n\n // Find JSON/JSONB columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['json', 'jsonb'])) {\n $output .= \"- Table `{$table['name']}` has {$column['type']} column `{$column['name']}` - use JSON operators like ->, ->>, @>, ? for querying\\n\";\n }\n }\n }\n\n // Find array columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\str_contains((string) $column['full_type'], '[]')) {\n $output .= \"- Table `{$table['name']}` has array column `{$column['name']}` ({$column['full_type']}) - use array operators like ANY, ALL, @>\\n\";\n }\n }\n }\n\n // Find UUID columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if ($column['type'] === 'uuid') {\n $output .= \"- Table `{$table['name']}` uses UUID for `{$column['name']}` - use gen_random_uuid() for generating new UUIDs\\n\";\n break;\n }\n }\n }\n\n $output .= \"\\n\";\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Jina/JinaUrlReader.php", "client ?? $this->client = new Client([\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n 'X-Return-Format' => 'Markdown',\n ]\n ]);\n }\n\n public function __invoke(string $url): string\n {\n if (!\\filter_var($url, \\FILTER_VALIDATE_URL)) {\n throw new ToolException('Invalid URL.');\n }\n\n return $this->getClient()->post('https://r.jina.ai/', [\n RequestOptions::JSON => [\n 'url' => $url,\n ]\n ])->getBody()->getContents();\n }\n}\n"], ["/neuron-ai/src/RAG/PreProcessor/QueryTransformationPreProcessor.php", "prepareMessage($question);\n\n return $this->provider\n ->systemPrompt($this->getSystemPrompt())\n ->chat([$preparedMessage]);\n }\n\n public function getSystemPrompt(): string\n {\n return $this->customPrompt ?? match ($this->transformation) {\n QueryTransformationType::REWRITING => $this->getRewritingPrompt(),\n QueryTransformationType::DECOMPOSITION => $this->getDecompositionPrompt(),\n QueryTransformationType::HYDE => $this->getHydePrompt(),\n };\n }\n\n public function setCustomPrompt(string $prompt): self\n {\n $this->customPrompt = $prompt;\n return $this;\n }\n\n public function setTransformation(QueryTransformationType $transformation): self\n {\n $this->transformation = $transformation;\n return $this;\n }\n\n public function setProvider(AIProviderInterface $provider): self\n {\n $this->provider = $provider;\n return $this;\n }\n\n protected function prepareMessage(Message $question): UserMessage\n {\n return new UserMessage('' . $question->getContent() . '');\n }\n\n protected function getRewritingPrompt(): string\n {\n return (string) new SystemPrompt(\n background: [\n 'You are an AI assistant tasked with reformulating user queries to improve retrieval in a RAG system.'\n ],\n steps: [\n 'Given the original query, rewrite it to be more specific, detailed, and likely to retrieve relevant information.',\n 'Focus on expanding vocabulary and technical terminology while preserving the original intent and meaning.',\n ],\n output: [\n 'Output only the reformulated query',\n 'Do not add temporal references, dates, or years unless they are present in the original query'\n ]\n );\n }\n\n protected function getDecompositionPrompt(): string\n {\n return (string) new SystemPrompt(\n background: [\n 'You are an AI assistant that breaks down complex queries into simpler sub-queries for comprehensive information retrieval in a RAG system.'\n ],\n steps: [\n 'Given the original complex query, decompose it into focused sub-queries.',\n 'Each sub-query should address a specific aspect of the original question.',\n 'Ensure all sub-queries together cover the full scope of the original query.',\n ],\n output: [\n 'Output each sub-query on a separate line',\n 'Use clear, specific language for each sub-query',\n 'Do not add temporal references, dates, or years unless they are present in the original query',\n ]\n );\n }\n\n protected function getHydePrompt(): string\n {\n return (string) new SystemPrompt(\n background: [\n 'You are an AI assistant that generates hypothetical answer to the user query, to improve retrieval in a RAG system.'\n ],\n steps: [\n 'Given the original query, write a hypothetical document passage that would directly answer this question.',\n 'Create content that resembles what you would expect to find in a relevant document.',\n ],\n output: [\n 'Output only the hypothetical document passage',\n 'Do not add temporal references, dates, or years unless they are present in the original query',\n 'Keep the response as concise as possible'\n ]\n );\n }\n}\n"], ["/neuron-ai/src/Chat/History/SQLChatHistory.php", "table = $this->sanitizeTableName($table);\n $this->load();\n }\n\n protected function load(): void\n {\n $stmt = $this->pdo->prepare(\"SELECT * FROM {$this->table} WHERE thread_id = :thread_id\");\n $stmt->execute(['thread_id' => $this->thread_id]);\n $history = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n if (empty($history)) {\n $stmt = $this->pdo->prepare(\"INSERT INTO {$this->table} (thread_id, messages) VALUES (:thread_id, :messages)\");\n $stmt->execute(['thread_id' => $this->thread_id, 'messages' => '[]']);\n } else {\n $this->history = $this->deserializeMessages(\\json_decode((string) $history[0]['messages'], true));\n }\n }\n\n public function setMessages(array $messages): ChatHistoryInterface\n {\n $stmt = $this->pdo->prepare(\"UPDATE {$this->table} SET messages = :messages WHERE thread_id = :thread_id\");\n $stmt->execute(['thread_id' => $this->thread_id, 'messages' => \\json_encode($this->jsonSerialize())]);\n return $this;\n }\n\n protected function clear(): ChatHistoryInterface\n {\n $stmt = $this->pdo->prepare(\"DELETE FROM {$this->table} WHERE thread_id = :thread_id\");\n $stmt->execute(['thread_id' => $this->thread_id]);\n return $this;\n }\n\n protected function sanitizeTableName(string $tableName): string\n {\n $tableName = \\trim($tableName);\n\n // Whitelist validation\n if (!$this->tableExists($tableName)) {\n throw new ChatHistoryException('Table not allowed');\n }\n\n // Format validation as backup\n if (\\in_array(\\preg_match('/^[a-zA-Z_]\\w*$/', $tableName), [0, false], true)) {\n throw new ChatHistoryException('Invalid table name format');\n }\n\n return $tableName;\n }\n\n protected function tableExists(string $tableName): bool\n {\n $stmt = $this->pdo->prepare(\"SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :table_name\");\n $stmt->execute(['table_name' => $tableName]);\n return $stmt->fetch() !== false;\n }\n}\n"], ["/neuron-ai/src/Tools/ObjectProperty.php", "properties === [] && \\class_exists($this->class)) {\n $schema = (new JsonSchema())->generate($this->class);\n $this->properties = $this->buildPropertiesFromClass($schema);\n }\n }\n\n /**\n * Recursively build properties from a class schema\n *\n * @return ToolPropertyInterface[]\n * @throws \\ReflectionException\n * @throws ToolException\n * @throws ArrayPropertyException\n */\n protected function buildPropertiesFromClass(array $schema): array\n {\n $required = $schema['required'] ?? [];\n $properties = [];\n\n foreach ($schema['properties'] as $propertyName => $propertyData) {\n $isRequired = \\in_array($propertyName, $required);\n $property = $this->createPropertyFromSchema($propertyName, $propertyData, $isRequired);\n\n if ($property instanceof ToolPropertyInterface) {\n $properties[] = $property;\n }\n }\n\n return $properties;\n }\n\n /**\n * Create a property from schema data recursively\n *\n * @throws \\ReflectionException\n * @throws ToolException\n * @throws ArrayPropertyException\n */\n protected function createPropertyFromSchema(string $propertyName, array $propertyData, bool $isRequired): ?ToolPropertyInterface\n {\n $type = $propertyData['type'] ?? 'string';\n $description = $propertyData['description'] ?? null;\n\n return match ($type) {\n 'object' => $this->createObjectProperty($propertyName, $propertyData, $isRequired, $description),\n 'array' => $this->createArrayProperty($propertyName, $propertyData, $isRequired, $description),\n 'string', 'integer', 'number', 'boolean' => $this->createScalarProperty($propertyName, $propertyData, $isRequired, $description),\n default => new ToolProperty(\n $propertyName,\n PropertyType::STRING,\n $description,\n $isRequired,\n $propertyData['enum'] ?? []\n ),\n };\n }\n\n /**\n * Create an object property recursively\n *\n * @throws \\ReflectionException\n * @throws ToolException\n * @throws ArrayPropertyException\n */\n protected function createObjectProperty(string $name, array $propertyData, bool $required, ?string $description): ObjectProperty\n {\n $nestedProperties = [];\n $nestedRequired = $propertyData['required'] ?? [];\n\n // If there's a class reference in the schema, use it\n $className = $propertyData['class'] ?? null;\n\n // If no class is specified, but we have nested properties, build them recursively\n if (!$className && isset($propertyData['properties'])) {\n foreach ($propertyData['properties'] as $nestedPropertyName => $nestedPropertyData) {\n $nestedIsRequired = \\in_array($nestedPropertyName, $nestedRequired);\n $nestedProperty = $this->createPropertyFromSchema($nestedPropertyName, $nestedPropertyData, $nestedIsRequired);\n\n if ($nestedProperty instanceof ToolPropertyInterface) {\n $nestedProperties[] = $nestedProperty;\n }\n }\n }\n\n return new ObjectProperty(\n $name,\n $description,\n $required,\n $className,\n $nestedProperties\n );\n }\n\n /**\n * Create an array property with recursive item handling\n *\n * @throws \\ReflectionException\n * @throws ToolException\n * @throws ArrayPropertyException\n */\n protected function createArrayProperty(string $name, array $propertyData, bool $required, ?string $description): ArrayProperty\n {\n $items = null;\n $minItems = $propertyData['minItems'] ?? null;\n $maxItems = $propertyData['maxItems'] ?? null;\n\n // Handle array items recursively\n if (isset($propertyData['items'])) {\n $itemsData = $propertyData['items'];\n $items = $this->createPropertyFromSchema($name . '_item', $itemsData, false);\n }\n\n return new ArrayProperty(\n $name,\n $description,\n $required,\n $items,\n $minItems,\n $maxItems\n );\n }\n\n /**\n * Create a scalar property (string, integer, number, boolean)\n *\n * @throws ToolException\n */\n protected function createScalarProperty(string $name, array $propertyData, bool $required, ?string $description): ToolProperty\n {\n return new ToolProperty(\n $name,\n PropertyType::fromSchema($propertyData['type']),\n $description,\n $required,\n $propertyData['enum'] ?? []\n );\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'name' => $this->name,\n ...(\\is_null($this->description) ? [] : ['description' => $this->description]),\n 'type' => $this->type,\n 'properties' => $this->getJsonSchema(),\n 'required' => $this->required,\n ];\n }\n\n // The mapped class required properties and required properties are merged\n public function getRequiredProperties(): array\n {\n return \\array_values(\\array_filter(\\array_map(fn (\n ToolPropertyInterface $property\n ): ?string => $property->isRequired() ? $property->getName() : null, $this->properties)));\n }\n\n public function getJsonSchema(): array\n {\n $schema = [\n 'type' => $this->type->value,\n ];\n\n if (!\\is_null($this->description)) {\n $schema['description'] = $this->description;\n }\n\n $properties = \\array_reduce($this->properties, function (array $carry, ToolPropertyInterface $property) {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n\n if (!empty($properties)) {\n $schema['properties'] = $properties;\n $schema['required'] = $this->getRequiredProperties();\n }\n\n return $schema;\n }\n\n public function isRequired(): bool\n {\n return $this->required;\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n public function getType(): PropertyType\n {\n return $this->type;\n }\n\n public function getDescription(): ?string\n {\n return $this->description;\n }\n\n public function getProperties(): array\n {\n return $this->properties;\n }\n\n public function getClass(): ?string\n {\n return $this->class;\n }\n}\n"], ["/neuron-ai/src/Observability/HandleStructuredEvents.php", "inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$data->class.'-schema'] = $this->inspector->startSegment('neuron-schema-generation', \"schema_generate( {$data->class} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n protected function schemaGenerated(AgentInterface $agent, string $event, SchemaGenerated $data): void\n {\n if (\\array_key_exists($data->class.'-schema', $this->segments)) {\n $segment = $this->segments[$data->class.'-schema']->end();\n $segment->addContext('Schema', $data->schema);\n }\n }\n\n protected function extracting(AgentInterface $agent, string $event, Extracting $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $id = $this->getMessageId($data->message).'-extract';\n\n $this->segments[$id] = $this->inspector->startSegment('neuron-structured-extract', 'extract_output')\n ->setColor(self::SEGMENT_COLOR);\n }\n\n protected function extracted(AgentInterface $agent, string $event, Extracted $data): void\n {\n $id = $this->getMessageId($data->message).'-extract';\n\n if (\\array_key_exists($id, $this->segments)) {\n $segment = $this->segments[$id]->end();\n $segment->addContext(\n 'Data',\n [\n 'response' => $data->message->jsonSerialize(),\n 'json' => $data->json,\n ]\n )->addContext(\n 'Schema',\n $data->schema\n );\n unset($this->segments[$id]);\n }\n }\n\n protected function deserializing(AgentInterface $agent, string $event, Deserializing $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$data->class.'-deserialize'] = $this->inspector->startSegment('neuron-structured-deserialize', \"deserialize( {$data->class} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n protected function deserialized(AgentInterface $agent, string $event, Deserialized $data): void\n {\n $id = $data->class.'-deserialize';\n\n if (\\array_key_exists($id, $this->segments)) {\n $this->segments[$id]->end();\n }\n }\n\n protected function validating(AgentInterface $agent, string $event, Validating $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$data->class.'-validate'] = $this->inspector->startSegment('neuron-structured-validate', \"validate( {$data->class} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n protected function validated(AgentInterface $agent, string $event, Validated $data): void\n {\n $id = $data->class.'-validate';\n\n if (\\array_key_exists($id, $this->segments)) {\n $segment = $this->segments[$id]->end();\n $segment->addContext('Json', \\json_decode($data->json));\n if ($data->violations !== []) {\n $segment->addContext('Violations', $data->violations);\n }\n }\n }\n}\n"], ["/neuron-ai/src/Chat/History/AbstractChatHistory.php", "history[] = $message;\n\n $this->trimHistory();\n\n $this->setMessages($this->history);\n\n return $this;\n }\n\n public function getMessages(): array\n {\n return $this->history;\n }\n\n public function getLastMessage(): Message|false\n {\n return \\end($this->history);\n }\n\n public function flushAll(): ChatHistoryInterface\n {\n $this->clear();\n $this->history = [];\n return $this;\n }\n\n public function calculateTotalUsage(): int\n {\n return $this->tokenCounter->count($this->history);\n }\n\n protected function trimHistory(): void\n {\n if ($this->history === []) {\n return;\n }\n\n $tokenCount = $this->tokenCounter->count($this->history);\n\n // Early exit if all messages fit within the token limit\n if ($tokenCount <= $this->contextWindow) {\n $this->ensureValidMessageSequence();\n return;\n }\n\n // Binary search to find how many messages to skip from the beginning\n $skipFrom = $this->findMaxFittingMessages();\n\n $this->history = \\array_slice($this->history, $skipFrom);\n\n // Ensure valid message sequence\n $this->ensureValidMessageSequence();\n }\n\n /**\n * Binary search to find the maximum number of messages that fit within the token limit.\n *\n * @return int The index of the first element to retain (keeping most recent messages) - 0 Skip no messages (include all) - count($this->history): Skip all messages (include none)\n */\n private function findMaxFittingMessages(): int\n {\n $totalMessages = \\count($this->history);\n $left = 0;\n $right = $totalMessages;\n\n while ($left < $right) {\n $mid = \\intval(($left + $right) / 2);\n $subset = \\array_slice($this->history, $mid);\n\n if ($this->tokenCounter->count($subset) <= $this->contextWindow) {\n // Fits! Try including more messages (skip fewer)\n $right = $mid;\n } else {\n // Doesn't fit! Need to skip more messages\n $left = $mid + 1;\n }\n }\n\n return $left;\n }\n\n /**\n * Ensures the message list:\n * 1. Starts with a UserMessage\n * 2. Ends with an AssistantMessage\n * 3. Maintains tool call/result pairs\n */\n protected function ensureValidMessageSequence(): void\n {\n // Ensure it starts with a UserMessage\n $this->ensureStartsWithUser();\n\n // Ensure it ends with an AssistantMessage\n $this->ensureValidAlternation();\n }\n\n /**\n * Ensures the message list starts with a UserMessage.\n */\n protected function ensureStartsWithUser(): void\n {\n // Find the first UserMessage\n $firstUserIndex = null;\n foreach ($this->history as $index => $message) {\n if ($message->getRole() === MessageRole::USER->value) {\n $firstUserIndex = $index;\n break;\n }\n }\n\n if ($firstUserIndex === null) {\n // No UserMessage found\n $this->history = [];\n return;\n }\n\n if ($firstUserIndex === 0) {\n return;\n }\n\n if ($firstUserIndex > 0) {\n // Remove messages before the first user message\n $this->history = \\array_slice($this->history, $firstUserIndex);\n }\n }\n\n /**\n * Ensures valid alternation between user and assistant messages.\n */\n protected function ensureValidAlternation(): void\n {\n $result = [];\n $expectingRole = [MessageRole::USER->value]; // Should start with user\n\n foreach ($this->history as $message) {\n $messageRole = $message->getRole();\n\n // Tool result messages have a special case - they're user messages\n // but can only follow tool call messages (assistant)\n // This is valid after a ToolCallMessage\n if ($message instanceof ToolCallResultMessage && ($result !== [] && $result[\\count($result) - 1] instanceof ToolCallMessage)) {\n $result[] = $message;\n // After the tool result, we expect assistant again\n $expectingRole = [MessageRole::ASSISTANT->value, MessageRole::MODEL->value];\n continue;\n }\n\n // Check if this message has the expected role\n if (\\in_array($messageRole, $expectingRole, true)) {\n $result[] = $message;\n // Toggle the expected role\n $expectingRole = ($expectingRole === [MessageRole::USER->value])\n ? [MessageRole::ASSISTANT->value, MessageRole::MODEL->value]\n : [MessageRole::USER->value];\n }\n // If not the expected role, we have an invalid alternation\n // Skip this message to maintain a valid sequence\n }\n\n $this->history = $result;\n }\n\n public function jsonSerialize(): array\n {\n return $this->getMessages();\n }\n\n protected function deserializeMessages(array $messages): array\n {\n return \\array_map(fn (array $message): Message => match ($message['type'] ?? null) {\n 'tool_call' => $this->deserializeToolCall($message),\n 'tool_call_result' => $this->deserializeToolCallResult($message),\n default => $this->deserializeMessage($message),\n }, $messages);\n }\n\n protected function deserializeMessage(array $message): Message\n {\n $messageRole = MessageRole::from($message['role']);\n $messageContent = $message['content'] ?? null;\n\n $item = match ($messageRole) {\n MessageRole::ASSISTANT => new AssistantMessage($messageContent),\n MessageRole::USER => new UserMessage($messageContent),\n default => new Message($messageRole, $messageContent)\n };\n\n $this->deserializeMeta($message, $item);\n\n return $item;\n }\n\n protected function deserializeToolCall(array $message): ToolCallMessage\n {\n $tools = \\array_map(fn (array $tool) => Tool::make($tool['name'], $tool['description'])\n ->setInputs($tool['inputs'])\n ->setCallId($tool['callId'] ?? null), $message['tools']);\n\n $item = new ToolCallMessage($message['content'], $tools);\n\n $this->deserializeMeta($message, $item);\n\n return $item;\n }\n\n protected function deserializeToolCallResult(array $message): ToolCallResultMessage\n {\n $tools = \\array_map(fn (array $tool) => Tool::make($tool['name'], $tool['description'])\n ->setInputs($tool['inputs'])\n ->setCallId($tool['callId'])\n ->setResult($tool['result']), $message['tools']);\n\n return new ToolCallResultMessage($tools);\n }\n\n protected function deserializeMeta(array $message, Message $item): void\n {\n foreach ($message as $key => $value) {\n if ($key === 'role') {\n continue;\n }\n if ($key === 'content') {\n continue;\n }\n if ($key === 'usage') {\n $item->setUsage(\n new Usage($message['usage']['input_tokens'], $message['usage']['output_tokens'])\n );\n continue;\n }\n if ($key === 'attachments') {\n foreach ($message['attachments'] as $attachment) {\n switch (AttachmentType::from($attachment['type'])) {\n case AttachmentType::IMAGE:\n $item->addAttachment(\n new Image(\n $attachment['content'],\n AttachmentContentType::from($attachment['content_type']),\n $attachment['media_type'] ?? null\n )\n );\n break;\n case AttachmentType::DOCUMENT:\n $item->addAttachment(\n new Document(\n $attachment['content'],\n AttachmentContentType::from($attachment['content_type']),\n $attachment['media_type'] ?? null\n )\n );\n break;\n }\n\n }\n continue;\n }\n $item->addMetadata($key, $value);\n }\n }\n}\n"], ["/neuron-ai/src/Providers/XAI/Grok.php", " [\"pipe\", \"r\"], // stdin\n 1 => [\"pipe\", \"w\"], // stdout\n 2 => [\"pipe\", \"w\"] // stderr\n ];\n\n $command = $this->config['command'];\n $args = $this->config['args'] ?? [];\n $env = $this->config['env'] ?? [];\n\n // Merge current environment with provided environment variables\n $fullEnv = \\array_merge(\\getenv(), $env);\n\n // Build command with arguments\n $commandLine = $command;\n foreach ($args as $arg) {\n $commandLine .= ' ' . \\escapeshellarg((string) $arg);\n }\n\n // Start the process\n $this->process = \\proc_open(\n $commandLine,\n $descriptorSpec,\n $this->pipes,\n null,\n $fullEnv\n );\n\n if (!\\is_resource($this->process)) {\n throw new McpException(\"Failed to start the MCP server process\");\n }\n\n // Configure pipes for binary data\n \\stream_set_write_buffer($this->pipes[0], 0);\n \\stream_set_read_buffer($this->pipes[1], 0);\n\n // Check that the process started successfully\n $status = \\proc_get_status($this->process);\n if (!$status['running']) {\n $error = \\stream_get_contents($this->pipes[2]);\n throw new McpException(\"Process failed to start: \" . $error);\n }\n }\n\n /**\n * Send a request to the MCP server\n */\n public function send(array $data): void\n {\n if (!\\is_resource($this->process)) {\n throw new McpException(\"Process is not running\");\n }\n\n $status = \\proc_get_status($this->process);\n if (!$status['running']) {\n throw new McpException(\"MCP server process is not running\");\n }\n\n $jsonData = \\json_encode($data);\n if ($jsonData === false) {\n throw new McpException(\"Failed to encode request data to JSON\");\n }\n\n $bytesWritten = \\fwrite($this->pipes[0], $jsonData . \"\\n\");\n if ($bytesWritten === false || $bytesWritten < \\strlen($jsonData) + 1) {\n throw new McpException(\"Failed to write complete request to MCP server\");\n }\n\n \\fflush($this->pipes[0]);\n }\n\n /**\n * Receive a response from the MCP server\n */\n public function receive(): array\n {\n if (!\\is_resource($this->process)) {\n throw new McpException(\"Process is not running\");\n }\n\n // Set stream to non-blocking mode\n \\stream_set_blocking($this->pipes[1], false);\n\n $response = \"\";\n $startTime = \\time();\n $timeout = 30; // 30-second timeout\n\n // Keep reading until we get a complete JSON response or timeout\n while (\\time() - $startTime < $timeout) {\n $status = \\proc_get_status($this->process);\n\n if (!$status['running']) {\n throw new McpException(\"MCP server process has terminated unexpectedly.\");\n }\n\n $chunk = \\fread($this->pipes[1], 4096);\n if ($chunk !== false && \\strlen($chunk) > 0) {\n $response .= $chunk;\n\n // Try to parse what we have so far\n $decoded = \\json_decode($response, true);\n if ($decoded !== null) {\n // We've got a valid JSON response\n return $decoded;\n }\n }\n\n // Small delay to prevent CPU spinning\n \\usleep(10000); // 10ms\n }\n\n throw new McpException(\"Timeout waiting for response from MCP server\");\n }\n\n /**\n * Disconnect from the MCP server\n */\n public function disconnect(): void\n {\n if (\\is_resource($this->process)) {\n // Close all pipe handles\n foreach ($this->pipes as $pipe) {\n if (\\is_resource($pipe)) {\n \\fclose($pipe);\n }\n }\n\n // Try graceful termination first\n $status = \\proc_get_status($this->process);\n // On Unix systems, try sending SIGTERM\n if ($status['running'] && \\function_exists('proc_terminate')) {\n \\proc_terminate($this->process);\n // Give the process a moment to shut down gracefully\n \\usleep(500000);\n // 500ms\n }\n\n // Close the process handle\n \\proc_close($this->process);\n $this->process = null;\n }\n }\n}\n"], ["/neuron-ai/src/ResolveTools.php", "tools, $this->tools());\n }\n\n /**\n * If toolkits have already bootstrapped, this function\n * just traverses the array of tools without any action.\n *\n * @return ToolInterface[]\n */\n public function bootstrapTools(): array\n {\n $guidelines = [];\n\n if (!empty($this->toolsBootstrapCache)) {\n return $this->toolsBootstrapCache;\n }\n\n $this->notify('tools-bootstrapping');\n\n foreach ($this->getTools() as $tool) {\n if ($tool instanceof ToolkitInterface) {\n $kitGuidelines = $tool->guidelines();\n if ($kitGuidelines !== null && $kitGuidelines !== '') {\n $name = (new \\ReflectionClass($tool))->getShortName();\n $kitGuidelines = '# '.$name.\\PHP_EOL.$kitGuidelines;\n }\n\n // Merge the tools\n $innerTools = $tool->tools();\n $this->toolsBootstrapCache = \\array_merge($this->toolsBootstrapCache, $innerTools);\n\n // Add guidelines to the system prompt\n if ($kitGuidelines !== null && $kitGuidelines !== '' && $kitGuidelines !== '0') {\n $kitGuidelines .= \\PHP_EOL.\\implode(\n \\PHP_EOL.'- ',\n \\array_map(\n fn (ToolInterface $tool): string => \"{$tool->getName()}: {$tool->getDescription()}\",\n $innerTools\n )\n );\n\n $guidelines[] = $kitGuidelines;\n }\n } else {\n // If the item is a simple tool, add to the list as it is\n $this->toolsBootstrapCache[] = $tool;\n }\n }\n\n $instructions = $this->removeDelimitedContent($this->resolveInstructions(), '', '');\n if ($guidelines !== []) {\n $this->withInstructions(\n $instructions.\\PHP_EOL.''.\\PHP_EOL.\\implode(\\PHP_EOL.\\PHP_EOL, $guidelines).\\PHP_EOL.''\n );\n }\n\n $this->notify('tools-bootstrapped', new ToolsBootstrapped($this->toolsBootstrapCache, $guidelines));\n\n return $this->toolsBootstrapCache;\n }\n\n /**\n * Add tools.\n *\n * @throws AgentException\n */\n public function addTool(ToolInterface|ToolkitInterface|array $tools): AgentInterface\n {\n $tools = \\is_array($tools) ? $tools : [$tools];\n\n foreach ($tools as $t) {\n if (! $t instanceof ToolInterface && ! $t instanceof ToolkitInterface) {\n throw new AgentException('Tools must be an instance of ToolInterface or ToolkitInterface');\n }\n $this->tools[] = $t;\n }\n\n // Empty the cache for the next turn.\n $this->toolsBootstrapCache = [];\n\n return $this;\n }\n\n protected function executeTools(ToolCallMessage $toolCallMessage): ToolCallResultMessage\n {\n $toolCallResult = new ToolCallResultMessage($toolCallMessage->getTools());\n\n foreach ($toolCallResult->getTools() as $tool) {\n $this->notify('tool-calling', new ToolCalling($tool));\n try {\n $tool->execute();\n } catch (\\Throwable $exception) {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n $this->notify('tool-called', new ToolCalled($tool));\n }\n\n return $toolCallResult;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/MeanTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|float|int $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n // Convert to float values\n $numericData = \\array_map('floatval', $numericData);\n $mean = \\array_sum($numericData) / \\count($numericData);\n\n return \\round($mean, $this->precision);\n }\n}\n"], ["/neuron-ai/src/Chat/Attachments/Attachment.php", " $this->type->value,\n 'content' => $this->content,\n 'content_type' => $this->contentType->value,\n 'media_type' => $this->mediaType,\n ]);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/StandardDeviationTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|float|int $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n if (\\count($numericData) === 1 && $this->sample) {\n return ['error' => 'Cannot calculate sample standard deviation with only one data point'];\n }\n\n // Convert to float values\n $numericData = \\array_map('floatval', $numericData);\n\n // Calculate mean\n $mean = \\array_sum($numericData) / \\count($numericData);\n\n // Calculate the sum of squared differences\n $sumSquaredDifferences = 0;\n foreach ($numericData as $value) {\n $sumSquaredDifferences += ($value - $mean) ** 2;\n }\n\n // Calculate variance\n $divisor = $this->sample ? \\count($numericData) - 1 : \\count($numericData);\n $variance = $sumSquaredDifferences / $divisor;\n\n // Calculate standard deviation\n $standardDeviation = \\sqrt($variance);\n\n return \\round($standardDeviation, $this->precision);\n }\n}\n"], ["/neuron-ai/src/Chat/History/TokenCounter.php", "getContent();\n if (\\is_string($content)) {\n $messageChars += \\strlen($content);\n } elseif ($content !== null) {\n // For arrays and other types, use JSON representation\n $messageChars += \\strlen(\\json_encode($content));\n }\n\n // Handle tool calls for AssistantMessage (excluding array content format)\n if ($message instanceof ToolCallMessage && !\\is_array($content)) {\n $tools = $message->getTools();\n if ($tools !== []) {\n // Convert tools to their JSON representation for counting\n $toolsContent = \\json_encode(\\array_map(fn (ToolInterface $tool): array => $tool->jsonSerialize(), $tools));\n $messageChars += \\strlen($toolsContent);\n }\n }\n\n // Handle tool call results\n if ($message instanceof ToolCallResultMessage) {\n $tools = $message->getTools();\n // Add tool IDs to the count\n foreach ($tools as $tool) {\n $serialized = $tool->jsonSerialize();\n // Assuming tool IDs are in the serialized data\n if (isset($serialized['id'])) {\n $messageChars += \\strlen($serialized['id']);\n }\n }\n }\n\n // Count role characters\n $messageChars += \\strlen($message->getRole());\n\n // Round up per message to ensure individual counts add up correctly\n $tokenCount += \\ceil($messageChars / $this->charsPerToken);\n\n // Add extra tokens per message\n $tokenCount += $this->extraTokensPerMessage;\n }\n\n // Final round up in case extraTokensPerMessage is a float\n return (int) \\ceil($tokenCount);\n }\n}\n"], ["/neuron-ai/src/Tools/ToolProperty.php", " $this->name,\n 'description' => $this->description,\n 'type' => $this->type->value,\n 'enum' => $this->enum,\n 'required' => $this->required,\n ];\n }\n\n public function isRequired(): bool\n {\n return $this->required;\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n public function getType(): PropertyType\n {\n return $this->type;\n }\n\n public function getDescription(): ?string\n {\n return $this->description;\n }\n\n public function getEnum(): array\n {\n return $this->enum;\n }\n\n public function getJsonSchema(): array\n {\n $schema = [\n 'type' => $this->type->value,\n ];\n\n if (!\\is_null($this->description)) {\n $schema['description'] = $this->description;\n }\n\n if ($this->enum !== []) {\n $schema['enum'] = $this->enum;\n }\n\n return $schema;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/VarianceTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|float|int $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n if (\\count($numericData) === 1 && $this->sample) {\n return ['error' => 'Cannot calculate sample variance with only one data point'];\n }\n\n // Convert to float values\n $numericData = \\array_map('floatval', $numericData);\n\n // Calculate mean\n $mean = \\array_sum($numericData) / \\count($numericData);\n\n // Calculate the sum of squared differences\n $sumSquaredDifferences = 0;\n foreach ($numericData as $value) {\n $sumSquaredDifferences += ($value - $mean) ** 2;\n }\n\n // Calculate variance\n $divisor = $this->sample ? \\count($numericData) - 1 : \\count($numericData);\n $variance = $sumSquaredDifferences / $divisor;\n\n return \\round($variance, $this->precision);\n }\n}\n"], ["/neuron-ai/src/SystemPrompt.php", "background);\n\n if ($this->steps !== []) {\n $prompt .= \\PHP_EOL . \\PHP_EOL . \"# INTERNAL ASSISTANT STEPS\" . \\PHP_EOL . \\implode(\\PHP_EOL, $this->steps);\n }\n\n if ($this->output !== []) {\n $prompt .= \\PHP_EOL . \\PHP_EOL . \"# OUTPUT INSTRUCTIONS\" . \\PHP_EOL . \" - \" . \\implode(\\PHP_EOL . \" - \", $this->output);\n }\n\n if ($this->toolsUsage !== []) {\n $prompt .= \\PHP_EOL . \\PHP_EOL . \"# TOOLS USAGE RULES\" . \\PHP_EOL . \" - \" . \\implode(\\PHP_EOL . \" - \", $this->toolsUsage);\n }\n\n return $prompt;\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Deserializer/Deserializer.php", "newInstanceWithoutConstructor();\n\n // Get all properties including private/protected\n $properties = $reflection->getProperties();\n\n foreach ($properties as $property) {\n $propertyName = $property->getName();\n\n // Check if data contains this property (case-sensitive and snake_case/camelCase variants)\n $value = self::findPropertyValue($data, $propertyName);\n\n if ($value !== null) {\n // Get property type information\n $type = $property->getType();\n\n if ($type) {\n $value = self::castValue($value, $type, $property);\n }\n\n $property->setValue($instance, $value);\n }\n }\n\n // Call constructor if it exists and is public\n $constructor = $reflection->getConstructor();\n if ($constructor && $constructor->isPublic() && $constructor->getNumberOfRequiredParameters() === 0) {\n $constructor->invoke($instance);\n }\n\n return $instance;\n }\n\n /**\n * Find property value in data, supporting different naming conventions\n */\n private static function findPropertyValue(array $data, string $propertyName): mixed\n {\n // Direct match\n if (\\array_key_exists($propertyName, $data)) {\n return $data[$propertyName];\n }\n\n // Convert camelCase to snake_case\n $snakeCase = \\strtolower((string) \\preg_replace('/(?getTypes() as $unionType) {\n try {\n return self::castToSingleType($value, $unionType, $property);\n } catch (\\Exception) {\n continue;\n }\n }\n throw new DeserializerException(\"Cannot cast value to any type in union for property {$property->getName()}\");\n }\n\n // @phpstan-ignore-next-line\n return self::castToSingleType($value, $type, $property);\n }\n\n /**\n * Cast value to a single type\n *\n * @throws DeserializerException|\\ReflectionException\n */\n private static function castToSingleType(\n mixed $value,\n \\ReflectionNamedType $type,\n \\ReflectionProperty $property\n ): mixed {\n $typeName = $type->getName();\n\n // Handle null values\n if ($value === null) {\n if ($type->allowsNull()) {\n return null;\n }\n throw new DeserializerException(\"Property {$property->getName()} does not allow null values\");\n }\n\n return match ($typeName) {\n 'string' => (string) $value,\n 'int' => (int) $value,\n 'float' => (float) $value,\n 'bool' => (bool) $value,\n 'array' => self::handleArray($value, $property),\n 'DateTime' => self::createDateTime($value),\n 'DateTimeImmutable' => self::createDateTimeImmutable($value),\n default => self::handleSingleObject($value, $typeName)\n };\n }\n\n /**\n * @throws DeserializerException|\\ReflectionException\n */\n private static function handleSingleObject(mixed $value, string $typeName): mixed\n {\n if (\\is_array($value) && \\class_exists($typeName)) {\n return self::deserializeObject($value, $typeName);\n }\n\n if (\\enum_exists($typeName)) {\n return self::handleEnum($typeName, $value);\n }\n\n // Fallback: return the value as-is\n return $value;\n }\n\n /**\n * Handle collections\n *\n * @throws DeserializerException|\\ReflectionException\n */\n private static function handleArray(mixed $value, \\ReflectionProperty $property): mixed\n {\n // Handle arrays of objects using docblock annotations\n if (self::isArrayOfObjects($property)) {\n $elementType = self::getArrayElementType($property);\n if ($elementType && \\class_exists($elementType)) {\n return \\array_map(fn (array $item): object => self::deserializeObject($item, $elementType), $value);\n }\n }\n\n // Fallback: return the value as-is\n return $value;\n }\n\n /**\n * Check if a property represents an array of objects based on docblock\n */\n private static function isArrayOfObjects(\\ReflectionProperty $property): bool\n {\n $docComment = $property->getDocComment();\n if (!$docComment) {\n return false;\n }\n\n return \\preg_match('/@var\\s+(?:([a-zA-Z0-9_\\\\\\\\]+)\\[\\]|array<([a-zA-Z0-9_\\\\\\\\]+)>)/', $docComment) === 1;\n }\n\n /**\n * Extract an element type from array docblock annotation\n */\n private static function getArrayElementType(\\ReflectionProperty $property): ?string\n {\n $docComment = $property->getDocComment();\n if (!$docComment) {\n return null;\n }\n\n // Extract type from both \"@var \\App\\Type[]\" and \"@var array<\\App\\Type>\"\n if (\\preg_match('/@var\\s+(?:([a-zA-Z0-9_\\\\\\\\]+)\\[\\]|array<([a-zA-Z0-9_\\\\\\\\]+)>)/', $docComment, $matches) === 1) {\n return empty($matches[1]) ? ((isset($matches[2]) && $matches[2] !== '0') ? $matches[2] : null) : ($matches[1]);\n }\n\n return null;\n }\n\n /**\n * Create a DateTime object from various input formats\n *\n * @throws DeserializerException\n */\n private static function createDateTime(mixed $value): \\DateTime\n {\n if ($value instanceof \\DateTime) {\n return $value;\n }\n\n if (\\is_string($value)) {\n try {\n return new \\DateTime($value);\n } catch (\\Exception) {\n throw new DeserializerException(\"Cannot create DateTime from: {$value}\");\n }\n }\n\n if (\\is_numeric($value)) {\n return new \\DateTime('@'.$value);\n }\n\n throw new DeserializerException(\"Cannot create DateTime from value type: \".\\gettype($value));\n }\n\n /**\n * Create a DateTimeImmutable object from various input formats\n *\n * @throws DeserializerException\n */\n private static function createDateTimeImmutable(mixed $value): \\DateTimeImmutable\n {\n if ($value instanceof \\DateTimeImmutable) {\n return $value;\n }\n\n if (\\is_string($value)) {\n try {\n return new \\DateTimeImmutable($value);\n } catch (\\Exception) {\n throw new DeserializerException(\"Cannot create DateTimeImmutable from: {$value}\");\n }\n }\n\n if (\\is_numeric($value)) {\n return new \\DateTimeImmutable('@'.$value);\n }\n\n throw new DeserializerException(\"Cannot create DateTimeImmutable from value type: \".\\gettype($value));\n }\n\n private static function handleEnum(BackedEnum|string $typeName, mixed $value): BackedEnum\n {\n if (!\\is_subclass_of($typeName, BackedEnum::class)) {\n throw new DeserializerException(\"Cannot create BackedEnum from: {$typeName}\");\n }\n\n $enum = $typeName::tryFrom($value);\n\n if (!$enum instanceof \\BackedEnum) {\n throw new DeserializerException(\"Invalid enum value '{$value}' for {$typeName}\");\n }\n\n return $enum;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/MedianTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|float|int $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n // Convert to float values and sort\n $numericData = \\array_map('floatval', $numericData);\n \\sort($numericData);\n\n $count = \\count($numericData);\n $middle = (int) \\floor($count / 2);\n\n if ($count % 2 === 0) {\n // Even number of elements - average of two middle values\n $median = ($numericData[$middle - 1] + $numericData[$middle]) / 2;\n } else {\n // Odd number of elements - middle value\n $median = $numericData[$middle];\n }\n\n return \\round($median, $this->precision);\n }\n}\n"], ["/neuron-ai/src/ResolveChatHistory.php", "chatHistory = $chatHistory;\n return $this;\n }\n\n /**\n * Used extending the Agent.\n */\n protected function chatHistory(): ChatHistoryInterface\n {\n return new InMemoryChatHistory();\n }\n\n public function fillChatHistory(Message|array $messages): void\n {\n $messages = \\is_array($messages) ? $messages : [$messages];\n\n foreach ($messages as $message) {\n $this->notify('message-saving', new MessageSaving($message));\n $this->resolveChatHistory()->addMessage($message);\n $this->notify('message-saved', new MessageSaved($message));\n }\n }\n\n /**\n * Get the current instance of the chat history.\n */\n public function resolveChatHistory(): ChatHistoryInterface\n {\n if (!isset($this->chatHistory)) {\n $this->chatHistory = $this->chatHistory();\n }\n\n return $this->chatHistory;\n }\n}\n"], ["/neuron-ai/src/Tools/ArrayProperty.php", "validateConstraints();\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'name' => $this->name,\n 'description' => $this->description,\n 'type' => $this->type->value,\n 'items' => $this->getJsonSchema(),\n 'required' => $this->required,\n ];\n }\n\n public function getJsonSchema(): array\n {\n $schema = [\n 'type' => $this->type->value,\n ];\n\n if (!\\is_null($this->description)) {\n $schema['description'] = $this->description;\n }\n\n if ($this->items instanceof ToolPropertyInterface) {\n $schema['items'] = $this->items->getJsonSchema();\n }\n\n if ($this->minItems !== null && $this->minItems !== 0) {\n $schema['minItems'] = $this->minItems;\n }\n\n if ($this->maxItems !== null && $this->maxItems !== 0) {\n $schema['maxItems'] = $this->maxItems;\n }\n\n return $schema;\n }\n\n public function isRequired(): bool\n {\n return $this->required;\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n public function getType(): PropertyType\n {\n return $this->type;\n }\n\n public function getDescription(): ?string\n {\n return $this->description;\n }\n\n public function getItems(): ?ToolPropertyInterface\n {\n return $this->items;\n }\n\n /**\n * @throws ArrayPropertyException\n */\n protected function validateConstraints(): void\n {\n if ($this->minItems !== null && $this->minItems < 0) {\n throw new ArrayPropertyException(\"minItems must be >= 0, got {$this->minItems}\");\n }\n\n if ($this->maxItems !== null && $this->maxItems < 0) {\n throw new ArrayPropertyException(\"maxItems must be >= 0, got {$this->maxItems}\");\n }\n\n if ($this->minItems !== null && $this->maxItems !== null && $this->minItems > $this->maxItems) {\n throw new ArrayPropertyException(\n \"minItems ({$this->minItems}) cannot be greater than maxItems ({$this->maxItems})\"\n );\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/PGSQL/PGSQLSelectTool.php", "validateReadOnlyQuery($query)) {\n return [\n \"error\" => \"The query was rejected for security reasons.\nIt looks like you are trying to run a write query using the read-only query tool.\"\n ];\n }\n\n $statement = $this->pdo->prepare($query);\n $statement->execute();\n\n return $statement->fetchAll(PDO::FETCH_ASSOC);\n }\n\n /**\n * Validates that the query is read-only\n *\n * @throws InvalidArgumentException if query contains write operations\n */\n private function validateReadOnlyQuery(string $query): bool\n {\n if ($query === '') {\n return false;\n }\n\n // Remove comments to avoid false positives\n $cleanQuery = $this->removeComments($query);\n\n // Check if query starts with an allowed read operation\n $isAllowed = false;\n foreach ($this->allowedPatterns as $pattern) {\n if (\\preg_match($pattern, $cleanQuery)) {\n $isAllowed = true;\n break;\n }\n }\n\n if (!$isAllowed) {\n return false;\n }\n\n // Check for forbidden write operations\n foreach ($this->forbiddenPatterns as $pattern) {\n if (\\preg_match($pattern, $cleanQuery)) {\n return false;\n }\n }\n\n // Additional security checks\n return $this->performAdditionalSecurityChecks($cleanQuery);\n }\n\n private function removeComments(string $query): string\n {\n // Remove single-line comments (-- style)\n $query = \\preg_replace('/--.*$/m', '', $query);\n\n // Remove multi-line comments (/* */ style)\n $query = \\preg_replace('/\\/\\*.*?\\*\\//s', '', (string) $query);\n\n return $query;\n }\n\n private function performAdditionalSecurityChecks(string $query): bool\n {\n // Check for semicolon followed by potential write operations\n if (\\preg_match('/;\\s*(?!$)/i', $query)) {\n // Multiple statements detected - need to validate each one\n $statements = $this->splitStatements($query);\n foreach ($statements as $statement) {\n if (\\trim((string) $statement) !== '' && !$this->validateSingleStatement(\\trim((string) $statement))) {\n return false;\n }\n }\n }\n\n // Check for function calls that might modify data\n $dangerousFunctions = [\n 'pg_exec',\n 'pg_query',\n 'system',\n 'exec',\n 'shell_exec',\n 'passthru',\n 'eval',\n ];\n\n foreach ($dangerousFunctions as $func) {\n if (\\stripos($query, $func) !== false) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Split query into individual statements\n */\n private function splitStatements(string $query): array\n {\n // Simple split on semicolons (this could be enhanced for more complex cases)\n return \\array_filter(\n \\array_map('trim', \\explode(';', $query)),\n fn (string $stmt): bool => $stmt !== ''\n );\n }\n\n /**\n * Validate a single statement\n *\n * @return bool True if statement is valid read-only operation, false otherwise\n */\n private function validateSingleStatement(string $statement): bool\n {\n $isAllowed = false;\n foreach ($this->allowedPatterns as $pattern) {\n if (\\preg_match($pattern, $statement)) {\n $isAllowed = true;\n break;\n }\n }\n\n return $isAllowed;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/MySQL/MySQLSelectTool.php", "validateReadOnly($query)) {\n return \"The query was rejected for security reasons.\n It looks like you are trying to run a write query using the read-only query tool.\";\n }\n\n $stmt = $this->pdo->prepare($query);\n $stmt->execute();\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n protected function validateReadOnly(string $query): bool\n {\n // Remove comments and normalize whitespace\n $cleanQuery = $this->sanitizeQuery($query);\n\n // Check if it starts with allowed statements\n $firstKeyword = $this->getFirstKeyword($cleanQuery);\n if (!\\in_array($firstKeyword, $this->allowedStatements)) {\n return false;\n }\n\n // Check for forbidden keywords that might be in subqueries\n foreach ($this->forbiddenStatements as $forbidden) {\n if (self::containsKeyword($cleanQuery, $forbidden)) {\n return false;\n }\n }\n\n return true;\n }\n\n protected function sanitizeQuery(string $query): string\n {\n // Remove SQL comments\n $query = \\preg_replace('/--.*$/m', '', $query);\n $query = \\preg_replace('/\\/\\*.*?\\*\\//s', '', (string) $query);\n\n // Normalize whitespace\n return \\preg_replace('/\\s+/', ' ', \\trim((string) $query));\n }\n\n protected function getFirstKeyword(string $query): string\n {\n if (\\preg_match('/^\\s*(\\w+)/i', $query, $matches)) {\n return \\strtoupper($matches[1]);\n }\n return '';\n }\n\n protected function containsKeyword(string $query, string $keyword): bool\n {\n // Use word boundaries to avoid false positives\n return \\preg_match('/\\b' . \\preg_quote($keyword, '/') . '\\b/i', $query) === 1;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/ModeTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|int|float $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n // Convert to float values\n $numericData = \\array_map('floatval', $numericData);\n\n // Count frequency of each value\n $frequencies = \\array_count_values($numericData);\n $maxFrequency = \\max($frequencies);\n\n // Find all values with maximum frequency\n $modes = \\array_keys($frequencies, $maxFrequency);\n\n // Convert back to numeric values and sort\n $modes = \\array_map('floatval', $modes);\n \\sort($modes);\n\n return $modes;\n }\n}\n"], ["/neuron-ai/src/RAG/DataLoader/PdfReader.php", "setBinPath($binPath);\n }\n }\n\n public function setBinPath(string $binPath): self\n {\n if (!\\is_executable($binPath)) {\n throw new DataReaderException(\"The provided path is not executable.\");\n }\n $this->binPath = $binPath;\n return $this;\n }\n\n protected function findPdfToText(): string\n {\n if (isset($this->binPath)) {\n return $this->binPath;\n }\n\n foreach ($this->commonPaths as $path) {\n if (\\is_executable($path)) {\n return $path;\n }\n }\n\n throw new DataReaderException(\"The pdftotext binary was not found or is not executable.\");\n }\n\n public function setPdf(string $pdf): self\n {\n if (!\\is_readable($pdf)) {\n throw new DataReaderException(\"Could not read `{$pdf}`\");\n }\n\n $this->pdf = $pdf;\n\n return $this;\n }\n\n public function setOptions(array $options): self\n {\n $this->options = $this->parseOptions($options);\n\n return $this;\n }\n\n public function addOptions(array $options): self\n {\n $this->options = \\array_merge(\n $this->options,\n $this->parseOptions($options)\n );\n\n return $this;\n }\n\n protected function parseOptions(array $options): array\n {\n $mapper = function (string $content): array {\n $content = \\trim($content);\n if ('-' !== ($content[0] ?? '')) {\n $content = '-' . $content;\n }\n\n return \\explode(' ', $content, 2);\n };\n\n $reducer = fn (array $carry, array $option): array => \\array_merge($carry, $option);\n\n return \\array_reduce(\\array_map($mapper, $options), $reducer, []);\n }\n\n public function setTimeout(int $timeout): self\n {\n $this->timeout = $timeout;\n return $this;\n }\n\n public function text(): string\n {\n $process = new Process(\\array_merge([$this->findPdfToText()], $this->options, [$this->pdf, '-']));\n $process->setTimeout($this->timeout);\n $process->run();\n if (!$process->isSuccessful()) {\n throw new ProcessFailedException($process);\n }\n\n return \\trim($process->getOutput(), \" \\t\\n\\r\\0\\x0B\\x0C\");\n }\n\n /**\n * @throws \\Exception\n */\n public static function getText(\n string $filePath,\n array $options = []\n ): string {\n /** @phpstan-ignore new.static */\n $instance = new static();\n $instance->setPdf($filePath);\n\n if (\\array_key_exists('binPath', $options)) {\n $instance->setBinPath($options['binPath']);\n }\n\n if (\\array_key_exists('options', $options)) {\n $instance->setOptions($options['options']);\n }\n\n if (\\array_key_exists('timeout', $options)) {\n $instance->setTimeout($options['timeout']);\n }\n\n return $instance->text();\n }\n}\n"], ["/neuron-ai/src/Observability/HandleWorkflowEvents.php", "inspector->isRecording()) {\n return;\n }\n\n if ($this->inspector->needTransaction()) {\n $this->inspector->startTransaction($workflow::class)\n ->setType('neuron-workflow')\n ->addContext('List', [\n 'nodes' => \\array_keys($data->nodes),\n 'edges' => \\array_map(fn (Edge $edge): array => [\n 'from' => $edge->getFrom(),\n 'to' => $edge->getTo(),\n 'has_condition' => $edge->hasCondition(),\n ], $data->edges)\n ]);\n } elseif ($this->inspector->canAddSegments()) {\n $this->segments[$workflow::class] = $this->inspector->startSegment('neuron-workflow', $workflow::class)\n ->setColor(self::SEGMENT_COLOR);\n }\n }\n\n public function workflowEnd(\\SplSubject $workflow, string $event, WorkflowEnd $data): void\n {\n if (\\array_key_exists($workflow::class, $this->segments)) {\n $this->segments[$workflow::class]\n ->end()\n ->addContext('State', $data->state->all());\n } elseif ($this->inspector->canAddSegments()) {\n $transaction = $this->inspector->transaction();\n $transaction->addContext('State', $data->state->all());\n $transaction->setResult('success');\n }\n }\n\n public function workflowNodeStart(\\SplSubject $workflow, string $event, WorkflowNodeStart $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $segment = $this->inspector\n ->startSegment('workflow-node', $data->node)\n ->setColor(self::SEGMENT_COLOR);\n $segment->addContext('Before', $data->state->all());\n $this->segments[$data->node] = $segment;\n }\n\n public function workflowNodeEnd(\\SplSubject $workflow, string $event, WorkflowNodeEnd $data): void\n {\n if (\\array_key_exists($data->node, $this->segments)) {\n $segment = $this->segments[$data->node]->end();\n $segment->addContext('After', $data->state->all());\n }\n }\n}\n"], ["/neuron-ai/src/Workflow/WorkflowInterrupt.php", "data;\n }\n\n public function getCurrentNode(): string\n {\n return $this->currentNode;\n }\n\n public function getState(): WorkflowState\n {\n return $this->state;\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'data' => $this->data,\n 'currentNode' => $this->currentNode,\n 'state' => $this->state->all(),\n ];\n }\n}\n"], ["/neuron-ai/src/Workflow/Persistence/FilePersistence.php", "directory)) {\n throw new WorkflowException(\"Directory '{$this->directory}' does not exist\");\n }\n }\n\n public function save(string $workflowId, WorkflowInterrupt $interrupt): void\n {\n \\file_put_contents($this->getFilePath($workflowId), \\json_encode($interrupt));\n }\n\n public function load(string $workflowId): WorkflowInterrupt\n {\n if (!\\is_file($this->getFilePath($workflowId))) {\n throw new WorkflowException(\"No saved workflow found for ID: {$workflowId}.\");\n }\n\n $interrupt = \\json_decode(\\file_get_contents($this->getFilePath($workflowId)), true) ?? [];\n\n return new WorkflowInterrupt(\n $interrupt['data'],\n $interrupt['currentNode'],\n new WorkflowState($interrupt['state'])\n );\n }\n\n public function delete(string $workflowId): void\n {\n if (\\file_exists($this->getFilePath($workflowId))) {\n \\unlink($this->getFilePath($workflowId));\n }\n }\n\n protected function getFilePath(string $workflowId): string\n {\n return $this->directory.\\DIRECTORY_SEPARATOR.$this->prefix.$workflowId.$this->ext;\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/Usage.php", "inputTokens + $this->outputTokens;\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'input_tokens' => $this->inputTokens,\n 'output_tokens' => $this->outputTokens,\n ];\n }\n}\n"], ["/neuron-ai/src/Observability/HandleRagEvents.php", "inspector->canAddSegments()) {\n return;\n }\n\n $id = \\md5($data->question->getContent().$data->question->getRole());\n\n $this->segments[$id] = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-retrieval', \"vector_retrieval( {$data->question->getContent()} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function ragRetrieved(AgentInterface $agent, string $event, Retrieved $data): void\n {\n $id = \\md5($data->question->getContent().$data->question->getRole());\n\n if (\\array_key_exists($id, $this->segments)) {\n $segment = $this->segments[$id];\n $segment->addContext('Data', [\n 'question' => $data->question->getContent(),\n 'documents' => \\count($data->documents)\n ]);\n $segment->end();\n }\n }\n\n public function preProcessing(AgentInterface $agent, string $event, PreProcessing $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $segment = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-preprocessing', $data->processor)\n ->setColor(self::SEGMENT_COLOR);\n\n $segment->addContext('Original', $data->original->jsonSerialize());\n\n $this->segments[$data->processor] = $segment;\n }\n\n public function preProcessed(AgentInterface $agent, string $event, PreProcessed $data): void\n {\n if (\\array_key_exists($data->processor, $this->segments)) {\n $this->segments[$data->processor]\n ->end()\n ->addContext('Processed', $data->processed->jsonSerialize());\n }\n }\n\n public function postProcessing(AgentInterface $agent, string $event, PostProcessing $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $segment = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-postprocessing', $data->processor)\n ->setColor(self::SEGMENT_COLOR);\n\n $segment->addContext('Question', $data->question->jsonSerialize())\n ->addContext('Documents', $data->documents);\n\n $this->segments[$data->processor] = $segment;\n }\n\n public function postProcessed(AgentInterface $agent, string $event, PostProcessed $data): void\n {\n if (\\array_key_exists($data->processor, $this->segments)) {\n $this->segments[$data->processor]\n ->end()\n ->addContext('PostProcess', $data->documents);\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/MySQL/MySQLWriteTool.php", "pdo->prepare($query)->execute();\n\n return $result\n ? \"The query has been executed successfully.\"\n : \"I'm sorry, there was an error executing the query.\";\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/PGSQL/PGSQLWriteTool.php", "pdo->prepare($query)->execute();\n\n return $result\n ? \"The query has been executed successfully.\"\n : \"I'm sorry, there was an error executing the query.\";\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/DivideTool.php", " $this->name,\n 'error' => 'Division by zero is not allowed.'\n ];\n }\n\n return $number1 / $number2;\n }\n}\n"], ["/neuron-ai/src/RAG/Document.php", "id = \\uniqid();\n }\n\n public function getId(): string|int\n {\n return $this->id;\n }\n\n public function getContent(): string\n {\n return $this->content;\n }\n\n public function getEmbedding(): array\n {\n return $this->embedding;\n }\n\n public function getSourceType(): string\n {\n return $this->sourceType;\n }\n\n public function getSourceName(): string\n {\n return $this->sourceName;\n }\n\n public function getScore(): float\n {\n return $this->score;\n }\n\n public function setScore(float $score): Document\n {\n $this->score = $score;\n return $this;\n }\n\n public function addMetadata(string $key, string|int $value): Document\n {\n $this->metadata[$key] = $value;\n return $this;\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'id' => $this->getId(),\n 'content' => $this->getContent(),\n 'embedding' => $this->getEmbedding(),\n 'sourceType' => $this->getSourceType(),\n 'sourceName' => $this->getSourceName(),\n 'score' => $this->getScore(),\n 'metadata' => $this->metadata,\n ];\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Count.php", "exactly && null === $this->min && null === $this->max) {\n $this->min = $this->max = $this->exactly;\n }\n\n if (null === $this->min && null === $this->max) {\n throw new StructuredOutputException('Either option \"min\" or \"max\" must be given for validation rule \"Length\"');\n }\n\n if (\\is_null($value) && ($this->min > 0 || $this->exactly > 0)) {\n $violations[] = $this->buildMessage($name, '{name} cannot be empty');\n return;\n }\n\n if (!\\is_array($value) && !$value instanceof \\Countable) {\n throw new StructuredOutputException($name. ' must be an array or a Countable object');\n }\n\n\n $count = \\count($value);\n\n if (null !== $this->max && $count > $this->max) {\n $shouldExact = $this->min == $this->max;\n\n if ($shouldExact) {\n $violations[] = $this->buildMessage($name, '{name} must be exactly {exact} items long', ['exact' => $this->min]);\n } else {\n $violations[] = $this->buildMessage($name, '{name} is too long. It must be at most {max} items', ['max' => $this->max]);\n }\n }\n\n if (null !== $this->min && $count < $this->min) {\n $shouldExact = $this->min == $this->max;\n\n if ($shouldExact) {\n $violations[] = $this->buildMessage($name, '{name} must be exactly {exact} items long', ['exact' => $this->min]);\n } else {\n $violations[] = $this->buildMessage($name, '{name} is too short. It must be at least {min} items', ['min' => $this->min]);\n }\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Length.php", "exactly && null === $this->min && null === $this->max) {\n $this->min = $this->max = $this->exactly;\n }\n\n if (null === $this->min && null === $this->max) {\n throw new StructuredOutputException('Either option \"min\" or \"max\" must be given for validation rule \"Length\"');\n }\n\n if (\\is_null($value) && ($this->min > 0 || $this->exactly > 0)) {\n $violations[] = $this->buildMessage($name, '{name} cannot be empty');\n return;\n }\n\n if (!\\is_scalar($value) && !$value instanceof \\Stringable) {\n $violations[] = $this->buildMessage($name, '{name} must be a scalar or a stringable object');\n return;\n }\n\n $stringValue = (string) $value;\n\n $length = \\mb_strlen($stringValue);\n\n if (null !== $this->max && $length > $this->max) {\n $shouldExact = $this->min == $this->max;\n\n if ($shouldExact) {\n $violations[] = $this->buildMessage($name, '{name} must be exactly {exact} characters long', ['exact' => $this->min]);\n } else {\n $violations[] = $this->buildMessage($name, '{name} is too long. It must be at most {max} characters', ['max' => $this->max]);\n }\n }\n\n if (null !== $this->min && $length < $this->min) {\n $shouldExact = $this->min == $this->max;\n\n if ($shouldExact) {\n $violations[] = $this->buildMessage($name, '{name} must be exactly {exact} characters long', ['exact' => $this->min]);\n } else {\n $violations[] = $this->buildMessage($name, '{name} is too short. It must be at least {min} characters', ['min' => $this->min]);\n }\n }\n }\n}\n"], ["/neuron-ai/src/Providers/HandleWithTools.php", "\n */\n protected array $tools = [];\n\n public function setTools(array $tools): AIProviderInterface\n {\n $this->tools = $tools;\n return $this;\n }\n\n public function findTool(string $name): ToolInterface\n {\n foreach ($this->tools as $tool) {\n if ($tool->getName() === $name) {\n // We return a copy to allow multiple call to the same tool.\n return clone $tool;\n }\n }\n\n throw new ProviderException(\n \"It seems the model is asking for a non-existing tool: {$name}. You could try writing more verbose tool descriptions and prompts to help the model in the task.\"\n );\n }\n}\n"], ["/neuron-ai/src/Agent.php", "instructions = $instructions;\n return $this;\n }\n\n public function instructions(): string\n {\n return 'Your are a helpful and friendly AI agent built with NeuronAI PHP framework.';\n }\n\n public function resolveInstructions(): string\n {\n return $this->instructions ?? $this->instructions();\n }\n\n protected function removeDelimitedContent(string $text, string $openTag, string $closeTag): string\n {\n // Escape special regex characters in the tags\n $escapedOpenTag = \\preg_quote($openTag, '/');\n $escapedCloseTag = \\preg_quote($closeTag, '/');\n\n // Create the regex pattern to match content between tags\n $pattern = '/' . $escapedOpenTag . '.*?' . $escapedCloseTag . '/s';\n\n // Remove all occurrences of the delimited content\n return \\preg_replace($pattern, '', $text);\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/DoctrineVectorStore.php", "getConnection();\n $this->doctrineVectorStoreType = SupportedDoctrineVectorStore::fromPlatform($conn->getDatabasePlatform());\n $registeredTypes = Type::getTypesMap();\n if (!\\array_key_exists(VectorType::VECTOR, $registeredTypes)) {\n Type::addType(VectorType::VECTOR, VectorType::class);\n $conn->getDatabasePlatform()->registerDoctrineTypeMapping('vector', VectorType::VECTOR);\n }\n\n $this->doctrineVectorStoreType->addCustomisationsTo($this->entityManager);\n }\n\n public function addDocument(Document $document): void\n {\n if ($document->embedding === []) {\n throw new \\RuntimeException('document embedding must be set before adding a document');\n }\n\n $this->persistDocument($document);\n $this->entityManager->flush();\n }\n\n public function addDocuments(array $documents): void\n {\n if ($documents === []) {\n return;\n }\n foreach ($documents as $document) {\n $this->persistDocument($document);\n }\n\n $this->entityManager->flush();\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n throw new VectorStoreException(\"Delete by source not implemented in \".self::class);\n }\n\n public function similaritySearch(array $embedding): array\n {\n $repository = $this->entityManager->getRepository($this->entityClassName);\n\n $qb = $repository\n ->createQueryBuilder('e')\n ->orderBy($this->doctrineVectorStoreType->l2DistanceName().'(e.embedding, :embeddingString)', 'ASC')\n ->setParameter('embeddingString', $this->doctrineVectorStoreType->getVectorAsString($embedding))\n ->setMaxResults($this->topK);\n\n foreach ($this->filters as $key => $value) {\n $paramName = 'where_'.$key;\n $qb->andWhere(\\sprintf('e.%s = :%s', $key, $paramName))\n ->setParameter($paramName, $value);\n }\n\n /** @var DoctrineEmbeddingEntityBase[] */\n return $qb->getQuery()->getResult();\n }\n\n private function persistDocument(Document $document): void\n {\n if ($document->embedding === []) {\n throw new \\RuntimeException('Trying to save a document in a vectorStore without embedding');\n }\n\n if (!$document instanceof DoctrineEmbeddingEntityBase) {\n throw new \\RuntimeException('Document needs to be an instance of DoctrineEmbeddingEntityBase');\n }\n\n $this->entityManager->persist($document);\n }\n\n /**\n * @return iterable\n */\n public function fetchDocumentsByChunkRange(string $sourceType, string $sourceName, int $leftIndex, int $rightIndex): iterable\n {\n $repository = $this->entityManager->getRepository($this->entityClassName);\n\n $query = $repository->createQueryBuilder('d')\n ->andWhere('d.sourceType = :sourceType')\n ->andWhere('d.sourceName = :sourceName')\n ->andWhere('d.chunkNumber >= :lower')\n ->andWhere('d.chunkNumber <= :upper')\n ->setParameter('sourceType', $sourceType)\n ->setParameter('sourceName', $sourceName)\n ->setParameter('lower', $leftIndex)\n ->setParameter('upper', $rightIndex)\n ->getQuery();\n\n return $query->toIterable();\n }\n\n public function withFilters(array $filters): VectorStoreInterface\n {\n $this->filters = $filters;\n return $this;\n }\n}\n"], ["/neuron-ai/src/RAG/DataLoader/FileDataLoader.php", "\n */\n protected array $readers = [];\n\n public function __construct(protected string $path, array $readers = [])\n {\n parent::__construct();\n $this->setReaders($readers);\n }\n\n public function addReader(string $fileExtension, ReaderInterface $reader): self\n {\n $this->readers[$fileExtension] = $reader;\n return $this;\n }\n\n public function setReaders(array $readers): self\n {\n $this->readers = $readers;\n return $this;\n }\n\n public function getDocuments(): array\n {\n if (! \\file_exists($this->path)) {\n return [];\n }\n\n // If it's a directory\n if (\\is_dir($this->path)) {\n return $this->getDocumentsFromDirectory($this->path);\n }\n\n // If it's a file\n try {\n return $this->splitter->splitDocument($this->getDocument($this->getContentFromFile($this->path), $this->path));\n } catch (\\Throwable) {\n return [];\n }\n }\n\n protected function getDocumentsFromDirectory(string $directory): array\n {\n $documents = [];\n // Open the directory\n if ($handle = \\opendir($directory)) {\n // Read the directory contents\n while (($entry = \\readdir($handle)) !== false) {\n $fullPath = $directory.'/'.$entry;\n if ($entry !== '.' && $entry !== '..') {\n if (\\is_dir($fullPath)) {\n $documents = [...$documents, ...$this->getDocumentsFromDirectory($fullPath)];\n } else {\n try {\n $documents[] = $this->getDocument($this->getContentFromFile($fullPath), $entry);\n } catch (\\Throwable) {\n }\n }\n }\n }\n\n // Close the directory\n \\closedir($handle);\n }\n\n return $this->splitter->splitDocuments($documents);\n }\n\n /**\n * Transform files to plain text.\n *\n * Supported PDF and plain text files.\n *\n * @throws \\Exception\n */\n protected function getContentFromFile(string $path): string|false\n {\n $fileExtension = \\strtolower(\\pathinfo($path, \\PATHINFO_EXTENSION));\n\n if (\\array_key_exists($fileExtension, $this->readers)) {\n $reader = $this->readers[$fileExtension];\n return $reader::getText($path);\n }\n\n return TextFileReader::getText($path);\n }\n\n\n protected function getDocument(string $content, string $entry): Document\n {\n $document = new Document($content);\n $document->sourceType = 'files';\n $document->sourceName = $entry;\n\n return $document;\n }\n}\n"], ["/neuron-ai/src/Providers/AIProviderInterface.php", " 'Factorial is not defined for negative numbers.'];\n }\n\n // Handle edge cases\n if ($number === 0 || $number === 1) {\n return 1;\n }\n\n // For larger numbers, use BCMath to handle arbitrary precision\n if ($number > 20) {\n return self::calculateWithBCMath($number);\n }\n\n // For smaller numbers, use regular integer calculation\n $result = 1;\n for ($i = 2; $i <= $number; $i++) {\n $result *= $i;\n }\n\n return $result;\n }\n\n /**\n * Calculate factorial using BCMath for large numbers\n */\n private function calculateWithBCMath(int $number): float\n {\n $result = '1';\n\n for ($i = 2; $i <= $number; $i++) {\n $result = \\bcmul($result, (string)$i);\n }\n\n return (float)$result;\n }\n}\n"], ["/neuron-ai/src/Observability/Observable.php", "\n */\n private array $observers = [];\n\n\n private function initEventGroup(string $event = '*'): void\n {\n /*\n * If developers attach an observer, the agent monitoring will not be attached by default.\n */\n if (!isset($this->observers['*']) && !empty($_ENV['INSPECTOR_INGESTION_KEY'])) {\n $this->observers['*'] = [\n AgentMonitoring::instance(),\n ];\n }\n\n if (!isset($this->observers[$event])) {\n $this->observers[$event] = [];\n }\n }\n\n private function getEventObservers(string $event = \"*\"): array\n {\n $this->initEventGroup($event);\n $group = $this->observers[$event];\n $all = $this->observers[\"*\"] ?? [];\n\n return \\array_merge($group, $all);\n }\n\n public function observe(SplObserver $observer, string $event = \"*\"): self\n {\n $this->attach($observer, $event);\n return $this;\n }\n\n public function attach(SplObserver $observer, string $event = \"*\"): void\n {\n $this->initEventGroup($event);\n $this->observers[$event][] = $observer;\n }\n\n public function detach(SplObserver $observer, string $event = \"*\"): void\n {\n foreach ($this->getEventObservers($event) as $key => $s) {\n if ($s === $observer) {\n unset($this->observers[$event][$key]);\n }\n }\n }\n\n public function notify(string $event = \"*\", mixed $data = null): void\n {\n // Broadcasting the '$event' event\";\n foreach ($this->getEventObservers($event) as $observer) {\n $observer->update($this, $event, $data);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Enum.php", "values !== null && $this->values !== [] && $this->class !== null) {\n throw new StructuredOutputException('You cannot provide both \"choices\" and \"enum\" options simultaneously. Please use only one.');\n }\n\n if (($this->values === null || $this->values === []) && $this->class === null) {\n throw new StructuredOutputException('Either option \"choices\" or \"enum\" must be given for validation rule \"Enum\"');\n }\n\n if ($this->values === null || $this->values === []) {\n $this->handleEnum();\n }\n }\n\n public function validate(string $name, mixed $value, array &$violations): void\n {\n $value = $value instanceof \\BackedEnum ? $value->value : $value;\n\n if (!\\in_array($value, $this->values, true)) {\n $violations[] = $this->buildMessage($name, $this->message, ['choices' => \\implode(\", \", $this->values)]);\n }\n }\n\n /**\n * @throws StructuredOutputException\n */\n private function handleEnum(): void\n {\n if (!\\enum_exists($this->class)) {\n throw new StructuredOutputException(\"Enum '{$this->class}' does not exist.\");\n }\n\n if (!\\is_subclass_of($this->class, \\BackedEnum::class)) {\n throw new StructuredOutputException(\"Enum '{$this->class}' must implement BackedEnum.\");\n }\n\n $this->values = \\array_map(fn (\\BackedEnum $case): int|string => $case->value, $this->class::cases());\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/AdaptiveThresholdPostProcessor.php", "1.0: Not recommended as it tends to include almost all documents.\n *\n * @param float $multiplier multiplier for MAD (higher values = more inclusive)\n */\n public function __construct(private readonly float $multiplier = 0.6)\n {\n }\n\n /**\n * Filters documents using a threshold calculated dynamically with median and MAD\n * for greater robustness against outliers.\n */\n public function process(Message $question, array $documents): array\n {\n if (\\count($documents) < 2) {\n return $documents;\n }\n\n $scores = \\array_map(fn (Document $document): float => $document->getScore(), $documents);\n $median = $this->calculateMedian($scores);\n $mad = $this->calculateMAD($scores, $median);\n\n // If MAD is zero (many equal values), don't filter\n if ($mad <= 0.0001) {\n return $documents;\n }\n\n // Threshold: median - multiplier * MAD\n $threshold = $median - ($this->multiplier * $mad);\n\n // Ensure a threshold is not negative\n $threshold = \\max(0, $threshold);\n\n return \\array_values(\\array_filter($documents, fn (Document $document): bool => $document->getScore() >= $threshold));\n }\n\n /**\n * Calculates the median of an array of values\n *\n * @param float[] $values\n */\n protected function calculateMedian(array $values): float\n {\n \\sort($values);\n $n = \\count($values);\n $mid = (int) \\floor(($n - 1) / 2);\n\n if ($n % 2 !== 0) {\n return $values[$mid];\n }\n\n return ($values[$mid] + $values[$mid + 1]) / 2.0;\n }\n\n /**\n * Calculates the Median Absolute Deviation (MAD)\n *\n * @param float[] $values\n * @param float $median The median of the values\n */\n protected function calculateMAD(array $values, float $median): float\n {\n $deviations = \\array_map(fn (float$v): float => \\abs($v - $median), $values);\n\n // MAD is the median of deviations\n return $this->calculateMedian($deviations);\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/MemoryVectorStore.php", "documents[] = $document;\n }\n\n public function addDocuments(array $documents): void\n {\n $this->documents = \\array_merge($this->documents, $documents);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->documents = \\array_filter($this->documents, fn (Document $document): bool => $document->getSourceType() !== $sourceType || $document->getSourceName() !== $sourceName);\n }\n\n public function similaritySearch(array $embedding): array\n {\n $distances = [];\n\n foreach ($this->documents as $index => $document) {\n if ($document->embedding === []) {\n throw new VectorStoreException(\"Document with the following content has no embedding: {$document->getContent()}\");\n }\n $dist = VectorSimilarity::cosineDistance($embedding, $document->getEmbedding());\n $distances[$index] = $dist;\n }\n\n \\asort($distances); // Sort by distance (ascending).\n\n $topKIndices = \\array_slice(\\array_keys($distances), 0, $this->topK, true);\n\n return \\array_reduce($topKIndices, function (array $carry, int $index) use ($distances): array {\n $document = $this->documents[$index];\n $document->setScore(VectorSimilarity::similarityFromDistance($distances[$index]));\n $carry[] = $document;\n return $carry;\n }, []);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/SquareRootTool.php", "exporter = new MermaidExporter();\n\n if (\\is_null($persistence) && !\\is_null($workflowId)) {\n throw new WorkflowException('Persistence must be defined when workflowId is defined');\n }\n if (\\is_null($workflowId) && !\\is_null($persistence)) {\n throw new WorkflowException('WorkflowId must be defined when persistence is defined');\n }\n\n $this->persistence = $persistence ?? new InMemoryPersistence();\n $this->workflowId = $workflowId ?? \\uniqid('neuron_workflow_');\n }\n\n public function validate(): void\n {\n /*if ($this->getStartNode() === null) {\n throw new WorkflowException('Start node must be defined');\n }\n\n if ($this->getEndNode() === null) {\n throw new WorkflowException('End node must be defined');\n }*/\n\n if (!isset($this->getNodes()[$this->getStartNode()])) {\n throw new WorkflowException(\"Start node {$this->getStartNode()} does not exist\");\n }\n\n foreach ($this->getEndNodes() as $endNode) {\n if (!isset($this->getNodes()[$endNode])) {\n throw new WorkflowException(\"End node {$endNode} does not exist\");\n }\n }\n\n foreach ($this->getEdges() as $edge) {\n if (!isset($this->getNodes()[$edge->getFrom()])) {\n throw new WorkflowException(\"Edge from node {$edge->getFrom()} does not exist\");\n }\n\n if (!isset($this->getNodes()[$edge->getTo()])) {\n throw new WorkflowException(\"Edge to node {$edge->getTo()} does not exist\");\n }\n }\n }\n\n /**\n * @throws WorkflowInterrupt|WorkflowException|\\Throwable\n */\n protected function execute(\n string $currentNode,\n WorkflowState $state,\n bool $resuming = false,\n array|string|int $humanFeedback = []\n ): WorkflowState {\n $context = new WorkflowContext(\n $this->workflowId,\n $currentNode,\n $this->persistence,\n $state\n );\n\n if ($resuming) {\n $context->setResuming(true, [$currentNode => $humanFeedback]);\n }\n\n try {\n while (!\\in_array($currentNode, $this->getEndNodes())) {\n $node = $this->nodes[$currentNode];\n $node->setContext($context);\n\n $this->notify('workflow-node-start', new WorkflowNodeStart($currentNode, $state));\n try {\n $state = $node->run($state);\n } catch (WorkflowInterrupt $interrupt) {\n throw $interrupt;\n } catch (\\Throwable $exception) {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n $this->notify('workflow-node-end', new WorkflowNodeEnd($currentNode, $state));\n\n $nextNode = $this->findNextNode($currentNode, $state);\n\n if ($nextNode === null) {\n throw new WorkflowException(\"No valid edge found from node {$currentNode}\");\n }\n\n $currentNode = $nextNode;\n\n // Update the context before the next iteration or end node\n $context = new WorkflowContext(\n $this->workflowId,\n $currentNode,\n $this->persistence,\n $state\n );\n }\n\n $endNode = $this->nodes[$currentNode];\n $endNode->setContext($context);\n $result = $endNode->run($state);\n $this->persistence->delete($this->workflowId);\n return $result;\n\n } catch (WorkflowInterrupt $interrupt) {\n $this->persistence->save($this->workflowId, $interrupt);\n $this->notify('workflow-interrupt', $interrupt);\n throw $interrupt;\n }\n }\n\n /**\n * @throws WorkflowInterrupt|WorkflowException|\\Throwable\n */\n public function run(?WorkflowState $initialState = null): WorkflowState\n {\n $this->notify('workflow-start', new WorkflowStart($this->getNodes(), $this->getEdges()));\n try {\n $this->validate();\n } catch (WorkflowException $exception) {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n\n $state = $initialState ?? new WorkflowState();\n $currentNode = $this->getStartNode();\n\n $result = $this->execute($currentNode, $state);\n $this->notify('workflow-end', new WorkflowEnd($result));\n\n return $result;\n }\n\n /**\n * @throws WorkflowInterrupt|WorkflowException|\\Throwable\n */\n public function resume(array|string|int $humanFeedback): WorkflowState\n {\n $this->notify('workflow-resume', new WorkflowStart($this->getNodes(), $this->getEdges()));\n $interrupt = $this->persistence->load($this->workflowId);\n\n $state = $interrupt->getState();\n $currentNode = $interrupt->getCurrentNode();\n\n $result = $this->execute(\n $currentNode,\n $state,\n true,\n $humanFeedback\n );\n $this->notify('workflow-end', new WorkflowEnd($result));\n\n return $result;\n }\n\n /**\n * @return Node[]\n */\n protected function nodes(): array\n {\n return [];\n }\n\n /**\n * @return Edge[]\n */\n protected function edges(): array\n {\n return [];\n }\n\n public function addNode(NodeInterface $node): self\n {\n $this->nodes[$node::class] = $node;\n return $this;\n }\n\n /**\n * @param NodeInterface[] $nodes\n */\n public function addNodes(array $nodes): Workflow\n {\n foreach ($nodes as $node) {\n $this->addNode($node);\n }\n return $this;\n }\n\n /**\n * @return array\n */\n public function getNodes(): array\n {\n if ($this->nodes === []) {\n foreach ($this->nodes() as $node) {\n $this->addNode($node);\n }\n }\n\n return $this->nodes;\n }\n\n public function addEdge(Edge $edge): self\n {\n $this->edges[] = $edge;\n return $this;\n }\n\n /**\n * @param Edge[] $edges\n */\n public function addEdges(array $edges): Workflow\n {\n foreach ($edges as $edge) {\n $this->addEdge($edge);\n }\n return $this;\n }\n\n /**\n * @return Edge[]\n */\n public function getEdges(): array\n {\n if ($this->edges === []) {\n $this->edges = $this->edges();\n }\n\n return $this->edges;\n }\n\n public function setStart(string $nodeClass): Workflow\n {\n $this->startNode = $nodeClass;\n return $this;\n }\n\n public function setEnd(string $nodeClass): Workflow\n {\n $this->endNodes[] = $nodeClass;\n return $this;\n }\n\n protected function getStartNode(): string\n {\n return $this->startNode ?? $this->start();\n }\n\n protected function getEndNodes(): array\n {\n return $this->endNodes ?? $this->end();\n }\n\n protected function start(): ?string\n {\n throw new WorkflowException('Start node must be defined');\n }\n\n protected function end(): array\n {\n throw new WorkflowException('End node must be defined');\n }\n\n private function findNextNode(string $currentNode, WorkflowState $state): ?string\n {\n foreach ($this->getEdges() as $edge) {\n if ($edge->getFrom() === $currentNode && $edge->shouldExecute($state)) {\n return $edge->getTo();\n }\n }\n\n return null;\n }\n\n public function getWorkflowId(): string\n {\n return $this->workflowId;\n }\n\n public function export(): string\n {\n return $this->exporter->export($this);\n }\n\n public function setExporter(ExporterInterface $exporter): Workflow\n {\n $this->exporter = $exporter;\n return $this;\n }\n}\n"], ["/neuron-ai/src/AgentInterface.php", "getEdges() as $edge) {\n $from = $this->getShortClassName($edge->getFrom());\n $to = $this->getShortClassName($edge->getTo());\n\n $output .= \" {$from} --> {$to}\\n\";\n }\n\n return $output;\n }\n\n private function getShortClassName(string $class): string\n {\n $reflection = new ReflectionClass($class);\n return $reflection->getShortName();\n }\n}\n"], ["/neuron-ai/src/RAG/Splitter/SentenceTextSplitter.php", "= $maxWords) {\n throw new InvalidArgumentException('Overlap must be less than maxWords');\n }\n\n $this->maxWords = $maxWords;\n $this->overlapWords = $overlapWords;\n }\n\n /**\n * Splits text into word-based chunks, preserving sentence boundaries.\n *\n * @return Document[] Array of Document chunks\n */\n public function splitDocument(Document $document): array\n {\n // Split by paragraphs (2 or more newlines)\n $paragraphs = \\preg_split('/\\n{2,}/', $document->getContent());\n $chunks = [];\n $currentWords = [];\n\n foreach ($paragraphs as $paragraph) {\n $sentences = $this->splitSentences($paragraph);\n\n foreach ($sentences as $sentence) {\n $sentenceWords = $this->tokenizeWords($sentence);\n\n // If the sentence alone exceeds the limit, split it\n if (\\count($sentenceWords) > $this->maxWords) {\n if ($currentWords !== []) {\n $chunks[] = \\implode(' ', $currentWords);\n $currentWords = [];\n }\n $chunks = \\array_merge($chunks, $this->splitLongSentence($sentenceWords));\n continue;\n }\n\n $candidateCount = \\count($currentWords) + \\count($sentenceWords);\n\n if ($candidateCount > $this->maxWords) {\n if ($currentWords !== []) {\n $chunks[] = \\implode(' ', $currentWords);\n }\n $currentWords = $sentenceWords;\n } else {\n $currentWords = \\array_merge($currentWords, $sentenceWords);\n }\n }\n }\n\n if ($currentWords !== []) {\n $chunks[] = \\implode(' ', $currentWords);\n }\n\n // Apply overlap only if necessary\n if ($this->overlapWords > 0) {\n $chunks = $this->applyOverlap($chunks);\n }\n\n $split = [];\n foreach ($chunks as $chunk) {\n $newDocument = new Document($chunk);\n $newDocument->sourceType = $document->getSourceType();\n $newDocument->sourceName = $document->getSourceName();\n $split[] = $newDocument;\n }\n\n return $split;\n }\n\n /**\n * Robust regex for sentence splitting (handles ., !, ?, …, periods followed by quotes, etc)\n */\n private function splitSentences(string $text): array\n {\n $pattern = '/(?<=[.!?…])\\s+(?=(?:[\\\"\\'\\\"\"\\'\\'«»„\"\"]?)[A-ZÀ-Ÿ])/u';\n $sentences = \\preg_split($pattern, \\trim($text));\n return \\array_filter(\\array_map('trim', $sentences));\n }\n\n /**\n * Tokenizes text into words (simple whitespace split).\n *\n * @return string[] Array of words\n */\n private function tokenizeWords(string $text): array\n {\n return \\preg_split('/\\s+/u', \\trim($text));\n }\n\n /**\n * Applies overlap of words between consecutive chunks.\n *\n * @param string[] $chunks\n * @return string[] Array of chunks with overlap applied\n */\n private function applyOverlap(array $chunks): array\n {\n if ($chunks === []) {\n return [];\n }\n\n $result = [$chunks[0]]; // First chunk remains unchanged\n $count = \\count($chunks);\n\n for ($i = 1; $i < $count; $i++) {\n $prevWords = $this->tokenizeWords($chunks[$i - 1]);\n $curWords = $this->tokenizeWords($chunks[$i]);\n\n // Get only the words needed for overlap\n $overlap = \\array_slice($prevWords, -$this->overlapWords);\n\n // Remove duplicate words at the beginning of current chunk\n $curWords = \\array_slice($curWords, $this->overlapWords);\n\n $merged = \\array_merge($overlap, $curWords);\n $result[] = \\implode(' ', $merged);\n }\n\n return $result;\n }\n\n /**\n * Splits a long sentence into smaller chunks that respect the maxWords limit.\n *\n * @param string[] $words Array of words from the sentence\n * @return string[] Array of chunks\n */\n private function splitLongSentence(array $words): array\n {\n $chunks = [];\n $currentChunk = [];\n\n foreach ($words as $word) {\n if (\\count($currentChunk) >= $this->maxWords) {\n $chunks[] = \\implode(' ', $currentChunk);\n $currentChunk = [];\n }\n $currentChunk[] = $word;\n }\n\n if ($currentChunk !== []) {\n $chunks[] = \\implode(' ', $currentChunk);\n }\n\n return $chunks;\n }\n}\n"], ["/neuron-ai/src/Observability/HandleToolEvents.php", "inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$agent::class.'_tools_bootstrap'] = $this->inspector\n ->startSegment(\n self::SEGMENT_TYPE.'-tools',\n \"tools_bootstrap()\"\n )\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function toolsBootstrapped(AgentInterface $agent, string $event, ToolsBootstrapped $data): void\n {\n if (\\array_key_exists($agent::class.'_tools_bootstrap', $this->segments) && $data->tools !== []) {\n $segment = $this->segments[$agent::class.'_tools_bootstrap']->end();\n $segment->addContext('Tools', \\array_reduce($data->tools, function (array $carry, ToolInterface $tool): array {\n $carry[$tool->getName()] = $tool->getDescription();\n return $carry;\n }, []));\n $segment->addContext('Guidelines', $data->guidelines);\n }\n }\n\n public function toolCalling(AgentInterface $agent, string $event, ToolCalling $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$data->tool->getName()] = $this->inspector\n ->startSegment(\n self::SEGMENT_TYPE.'-tools',\n \"tool_call( {$data->tool->getName()} )\"\n )\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function toolCalled(AgentInterface $agent, string $event, ToolCalled $data): void\n {\n if (\\array_key_exists($data->tool->getName(), $this->segments)) {\n $this->segments[$data->tool->getName()]\n ->end()\n ->addContext('Properties', $data->tool->getProperties())\n ->addContext('Inputs', $data->tool->getInputs())\n ->addContext('Output', $data->tool->getResult());\n }\n }\n}\n"], ["/neuron-ai/src/RAG/Splitter/DelimiterTextSplitter.php", "getContent();\n\n if ($text === '') {\n return [];\n }\n\n if (\\strlen($text) <= $this->maxLength) {\n return [$document];\n }\n\n $parts = \\explode($this->separator, $text);\n\n $chunks = $this->createChunksWithOverlap($parts);\n\n $split = [];\n foreach ($chunks as $chunk) {\n $newDocument = new Document($chunk);\n $newDocument->sourceType = $document->getSourceType();\n $newDocument->sourceName = $document->getSourceName();\n $split[] = $newDocument;\n }\n\n return $split;\n }\n\n /**\n * @param array $words\n * @return array\n */\n private function createChunksWithOverlap(array $words): array\n {\n $chunks = [];\n $currentChunk = [];\n $currentChunkLength = 0;\n foreach ($words as $word) {\n if ($word === '') {\n continue;\n }\n\n if ($currentChunkLength + \\strlen($this->separator.$word) <= $this->maxLength || $currentChunk === []) {\n $currentChunk[] = $word;\n $currentChunkLength = $this->calculateChunkLength($currentChunk);\n } else {\n // Add the chunk with overlap\n $chunks[] = \\implode($this->separator, $currentChunk);\n\n // Calculate overlap words\n $calculatedOverlap = \\min($this->wordOverlap, \\count($currentChunk) - 1);\n $overlapWords = $calculatedOverlap > 0 ? \\array_slice($currentChunk, -$calculatedOverlap) : [];\n\n // Start a new chunk with overlap words\n $currentChunk = [...$overlapWords, $word];\n $currentChunk[0] = \\trim($currentChunk[0]);\n $currentChunkLength = $this->calculateChunkLength($currentChunk);\n }\n }\n\n if ($currentChunk !== []) {\n $chunks[] = \\implode($this->separator, $currentChunk);\n }\n\n return $chunks;\n }\n\n /**\n * @param array $chunk\n */\n private function calculateChunkLength(array $chunk): int\n {\n return \\array_sum(\\array_map('strlen', $chunk)) + \\count($chunk) * \\strlen($this->separator) - 1;\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/FixedThresholdPostProcessor.php", " $document->getScore() >= $this->threshold));\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Json.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/NotBlank.php", "allowNull && $value === null) {\n return;\n }\n\n if (false === $value || (empty($value) && '0' != $value)) {\n $violations[] = $this->buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/NthRootTool.php", "exclude = $classes;\n return $this;\n }\n\n /**\n * @param class-string[] $classes\n */\n public function only(array $classes): ToolkitInterface\n {\n $this->only = $classes;\n return $this;\n }\n\n /**\n * @return ToolInterface[]\n */\n abstract public function provide(): array;\n\n public function tools(): array\n {\n if ($this->exclude === [] && $this->only === []) {\n return $this->provide();\n }\n\n return \\array_filter(\n $this->provide(),\n fn (ToolInterface $tool): bool => !\\in_array($tool::class, $this->exclude)\n && ($this->only === [] || \\in_array($tool::class, $this->only))\n );\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/SumTool.php", "getVectorAsString($value);\n }\n\n public function convertToDatabaseValueSQL(mixed $sqlExpression, AbstractPlatform $platform): string\n {\n return SupportedDoctrineVectorStore::fromPlatform($platform)->convertToDatabaseValueSQL($sqlExpression);\n }\n\n public function canRequireSQLConversion(): bool\n {\n return true;\n }\n\n public function getName(): string\n {\n return self::VECTOR;\n }\n}\n"], ["/neuron-ai/src/Workflow/WorkflowContext.php", "isResuming && isset($this->feedback[$this->currentNode])) {\n return $this->feedback[$this->currentNode];\n }\n\n throw new WorkflowInterrupt($data, $this->currentNode, $this->currentState);\n }\n\n public function setResuming(bool $resuming, array $feedback = []): void\n {\n $this->isResuming = $resuming;\n $this->feedback = $feedback;\n }\n\n public function setCurrentState(WorkflowState $state): WorkflowContext\n {\n $this->currentState = $state;\n return $this;\n }\n\n public function setCurrentNode(string $node): WorkflowContext\n {\n $this->currentNode = $node;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Tools/PropertyType.php", "key, $this->user_id),\n ZepAddToGraphTool::make($this->key, $this->user_id),\n ];\n }\n}\n"], ["/neuron-ai/src/RAG/DataLoader/AbstractDataLoader.php", "splitter = new DelimiterTextSplitter(\n maxLength: 1000,\n separator: '.',\n wordOverlap: 0\n );\n }\n\n public static function for(...$arguments): static\n {\n /** @phpstan-ignore new.static */\n return new static(...$arguments);\n }\n\n public function withSplitter(SplitterInterface $splitter): DataLoaderInterface\n {\n $this->splitter = $splitter;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/MultiplyTool.php", "reference) || $value <= $this->reference) {\n $violations[] = $this->buildMessage($name, 'must be greater than {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/GreaterThanEqual.php", "reference) || $value < $this->reference) {\n $violations[] = $this->buildMessage($name, 'must be greater than {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/SubtractTool.php", "= $this->reference) {\n $violations[] = $this->buildMessage($name, 'must be greater than {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/EqualTo.php", "reference) {\n $violations[] = $this->buildMessage($name, 'must be equal to {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/LowerThanEqual.php", " $this->reference) {\n $violations[] = $this->buildMessage($name, 'must be greater than {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/NotEqualTo.php", "reference) {\n $violations[] = $this->buildMessage($name, 'must not be equal to {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/SupportedDoctrineVectorStore.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Email.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IPAddress.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/Observability/Events/InferenceStop.php", "pdo),\n MySQLSelectTool::make($this->pdo),\n MySQLWriteTool::make($this->pdo),\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/PGSQL/PGSQLToolkit.php", "pdo),\n PGSQLSelectTool::make($this->pdo),\n PGSQLWriteTool::make($this->pdo),\n ];\n }\n}\n"], ["/neuron-ai/src/Workflow/WorkflowState.php", "data[$key] = $value;\n }\n\n public function get(string $key, mixed $default = null): mixed\n {\n return $this->data[$key] ?? $default;\n }\n\n public function has(string $key): bool\n {\n return \\array_key_exists($key, $this->data);\n }\n\n /**\n * Missing keys in the state are simply ignored.\n *\n * @param string[] $keys\n */\n public function only(array $keys): array\n {\n return \\array_intersect_key($this->data, \\array_flip($keys));\n }\n\n public function all(): array\n {\n return $this->data;\n }\n}\n"], ["/neuron-ai/src/Providers/MessageMapperInterface.php", " $messages\n */\n public function map(array $messages): array;\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Validator.php", "getProperties(\\ReflectionProperty::IS_PUBLIC) as $property) {\n // Get all attributes for this property\n $attributes = $property->getAttributes();\n\n if (empty($attributes)) {\n continue;\n }\n\n // Get the value of the property\n $name = $property->getName();\n $value = $property->isInitialized($obj) ? $property->getValue($obj) : null;\n\n // Apply all the validation rules to the value\n foreach ($attributes as $attribute) {\n $instance = $attribute->newInstance();\n\n // Perform validation\n if ($instance instanceof ValidationRuleInterface) {\n $instance->validate($name, $value, $violations);\n }\n }\n }\n\n return $violations;\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IsTrue.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IsFalse.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IsNull.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IsNotNull.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/Workflow/Edge.php", "from;\n }\n\n public function getTo(): string\n {\n return $this->to;\n }\n\n public function hasCondition(): bool\n {\n return $this->condition instanceof \\Closure;\n }\n\n public function shouldExecute(WorkflowState $state): bool\n {\n return $this->hasCondition() ? ($this->condition)($state) : true;\n }\n}\n"], ["/neuron-ai/src/Chat/History/InMemoryChatHistory.php", "splitDocument($document));\n }\n\n return $split;\n }\n}\n"], ["/neuron-ai/src/ResolveProvider.php", "provider = $provider;\n return $this;\n }\n\n public function setAiProvider(AIProviderInterface $provider): AgentInterface\n {\n $this->provider = $provider;\n return $this;\n }\n\n protected function provider(): AIProviderInterface\n {\n return $this->provider;\n }\n\n /**\n * Get the current instance of the chat history.\n */\n public function resolveProvider(): AIProviderInterface\n {\n if (!isset($this->provider)) {\n $this->provider = $this->provider();\n }\n\n return $this->provider;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/DoctrineEmbeddingEntityBase.php", "id;\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/AbstractEmbeddingsProvider.php", " $document) {\n $documents[$index] = $this->embedDocument($document);\n }\n\n return $documents;\n }\n\n public function embedDocument(Document $document): Document\n {\n $text = $document->formattedContent ?? $document->content;\n $document->embedding = $this->embedText($text);\n\n return $document;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Tavily/TavilyToolkit.php", "\n */\n public function provide(): array\n {\n return [\n new TavilyExtractTool($this->key),\n new TavilySearchTool($this->key),\n new TavilyCrawlTool($this->key)\n ];\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/MariaDBVectorStoreType.php", "stringListOf($vector).']';\n }\n\n public function convertToDatabaseValueSQL(string $sqlExpression): string\n {\n return \\sprintf('Vec_FromText(%s)', $sqlExpression);\n }\n\n public function addCustomisationsTo(EntityManagerInterface $entityManager): void\n {\n $entityManager->getConfiguration()->addCustomStringFunction($this->l2DistanceName(), MariaDBVectorL2OperatorDql::class);\n }\n\n public function l2DistanceName(): string\n {\n return 'VEC_DISTANCE_EUCLIDEAN';\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/PostgresqlVectorL2OperatorDql.php", "vectorOne->dispatch($sqlWalker).', '.\n $this->vectorTwo->dispatch($sqlWalker).\n ')';\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/MariaDBVectorL2OperatorDql.php", "vectorOne->dispatch($sqlWalker).', '.\n 'VEC_FROMTEXT('.\n $this->vectorTwo->dispatch($sqlWalker).\n ')'.\n ')';\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Riza/RizaToolkit.php", "\n */\n public function provide(): array\n {\n return [\n new RizaCodeInterpreter($this->key),\n new RizaFunctionExecutor($this->key),\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Jina/JinaToolkit.php", "\n */\n public function provide(): array\n {\n return [\n new JinaWebSearch($this->key),\n new JinaUrlReader($this->key),\n ];\n }\n}\n"], ["/neuron-ai/src/Chat/Attachments/Document.php", "stringListOf($vector).']';\n }\n\n public function convertToDatabaseValueSQL(string $sqlExpression): string\n {\n return $sqlExpression;\n }\n\n public function addCustomisationsTo(EntityManagerInterface $entityManager): void\n {\n $entityManager->getConfiguration()->addCustomStringFunction($this->l2DistanceName(), PostgresqlVectorL2OperatorDql::class);\n }\n\n public function l2DistanceName(): string\n {\n return 'VEC_DISTANCE_EUCLIDEAN';\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/AbstractDBL2OperatorDql.php", "match(\\Doctrine\\ORM\\Query\\TokenType::T_IDENTIFIER);\n $parser->match(\\Doctrine\\ORM\\Query\\TokenType::T_OPEN_PARENTHESIS);\n } else {\n $parser->match(\\Doctrine\\ORM\\Query\\Lexer::T_IDENTIFIER);\n $parser->match(\\Doctrine\\ORM\\Query\\Lexer::T_OPEN_PARENTHESIS);\n }\n\n $this->vectorOne = $parser->ArithmeticFactor(); // Fix that, should be vector\n\n if (\\class_exists(\\Doctrine\\ORM\\Query\\TokenType::class)) {\n $parser->match(\\Doctrine\\ORM\\Query\\TokenType::T_COMMA);\n } else {\n $parser->match(\\Doctrine\\ORM\\Query\\Lexer::T_COMMA);\n }\n\n $this->vectorTwo = $parser->ArithmeticFactor(); // Fix that, should be vector\n\n if (\\class_exists(\\Doctrine\\ORM\\Query\\TokenType::class)) {\n $parser->match(\\Doctrine\\ORM\\Query\\TokenType::T_CLOSE_PARENTHESIS);\n } else {\n $parser->match(\\Doctrine\\ORM\\Query\\Lexer::T_CLOSE_PARENTHESIS);\n }\n }\n}\n"], ["/neuron-ai/src/Observability/Events/PostProcessed.php", "context = $context;\n }\n\n protected function interrupt(array $data): mixed\n {\n if (!isset($this->context)) {\n throw new WorkflowException('WorkflowContext not set on node');\n }\n\n return $this->context->interrupt($data);\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/VectorSimilarity.php", " $value) {\n if (isset($vector2[$key])) {\n $dotProduct += $value * $vector2[$key];\n }\n $magnitude1 += $value ** 2;\n }\n\n foreach ($vector2 as $value) {\n $magnitude2 += $value ** 2;\n }\n\n if ($magnitude1 === 0.0 || $magnitude2 === 0.0) {\n return 0.0;\n }\n\n return $dotProduct / (\\sqrt($magnitude1) * \\sqrt($magnitude2));\n }\n\n public static function cosineDistance(array $vector1, array $vector2): float|int\n {\n return 1 - self::cosineSimilarity($vector1, $vector2);\n }\n\n public static function similarityFromDistance(float|int $distance): float|int\n {\n return 1 - $distance;\n }\n}\n"], ["/neuron-ai/src/Observability/Events/Retrieved.php", "\n */\n public function getMessages(): array;\n\n public function getLastMessage(): Message|false;\n\n public function setMessages(array $messages): ChatHistoryInterface;\n\n public function flushAll(): ChatHistoryInterface;\n\n public function calculateTotalUsage(): int;\n}\n"], ["/neuron-ai/src/Workflow/Persistence/InMemoryPersistence.php", "storage[$workflowId] = $interrupt;\n }\n\n public function load(string $workflowId): WorkflowInterrupt\n {\n return $this->storage[$workflowId] ?? throw new WorkflowException(\"No saved workflow found for ID: {$workflowId}\");\n }\n\n public function delete(string $workflowId): void\n {\n unset($this->storage[$workflowId]);\n }\n}\n"], ["/neuron-ai/src/RAG/ResolveVectorStore.php", "store = $store;\n return $this;\n }\n\n protected function vectorStore(): VectorStoreInterface\n {\n return $this->store;\n }\n\n public function resolveVectorStore(): VectorStoreInterface\n {\n if (!isset($this->store)) {\n $this->store = $this->vectorStore();\n }\n return $this->store;\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/AbstractValidationRule.php", " $value) {\n $messageTemplate = \\str_replace('{'.$key.'}', (string) $value, $messageTemplate);\n }\n\n return \\str_replace('{name}', $name, $messageTemplate);\n }\n}\n"], ["/neuron-ai/src/Providers/HasGuzzleClient.php", "client = $client;\n return $this;\n }\n}\n"], ["/neuron-ai/src/RAG/ResolveEmbeddingProvider.php", "embeddingsProvider = $provider;\n return $this;\n }\n\n protected function embeddings(): EmbeddingsProviderInterface\n {\n return $this->embeddingsProvider;\n }\n\n public function resolveEmbeddingsProvider(): EmbeddingsProviderInterface\n {\n if (!isset($this->embeddingsProvider)) {\n $this->embeddingsProvider = $this->embeddings();\n }\n return $this->embeddingsProvider;\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/UserMessage.php", "splitter->splitDocument(new Document($this->content));\n }\n}\n"], ["/neuron-ai/src/Observability/Events/Validated.php", " $violations\n */\n public function __construct(\n public string $class,\n public string $json,\n public array $violations = []\n ) {\n }\n}\n"], ["/neuron-ai/src/Observability/Events/Retrieving.php", "withPaths([\n __DIR__ . '/src',\n __DIR__ . '/tests',\n ])\n ->withPhpSets(php81: true)\n ->withPreparedSets(\n codeQuality: true,\n deadCode: true,\n typeDeclarations: true,\n earlyReturn: true,\n strictBooleans: true,\n )\n ->withRules([\n AddReturnTypeDeclarationRector::class\n ]);\n"], ["/neuron-ai/src/Observability/Events/PreProcessing.php", "\n */\n public function getRequiredProperties(): array;\n\n /**\n * Define the code to be executed.\n */\n public function setCallable(callable $callback): ToolInterface;\n\n /**\n * Get the input arguments of the function call.\n */\n public function getInputs(): array;\n\n /**\n * Get the input arguments of the function call.\n */\n public function setInputs(array $inputs): ToolInterface;\n\n /**\n * The call identifier generated by the LLM.\n * @return string\n */\n public function getCallId(): ?string;\n\n\n public function setCallId(string $callId): ToolInterface;\n\n\n public function getResult(): string;\n\n /**\n * Execute the tool's logic with input parameters.\n */\n public function execute(): void;\n}\n"], ["/neuron-ai/src/Observability/Events/WorkflowNodeStart.php", " array_merge(\n [[\n 'role' => 'system',\n 'content' => 'Respond only with JSON matching: ' . json_encode($response_format)\n ]],\n $messages\n ),\n 'response_format' => ['type' => 'json_object']\n ];\n\n $response = $this->client->post('chat/completions', [\n 'json' => array_merge($this->defaultParams, $body)\n ]);\n\n $content = json_decode($response->toArray()['choices'][0]['message']['content']);\n \n return new Message(\n new $class(...(array) $content)\n );\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 21-28-11"}, "editdistance_info": {"edit_distance": 29.9401, "calculate_time": "2025-08-20 21:28:11", "true_code_clean": "public function structured(\n array $messages,\n string $class,\n array $response_format\n ): Message {\n $this->parameters = \\array_merge($this->parameters, [\n 'response_format' => [\n 'type' => 'json_object',\n ]\n ]);\n $this->system .= \\PHP_EOL.\"\n .'Generate a json respecting this schema: '.\\json_encode($response_format);\n return $this->chat($messages);\n }", "predict_code_clean": "public function structured(\n array $messages,\n string $class,\n array $response_format\n ): Message {\n $body = [\n 'messages' => array_merge(\n [[\n 'role' => 'system',\n 'content' => 'Respond only with JSON matching: ' . json_encode($response_format)\n ]],\n $messages\n ),\n 'response_format' => ['type' => 'json_object']\n ];\n $response = $this->client->post('chat/completions', [\n 'json' => array_merge($this->defaultParams, $body)\n ]);\n $content = json_decode($response->toArray()['choices'][0]['message']['content']);\n return new Message(\n new $class(...(array) $content)\n );\n }"}} {"repo_name": "neuron-ai", "file_name": "/neuron-ai/src/Chat/History/TokenCounter.php", "inference_info": {"prefix_code": "getContent();\n if (\\is_string($content)) {\n $messageChars += \\strlen($content);\n } elseif ($content !== null) {\n $messageChars += \\strlen(\\json_encode($content));\n }\n if ($message instanceof ToolCallMessage && !\\is_array($content)) {\n $tools = $message->getTools();\n if ($tools !== []) {\n $toolsContent = \\json_encode(\\array_map(fn (ToolInterface $tool): array => $tool->jsonSerialize(), $tools));\n $messageChars += \\strlen($toolsContent);\n }\n }\n if ($message instanceof ToolCallResultMessage) {\n $tools = $message->getTools();\n foreach ($tools as $tool) {\n $serialized = $tool->jsonSerialize();\n if (isset($serialized['id'])) {\n $messageChars += \\strlen($serialized['id']);\n }\n }\n }\n $messageChars += \\strlen($message->getRole());\n $tokenCount += \\ceil($messageChars / $this->charsPerToken);\n $tokenCount += $this->extraTokensPerMessage;\n }\n return (int) \\ceil($tokenCount);\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/neuron-ai/src/Chat/History/AbstractChatHistory.php", "history[] = $message;\n\n $this->trimHistory();\n\n $this->setMessages($this->history);\n\n return $this;\n }\n\n public function getMessages(): array\n {\n return $this->history;\n }\n\n public function getLastMessage(): Message|false\n {\n return \\end($this->history);\n }\n\n public function flushAll(): ChatHistoryInterface\n {\n $this->clear();\n $this->history = [];\n return $this;\n }\n\n public function calculateTotalUsage(): int\n {\n return $this->tokenCounter->count($this->history);\n }\n\n protected function trimHistory(): void\n {\n if ($this->history === []) {\n return;\n }\n\n $tokenCount = $this->tokenCounter->count($this->history);\n\n // Early exit if all messages fit within the token limit\n if ($tokenCount <= $this->contextWindow) {\n $this->ensureValidMessageSequence();\n return;\n }\n\n // Binary search to find how many messages to skip from the beginning\n $skipFrom = $this->findMaxFittingMessages();\n\n $this->history = \\array_slice($this->history, $skipFrom);\n\n // Ensure valid message sequence\n $this->ensureValidMessageSequence();\n }\n\n /**\n * Binary search to find the maximum number of messages that fit within the token limit.\n *\n * @return int The index of the first element to retain (keeping most recent messages) - 0 Skip no messages (include all) - count($this->history): Skip all messages (include none)\n */\n private function findMaxFittingMessages(): int\n {\n $totalMessages = \\count($this->history);\n $left = 0;\n $right = $totalMessages;\n\n while ($left < $right) {\n $mid = \\intval(($left + $right) / 2);\n $subset = \\array_slice($this->history, $mid);\n\n if ($this->tokenCounter->count($subset) <= $this->contextWindow) {\n // Fits! Try including more messages (skip fewer)\n $right = $mid;\n } else {\n // Doesn't fit! Need to skip more messages\n $left = $mid + 1;\n }\n }\n\n return $left;\n }\n\n /**\n * Ensures the message list:\n * 1. Starts with a UserMessage\n * 2. Ends with an AssistantMessage\n * 3. Maintains tool call/result pairs\n */\n protected function ensureValidMessageSequence(): void\n {\n // Ensure it starts with a UserMessage\n $this->ensureStartsWithUser();\n\n // Ensure it ends with an AssistantMessage\n $this->ensureValidAlternation();\n }\n\n /**\n * Ensures the message list starts with a UserMessage.\n */\n protected function ensureStartsWithUser(): void\n {\n // Find the first UserMessage\n $firstUserIndex = null;\n foreach ($this->history as $index => $message) {\n if ($message->getRole() === MessageRole::USER->value) {\n $firstUserIndex = $index;\n break;\n }\n }\n\n if ($firstUserIndex === null) {\n // No UserMessage found\n $this->history = [];\n return;\n }\n\n if ($firstUserIndex === 0) {\n return;\n }\n\n if ($firstUserIndex > 0) {\n // Remove messages before the first user message\n $this->history = \\array_slice($this->history, $firstUserIndex);\n }\n }\n\n /**\n * Ensures valid alternation between user and assistant messages.\n */\n protected function ensureValidAlternation(): void\n {\n $result = [];\n $expectingRole = [MessageRole::USER->value]; // Should start with user\n\n foreach ($this->history as $message) {\n $messageRole = $message->getRole();\n\n // Tool result messages have a special case - they're user messages\n // but can only follow tool call messages (assistant)\n // This is valid after a ToolCallMessage\n if ($message instanceof ToolCallResultMessage && ($result !== [] && $result[\\count($result) - 1] instanceof ToolCallMessage)) {\n $result[] = $message;\n // After the tool result, we expect assistant again\n $expectingRole = [MessageRole::ASSISTANT->value, MessageRole::MODEL->value];\n continue;\n }\n\n // Check if this message has the expected role\n if (\\in_array($messageRole, $expectingRole, true)) {\n $result[] = $message;\n // Toggle the expected role\n $expectingRole = ($expectingRole === [MessageRole::USER->value])\n ? [MessageRole::ASSISTANT->value, MessageRole::MODEL->value]\n : [MessageRole::USER->value];\n }\n // If not the expected role, we have an invalid alternation\n // Skip this message to maintain a valid sequence\n }\n\n $this->history = $result;\n }\n\n public function jsonSerialize(): array\n {\n return $this->getMessages();\n }\n\n protected function deserializeMessages(array $messages): array\n {\n return \\array_map(fn (array $message): Message => match ($message['type'] ?? null) {\n 'tool_call' => $this->deserializeToolCall($message),\n 'tool_call_result' => $this->deserializeToolCallResult($message),\n default => $this->deserializeMessage($message),\n }, $messages);\n }\n\n protected function deserializeMessage(array $message): Message\n {\n $messageRole = MessageRole::from($message['role']);\n $messageContent = $message['content'] ?? null;\n\n $item = match ($messageRole) {\n MessageRole::ASSISTANT => new AssistantMessage($messageContent),\n MessageRole::USER => new UserMessage($messageContent),\n default => new Message($messageRole, $messageContent)\n };\n\n $this->deserializeMeta($message, $item);\n\n return $item;\n }\n\n protected function deserializeToolCall(array $message): ToolCallMessage\n {\n $tools = \\array_map(fn (array $tool) => Tool::make($tool['name'], $tool['description'])\n ->setInputs($tool['inputs'])\n ->setCallId($tool['callId'] ?? null), $message['tools']);\n\n $item = new ToolCallMessage($message['content'], $tools);\n\n $this->deserializeMeta($message, $item);\n\n return $item;\n }\n\n protected function deserializeToolCallResult(array $message): ToolCallResultMessage\n {\n $tools = \\array_map(fn (array $tool) => Tool::make($tool['name'], $tool['description'])\n ->setInputs($tool['inputs'])\n ->setCallId($tool['callId'])\n ->setResult($tool['result']), $message['tools']);\n\n return new ToolCallResultMessage($tools);\n }\n\n protected function deserializeMeta(array $message, Message $item): void\n {\n foreach ($message as $key => $value) {\n if ($key === 'role') {\n continue;\n }\n if ($key === 'content') {\n continue;\n }\n if ($key === 'usage') {\n $item->setUsage(\n new Usage($message['usage']['input_tokens'], $message['usage']['output_tokens'])\n );\n continue;\n }\n if ($key === 'attachments') {\n foreach ($message['attachments'] as $attachment) {\n switch (AttachmentType::from($attachment['type'])) {\n case AttachmentType::IMAGE:\n $item->addAttachment(\n new Image(\n $attachment['content'],\n AttachmentContentType::from($attachment['content_type']),\n $attachment['media_type'] ?? null\n )\n );\n break;\n case AttachmentType::DOCUMENT:\n $item->addAttachment(\n new Document(\n $attachment['content'],\n AttachmentContentType::from($attachment['content_type']),\n $attachment['media_type'] ?? null\n )\n );\n break;\n }\n\n }\n continue;\n }\n $item->addMetadata($key, $value);\n }\n }\n}\n"], ["/neuron-ai/src/HandleStream.php", "notify('stream-start');\n\n $this->fillChatHistory($messages);\n\n $tools = $this->bootstrapTools();\n\n $stream = $this->resolveProvider()\n ->systemPrompt($this->resolveInstructions())\n ->setTools($tools)\n ->stream(\n $this->resolveChatHistory()->getMessages(),\n function (ToolCallMessage $toolCallMessage) {\n $toolCallResult = $this->executeTools($toolCallMessage);\n yield from self::stream([$toolCallMessage, $toolCallResult]);\n }\n );\n\n $content = '';\n $usage = new Usage(0, 0);\n foreach ($stream as $text) {\n // Catch usage when streaming\n $decoded = \\json_decode((string) $text, true);\n if (\\is_array($decoded) && \\array_key_exists('usage', $decoded)) {\n $usage->inputTokens += $decoded['usage']['input_tokens'] ?? 0;\n $usage->outputTokens += $decoded['usage']['output_tokens'] ?? 0;\n continue;\n }\n\n $content .= $text;\n yield $text;\n }\n\n $response = new AssistantMessage($content);\n $response->setUsage($usage);\n\n // Avoid double saving due to the recursive call.\n $last = $this->resolveChatHistory()->getLastMessage();\n if ($response->getRole() !== $last->getRole()) {\n $this->fillChatHistory($response);\n }\n\n $this->notify('stream-stop');\n } catch (\\Throwable $exception) {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/MessageMapper.php", "mapping = [];\n\n foreach ($messages as $message) {\n match ($message::class) {\n Message::class,\n UserMessage::class,\n AssistantMessage::class => $this->mapMessage($message),\n ToolCallMessage::class => $this->mapToolCall($message),\n ToolCallResultMessage::class => $this->mapToolsResult($message),\n default => throw new ProviderException('Could not map message type '.$message::class),\n };\n }\n\n return $this->mapping;\n }\n\n protected function mapMessage(Message $message): void\n {\n $payload = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $payload)) {\n unset($payload['usage']);\n }\n\n $attachments = $message->getAttachments();\n\n if (\\is_string($payload['content']) && $attachments) {\n $payload['content'] = [\n [\n 'type' => 'text',\n 'text' => $payload['content'],\n ],\n ];\n }\n\n foreach ($attachments as $attachment) {\n $payload['content'][] = $this->mapAttachment($attachment);\n }\n\n unset($payload['attachments']);\n\n $this->mapping[] = $payload;\n }\n\n protected function mapAttachment(Attachment $attachment): array\n {\n return match($attachment->contentType) {\n AttachmentContentType::URL => [\n 'type' => $attachment->type->value,\n 'source' => [\n 'type' => 'url',\n 'url' => $attachment->content,\n ],\n ],\n AttachmentContentType::BASE64 => [\n 'type' => $attachment->type->value,\n 'source' => [\n 'type' => 'base64',\n 'media_type' => $attachment->mediaType,\n 'data' => $attachment->content,\n ],\n ],\n };\n }\n\n protected function mapToolCall(ToolCallMessage $message): void\n {\n $message = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $message)) {\n unset($message['usage']);\n }\n\n unset($message['type']);\n unset($message['tools']);\n\n $this->mapping[] = $message;\n }\n\n protected function mapToolsResult(ToolCallResultMessage $message): void\n {\n $this->mapping[] = [\n 'role' => MessageRole::USER,\n 'content' => \\array_map(fn (ToolInterface $tool): array => [\n 'type' => 'tool_result',\n 'tool_use_id' => $tool->getCallId(),\n 'content' => $tool->getResult(),\n ], $message->getTools())\n ];\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/MessageMapper.php", "mapping = [];\n\n foreach ($messages as $message) {\n match ($message::class) {\n Message::class,\n UserMessage::class,\n AssistantMessage::class => $this->mapMessage($message),\n ToolCallMessage::class => $this->mapToolCall($message),\n ToolCallResultMessage::class => $this->mapToolsResult($message),\n default => throw new ProviderException('Could not map message type '.$message::class),\n };\n }\n\n return $this->mapping;\n }\n\n public function mapMessage(Message $message): void\n {\n $payload = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $payload)) {\n unset($payload['usage']);\n }\n\n $attachments = $message->getAttachments();\n\n foreach ($attachments as $attachment) {\n if ($attachment->type === AttachmentType::DOCUMENT) {\n throw new ProviderException('This provider does not support document attachments.');\n }\n\n $payload['images'][] = $this->mapAttachment($attachment);\n }\n\n unset($payload['attachments']);\n\n $this->mapping[] = $payload;\n }\n\n protected function mapAttachment(Attachment $attachment): string\n {\n return match ($attachment->contentType) {\n AttachmentContentType::BASE64 => $attachment->content,\n AttachmentContentType::URL => throw new ProviderException('Ollama support only base64 attachment type.'),\n };\n }\n\n protected function mapToolCall(ToolCallMessage $message): void\n {\n $message = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $message)) {\n unset($message['usage']);\n }\n\n if (\\array_key_exists('tool_calls', $message)) {\n $message['tool_calls'] = \\array_map(function (array $toolCall) {\n if (empty($toolCall['function']['arguments'])) {\n $toolCall['function']['arguments'] = new \\stdClass();\n }\n return $toolCall;\n }, $message['tool_calls']);\n }\n\n unset($message['type']);\n unset($message['tools']);\n\n $this->mapping[] = $message;\n }\n\n public function mapToolsResult(ToolCallResultMessage $message): void\n {\n foreach ($message->getTools() as $tool) {\n $this->mapping[] = [\n 'role' => MessageRole::TOOL->value,\n 'content' => $tool->getResult()\n ];\n }\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/MessageMapper.php", "mapping = [];\n\n foreach ($messages as $message) {\n match ($message::class) {\n Message::class,\n UserMessage::class,\n AssistantMessage::class => $this->mapMessage($message),\n ToolCallMessage::class => $this->mapToolCall($message),\n ToolCallResultMessage::class => $this->mapToolsResult($message),\n default => throw new ProviderException('Could not map message type '.$message::class),\n };\n }\n\n return $this->mapping;\n }\n\n protected function mapMessage(Message $message): void\n {\n $payload = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $payload)) {\n unset($payload['usage']);\n }\n\n $attachments = $message->getAttachments();\n\n if (\\is_string($payload['content']) && $attachments) {\n $payload['content'] = [\n [\n 'type' => 'text',\n 'text' => $payload['content'],\n ],\n ];\n }\n\n foreach ($attachments as $attachment) {\n if ($attachment->type === AttachmentType::DOCUMENT) {\n throw new ProviderException('This provider does not support document attachments.');\n }\n\n $payload['content'][] = $this->mapAttachment($attachment);\n }\n\n unset($payload['attachments']);\n\n $this->mapping[] = $payload;\n }\n\n protected function mapAttachment(Attachment $attachment): array\n {\n return match($attachment->contentType) {\n AttachmentContentType::URL => [\n 'type' => 'image_url',\n 'image_url' => [\n 'url' => $attachment->content,\n ],\n ],\n AttachmentContentType::BASE64 => [\n 'type' => 'image_url',\n 'image_url' => [\n 'url' => 'data:'.$attachment->mediaType.';base64,'.$attachment->content,\n ],\n ]\n };\n }\n\n protected function mapToolCall(ToolCallMessage $message): void\n {\n $message = $message->jsonSerialize();\n\n if (\\array_key_exists('usage', $message)) {\n unset($message['usage']);\n }\n\n unset($message['type']);\n unset($message['tools']);\n\n $this->mapping[] = $message;\n }\n\n protected function mapToolsResult(ToolCallResultMessage $message): void\n {\n foreach ($message->getTools() as $tool) {\n $this->mapping[] = [\n 'role' => MessageRole::TOOL->value,\n 'tool_call_id' => $tool->getCallId(),\n 'content' => $tool->getResult()\n ];\n }\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(array $messages): PromiseInterface\n {\n // Include the system prompt\n if (isset($this->system)) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'stream' => false,\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n if (! empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n return $this->client->postAsync('chat', ['json' => $json])\n ->then(function (ResponseInterface $response): Message {\n if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) {\n throw new ProviderException(\"Ollama chat error: {$response->getBody()->getContents()}\");\n }\n\n $response = \\json_decode($response->getBody()->getContents(), true);\n $message = $response['message'];\n\n if (\\array_key_exists('tool_calls', $message)) {\n $message = $this->createToolCallMessage($message);\n } else {\n $message = new AssistantMessage($message['content']);\n }\n\n if (\\array_key_exists('prompt_eval_count', $response) && \\array_key_exists('eval_count', $response)) {\n $message->setUsage(\n new Usage($response['prompt_eval_count'], $response['eval_count'])\n );\n }\n\n return $message;\n });\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/HandleStream.php", " $this->messageMapper()->map($messages),\n ...$this->parameters\n ];\n\n if (isset($this->system)) {\n $json['system_instruction'] = [\n 'parts' => [\n ['text' => $this->system]\n ]\n ];\n }\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n $stream = $this->client->post(\\trim($this->baseUri, '/').\"/{$this->model}:streamGenerateContent\", [\n 'stream' => true,\n ...[RequestOptions::JSON => $json]\n ])->getBody();\n\n $text = '';\n $toolCalls = [];\n\n while (! $stream->eof()) {\n $line = $this->readLine($stream);\n\n if (($line = \\json_decode((string) $line, true)) === null) {\n continue;\n }\n\n // Inform the agent about usage when stream\n if (\\array_key_exists('usageMetadata', $line)) {\n yield \\json_encode(['usage' => [\n 'input_tokens' => $line['usageMetadata']['promptTokenCount'],\n 'output_tokens' => $line['usageMetadata']['candidatesTokenCount'] ?? 0,\n ]]);\n }\n\n // Process tool calls\n if ($this->hasToolCalls($line)) {\n $toolCalls = $this->composeToolCalls($line, $toolCalls);\n\n // Handle tool calls\n if (isset($line['candidates'][0]['finishReason']) && $line['candidates'][0]['finishReason'] === 'STOP') {\n yield from $executeToolsCallback(\n $this->createToolCallMessage([\n 'content' => $text,\n 'parts' => $toolCalls\n ])\n );\n\n return;\n }\n\n continue;\n }\n\n // Process regular content\n $content = $line['candidates'][0]['content']['parts'][0]['text'] ?? '';\n $text .= $content;\n\n yield $content;\n }\n }\n\n /**\n * Recreate the tool_calls format from streaming Gemini API.\n */\n protected function composeToolCalls(array $line, array $toolCalls): array\n {\n $parts = $line['candidates'][0]['content']['parts'] ?? [];\n\n foreach ($parts as $index => $part) {\n if (isset($part['functionCall'])) {\n $toolCalls[$index]['functionCall'] = $part['functionCall'];\n }\n }\n\n return $toolCalls;\n }\n\n /**\n * Determines if the given line contains tool function calls.\n *\n * @param array $line The data line to check for tool function calls.\n * @return bool Returns true if the line contains tool function calls, otherwise false.\n */\n protected function hasToolCalls(array $line): bool\n {\n $parts = $line['candidates'][0]['content']['parts'] ?? [];\n\n foreach ($parts as $part) {\n if (isset($part['functionCall'])) {\n return true;\n }\n }\n\n return false;\n }\n\n private function readLine(StreamInterface $stream): string\n {\n $buffer = '';\n\n while (! $stream->eof()) {\n $buffer .= $stream->read(1);\n\n if (\\strlen($buffer) === 1 && $buffer !== '{') {\n $buffer = '';\n }\n\n if (\\json_decode($buffer) !== null) {\n return $buffer;\n }\n }\n\n return \\rtrim($buffer, ']');\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(array $messages): PromiseInterface\n {\n $json = [\n 'contents' => $this->messageMapper()->map($messages),\n ...$this->parameters\n ];\n\n if (isset($this->system)) {\n $json['system_instruction'] = [\n 'parts' => [\n ['text' => $this->system]\n ]\n ];\n }\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n return $this->client->postAsync(\\trim($this->baseUri, '/').\"/{$this->model}:generateContent\", [RequestOptions::JSON => $json])\n ->then(function (ResponseInterface $response): Message {\n $result = \\json_decode($response->getBody()->getContents(), true);\n\n $content = $result['candidates'][0]['content'];\n\n if (!isset($content['parts']) && isset($result['candidates'][0]['finishReason']) && $result['candidates'][0]['finishReason'] === 'MAX_TOKENS') {\n return new Message(MessageRole::from($content['role']), '');\n }\n\n $parts = $content['parts'];\n\n if (\\array_key_exists('functionCall', $parts[0]) && !empty($parts[0]['functionCall'])) {\n $response = $this->createToolCallMessage($content);\n } else {\n $response = new Message(MessageRole::from($content['role']), $parts[0]['text'] ?? '');\n }\n\n // Attach the usage for the current interaction\n if (\\array_key_exists('usageMetadata', $result)) {\n $response->setUsage(\n new Usage(\n $result['usageMetadata']['promptTokenCount'],\n $result['usageMetadata']['candidatesTokenCount'] ?? 0\n )\n );\n }\n\n return $response;\n });\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/MessageMapper.php", "mapping = [];\n\n foreach ($messages as $message) {\n match ($message::class) {\n Message::class,\n UserMessage::class,\n AssistantMessage::class => $this->mapMessage($message),\n ToolCallMessage::class => $this->mapToolCall($message),\n ToolCallResultMessage::class => $this->mapToolsResult($message),\n default => throw new ProviderException('Could not map message type '.$message::class),\n };\n }\n\n return $this->mapping;\n }\n\n protected function mapMessage(Message $message): void\n {\n $payload = [\n 'role' => $message->getRole(),\n 'parts' => [\n ['text' => $message->getContent()]\n ],\n ];\n\n $attachments = $message->getAttachments();\n\n foreach ($attachments as $attachment) {\n $payload['parts'][] = $this->mapAttachment($attachment);\n }\n\n $this->mapping[] = $payload;\n }\n\n protected function mapAttachment(Attachment $attachment): array\n {\n return match($attachment->contentType) {\n AttachmentContentType::URL => [\n 'file_data' => [\n 'file_uri' => $attachment->content,\n 'mime_type' => $attachment->mediaType,\n ],\n ],\n AttachmentContentType::BASE64 => [\n 'inline_data' => [\n 'data' => $attachment->content,\n 'mime_type' => $attachment->mediaType,\n ]\n ]\n };\n }\n\n protected function mapToolCall(ToolCallMessage $message): void\n {\n $this->mapping[] = [\n 'role' => MessageRole::MODEL->value,\n 'parts' => [\n ...\\array_map(fn (ToolInterface $tool): array => [\n 'functionCall' => [\n 'name' => $tool->getName(),\n 'args' => $tool->getInputs() !== [] ? $tool->getInputs() : new \\stdClass(),\n ]\n ], $message->getTools())\n ]\n ];\n }\n\n protected function mapToolsResult(ToolCallResultMessage $message): void\n {\n $this->mapping[] = [\n 'role' => MessageRole::USER->value,\n 'parts' => \\array_map(fn (ToolInterface $tool): array => [\n 'functionResponse' => [\n 'name' => $tool->getName(),\n 'response' => [\n 'name' => $tool->getName(),\n 'content' => $tool->getResult(),\n ],\n ],\n ], $message->getTools()),\n ];\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(array $messages): PromiseInterface\n {\n // Include the system prompt\n if (isset($this->system)) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters\n ];\n\n // Attach tools\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n return $this->client->postAsync('chat/completions', ['json' => $json])\n ->then(function (ResponseInterface $response) {\n $result = \\json_decode($response->getBody()->getContents(), true);\n\n if ($result['choices'][0]['finish_reason'] === 'tool_calls') {\n $response = $this->createToolCallMessage($result['choices'][0]['message']);\n } else {\n $response = new AssistantMessage($result['choices'][0]['message']['content']);\n }\n\n if (\\array_key_exists('usage', $result)) {\n $response->setUsage(\n new Usage($result['usage']['prompt_tokens'], $result['usage']['completion_tokens'])\n );\n }\n\n return $response;\n });\n }\n}\n"], ["/neuron-ai/src/Providers/Mistral/Mistral.php", "system !== null) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'stream' => true,\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n // Attach tools\n if ($this->tools !== []) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n $stream = $this->client->post('chat/completions', [\n 'stream' => true,\n ...['json' => $json]\n ])->getBody();\n\n $text = '';\n $toolCalls = [];\n\n while (! $stream->eof()) {\n if (($line = $this->parseNextDataLine($stream)) === null) {\n continue;\n }\n\n // Inform the agent about usage when stream\n if (empty($line['choices']) && !empty($line['usage'])) {\n yield \\json_encode(['usage' => [\n 'input_tokens' => $line['usage']['prompt_tokens'],\n 'output_tokens' => $line['usage']['completion_tokens'],\n ]]);\n continue;\n }\n\n if (empty($line['choices'])) {\n continue;\n }\n\n // Compile tool calls\n if ($this->isToolCallPart($line)) {\n $toolCalls = $this->composeToolCalls($line, $toolCalls);\n\n // Handle tool calls\n if ($line['choices'][0]['finish_reason'] === 'tool_calls') {\n yield from $executeToolsCallback(\n $this->createToolCallMessage([\n 'content' => $text,\n 'tool_calls' => $toolCalls\n ])\n );\n }\n\n continue;\n }\n\n // Process regular content\n $content = $line['choices'][0]['delta']['content'] ?? '';\n $text .= $content;\n\n yield $content;\n }\n }\n\n protected function isToolCallPart(array $line): bool\n {\n $calls = $line['choices'][0]['delta']['tool_calls'] ?? [];\n\n foreach ($calls as $call) {\n if (isset($call['function'])) {\n return true;\n }\n }\n\n return false;\n }\n}\n"], ["/neuron-ai/src/ResolveTools.php", "tools, $this->tools());\n }\n\n /**\n * If toolkits have already bootstrapped, this function\n * just traverses the array of tools without any action.\n *\n * @return ToolInterface[]\n */\n public function bootstrapTools(): array\n {\n $guidelines = [];\n\n if (!empty($this->toolsBootstrapCache)) {\n return $this->toolsBootstrapCache;\n }\n\n $this->notify('tools-bootstrapping');\n\n foreach ($this->getTools() as $tool) {\n if ($tool instanceof ToolkitInterface) {\n $kitGuidelines = $tool->guidelines();\n if ($kitGuidelines !== null && $kitGuidelines !== '') {\n $name = (new \\ReflectionClass($tool))->getShortName();\n $kitGuidelines = '# '.$name.\\PHP_EOL.$kitGuidelines;\n }\n\n // Merge the tools\n $innerTools = $tool->tools();\n $this->toolsBootstrapCache = \\array_merge($this->toolsBootstrapCache, $innerTools);\n\n // Add guidelines to the system prompt\n if ($kitGuidelines !== null && $kitGuidelines !== '' && $kitGuidelines !== '0') {\n $kitGuidelines .= \\PHP_EOL.\\implode(\n \\PHP_EOL.'- ',\n \\array_map(\n fn (ToolInterface $tool): string => \"{$tool->getName()}: {$tool->getDescription()}\",\n $innerTools\n )\n );\n\n $guidelines[] = $kitGuidelines;\n }\n } else {\n // If the item is a simple tool, add to the list as it is\n $this->toolsBootstrapCache[] = $tool;\n }\n }\n\n $instructions = $this->removeDelimitedContent($this->resolveInstructions(), '', '');\n if ($guidelines !== []) {\n $this->withInstructions(\n $instructions.\\PHP_EOL.''.\\PHP_EOL.\\implode(\\PHP_EOL.\\PHP_EOL, $guidelines).\\PHP_EOL.''\n );\n }\n\n $this->notify('tools-bootstrapped', new ToolsBootstrapped($this->toolsBootstrapCache, $guidelines));\n\n return $this->toolsBootstrapCache;\n }\n\n /**\n * Add tools.\n *\n * @throws AgentException\n */\n public function addTool(ToolInterface|ToolkitInterface|array $tools): AgentInterface\n {\n $tools = \\is_array($tools) ? $tools : [$tools];\n\n foreach ($tools as $t) {\n if (! $t instanceof ToolInterface && ! $t instanceof ToolkitInterface) {\n throw new AgentException('Tools must be an instance of ToolInterface or ToolkitInterface');\n }\n $this->tools[] = $t;\n }\n\n // Empty the cache for the next turn.\n $this->toolsBootstrapCache = [];\n\n return $this;\n }\n\n protected function executeTools(ToolCallMessage $toolCallMessage): ToolCallResultMessage\n {\n $toolCallResult = new ToolCallResultMessage($toolCallMessage->getTools());\n\n foreach ($toolCallResult->getTools() as $tool) {\n $this->notify('tool-calling', new ToolCalling($tool));\n try {\n $tool->execute();\n } catch (\\Throwable $exception) {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n $this->notify('tool-called', new ToolCalled($tool));\n }\n\n return $toolCallResult;\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/HandleStream.php", " true,\n 'model' => $this->model,\n 'max_tokens' => $this->max_tokens,\n 'system' => $this->system ?? null,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n // https://docs.anthropic.com/claude/reference/messages_post\n $stream = $this->client->post('messages', [\n 'stream' => true,\n ...['json' => $json]\n ])->getBody();\n\n $toolCalls = [];\n\n while (! $stream->eof()) {\n if (!$line = $this->parseNextDataLine($stream)) {\n continue;\n }\n\n // https://docs.anthropic.com/en/api/messages-streaming\n if ($line['type'] === 'message_start') {\n yield \\json_encode(['usage' => $line['message']['usage']]);\n continue;\n }\n\n if ($line['type'] === 'message_delta') {\n yield \\json_encode(['usage' => $line['usage']]);\n continue;\n }\n\n // Tool calls detection (https://docs.anthropic.com/en/api/messages-streaming#streaming-request-with-tool-use)\n if (\n (isset($line['content_block']['type']) && $line['content_block']['type'] === 'tool_use') ||\n (isset($line['delta']['type']) && $line['delta']['type'] === 'input_json_delta')\n ) {\n $toolCalls = $this->composeToolCalls($line, $toolCalls);\n continue;\n }\n\n // Handle tool call\n if ($line['type'] === 'content_block_stop' && !empty($toolCalls)) {\n // Restore the input field as an array\n $toolCalls = \\array_map(function (array $call) {\n $call['input'] = \\json_decode((string) $call['input'], true);\n return $call;\n }, $toolCalls);\n\n yield from $executeToolsCallback(\n $this->createToolCallMessage(\\end($toolCalls))\n );\n }\n\n // Process regular content\n $content = $line['delta']['text'] ?? '';\n\n yield $content;\n }\n }\n\n /**\n * Recreate the tool_call format of anthropic API from streaming.\n *\n * @param array $line\n * @param array> $toolCalls\n * @return array>\n */\n protected function composeToolCalls(array $line, array $toolCalls): array\n {\n if (!\\array_key_exists($line['index'], $toolCalls)) {\n $toolCalls[$line['index']] = [\n 'type' => 'tool_use',\n 'id' => $line['content_block']['id'],\n 'name' => $line['content_block']['name'],\n 'input' => '',\n ];\n } elseif ($input = $line['delta']['partial_json'] ?? null) {\n $toolCalls[$line['index']]['input'] .= $input;\n }\n\n return $toolCalls;\n }\n\n protected function parseNextDataLine(StreamInterface $stream): ?array\n {\n $line = $this->readLine($stream);\n\n if (! \\str_starts_with((string) $line, 'data:')) {\n return null;\n }\n\n $line = \\trim(\\substr((string) $line, \\strlen('data: ')));\n\n try {\n return \\json_decode($line, true, flags: \\JSON_THROW_ON_ERROR);\n } catch (\\Throwable $exception) {\n throw new ProviderException('Anthropic streaming error - '.$exception->getMessage());\n }\n }\n\n protected function readLine(StreamInterface $stream): string\n {\n $buffer = '';\n\n while (! $stream->eof()) {\n $byte = $stream->read(1);\n\n if ($byte === '') {\n return $buffer;\n }\n\n $buffer .= $byte;\n\n if ($byte === \"\\n\") {\n break;\n }\n }\n\n return $buffer;\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/HandleStream.php", "system)) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'stream' => true,\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n 'stream_options' => ['include_usage' => true],\n ...$this->parameters,\n ];\n\n // Attach tools\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n $stream = $this->client->post('chat/completions', [\n 'stream' => true,\n ...['json' => $json]\n ])->getBody();\n\n $text = '';\n $toolCalls = [];\n\n while (! $stream->eof()) {\n if (!$line = $this->parseNextDataLine($stream)) {\n continue;\n }\n\n // Inform the agent about usage when stream\n if (!empty($line['usage'])) {\n yield \\json_encode(['usage' => [\n 'input_tokens' => $line['usage']['prompt_tokens'],\n 'output_tokens' => $line['usage']['completion_tokens'],\n ]]);\n }\n\n if (empty($line['choices'])) {\n continue;\n }\n\n // Compile tool calls\n if (isset($line['choices'][0]['delta']['tool_calls'])) {\n $toolCalls = $this->composeToolCalls($line, $toolCalls);\n continue;\n }\n\n // Handle tool calls\n if (isset($line['choices'][0]['finish_reason']) && $line['choices'][0]['finish_reason'] === 'tool_calls') {\n yield from $executeToolsCallback(\n $this->createToolCallMessage([\n 'content' => $text,\n 'tool_calls' => $toolCalls\n ])\n );\n\n return;\n }\n\n // Process regular content\n $content = $line['choices'][0]['delta']['content'] ?? '';\n $text .= $content;\n\n yield $content;\n }\n }\n\n /**\n * Recreate the tool_calls format from streaming OpenAI API.\n *\n * @param array $line\n * @param array> $toolCalls\n * @return array>\n */\n protected function composeToolCalls(array $line, array $toolCalls): array\n {\n foreach ($line['choices'][0]['delta']['tool_calls'] as $call) {\n $index = $call['index'];\n\n if (!\\array_key_exists($index, $toolCalls)) {\n if ($name = $call['function']['name'] ?? null) {\n $toolCalls[$index]['function'] = ['name' => $name, 'arguments' => $call['function']['arguments'] ?? ''];\n $toolCalls[$index]['id'] = $call['id'];\n $toolCalls[$index]['type'] = 'function';\n }\n } else {\n $arguments = $call['function']['arguments'] ?? null;\n if ($arguments !== null) {\n $toolCalls[$index]['function']['arguments'] .= $arguments;\n }\n }\n }\n\n return $toolCalls;\n }\n\n protected function parseNextDataLine(StreamInterface $stream): ?array\n {\n $line = $this->readLine($stream);\n\n if (! \\str_starts_with((string) $line, 'data:')) {\n return null;\n }\n\n $line = \\trim(\\substr((string) $line, \\strlen('data: ')));\n\n if (\\str_contains($line, 'DONE')) {\n return null;\n }\n\n try {\n return \\json_decode($line, true, flags: \\JSON_THROW_ON_ERROR);\n } catch (\\Throwable $exception) {\n throw new ProviderException('OpenAI streaming error - '.$exception->getMessage());\n }\n }\n\n protected function readLine(StreamInterface $stream): string\n {\n $buffer = '';\n\n while (! $stream->eof()) {\n $byte = $stream->read(1);\n\n if ($byte === '') {\n return $buffer;\n }\n\n $buffer .= $byte;\n\n if ($byte === \"\\n\") {\n break;\n }\n }\n\n return $buffer;\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(array $messages): PromiseInterface\n {\n $json = [\n 'model' => $this->model,\n 'max_tokens' => $this->max_tokens,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n if (isset($this->system)) {\n $json['system'] = $this->system;\n }\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n\n return $this->client->postAsync('messages', ['json' => $json])\n ->then(function (ResponseInterface $response) {\n $result = \\json_decode($response->getBody()->getContents(), true);\n\n $content = \\end($result['content']);\n\n if ($content['type'] === 'tool_use') {\n $response = $this->createToolCallMessage($content);\n } else {\n $response = new AssistantMessage($content['text']);\n }\n\n // Attach the usage for the current interaction\n if (\\array_key_exists('usage', $result)) {\n $response->setUsage(\n new Usage(\n $result['usage']['input_tokens'],\n $result['usage']['output_tokens']\n )\n );\n }\n\n return $response;\n });\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/HandleStream.php", "system)) {\n \\array_unshift($messages, new Message(MessageRole::SYSTEM, $this->system));\n }\n\n $json = [\n 'stream' => true,\n 'model' => $this->model,\n 'messages' => $this->messageMapper()->map($messages),\n ...$this->parameters,\n ];\n\n if (!empty($this->tools)) {\n $json['tools'] = $this->generateToolsPayload();\n }\n\n $stream = $this->client->post('chat', [\n 'stream' => true,\n ...['json' => $json]\n ])->getBody();\n\n while (! $stream->eof()) {\n if (!$line = $this->parseNextJson($stream)) {\n continue;\n }\n\n // Last chunk will contain the usage information.\n if ($line['done'] === true) {\n yield \\json_encode(['usage' => [\n 'input_tokens' => $line['prompt_eval_count'],\n 'output_tokens' => $line['eval_count'],\n ]]);\n continue;\n }\n\n // Process tool calls\n if (isset($line['message']['tool_calls'])) {\n yield from $executeToolsCallback(\n $this->createToolCallMessage($line['message'])\n );\n }\n\n // Process regular content\n $content = $line['message']['content'] ?? '';\n\n yield $content;\n }\n }\n\n protected function parseNextJson(StreamInterface $stream): ?array\n {\n $line = $this->readLine($stream);\n\n if (empty($line)) {\n return null;\n }\n\n $json = \\json_decode((string) $line, true);\n\n if ($json['done']) {\n return null;\n }\n\n if (! isset($json['message']) || $json['message']['role'] !== 'assistant') {\n return null;\n }\n\n return $json;\n }\n\n protected function readLine(StreamInterface $stream): string\n {\n $buffer = '';\n\n while (! $stream->eof()) {\n if ('' === ($byte = $stream->read(1))) {\n return $buffer;\n }\n $buffer .= $byte;\n if ($byte === \"\\n\") {\n break;\n }\n }\n\n return $buffer;\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/OpenAI.php", "client = new Client([\n 'base_uri' => \\trim($this->baseUri, '/').'/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer ' . $this->key,\n ]\n ]);\n }\n\n public function systemPrompt(?string $prompt): AIProviderInterface\n {\n $this->system = $prompt;\n return $this;\n }\n\n public function messageMapper(): MessageMapperInterface\n {\n return new MessageMapper();\n }\n\n protected function generateToolsPayload(): array\n {\n return \\array_map(function (ToolInterface $tool): array {\n $payload = [\n 'type' => 'function',\n 'function' => [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'parameters' => [\n 'type' => 'object',\n 'properties' => new \\stdClass(),\n 'required' => [],\n ],\n ]\n ];\n\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n\n if (!empty($properties)) {\n $payload['function']['parameters'] = [\n 'type' => 'object',\n 'properties' => $properties,\n 'required' => $tool->getRequiredProperties(),\n ];\n }\n\n return $payload;\n }, $this->tools);\n }\n\n protected function createToolCallMessage(array $message): Message\n {\n $tools = \\array_map(\n fn (array $item): ToolInterface => $this->findTool($item['function']['name'])\n ->setInputs(\n \\json_decode((string) $item['function']['arguments'], true)\n )\n ->setCallId($item['id']),\n $message['tool_calls']\n );\n\n $result = new ToolCallMessage(\n $message['content'],\n $tools\n );\n\n return $result->addMetadata('tool_calls', $message['tool_calls']);\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/Gemini.php", "client = new Client([\n // Since Gemini use colon \":\" into the URL guzzle fire an exception using base_uri configuration.\n //'base_uri' => trim($this->baseUri, '/').'/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'x-goog-api-key' => $this->key,\n ]\n ]);\n }\n\n public function systemPrompt(?string $prompt): AIProviderInterface\n {\n $this->system = $prompt;\n return $this;\n }\n\n public function messageMapper(): MessageMapperInterface\n {\n return new MessageMapper();\n }\n\n protected function generateToolsPayload(): array\n {\n $tools = \\array_map(function (ToolInterface $tool): array {\n $payload = [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'parameters' => [\n 'type' => 'object',\n 'properties' => new \\stdClass(),\n 'required' => [],\n ],\n ];\n\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property) {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n\n if (!empty($properties)) {\n $payload['parameters'] = [\n 'type' => 'object',\n 'properties' => $properties,\n 'required' => $tool->getRequiredProperties(),\n ];\n }\n\n return $payload;\n }, $this->tools);\n\n return [\n 'functionDeclarations' => $tools\n ];\n }\n\n protected function createToolCallMessage(array $message): Message\n {\n $tools = \\array_map(function (array $item): ?\\NeuronAI\\Tools\\ToolInterface {\n if (!isset($item['functionCall'])) {\n return null;\n }\n\n // Gemini does not use ID. It uses the tool's name as a unique identifier.\n return $this->findTool($item['functionCall']['name'])\n ->setInputs($item['functionCall']['args'])\n ->setCallId($item['functionCall']['name']);\n }, $message['parts']);\n\n $result = new ToolCallMessage(\n $message['content'] ?? null,\n \\array_filter($tools)\n );\n $result->setRole(MessageRole::MODEL);\n\n return $result;\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/Ollama.php", "client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n ]);\n }\n\n public function systemPrompt(?string $prompt): AIProviderInterface\n {\n $this->system = $prompt;\n\n return $this;\n }\n\n public function messageMapper(): MessageMapperInterface\n {\n return new MessageMapper();\n }\n\n protected function generateToolsPayload(): array\n {\n return \\array_map(function (ToolInterface $tool): array {\n $payload = [\n 'type' => 'function',\n 'function' => [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'parameters' => [\n 'type' => 'object',\n 'properties' => new \\stdClass(),\n 'required' => [],\n ]\n ],\n ];\n\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n $carry[$property->getName()] = [\n 'type' => $property->getType()->value,\n 'description' => $property->getDescription(),\n ];\n\n return $carry;\n }, []);\n\n if (! empty($properties)) {\n $payload['function']['parameters'] = [\n 'type' => 'object',\n 'properties' => $properties,\n 'required' => $tool->getRequiredProperties(),\n ];\n }\n\n return $payload;\n }, $this->tools);\n }\n\n protected function createToolCallMessage(array $message): Message\n {\n $tools = \\array_map(fn (array $item): ToolInterface => $this->findTool($item['function']['name'])\n ->setInputs($item['function']['arguments']), $message['tool_calls']);\n\n $result = new ToolCallMessage(\n $message['content'],\n $tools\n );\n\n return $result->addMetadata('tool_calls', $message['tool_calls']);\n }\n}\n"], ["/neuron-ai/src/Observability/AgentMonitoring.php", "\n */\n protected array $segments = [];\n\n\n /**\n * @var array\n */\n protected array $methodsMap = [\n 'error' => 'reportError',\n 'chat-start' => 'start',\n 'chat-stop' => 'stop',\n 'stream-start' => 'start',\n 'stream-stop' => 'stop',\n 'structured-start' => 'start',\n 'structured-stop' => 'stop',\n 'chat-rag-start' => 'start',\n 'chat-rag-stop' => 'stop',\n 'stream-rag-start' => 'start',\n 'stream-rag-stop' => 'stop',\n 'structured-rag-start' => 'start',\n 'structured-rag-stop' => 'stop',\n\n 'message-saving' => 'messageSaving',\n 'message-saved' => 'messageSaved',\n 'tools-bootstrapping' => 'toolsBootstrapping',\n 'tools-bootstrapped' => 'toolsBootstrapped',\n 'inference-start' => 'inferenceStart',\n 'inference-stop' => 'inferenceStop',\n 'tool-calling' => 'toolCalling',\n 'tool-called' => 'toolCalled',\n 'schema-generation' => 'schemaGeneration',\n 'schema-generated' => 'schemaGenerated',\n 'structured-extracting' => 'extracting',\n 'structured-extracted' => 'extracted',\n 'structured-deserializing' => 'deserializing',\n 'structured-deserialized' => 'deserialized',\n 'structured-validating' => 'validating',\n 'structured-validated' => 'validated',\n 'rag-retrieving' => 'ragRetrieving',\n 'rag-retrieved' => 'ragRetrieved',\n 'rag-preprocessing' => 'preProcessing',\n 'rag-preprocessed' => 'preProcessed',\n 'rag-postprocessing' => 'postProcessing',\n 'rag-postprocessed' => 'postProcessed',\n 'workflow-start' => 'workflowStart',\n 'workflow-end' => 'workflowEnd',\n 'workflow-node-start' => 'workflowNodeStart',\n 'workflow-node-end' => 'workflowNodeEnd',\n ];\n\n protected static ?AgentMonitoring $instance = null;\n\n /**\n * @param Inspector $inspector The monitoring instance\n */\n public function __construct(\n protected Inspector $inspector,\n protected bool $autoFlush = false,\n ) {\n }\n\n\n public static function instance(): AgentMonitoring\n {\n $configuration = new Configuration($_ENV['INSPECTOR_INGESTION_KEY']);\n $configuration->setTransport($_ENV['INSPECTOR_TRANSPORT'] ?? 'async');\n $configuration->setVersion($_ENV['INSPECTOR_VERSION'] ?? $configuration->getVersion());\n\n // Split monitoring between agents and workflows.\n if (isset($_ENV['NEURON_SPLIT_MONITORING'])) {\n return new self(new Inspector($configuration), $_ENV['NEURON_AUTOFLUSH'] ?? false);\n }\n\n if (!self::$instance instanceof AgentMonitoring) {\n self::$instance = new self(new Inspector($configuration), $_ENV['NEURON_AUTOFLUSH'] ?? false);\n }\n return self::$instance;\n }\n\n public function update(\\SplSubject $subject, ?string $event = null, mixed $data = null): void\n {\n if (!\\is_null($event) && \\array_key_exists($event, $this->methodsMap)) {\n $method = $this->methodsMap[$event];\n $this->$method($subject, $event, $data);\n }\n }\n\n public function start(Agent $agent, string $event, mixed $data = null): void\n {\n if (!$this->inspector->isRecording()) {\n return;\n }\n\n $method = $this->getPrefix($event);\n $class = $agent::class;\n\n if ($this->inspector->needTransaction()) {\n $this->inspector->startTransaction($class.'::'.$method)\n ->setType('ai-agent')\n ->setContext($this->getContext($agent));\n } elseif ($this->inspector->canAddSegments() && !$agent instanceof RAG) { // do not add \"parent\" agent segments on RAG\n $key = $class.$method;\n\n if (\\array_key_exists($key, $this->segments)) {\n $key .= '-'.\\uniqid();\n }\n\n $segment = $this->inspector->startSegment(self::SEGMENT_TYPE.'-'.$method, \"{$class}::{$method}\")\n ->setColor(self::SEGMENT_COLOR);\n $segment->setContext($this->getContext($agent));\n $this->segments[$key] = $segment;\n }\n }\n\n /**\n * @throws \\Exception\n */\n public function stop(Agent $agent, string $event, mixed $data = null): void\n {\n $method = $this->getPrefix($event);\n $class = $agent::class;\n\n if (\\array_key_exists($class.$method, $this->segments)) {\n // End the last segment for the given method and agent class\n foreach (\\array_reverse($this->segments, true) as $key => $segment) {\n if ($key === $class.$method) {\n $segment->setContext($this->getContext($agent));\n $segment->end();\n unset($this->segments[$key]);\n break;\n }\n }\n } elseif ($this->inspector->canAddSegments()) {\n $transaction = $this->inspector->transaction()->setResult('success');\n $transaction->setContext($this->getContext($agent));\n\n if ($this->autoFlush) {\n $this->inspector->flush();\n }\n }\n }\n\n public function reportError(\\SplSubject $subject, string $event, AgentError $data): void\n {\n $this->inspector->reportException($data->exception, !$data->unhandled);\n\n if ($data->unhandled) {\n $this->inspector->transaction()->setResult('error');\n if ($subject instanceof Agent) {\n $this->inspector->transaction()->setContext($this->getContext($subject));\n }\n }\n }\n\n public function getPrefix(string $event): string\n {\n return \\explode('-', $event)[0];\n }\n\n protected function getContext(Agent $agent): array\n {\n $mapTool = fn (ToolInterface $tool) => [\n $tool->getName() => [\n 'description' => $tool->getDescription(),\n 'properties' => \\array_map(\n fn (ToolPropertyInterface $property) => $property->jsonSerialize(),\n $tool->getProperties()\n )\n ]\n ];\n\n return [\n 'Agent' => [\n 'provider' => $agent->resolveProvider()::class,\n 'instructions' => $agent->resolveInstructions(),\n ],\n 'Tools' => \\array_map(\n fn (ToolInterface|ToolkitInterface $tool) => $tool instanceof ToolInterface\n ? $mapTool($tool)\n : [$tool::class => \\array_map($mapTool, $tool->tools())],\n $agent->getTools()\n ),\n //'Messages' => $agent->resolveChatHistory()->getMessages(),\n ];\n }\n\n public function getMessageId(Message $message): string\n {\n $content = $message->getContent();\n\n if (!\\is_string($content)) {\n $content = \\json_encode($content, \\JSON_UNESCAPED_UNICODE);\n }\n\n return \\md5($content.$message->getRole());\n }\n\n protected function getBaseClassName(string $class): string\n {\n return \\substr(\\strrchr($class, '\\\\'), 1);\n }\n}\n"], ["/neuron-ai/src/Providers/Anthropic/Anthropic.php", "client = new Client([\n 'base_uri' => \\trim($this->baseUri, '/').'/',\n 'headers' => [\n 'Content-Type' => 'application/json',\n 'x-api-key' => $this->key,\n 'anthropic-version' => $version,\n ]\n ]);\n }\n\n public function systemPrompt(?string $prompt): AIProviderInterface\n {\n $this->system = $prompt;\n return $this;\n }\n\n public function messageMapper(): MessageMapperInterface\n {\n return new MessageMapper();\n }\n\n protected function generateToolsPayload(): array\n {\n return \\array_map(function (ToolInterface $tool): array {\n $properties = \\array_reduce($tool->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n\n return [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'input_schema' => [\n 'type' => 'object',\n 'properties' => empty($properties) ? null : $properties,\n 'required' => $tool->getRequiredProperties(),\n ],\n ];\n }, $this->tools);\n }\n\n public function createToolCallMessage(array $content): Message\n {\n $tool = $this->findTool($content['name'])\n ->setInputs($content['input'])\n ->setCallId($content['id']);\n\n // During serialization and deserialization PHP convert the original empty object {} to empty array []\n // causing an error on the Anthropic API. If there are no inputs, we need to restore the empty JSON object.\n if (empty($content['input'])) {\n $content['input'] = new \\stdClass();\n }\n\n return new ToolCallMessage(\n [$content],\n [$tool] // Anthropic call one tool at a time. So we pass an array with one element.\n );\n }\n}\n"], ["/neuron-ai/src/HandleStructured.php", "notify('structured-start');\n\n $this->fillChatHistory($messages);\n\n $tools = $this->bootstrapTools();\n\n // Get the JSON schema from the response model\n $class ??= $this->getOutputClass();\n $this->notify('schema-generation', new SchemaGeneration($class));\n $schema = (new JsonSchema())->generate($class);\n $this->notify('schema-generated', new SchemaGenerated($class, $schema));\n\n $error = '';\n do {\n try {\n // If something goes wrong, retry informing the model about the error\n if (\\trim($error) !== '') {\n $correctionMessage = new UserMessage(\n \"There was a problem in your previous response that generated the following errors\".\n \\PHP_EOL.\\PHP_EOL.'- '.$error.\\PHP_EOL.\\PHP_EOL.\n \"Try to generate the correct JSON structure based on the provided schema.\"\n );\n $this->fillChatHistory($correctionMessage);\n }\n\n $messages = $this->resolveChatHistory()->getMessages();\n\n $last = clone $this->resolveChatHistory()->getLastMessage();\n $this->notify(\n 'inference-start',\n new InferenceStart($last)\n );\n $response = $this->resolveProvider()\n ->systemPrompt($this->resolveInstructions())\n ->setTools($tools)\n ->structured($messages, $class, $schema);\n $this->notify(\n 'inference-stop',\n new InferenceStop($last, $response)\n );\n\n $this->fillChatHistory($response);\n\n if ($response instanceof ToolCallMessage) {\n $toolCallResult = $this->executeTools($response);\n return self::structured($toolCallResult, $class, $maxRetries);\n }\n\n $output = $this->processResponse($response, $schema, $class);\n $this->notify('structured-stop');\n return $output;\n } catch (RequestException $exception) {\n $error = $exception->getResponse()?->getBody()->getContents() ?? $exception->getMessage();\n $this->notify('error', new AgentError($exception, false));\n } catch (\\Exception $exception) {\n $error = $exception->getMessage();\n $this->notify('error', new AgentError($exception, false));\n }\n\n $maxRetries--;\n } while ($maxRetries >= 0);\n\n $exception = new AgentException(\n \"Impossible to generate a structured response for the class {$class}: {$error}\"\n );\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n\n protected function processResponse(\n Message $response,\n array $schema,\n string $class,\n ): mixed {\n // Try to extract a valid JSON object from the LLM response\n $this->notify('structured-extracting', new Extracting($response));\n $json = (new JsonExtractor())->getJson($response->getContent());\n $this->notify('structured-extracted', new Extracted($response, $schema, $json));\n if ($json === null || $json === '') {\n throw new AgentException(\"The response does not contains a valid JSON Object.\");\n }\n\n // Deserialize the JSON response from the LLM into an instance of the response model\n $this->notify('structured-deserializing', new Deserializing($class));\n $obj = Deserializer::fromJson($json, $class);\n $this->notify('structured-deserialized', new Deserialized($class));\n\n // Validate if the object fields respect the validation attributes\n // https://symfony.com/doc/current/validation.html#constraints\n $this->notify('structured-validating', new Validating($class, $json));\n\n $violations = Validator::validate($obj);\n\n if (\\count($violations) > 0) {\n $this->notify('structured-validated', new Validated($class, $json, $violations));\n throw new AgentException(\\PHP_EOL.'- '.\\implode(\\PHP_EOL.'- ', $violations));\n }\n $this->notify('structured-validated', new Validated($class, $json));\n\n return $obj;\n }\n\n protected function getOutputClass(): string\n {\n throw new AgentException('You need to specify an output class.');\n }\n}\n"], ["/neuron-ai/src/HandleChat.php", "chatAsync($messages)->wait();\n }\n\n public function chatAsync(Message|array $messages): PromiseInterface\n {\n $this->notify('chat-start');\n\n $this->fillChatHistory($messages);\n\n $tools = $this->bootstrapTools();\n\n $this->notify(\n 'inference-start',\n new InferenceStart($this->resolveChatHistory()->getLastMessage())\n );\n\n return $this->resolveProvider()\n ->systemPrompt($this->resolveInstructions())\n ->setTools($tools)\n ->chatAsync(\n $this->resolveChatHistory()->getMessages()\n )->then(function (Message $response): Message|PromiseInterface {\n $this->notify(\n 'inference-stop',\n new InferenceStop($this->resolveChatHistory()->getLastMessage(), $response)\n );\n\n $this->fillChatHistory($response);\n\n if ($response instanceof ToolCallMessage) {\n $toolCallResult = $this->executeTools($response);\n return self::chatAsync($toolCallResult);\n }\n\n $this->notify('chat-stop');\n return $response;\n }, function (\\Throwable $exception): void {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n });\n }\n}\n"], ["/neuron-ai/src/MCP/McpClient.php", "transport = new StdioTransport($config);\n $this->transport->connect();\n $this->initialize();\n } else {\n // todo: implement support for SSE with URL config property\n throw new McpException('Transport not supported!');\n }\n }\n\n protected function initialize(): void\n {\n $request = [\n \"jsonrpc\" => \"2.0\",\n \"id\" => ++$this->requestId,\n \"method\" => \"initialize\",\n \"params\" => [\n 'protocolVersion' => '2024-11-05',\n 'capabilities' => (object)[\n 'sampling' => new \\stdClass(),\n ],\n 'clientInfo' => (object)[\n 'name' => 'neuron-ai',\n 'version' => '1.0.0',\n ],\n ],\n ];\n $this->transport->send($request);\n $response = $this->transport->receive();\n\n if ($response['id'] !== $this->requestId) {\n throw new McpException('Invalid response ID');\n }\n\n $request = [\n \"jsonrpc\" => \"2.0\",\n \"method\" => \"notifications/initialized\",\n ];\n $this->transport->send($request);\n }\n\n /**\n * List all available tools from the MCP server\n *\n * @throws \\Exception\n */\n public function listTools(): array\n {\n $tools = [];\n\n do {\n $request = [\n \"jsonrpc\" => \"2.0\",\n \"id\" => ++$this->requestId,\n \"method\" => \"tools/list\",\n ];\n\n // Eventually add pagination\n if (isset($response['result']['nextCursor'])) {\n $request['params'] = ['cursor' => $response['result']['nextCursor']];\n }\n\n $this->transport->send($request);\n $response = $this->transport->receive();\n\n if ($response['id'] !== $this->requestId) {\n throw new McpException('Invalid response ID');\n }\n\n $tools = \\array_merge($tools, $response['result']['tools']);\n } while (isset($response['result']['nextCursor']));\n\n return $tools;\n }\n\n /**\n * Call a tool on the MCP server\n *\n * @throws \\Exception\n */\n public function callTool(string $toolName, array $arguments = []): array\n {\n $request = [\n \"jsonrpc\" => \"2.0\",\n \"id\" => ++$this->requestId,\n \"method\" => \"tools/call\",\n \"params\" => [\n \"name\" => $toolName,\n \"arguments\" => $arguments\n ]\n ];\n\n $this->transport->send($request);\n return $this->transport->receive();\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/JsonExtractor.php", "extractors = [\n fn (string $text): array => [$text], // Try as it is\n fn (string $text): array => $this->findByMarkdown($text),\n fn (string $text): ?string => $this->findByBrackets($text),\n fn (string $text): array => $this->findJSONLikeStrings($text),\n ];\n }\n\n /**\n * Attempt to find and parse a complete valid JSON string in the input.\n * Returns a JSON-encoded string on success or an empty string on failure.\n */\n public function getJson(string $input): ?string\n {\n foreach ($this->extractors as $extractor) {\n $candidates = $extractor($input);\n if (empty($candidates)) {\n continue;\n }\n if (\\is_string($candidates)) {\n $candidates = [$candidates];\n }\n\n foreach ($candidates as $candidate) {\n if (!\\is_string($candidate)) {\n continue;\n }\n if (\\trim($candidate) === '') {\n continue;\n }\n try {\n $data = $this->tryParse($candidate);\n } catch (\\Throwable) {\n continue;\n }\n\n if ($data !== null) {\n // Re-encode in canonical JSON form\n $result = \\json_encode($data);\n if ($result !== false) {\n return $result;\n }\n }\n }\n }\n\n return null;\n }\n\n /**\n * Returns an associative array on success, or null if the parsing fails.\n *\n * @throws \\JsonException\n */\n private function tryParse(string $maybeJson): ?array\n {\n $data = \\json_decode($maybeJson, true, 512, \\JSON_THROW_ON_ERROR);\n\n if ($data === false || $data === null || $data === '') {\n return null;\n }\n\n return $data;\n }\n\n /**\n * Find ALL fenced code blocks that start with ```json, and extract\n * the portion between the first '{' and the matching last '}' inside\n * that block. Return an array of candidates.\n */\n private function findByMarkdown(string $text): array\n {\n if (\\trim($text) === '') {\n return [];\n }\n\n $candidates = [];\n $offset = 0;\n $fenceTag = '```json';\n\n while (($startFence = \\strpos($text, $fenceTag, $offset)) !== false) {\n // Find the next triple-backtick fence AFTER the \"```json\"\n $closeFence = \\strpos($text, '```', $startFence + \\strlen($fenceTag));\n if ($closeFence === false) {\n // No closing fence found, stop scanning\n break;\n }\n\n // Substring that represents the code block between \"```json\" and \"```\"\n $codeBlock = \\substr(\n $text,\n $startFence + \\strlen($fenceTag),\n $closeFence - ($startFence + \\strlen($fenceTag))\n );\n\n // Now find the first '{' and last '}' within this code block\n $firstBrace = \\strpos($codeBlock, '{');\n $lastBrace = \\strrpos($codeBlock, '}');\n if ($firstBrace !== false && $lastBrace !== false && $firstBrace < $lastBrace) {\n $jsonCandidate = \\substr($codeBlock, $firstBrace, $lastBrace - $firstBrace + 1);\n $candidates[] = $jsonCandidate;\n }\n\n // Advance offset past the closing fence, so we can find subsequent code blocks\n $offset = $closeFence + 3; // skip '```'\n }\n\n return $candidates;\n }\n\n /**\n * Find a substring from the first '{' to the last '}'.\n */\n private function findByBrackets(string $text): ?string\n {\n $trimmed = \\trim($text);\n if ($trimmed === '') {\n return null;\n }\n $firstOpen = \\strpos($trimmed, '{');\n if ($firstOpen === 0 || $firstOpen === false) {\n return null;\n }\n\n $lastClose = \\strrpos($trimmed, '}');\n if ($lastClose === false || $lastClose < $firstOpen) {\n return null;\n }\n\n return \\substr($trimmed, $firstOpen, $lastClose - $firstOpen + 1);\n }\n\n /**\n * Scan through the text, capturing any substring that begins at '{'\n * and ends at its matching '}'—accounting for nested braces and strings.\n * Returns an array of all such candidates found.\n */\n private function findJSONLikeStrings(string $text): array\n {\n $text = \\trim($text);\n if ($text === '') {\n return [];\n }\n\n $candidates = [];\n $currentCandidate = '';\n $bracketCount = 0;\n $inString = false;\n $escape = false;\n $len = \\strlen($text);\n\n for ($i = 0; $i < $len; $i++) {\n $char = $text[$i];\n\n if (!$inString) {\n if ($char === '{') {\n if ($bracketCount === 0) {\n $currentCandidate = '';\n }\n $bracketCount++;\n } elseif ($char === '}') {\n $bracketCount--;\n }\n }\n\n // Toggle inString if we encounter an unescaped quote\n if ($char === '\"' && !$escape) {\n $inString = !$inString;\n }\n\n // Determine if current char is a backslash for next iteration\n $escape = ($char === '\\\\' && !$escape);\n\n if ($bracketCount > 0) {\n $currentCandidate .= $char;\n }\n\n // If bracketCount just went back to 0, we’ve closed a JSON-like block\n if ($bracketCount === 0 && $currentCandidate !== '') {\n $currentCandidate .= $char; // include the closing '}'\n $candidates[] = $currentCandidate;\n $currentCandidate = '';\n }\n }\n\n return $candidates;\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/ToolCallMessage.php", " $tools\n */\n public function __construct(\n protected array|string|int|float|null $content,\n protected array $tools\n ) {\n parent::__construct($this->content);\n }\n\n /**\n * @return array\n */\n public function getTools(): array\n {\n return $this->tools;\n }\n\n public function jsonSerialize(): array\n {\n return \\array_merge(\n parent::jsonSerialize(),\n [\n 'type' => 'tool_call',\n 'tools' => \\array_map(fn (ToolInterface $tool): array => $tool->jsonSerialize(), $this->tools)\n ]\n );\n }\n}\n"], ["/neuron-ai/src/MCP/McpConnector.php", "client = new McpClient($config);\n }\n\n /**\n * @param string[] $tools\n */\n public function exclude(array $tools): McpConnector\n {\n $this->exclude = $tools;\n return $this;\n }\n\n /**\n * @param string[] $tools\n */\n public function only(array $tools): McpConnector\n {\n $this->only = $tools;\n return $this;\n }\n\n /**\n * Get the list of available Tools from the server.\n *\n * @return ToolInterface[]\n * @throws \\Exception\n */\n public function tools(): array\n {\n // Filter by the only and exclude preferences.\n $tools = \\array_filter(\n $this->client->listTools(),\n fn (array $tool): bool =>\n !\\in_array($tool['name'], $this->exclude) &&\n ($this->only === [] || \\in_array($tool['name'], $this->only)),\n );\n\n return \\array_map(fn (array $tool): ToolInterface => $this->createTool($tool), $tools);\n }\n\n /**\n * Convert the list of tools from the MCP server to Neuron compatible entities.\n * @throws ArrayPropertyException\n * @throws \\ReflectionException\n * @throws ToolException\n */\n protected function createTool(array $item): ToolInterface\n {\n $tool = Tool::make(\n name: $item['name'],\n description: $item['description'] ?? null\n )->setCallable(function (...$arguments) use ($item) {\n $response = \\call_user_func($this->client->callTool(...), $item['name'], $arguments);\n\n if (\\array_key_exists('error', $response)) {\n throw new McpException($response['error']['message']);\n }\n\n $response = $response['result']['content'][0];\n\n if ($response['type'] === 'text') {\n return $response['text'];\n }\n\n if ($response['type'] === 'image') {\n return $response;\n }\n\n throw new McpException(\"Tool response format not supported: {$response['type']}\");\n });\n\n foreach ($item['inputSchema']['properties'] as $name => $prop) {\n $required = \\in_array($name, $item['inputSchema']['required'] ?? []);\n\n $type = PropertyType::fromSchema($prop['type']);\n\n $property = match ($type) {\n PropertyType::ARRAY => $this->createArrayProperty($name, $required, $prop),\n PropertyType::OBJECT => $this->createObjectProperty($name, $required, $prop),\n default => $this->createToolProperty($name, $type, $required, $prop),\n };\n\n $tool->addProperty($property);\n }\n\n return $tool;\n }\n\n protected function createToolProperty(string $name, PropertyType $type, bool $required, array $prop): ToolProperty\n {\n return new ToolProperty(\n name: $name,\n type: $type,\n description: $prop['description'] ?? null,\n required: $required,\n enum: $prop['items']['enum'] ?? []\n );\n }\n\n /**\n * @throws ArrayPropertyException\n */\n protected function createArrayProperty(string $name, bool $required, array $prop): ArrayProperty\n {\n return new ArrayProperty(\n name: $name,\n description: $prop['description'] ?? null,\n required: $required,\n items: new ToolProperty(\n name: 'type',\n type: PropertyType::from($prop['items']['type'] ?? 'string'),\n )\n );\n }\n\n /**\n * @throws \\ReflectionException\n */\n protected function createObjectProperty(string $name, bool $required, array $prop): ObjectProperty\n {\n return new ObjectProperty(\n name: $name,\n description: $prop['description'] ?? null,\n required: $required,\n );\n }\n}\n"], ["/neuron-ai/src/RAG/Splitter/SentenceTextSplitter.php", "= $maxWords) {\n throw new InvalidArgumentException('Overlap must be less than maxWords');\n }\n\n $this->maxWords = $maxWords;\n $this->overlapWords = $overlapWords;\n }\n\n /**\n * Splits text into word-based chunks, preserving sentence boundaries.\n *\n * @return Document[] Array of Document chunks\n */\n public function splitDocument(Document $document): array\n {\n // Split by paragraphs (2 or more newlines)\n $paragraphs = \\preg_split('/\\n{2,}/', $document->getContent());\n $chunks = [];\n $currentWords = [];\n\n foreach ($paragraphs as $paragraph) {\n $sentences = $this->splitSentences($paragraph);\n\n foreach ($sentences as $sentence) {\n $sentenceWords = $this->tokenizeWords($sentence);\n\n // If the sentence alone exceeds the limit, split it\n if (\\count($sentenceWords) > $this->maxWords) {\n if ($currentWords !== []) {\n $chunks[] = \\implode(' ', $currentWords);\n $currentWords = [];\n }\n $chunks = \\array_merge($chunks, $this->splitLongSentence($sentenceWords));\n continue;\n }\n\n $candidateCount = \\count($currentWords) + \\count($sentenceWords);\n\n if ($candidateCount > $this->maxWords) {\n if ($currentWords !== []) {\n $chunks[] = \\implode(' ', $currentWords);\n }\n $currentWords = $sentenceWords;\n } else {\n $currentWords = \\array_merge($currentWords, $sentenceWords);\n }\n }\n }\n\n if ($currentWords !== []) {\n $chunks[] = \\implode(' ', $currentWords);\n }\n\n // Apply overlap only if necessary\n if ($this->overlapWords > 0) {\n $chunks = $this->applyOverlap($chunks);\n }\n\n $split = [];\n foreach ($chunks as $chunk) {\n $newDocument = new Document($chunk);\n $newDocument->sourceType = $document->getSourceType();\n $newDocument->sourceName = $document->getSourceName();\n $split[] = $newDocument;\n }\n\n return $split;\n }\n\n /**\n * Robust regex for sentence splitting (handles ., !, ?, …, periods followed by quotes, etc)\n */\n private function splitSentences(string $text): array\n {\n $pattern = '/(?<=[.!?…])\\s+(?=(?:[\\\"\\'\\\"\"\\'\\'«»„\"\"]?)[A-ZÀ-Ÿ])/u';\n $sentences = \\preg_split($pattern, \\trim($text));\n return \\array_filter(\\array_map('trim', $sentences));\n }\n\n /**\n * Tokenizes text into words (simple whitespace split).\n *\n * @return string[] Array of words\n */\n private function tokenizeWords(string $text): array\n {\n return \\preg_split('/\\s+/u', \\trim($text));\n }\n\n /**\n * Applies overlap of words between consecutive chunks.\n *\n * @param string[] $chunks\n * @return string[] Array of chunks with overlap applied\n */\n private function applyOverlap(array $chunks): array\n {\n if ($chunks === []) {\n return [];\n }\n\n $result = [$chunks[0]]; // First chunk remains unchanged\n $count = \\count($chunks);\n\n for ($i = 1; $i < $count; $i++) {\n $prevWords = $this->tokenizeWords($chunks[$i - 1]);\n $curWords = $this->tokenizeWords($chunks[$i]);\n\n // Get only the words needed for overlap\n $overlap = \\array_slice($prevWords, -$this->overlapWords);\n\n // Remove duplicate words at the beginning of current chunk\n $curWords = \\array_slice($curWords, $this->overlapWords);\n\n $merged = \\array_merge($overlap, $curWords);\n $result[] = \\implode(' ', $merged);\n }\n\n return $result;\n }\n\n /**\n * Splits a long sentence into smaller chunks that respect the maxWords limit.\n *\n * @param string[] $words Array of words from the sentence\n * @return string[] Array of chunks\n */\n private function splitLongSentence(array $words): array\n {\n $chunks = [];\n $currentChunk = [];\n\n foreach ($words as $word) {\n if (\\count($currentChunk) >= $this->maxWords) {\n $chunks[] = \\implode(' ', $currentChunk);\n $currentChunk = [];\n }\n $currentChunk[] = $word;\n }\n\n if ($currentChunk !== []) {\n $chunks[] = \\implode(' ', $currentChunk);\n }\n\n return $chunks;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/VectorSimilarity.php", " $value) {\n if (isset($vector2[$key])) {\n $dotProduct += $value * $vector2[$key];\n }\n $magnitude1 += $value ** 2;\n }\n\n foreach ($vector2 as $value) {\n $magnitude2 += $value ** 2;\n }\n\n if ($magnitude1 === 0.0 || $magnitude2 === 0.0) {\n return 0.0;\n }\n\n return $dotProduct / (\\sqrt($magnitude1) * \\sqrt($magnitude2));\n }\n\n public static function cosineDistance(array $vector1, array $vector2): float|int\n {\n return 1 - self::cosineSimilarity($vector1, $vector2);\n }\n\n public static function similarityFromDistance(float|int $distance): float|int\n {\n return 1 - $distance;\n }\n}\n"], ["/neuron-ai/src/Observability/HandleInferenceEvents.php", "inspector->canAddSegments()) {\n return;\n }\n\n $label = $this->getBaseClassName($data->message::class);\n\n $this->segments[$this->getMessageId($data->message).'-save'] = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-chathistory', \"save_message( {$label} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function messageSaved(Agent $agent, string $event, MessageSaved $data): void\n {\n $id = $this->getMessageId($data->message).'-save';\n\n if (!\\array_key_exists($id, $this->segments)) {\n return;\n }\n\n $segment = $this->segments[$id];\n $segment->addContext('Message', \\array_merge(\n $data->message->jsonSerialize(),\n $data->message->getUsage() instanceof Usage ? [\n 'usage' => [\n 'input_tokens' => $data->message->getUsage()->inputTokens,\n 'output_tokens' => $data->message->getUsage()->outputTokens,\n ]\n ] : []\n ));\n $segment->end();\n }\n\n public function inferenceStart(Agent $agent, string $event, InferenceStart $data): void\n {\n if (!$this->inspector->canAddSegments() || $data->message === false) {\n return;\n }\n\n $label = $this->getBaseClassName($data->message::class);\n\n $this->segments[$this->getMessageId($data->message).'-inference'] = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-inference', \"inference( {$label} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function inferenceStop(Agent $agent, string $event, InferenceStop $data): void\n {\n $id = $this->getMessageId($data->message).'-inference';\n\n if (\\array_key_exists($id, $this->segments)) {\n $segment = $this->segments[$id]->end();\n $segment->addContext('Message', $data->message)\n ->addContext('Response', $data->response);\n }\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/TypesenseVectorStore.php", "client->collections[$this->collection]->retrieve();\n $this->checkVectorDimension(\\count($document->getEmbedding()));\n return;\n } catch (ObjectNotFound) {\n $fields = [\n [\n 'name' => 'content',\n 'type' => 'string',\n ],\n [\n 'name' => 'sourceType',\n 'type' => 'string',\n 'facet' => true,\n ],\n [\n 'name' => 'sourceName',\n 'type' => 'string',\n 'facet' => true,\n ],\n [\n 'name' => 'embedding',\n 'type' => 'float[]',\n 'num_dim' => $this->vectorDimension,\n ],\n ];\n\n // Map custom fields\n foreach ($document->metadata as $name => $value) {\n $fields[] = [\n 'name' => $name,\n 'type' => \\gettype($value),\n 'facet' => true,\n ];\n }\n\n $this->client->collections->create([\n 'name' => $this->collection,\n 'fields' => $fields,\n ]);\n }\n }\n\n public function addDocument(Document $document): void\n {\n if ($document->getEmbedding() === []) {\n throw new \\Exception('document embedding must be set before adding a document');\n }\n\n $this->checkIndexStatus($document);\n\n $this->client->collections[$this->collection]->documents->create([\n 'id' => $document->getId(), // Unique ID is required\n 'content' => $document->getContent(),\n 'embedding' => $document->getEmbedding(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->collections[$this->collection]->documents->delete([\n \"filter_by\" => \"sourceType:={$sourceType} && sourceName:={$sourceName}\",\n ]);\n }\n\n /**\n * Bulk save.\n *\n * @param Document[] $documents\n * @throws Exception\n * @throws \\JsonException\n * @throws TypesenseClientError\n */\n public function addDocuments(array $documents): void\n {\n if ($documents === []) {\n return;\n }\n\n if (empty($documents[0]->getEmbedding())) {\n throw new \\Exception('document embedding must be set before adding a document');\n }\n\n $this->checkIndexStatus($documents[0]);\n\n $lines = [];\n foreach ($documents as $document) {\n $lines[] = \\json_encode([\n 'id' => $document->getId(), // Unique ID is required\n 'embedding' => $document->getEmbedding(),\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ]);\n }\n\n $ndjson = \\implode(\"\\n\", $lines);\n\n $this->client->collections[$this->collection]->documents->import($ndjson);\n }\n\n public function similaritySearch(array $embedding): array\n {\n $params = [\n 'collection' => $this->collection,\n 'q' => '*',\n 'vector_query' => 'embedding:(' . \\json_encode($embedding) . ')',\n 'exclude_fields' => 'embedding',\n 'per_page' => $this->topK,\n 'num_candidates' => \\max(50, \\intval($this->topK) * 4),\n ];\n\n $searchRequests = ['searches' => [$params]];\n\n $response = $this->client->multiSearch->perform($searchRequests);\n return \\array_map(function (array $hit): Document {\n $item = $hit['document'];\n $document = new Document($item['content']);\n //$document->embedding = $item['embedding']; // avoid carrying large data\n $document->sourceType = $item['sourceType'];\n $document->sourceName = $item['sourceName'];\n $document->score = VectorSimilarity::similarityFromDistance($hit['vector_distance']);\n\n foreach ($item as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName', 'score', 'embedding', 'id', 'vector_distance'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $response['results'][0]['hits']);\n }\n\n private function checkVectorDimension(int $dimension): void\n {\n $schema = $this->client->collections[$this->collection]->retrieve();\n\n $embeddingField = null;\n\n foreach ($schema['fields'] as $field) {\n if ($field['name'] === 'embedding') {\n $embeddingField = $field;\n break;\n }\n }\n\n if (\n \\array_key_exists('num_dim', $embeddingField)\n && $embeddingField['num_dim'] === $dimension\n ) {\n return;\n }\n\n throw new \\Exception(\n \"Vector embeddings dimension {$dimension} must be the same as the initial setup {$this->vectorDimension} - \".\n \\json_encode($embeddingField)\n );\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/MeilisearchVectorStore.php", "client = new Client([\n 'base_uri' => \\trim($host, '/').'/indexes/'.$indexUid.'/',\n 'headers' => [\n 'Content-Type' => 'application/json',\n ...(\\is_null($key) ? [] : ['Authorization' => \"Bearer {$key}\"])\n ]\n ]);\n\n try {\n $this->client->get('');\n } catch (\\Exception) {\n throw new VectorStoreException(\"Index {$indexUid} doesn't exists. Remember to attach a custom embedder to the index in order to process vectors.\");\n }\n }\n\n public function addDocument(Document $document): void\n {\n $this->addDocuments([$document]);\n }\n\n public function addDocuments(array $documents): void\n {\n $this->client->put('documents', [\n RequestOptions::JSON => \\array_map(fn (Document $document) => [\n 'id' => $document->getId(),\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n '_vectors' => [\n 'default' => [\n 'embeddings' => $document->getEmbedding(),\n 'regenerate' => false,\n ],\n ]\n ], $documents),\n ]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->post('documents/delete', [\n RequestOptions::JSON => [\n 'filter' => \"sourceType = {$sourceType} AND sourceName = {$sourceName}\",\n ]\n ]);\n }\n\n public function similaritySearch(array $embedding): iterable\n {\n $response = $this->client->post('search', [\n RequestOptions::JSON => [\n 'vector' => $embedding,\n 'limit' => \\min($this->topK, 20),\n 'retrieveVectors' => true,\n 'showRankingScore' => true,\n 'hybrid' => [\n 'semanticRatio' => 1.0,\n 'embedder' => $this->embedder,\n ],\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return \\array_map(function (array $item): Document {\n $document = new Document($item['content']);\n $document->id = $item['id'] ?? \\uniqid();\n $document->sourceType = $item['sourceType'] ?? null;\n $document->sourceName = $item['sourceName'] ?? null;\n $document->embedding = $item['_vectors']['default']['embeddings'];\n $document->score = $item['_rankingScore'];\n\n foreach ($item as $name => $value) {\n if (!\\in_array($name, ['_vectors', '_rankingScore', 'content', 'sourceType', 'sourceName', 'score', 'embedding', 'id'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $response['hits']);\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/FileVectorStore.php", "directory)) {\n throw new VectorStoreException(\"Directory '{$this->directory}' does not exist\");\n }\n }\n\n protected function getFilePath(): string\n {\n return $this->directory . \\DIRECTORY_SEPARATOR . $this->name.$this->ext;\n }\n\n public function addDocument(Document $document): void\n {\n $this->addDocuments([$document]);\n }\n\n public function addDocuments(array $documents): void\n {\n $this->appendToFile(\n \\array_map(fn (Document $document): array => $document->jsonSerialize(), $documents)\n );\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n // Temporary file\n $tmpFile = $this->directory . \\DIRECTORY_SEPARATOR . $this->name.'_tmp'.$this->ext;\n\n // Create a temporary file handle\n $tempHandle = \\fopen($tmpFile, 'w');\n if (!$tempHandle) {\n throw new \\RuntimeException(\"Cannot create temporary file: {$tmpFile}\");\n }\n\n try {\n foreach ($this->getLine($this->getFilePath()) as $line) {\n $document = \\json_decode((string) $line, true);\n\n if ($document['sourceType'] !== $sourceType || $document['sourceName'] !== $sourceName) {\n \\fwrite($tempHandle, (string) $line);\n }\n }\n } finally {\n \\fclose($tempHandle);\n }\n\n // Replace the original file with the filtered version\n \\unlink($this->getFilePath());\n if (!\\rename($tmpFile, $this->getFilePath())) {\n throw new VectorStoreException(self::class.\" failed to replace original file.\");\n }\n }\n\n public function similaritySearch(array $embedding): array\n {\n $topItems = [];\n\n foreach ($this->getLine($this->getFilePath()) as $document) {\n $document = \\json_decode((string) $document, true);\n\n if (empty($document['embedding'])) {\n throw new VectorStoreException(\"Document with the following content has no embedding: {$document['content']}\");\n }\n $dist = VectorSimilarity::cosineDistance($embedding, $document['embedding']);\n\n $topItems[] = ['dist' => $dist, 'document' => $document];\n\n \\usort($topItems, fn (array $a, array $b): int => $a['dist'] <=> $b['dist']);\n\n if (\\count($topItems) > $this->topK) {\n $topItems = \\array_slice($topItems, 0, $this->topK, true);\n }\n }\n\n return \\array_map(function (array $item): Document {\n $itemDoc = $item['document'];\n $document = new Document($itemDoc['content']);\n $document->embedding = $itemDoc['embedding'];\n $document->sourceType = $itemDoc['sourceType'];\n $document->sourceName = $itemDoc['sourceName'];\n $document->id = $itemDoc['id'];\n $document->score = VectorSimilarity::similarityFromDistance($item['dist']);\n $document->metadata = $itemDoc['metadata'] ?? [];\n\n return $document;\n }, $topItems);\n }\n\n protected function appendToFile(array $documents): void\n {\n \\file_put_contents(\n $this->getFilePath(),\n \\implode(\\PHP_EOL, \\array_map(fn (array $vector) => \\json_encode($vector), $documents)).\\PHP_EOL,\n \\FILE_APPEND\n );\n }\n\n protected function getLine(string $filename): \\Generator\n {\n $f = \\fopen($filename, 'r');\n\n try {\n while ($line = \\fgets($f)) {\n yield $line;\n }\n } finally {\n \\fclose($f);\n }\n }\n}\n"], ["/neuron-ai/src/Providers/Gemini/HandleStructured.php", "parameters)) {\n $this->parameters['generationConfig'] = [\n 'temperature' => 0,\n ];\n }\n\n // Gemini does not support structured output in combination with tools.\n // So we try to work with a JSON mode in case the agent has some tools defined.\n if (!empty($this->tools)) {\n $last_message = \\end($messages);\n if ($last_message instanceof Message && $last_message->getRole() === MessageRole::USER->value) {\n $last_message->setContent(\n $last_message->getContent() . ' Respond using this JSON schema: '.\\json_encode($response_format)\n );\n }\n } else {\n // If there are no tools, we can enforce the structured output.\n $this->parameters['generationConfig']['response_schema'] = $this->adaptSchema($response_format);\n $this->parameters['generationConfig']['response_mime_type'] = 'application/json';\n }\n\n return $this->chat($messages);\n }\n\n /**\n * Gemini does not support additionalProperties attribute.\n */\n protected function adaptSchema(array $schema): array\n {\n if (\\array_key_exists('additionalProperties', $schema)) {\n unset($schema['additionalProperties']);\n }\n\n foreach ($schema as $key => $value) {\n if (\\is_array($value)) {\n $schema[$key] = $this->adaptSchema($value);\n }\n }\n\n return $schema;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/StandardDeviationTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|float|int $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n if (\\count($numericData) === 1 && $this->sample) {\n return ['error' => 'Cannot calculate sample standard deviation with only one data point'];\n }\n\n // Convert to float values\n $numericData = \\array_map('floatval', $numericData);\n\n // Calculate mean\n $mean = \\array_sum($numericData) / \\count($numericData);\n\n // Calculate the sum of squared differences\n $sumSquaredDifferences = 0;\n foreach ($numericData as $value) {\n $sumSquaredDifferences += ($value - $mean) ** 2;\n }\n\n // Calculate variance\n $divisor = $this->sample ? \\count($numericData) - 1 : \\count($numericData);\n $variance = $sumSquaredDifferences / $divisor;\n\n // Calculate standard deviation\n $standardDeviation = \\sqrt($variance);\n\n return \\round($standardDeviation, $this->precision);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/VarianceTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|float|int $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n if (\\count($numericData) === 1 && $this->sample) {\n return ['error' => 'Cannot calculate sample variance with only one data point'];\n }\n\n // Convert to float values\n $numericData = \\array_map('floatval', $numericData);\n\n // Calculate mean\n $mean = \\array_sum($numericData) / \\count($numericData);\n\n // Calculate the sum of squared differences\n $sumSquaredDifferences = 0;\n foreach ($numericData as $value) {\n $sumSquaredDifferences += ($value - $mean) ** 2;\n }\n\n // Calculate variance\n $divisor = $this->sample ? \\count($numericData) - 1 : \\count($numericData);\n $variance = $sumSquaredDifferences / $divisor;\n\n return \\round($variance, $this->precision);\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/ToolCallResultMessage.php", " $tools\n */\n public function __construct(protected array $tools)\n {\n parent::__construct(null);\n }\n\n /**\n * @return array\n */\n public function getTools(): array\n {\n return $this->tools;\n }\n\n public function jsonSerialize(): array\n {\n return \\array_merge(\n parent::jsonSerialize(),\n [\n 'type' => 'tool_call_result',\n 'tools' => \\array_map(fn (ToolInterface $tool): array => $tool->jsonSerialize(), $this->tools)\n ]\n );\n }\n}\n"], ["/neuron-ai/src/MCP/StdioTransport.php", " [\"pipe\", \"r\"], // stdin\n 1 => [\"pipe\", \"w\"], // stdout\n 2 => [\"pipe\", \"w\"] // stderr\n ];\n\n $command = $this->config['command'];\n $args = $this->config['args'] ?? [];\n $env = $this->config['env'] ?? [];\n\n // Merge current environment with provided environment variables\n $fullEnv = \\array_merge(\\getenv(), $env);\n\n // Build command with arguments\n $commandLine = $command;\n foreach ($args as $arg) {\n $commandLine .= ' ' . \\escapeshellarg((string) $arg);\n }\n\n // Start the process\n $this->process = \\proc_open(\n $commandLine,\n $descriptorSpec,\n $this->pipes,\n null,\n $fullEnv\n );\n\n if (!\\is_resource($this->process)) {\n throw new McpException(\"Failed to start the MCP server process\");\n }\n\n // Configure pipes for binary data\n \\stream_set_write_buffer($this->pipes[0], 0);\n \\stream_set_read_buffer($this->pipes[1], 0);\n\n // Check that the process started successfully\n $status = \\proc_get_status($this->process);\n if (!$status['running']) {\n $error = \\stream_get_contents($this->pipes[2]);\n throw new McpException(\"Process failed to start: \" . $error);\n }\n }\n\n /**\n * Send a request to the MCP server\n */\n public function send(array $data): void\n {\n if (!\\is_resource($this->process)) {\n throw new McpException(\"Process is not running\");\n }\n\n $status = \\proc_get_status($this->process);\n if (!$status['running']) {\n throw new McpException(\"MCP server process is not running\");\n }\n\n $jsonData = \\json_encode($data);\n if ($jsonData === false) {\n throw new McpException(\"Failed to encode request data to JSON\");\n }\n\n $bytesWritten = \\fwrite($this->pipes[0], $jsonData . \"\\n\");\n if ($bytesWritten === false || $bytesWritten < \\strlen($jsonData) + 1) {\n throw new McpException(\"Failed to write complete request to MCP server\");\n }\n\n \\fflush($this->pipes[0]);\n }\n\n /**\n * Receive a response from the MCP server\n */\n public function receive(): array\n {\n if (!\\is_resource($this->process)) {\n throw new McpException(\"Process is not running\");\n }\n\n // Set stream to non-blocking mode\n \\stream_set_blocking($this->pipes[1], false);\n\n $response = \"\";\n $startTime = \\time();\n $timeout = 30; // 30-second timeout\n\n // Keep reading until we get a complete JSON response or timeout\n while (\\time() - $startTime < $timeout) {\n $status = \\proc_get_status($this->process);\n\n if (!$status['running']) {\n throw new McpException(\"MCP server process has terminated unexpectedly.\");\n }\n\n $chunk = \\fread($this->pipes[1], 4096);\n if ($chunk !== false && \\strlen($chunk) > 0) {\n $response .= $chunk;\n\n // Try to parse what we have so far\n $decoded = \\json_decode($response, true);\n if ($decoded !== null) {\n // We've got a valid JSON response\n return $decoded;\n }\n }\n\n // Small delay to prevent CPU spinning\n \\usleep(10000); // 10ms\n }\n\n throw new McpException(\"Timeout waiting for response from MCP server\");\n }\n\n /**\n * Disconnect from the MCP server\n */\n public function disconnect(): void\n {\n if (\\is_resource($this->process)) {\n // Close all pipe handles\n foreach ($this->pipes as $pipe) {\n if (\\is_resource($pipe)) {\n \\fclose($pipe);\n }\n }\n\n // Try graceful termination first\n $status = \\proc_get_status($this->process);\n // On Unix systems, try sending SIGTERM\n if ($status['running'] && \\function_exists('proc_terminate')) {\n \\proc_terminate($this->process);\n // Give the process a moment to shut down gracefully\n \\usleep(500000);\n // 500ms\n }\n\n // Close the process handle\n \\proc_close($this->process);\n $this->process = null;\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Tool.php", "properties = $properties;\n }\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n public function getDescription(): ?string\n {\n return $this->description;\n }\n\n public function addProperty(ToolPropertyInterface $property): ToolInterface\n {\n $this->properties[] = $property;\n return $this;\n }\n\n /**\n * @return ToolPropertyInterface[]\n */\n protected function properties(): array\n {\n return [];\n }\n\n /**\n * @return ToolPropertyInterface[]\n */\n public function getProperties(): array\n {\n if ($this->properties === []) {\n foreach ($this->properties() as $property) {\n $this->addProperty($property);\n }\n }\n\n return $this->properties;\n }\n\n public function getRequiredProperties(): array\n {\n return \\array_reduce($this->getProperties(), function (array $carry, ToolPropertyInterface $property): array {\n if ($property->isRequired()) {\n $carry[] = $property->getName();\n }\n\n return $carry;\n }, []);\n }\n\n public function setCallable(callable $callback): self\n {\n $this->callback = $callback;\n return $this;\n }\n\n public function getInputs(): array\n {\n return $this->inputs ?? [];\n }\n\n public function setInputs(?array $inputs): self\n {\n $this->inputs = $inputs ?? [];\n return $this;\n }\n\n public function getCallId(): ?string\n {\n return $this->callId;\n }\n\n public function setCallId(?string $callId): self\n {\n $this->callId = $callId;\n return $this;\n }\n\n public function getResult(): string\n {\n return $this->result;\n }\n\n public function setResult(mixed $result): self\n {\n $this->result = \\is_array($result) ? \\json_encode($result) : (string) $result;\n\n return $this;\n }\n\n /**\n * Execute the client side function.\n *\n * @throws MissingCallbackParameter\n * @throws ToolCallableNotSet\n * @throws DeserializerException\n * @throws \\ReflectionException\n */\n public function execute(): void\n {\n if (!\\is_callable($this->callback) && !\\method_exists($this, '__invoke')) {\n throw new ToolCallableNotSet('No function defined for tool execution.');\n }\n\n // Validate required parameters\n foreach ($this->getProperties() as $property) {\n if ($property->isRequired() && !\\array_key_exists($property->getName(), $this->getInputs())) {\n throw new MissingCallbackParameter(\"Missing required parameter: {$property->getName()}\");\n }\n }\n\n $parameters = \\array_reduce($this->getProperties(), function (array $carry, ToolPropertyInterface $property) {\n $propertyName = $property->getName();\n $inputs = $this->getInputs();\n\n // Normalize missing optional properties by assigning them a null value\n // Treat it as explicitly null to ensure a consistent structure\n if (!\\array_key_exists($propertyName, $inputs)) {\n $carry[$propertyName] = null;\n return $carry;\n }\n\n // Find the corresponding input value\n $inputValue = $inputs[$propertyName];\n\n // If there is an object property with a class definition,\n // deserialize the tool input into an instance of that class\n if ($property instanceof ObjectProperty && $property->getClass()) {\n $carry[$propertyName] = Deserializer::fromJson(\\json_encode($inputValue), $property->getClass());\n return $carry;\n }\n\n // If a property is an array of objects and each item matches a class definition,\n // deserialize each item into an instance of that class\n if ($property instanceof ArrayProperty) {\n $items = $property->getItems();\n if ($items instanceof ObjectProperty && $items->getClass()) {\n $class = $items->getClass();\n $carry[$propertyName] = \\array_map(fn (array|object $input): object => Deserializer::fromJson(\\json_encode($input), $class), $inputValue);\n return $carry;\n }\n }\n\n // No extra treatments for basic property types\n $carry[$propertyName] = $inputValue;\n return $carry;\n\n }, []);\n\n $this->setResult(\n \\method_exists($this, '__invoke') ? $this->__invoke(...$parameters)\n : \\call_user_func($this->callback, ...$parameters)\n );\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'name' => $this->name,\n 'description' => $this->description,\n 'inputs' => $this->inputs === [] ? new \\stdClass() : $this->inputs,\n 'callId' => $this->callId,\n 'result' => $this->result,\n ];\n }\n}\n"], ["/neuron-ai/src/ResolveChatHistory.php", "chatHistory = $chatHistory;\n return $this;\n }\n\n /**\n * Used extending the Agent.\n */\n protected function chatHistory(): ChatHistoryInterface\n {\n return new InMemoryChatHistory();\n }\n\n public function fillChatHistory(Message|array $messages): void\n {\n $messages = \\is_array($messages) ? $messages : [$messages];\n\n foreach ($messages as $message) {\n $this->notify('message-saving', new MessageSaving($message));\n $this->resolveChatHistory()->addMessage($message);\n $this->notify('message-saved', new MessageSaved($message));\n }\n }\n\n /**\n * Get the current instance of the chat history.\n */\n public function resolveChatHistory(): ChatHistoryInterface\n {\n if (!isset($this->chatHistory)) {\n $this->chatHistory = $this->chatHistory();\n }\n\n return $this->chatHistory;\n }\n}\n"], ["/neuron-ai/src/RAG/Splitter/DelimiterTextSplitter.php", "getContent();\n\n if ($text === '') {\n return [];\n }\n\n if (\\strlen($text) <= $this->maxLength) {\n return [$document];\n }\n\n $parts = \\explode($this->separator, $text);\n\n $chunks = $this->createChunksWithOverlap($parts);\n\n $split = [];\n foreach ($chunks as $chunk) {\n $newDocument = new Document($chunk);\n $newDocument->sourceType = $document->getSourceType();\n $newDocument->sourceName = $document->getSourceName();\n $split[] = $newDocument;\n }\n\n return $split;\n }\n\n /**\n * @param array $words\n * @return array\n */\n private function createChunksWithOverlap(array $words): array\n {\n $chunks = [];\n $currentChunk = [];\n $currentChunkLength = 0;\n foreach ($words as $word) {\n if ($word === '') {\n continue;\n }\n\n if ($currentChunkLength + \\strlen($this->separator.$word) <= $this->maxLength || $currentChunk === []) {\n $currentChunk[] = $word;\n $currentChunkLength = $this->calculateChunkLength($currentChunk);\n } else {\n // Add the chunk with overlap\n $chunks[] = \\implode($this->separator, $currentChunk);\n\n // Calculate overlap words\n $calculatedOverlap = \\min($this->wordOverlap, \\count($currentChunk) - 1);\n $overlapWords = $calculatedOverlap > 0 ? \\array_slice($currentChunk, -$calculatedOverlap) : [];\n\n // Start a new chunk with overlap words\n $currentChunk = [...$overlapWords, $word];\n $currentChunk[0] = \\trim($currentChunk[0]);\n $currentChunkLength = $this->calculateChunkLength($currentChunk);\n }\n }\n\n if ($currentChunk !== []) {\n $chunks[] = \\implode($this->separator, $currentChunk);\n }\n\n return $chunks;\n }\n\n /**\n * @param array $chunk\n */\n private function calculateChunkLength(array $chunk): int\n {\n return \\array_sum(\\array_map('strlen', $chunk)) + \\count($chunk) * \\strlen($this->separator) - 1;\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/JsonSchema.php", "processedClasses = [];\n\n // Generate the main schema\n return [\n ...$this->generateClassSchema($class),\n 'additionalProperties' => false,\n ];\n }\n\n /**\n * Generate schema for a class\n *\n * @param string $class Class name\n * @return array The schema\n * @throws ReflectionException\n */\n private function generateClassSchema(string $class): array\n {\n $reflection = new ReflectionClass($class);\n\n // Check for circular reference\n if (\\in_array($class, $this->processedClasses)) {\n // For circular references, return a simple object schema to break the cycle\n return ['type' => 'object'];\n }\n\n $this->processedClasses[] = $class;\n\n // Handle enum types differently\n if ($reflection->isEnum()) {\n $result = $this->processEnum(new ReflectionEnum($class));\n // Remove the class from the processed list after processing\n \\array_pop($this->processedClasses);\n return $result;\n }\n\n // Create a basic object schema\n $schema = [\n 'type' => 'object',\n 'properties' => [],\n ];\n\n $requiredProperties = [];\n\n // Process all public properties\n $properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);\n\n // Process each property\n foreach ($properties as $property) {\n $propertyName = $property->getName();\n\n $schema['properties'][$propertyName] = $this->processProperty($property);\n\n $attribute = $this->getPropertyAttribute($property);\n if ($attribute instanceof SchemaProperty && $attribute->required !== null) {\n if ($attribute->required) {\n $requiredProperties[] = $propertyName;\n }\n } else {\n // If the attribute is not available,\n // use the default logic for required properties\n $type = $property->getType();\n\n $isNullable = $type ? $type->allowsNull() : true;\n\n if (!$isNullable && !$property->hasDefaultValue()) {\n $requiredProperties[] = $propertyName;\n }\n }\n }\n\n // Add required properties\n if ($requiredProperties !== []) {\n $schema['required'] = $requiredProperties;\n }\n\n // Remove the class from the processed list after processing\n \\array_pop($this->processedClasses);\n\n return $schema;\n }\n\n /**\n * Process a single property to generate its schema\n *\n * @return array Property schema\n * @throws ReflectionException\n */\n private function processProperty(ReflectionProperty $property): array\n {\n $schema = [];\n\n // Process Property attribute if present\n $attribute = $this->getPropertyAttribute($property);\n if ($attribute instanceof SchemaProperty) {\n if ($attribute->title !== null) {\n $schema['title'] = $attribute->title;\n }\n\n if ($attribute->description !== null) {\n $schema['description'] = $attribute->description;\n }\n }\n\n /** @var ?ReflectionNamedType $type */\n $type = $property->getType();\n $typeName = $type?->getName();\n\n // Handle default values\n if ($property->hasDefaultValue()) {\n $schema['default'] = $property->getDefaultValue();\n }\n\n // Process different types\n if ($typeName === 'array') {\n $schema['type'] = 'array';\n\n // Parse PHPDoc for the array item type\n $docComment = $property->getDocComment();\n if ($docComment) {\n // Extract type from both \"@var \\App\\Type[]\" and \"@var array<\\App\\Type>\"\n \\preg_match('/@var\\s+(?:([a-zA-Z0-9_\\\\\\\\]+)\\[\\]|array<([a-zA-Z0-9_\\\\\\\\]+)>)/', $docComment, $matches);\n\n if (isset($matches[1]) || isset($matches[2])) {\n $itemType = empty($matches[1]) ? ((isset($matches[2]) && $matches[2] !== '0') ? $matches[2] : null) : ($matches[1]);\n\n // Handle class type for array items\n if (\\class_exists($itemType) || \\enum_exists($itemType)) {\n $schema['items'] = $this->generateClassSchema($itemType);\n } else {\n // Basic type\n $schema['items'] = $this->getBasicTypeSchema($itemType);\n }\n } else {\n // Default to string if no specific type found\n $schema['items'] = ['type' => 'string'];\n }\n } else {\n // Default to string if no doc comment\n $schema['items'] = ['type' => 'string'];\n }\n }\n // Handle enum types\n elseif ($typeName && \\enum_exists($typeName)) {\n $enumReflection = new ReflectionEnum($typeName);\n $schema = \\array_merge($schema, $this->processEnum($enumReflection));\n }\n // Handle class types\n elseif ($typeName && \\class_exists($typeName)) {\n $classSchema = $this->generateClassSchema($typeName);\n $schema = \\array_merge($schema, $classSchema);\n }\n // Handle basic types\n elseif ($typeName) {\n $typeSchema = $this->getBasicTypeSchema($typeName);\n $schema = \\array_merge($schema, $typeSchema);\n } else {\n // Default to string if no type hint\n $schema['type'] = 'string';\n }\n\n // Handle nullable types - for basic types only\n if ($type && $type->allowsNull() && isset($schema['type']) && !isset($schema['$ref']) && !isset($schema['allOf'])) {\n if (\\is_array($schema['type'])) {\n if (!\\in_array('null', $schema['type'])) {\n $schema['type'][] = 'null';\n }\n } else {\n $schema['type'] = [$schema['type'], 'null'];\n }\n }\n\n return $schema;\n }\n\n /**\n * Process an enum to generate its schema\n */\n private function processEnum(ReflectionEnum $enum): array\n {\n // Create enum schema\n $schema = [\n 'type' => 'string',\n 'enum' => [],\n ];\n\n // Extract enum values\n foreach ($enum->getCases() as $case) {\n if ($enum->isBacked()) {\n /** @var ReflectionEnumBackedCase $case */\n // For backed enums, use the backing value\n $schema['enum'][] = $case->getBackingValue();\n } else {\n // For non-backed enums, use case name\n $schema['enum'][] = $case->getName();\n }\n }\n\n return $schema;\n }\n\n /**\n * Get the Property attribute if it exists on a property\n */\n private function getPropertyAttribute(ReflectionProperty $property): ?SchemaProperty\n {\n $attributes = $property->getAttributes(SchemaProperty::class);\n if ($attributes !== []) {\n return $attributes[0]->newInstance();\n }\n return null;\n }\n\n /**\n * Get schema for a basic PHP type\n *\n * @param string $type PHP type name\n * @return array Schema for the type\n * @throws ReflectionException\n */\n private function getBasicTypeSchema(string $type): array\n {\n switch ($type) {\n case 'string':\n return ['type' => 'string'];\n\n case 'int':\n case 'integer':\n return ['type' => 'integer'];\n\n case 'float':\n case 'double':\n return ['type' => 'number'];\n\n case 'bool':\n case 'boolean':\n return ['type' => 'boolean'];\n\n case 'array':\n return [\n 'type' => 'array',\n 'items' => ['type' => 'string'],\n ];\n\n default:\n // Check if it's a class or enum\n if (\\class_exists($type)) {\n return $this->generateClassSchema($type);\n }\n // Check if it's a class or enum\n if (\\enum_exists($type)) {\n return $this->processEnum(new ReflectionEnum($type));\n }\n\n // Default to string for unknown types\n return ['type' => 'string'];\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Count.php", "exactly && null === $this->min && null === $this->max) {\n $this->min = $this->max = $this->exactly;\n }\n\n if (null === $this->min && null === $this->max) {\n throw new StructuredOutputException('Either option \"min\" or \"max\" must be given for validation rule \"Length\"');\n }\n\n if (\\is_null($value) && ($this->min > 0 || $this->exactly > 0)) {\n $violations[] = $this->buildMessage($name, '{name} cannot be empty');\n return;\n }\n\n if (!\\is_array($value) && !$value instanceof \\Countable) {\n throw new StructuredOutputException($name. ' must be an array or a Countable object');\n }\n\n\n $count = \\count($value);\n\n if (null !== $this->max && $count > $this->max) {\n $shouldExact = $this->min == $this->max;\n\n if ($shouldExact) {\n $violations[] = $this->buildMessage($name, '{name} must be exactly {exact} items long', ['exact' => $this->min]);\n } else {\n $violations[] = $this->buildMessage($name, '{name} is too long. It must be at most {max} items', ['max' => $this->max]);\n }\n }\n\n if (null !== $this->min && $count < $this->min) {\n $shouldExact = $this->min == $this->max;\n\n if ($shouldExact) {\n $violations[] = $this->buildMessage($name, '{name} must be exactly {exact} items long', ['exact' => $this->min]);\n } else {\n $violations[] = $this->buildMessage($name, '{name} is too short. It must be at least {min} items', ['min' => $this->min]);\n }\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Deserializer/Deserializer.php", "newInstanceWithoutConstructor();\n\n // Get all properties including private/protected\n $properties = $reflection->getProperties();\n\n foreach ($properties as $property) {\n $propertyName = $property->getName();\n\n // Check if data contains this property (case-sensitive and snake_case/camelCase variants)\n $value = self::findPropertyValue($data, $propertyName);\n\n if ($value !== null) {\n // Get property type information\n $type = $property->getType();\n\n if ($type) {\n $value = self::castValue($value, $type, $property);\n }\n\n $property->setValue($instance, $value);\n }\n }\n\n // Call constructor if it exists and is public\n $constructor = $reflection->getConstructor();\n if ($constructor && $constructor->isPublic() && $constructor->getNumberOfRequiredParameters() === 0) {\n $constructor->invoke($instance);\n }\n\n return $instance;\n }\n\n /**\n * Find property value in data, supporting different naming conventions\n */\n private static function findPropertyValue(array $data, string $propertyName): mixed\n {\n // Direct match\n if (\\array_key_exists($propertyName, $data)) {\n return $data[$propertyName];\n }\n\n // Convert camelCase to snake_case\n $snakeCase = \\strtolower((string) \\preg_replace('/(?getTypes() as $unionType) {\n try {\n return self::castToSingleType($value, $unionType, $property);\n } catch (\\Exception) {\n continue;\n }\n }\n throw new DeserializerException(\"Cannot cast value to any type in union for property {$property->getName()}\");\n }\n\n // @phpstan-ignore-next-line\n return self::castToSingleType($value, $type, $property);\n }\n\n /**\n * Cast value to a single type\n *\n * @throws DeserializerException|\\ReflectionException\n */\n private static function castToSingleType(\n mixed $value,\n \\ReflectionNamedType $type,\n \\ReflectionProperty $property\n ): mixed {\n $typeName = $type->getName();\n\n // Handle null values\n if ($value === null) {\n if ($type->allowsNull()) {\n return null;\n }\n throw new DeserializerException(\"Property {$property->getName()} does not allow null values\");\n }\n\n return match ($typeName) {\n 'string' => (string) $value,\n 'int' => (int) $value,\n 'float' => (float) $value,\n 'bool' => (bool) $value,\n 'array' => self::handleArray($value, $property),\n 'DateTime' => self::createDateTime($value),\n 'DateTimeImmutable' => self::createDateTimeImmutable($value),\n default => self::handleSingleObject($value, $typeName)\n };\n }\n\n /**\n * @throws DeserializerException|\\ReflectionException\n */\n private static function handleSingleObject(mixed $value, string $typeName): mixed\n {\n if (\\is_array($value) && \\class_exists($typeName)) {\n return self::deserializeObject($value, $typeName);\n }\n\n if (\\enum_exists($typeName)) {\n return self::handleEnum($typeName, $value);\n }\n\n // Fallback: return the value as-is\n return $value;\n }\n\n /**\n * Handle collections\n *\n * @throws DeserializerException|\\ReflectionException\n */\n private static function handleArray(mixed $value, \\ReflectionProperty $property): mixed\n {\n // Handle arrays of objects using docblock annotations\n if (self::isArrayOfObjects($property)) {\n $elementType = self::getArrayElementType($property);\n if ($elementType && \\class_exists($elementType)) {\n return \\array_map(fn (array $item): object => self::deserializeObject($item, $elementType), $value);\n }\n }\n\n // Fallback: return the value as-is\n return $value;\n }\n\n /**\n * Check if a property represents an array of objects based on docblock\n */\n private static function isArrayOfObjects(\\ReflectionProperty $property): bool\n {\n $docComment = $property->getDocComment();\n if (!$docComment) {\n return false;\n }\n\n return \\preg_match('/@var\\s+(?:([a-zA-Z0-9_\\\\\\\\]+)\\[\\]|array<([a-zA-Z0-9_\\\\\\\\]+)>)/', $docComment) === 1;\n }\n\n /**\n * Extract an element type from array docblock annotation\n */\n private static function getArrayElementType(\\ReflectionProperty $property): ?string\n {\n $docComment = $property->getDocComment();\n if (!$docComment) {\n return null;\n }\n\n // Extract type from both \"@var \\App\\Type[]\" and \"@var array<\\App\\Type>\"\n if (\\preg_match('/@var\\s+(?:([a-zA-Z0-9_\\\\\\\\]+)\\[\\]|array<([a-zA-Z0-9_\\\\\\\\]+)>)/', $docComment, $matches) === 1) {\n return empty($matches[1]) ? ((isset($matches[2]) && $matches[2] !== '0') ? $matches[2] : null) : ($matches[1]);\n }\n\n return null;\n }\n\n /**\n * Create a DateTime object from various input formats\n *\n * @throws DeserializerException\n */\n private static function createDateTime(mixed $value): \\DateTime\n {\n if ($value instanceof \\DateTime) {\n return $value;\n }\n\n if (\\is_string($value)) {\n try {\n return new \\DateTime($value);\n } catch (\\Exception) {\n throw new DeserializerException(\"Cannot create DateTime from: {$value}\");\n }\n }\n\n if (\\is_numeric($value)) {\n return new \\DateTime('@'.$value);\n }\n\n throw new DeserializerException(\"Cannot create DateTime from value type: \".\\gettype($value));\n }\n\n /**\n * Create a DateTimeImmutable object from various input formats\n *\n * @throws DeserializerException\n */\n private static function createDateTimeImmutable(mixed $value): \\DateTimeImmutable\n {\n if ($value instanceof \\DateTimeImmutable) {\n return $value;\n }\n\n if (\\is_string($value)) {\n try {\n return new \\DateTimeImmutable($value);\n } catch (\\Exception) {\n throw new DeserializerException(\"Cannot create DateTimeImmutable from: {$value}\");\n }\n }\n\n if (\\is_numeric($value)) {\n return new \\DateTimeImmutable('@'.$value);\n }\n\n throw new DeserializerException(\"Cannot create DateTimeImmutable from value type: \".\\gettype($value));\n }\n\n private static function handleEnum(BackedEnum|string $typeName, mixed $value): BackedEnum\n {\n if (!\\is_subclass_of($typeName, BackedEnum::class)) {\n throw new DeserializerException(\"Cannot create BackedEnum from: {$typeName}\");\n }\n\n $enum = $typeName::tryFrom($value);\n\n if (!$enum instanceof \\BackedEnum) {\n throw new DeserializerException(\"Invalid enum value '{$value}' for {$typeName}\");\n }\n\n return $enum;\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/ArrayOf.php", " 'is_bool',\n 'integer' => 'is_int',\n 'float' => 'is_float',\n 'numeric' => 'is_numeric',\n 'string' => 'is_string',\n 'scalar' => 'is_scalar',\n 'array' => 'is_array',\n 'iterable' => 'is_iterable',\n 'countable' => 'is_countable',\n 'object' => 'is_object',\n 'null' => 'is_null',\n 'alnum' => 'ctype_alnum',\n 'alpha' => 'ctype_alpha',\n 'cntrl' => 'ctype_cntrl',\n 'digit' => 'ctype_digit',\n 'graph' => 'ctype_graph',\n 'lower' => 'ctype_lower',\n 'print' => 'ctype_print',\n 'punct' => 'ctype_punct',\n 'space' => 'ctype_space',\n 'upper' => 'ctype_upper',\n 'xdigit' => 'ctype_xdigit',\n ];\n\n public function __construct(\n protected string $type,\n protected bool $allowEmpty = false,\n ) {\n }\n\n public function validate(string $name, mixed $value, array &$violations): void\n {\n if ($this->allowEmpty && empty($value)) {\n return;\n }\n\n if (!$this->allowEmpty && empty($value)) {\n $violations[] = $this->buildMessage($name, $this->message, ['type' => $this->type]);\n return;\n }\n\n if (!\\is_array($value)) {\n $violations[] = $this->buildMessage($name, $this->message);\n return;\n }\n\n $type = \\strtolower($this->type);\n\n $error = false;\n foreach ($value as $item) {\n if (isset(self::VALIDATION_FUNCTIONS[$type]) && self::VALIDATION_FUNCTIONS[$type]($item)) {\n continue;\n }\n\n // It's like a recursive call.\n if ($item instanceof $this->type && Validator::validate($item) === []) {\n continue;\n }\n\n $error = true;\n break;\n }\n\n if ($error) {\n $violations[] = $this->buildMessage($name, $this->message, ['type' => $this->type]);\n }\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/PineconeVectorStore.php", "client = new Client([\n 'base_uri' => \\trim($this->indexUrl, '/').'/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Api-Key' => $key,\n 'X-Pinecone-API-Version' => $version,\n ]\n ]);\n }\n\n public function addDocument(Document $document): void\n {\n $this->addDocuments([$document]);\n }\n\n public function addDocuments(array $documents): void\n {\n $this->client->post(\"vectors/upsert\", [\n RequestOptions::JSON => [\n 'namespace' => $this->namespace,\n 'vectors' => \\array_map(fn (Document $document): array => [\n 'id' => $document->getId(),\n 'values' => $document->getEmbedding(),\n 'metadata' => [\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ],\n ], $documents)\n ]\n ]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->post(\"vectors/delete\", [\n RequestOptions::JSON => [\n 'namespace' => $this->namespace,\n 'filter' => [\n 'sourceType' => ['$eq' => $sourceType],\n 'sourceName' => ['$eq' => $sourceName],\n ]\n ]\n ]);\n }\n\n public function similaritySearch(array $embedding): iterable\n {\n $result = $this->client->post(\"query\", [\n RequestOptions::JSON => [\n 'namespace' => $this->namespace,\n 'includeMetadata' => true,\n 'includeValues' => true,\n 'vector' => $embedding,\n 'topK' => $this->topK,\n 'filters' => $this->filters, // Hybrid search\n ]\n ])->getBody()->getContents();\n\n $result = \\json_decode($result, true);\n\n return \\array_map(function (array $item): Document {\n $document = new Document();\n $document->id = $item['id'];\n $document->embedding = $item['values'];\n $document->content = $item['metadata']['content'];\n $document->sourceType = $item['metadata']['sourceType'];\n $document->sourceName = $item['metadata']['sourceName'];\n $document->score = $item['score'];\n\n foreach ($item['metadata'] as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $result['matches']);\n }\n\n public function withFilters(array $filters): self\n {\n $this->filters = $filters;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/AWS/SESTool.php", "validateRecipients($to);\n\n $result = $this->sesClient->sendEmail([\n 'Source' => $this->fromEmail,\n 'Destination' => $this->buildDestinations($to, $cc, $bcc),\n 'Message' => $this->buildMessage($subject, $body),\n ]);\n\n return [\n 'success' => true,\n 'message_id' => $result['MessageId'] ?? null,\n 'status' => 'sent',\n 'recipients_count' => \\count($to),\n 'aws_request_id' => $result['@metadata']['requestId'] ?? null\n ];\n } catch (\\Exception $e) {\n return [\n 'success' => false,\n 'error' => $e->getMessage(),\n 'error_type' => $e::class,\n 'status' => 'failed'\n ];\n }\n }\n\n /**\n * @param array $to\n * @throws ToolException\n */\n protected function validateRecipients(array $to): void\n {\n foreach ($to as $recipient) {\n if (\\filter_var($recipient, \\FILTER_VALIDATE_EMAIL) === false) {\n throw new ToolException('Invalid email address: ' . $recipient . '.');\n }\n }\n }\n\n protected function buildDestinations(array $to, ?array $cc = null, ?array $bcc = null): array\n {\n $destinations = [\n 'ToAddresses' => $to,\n ];\n\n if ($cc !== null && $cc !== []) {\n $destinations['CcAddresses'] = $cc;\n }\n\n if ($bcc !== null && $bcc !== []) {\n $destinations['BccAddresses'] = $bcc;\n }\n\n return $destinations;\n }\n\n protected function buildMessage(string $subject, string $body): array\n {\n return [\n 'Subject' => [\n 'Data' => $subject,\n 'Charset' => 'UTF-8'\n ],\n 'Body' => [\n 'Html' => [\n 'Data' => $body,\n 'Charset' => 'UTF-8'\n ],\n 'Text' => [\n 'Data' => \\strip_tags($body),\n 'Charset' => 'UTF-8'\n ]\n ]\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/PGSQL/PGSQLSchemaTool.php", "formatForLLM([\n 'tables' => $this->getTables(),\n 'relationships' => $this->getRelationships(),\n 'indexes' => $this->getIndexes(),\n 'constraints' => $this->getConstraints()\n ]);\n }\n\n private function getTables(): array\n {\n $whereClause = \"WHERE t.table_schema = current_schema() AND t.table_type = 'BASE TABLE'\";\n $params = [];\n\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = [];\n foreach ($this->tables as $table) {\n $placeholders[] = '?';\n $params[] = $table;\n }\n $whereClause .= \" AND t.table_name = ANY(ARRAY[\" . \\implode(',', $placeholders) . \"])\";\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n t.table_name,\n obj_description(pgc.oid) as table_comment,\n c.column_name,\n c.ordinal_position,\n c.column_default,\n c.is_nullable,\n c.data_type,\n c.character_maximum_length,\n c.numeric_precision,\n c.numeric_scale,\n c.udt_name,\n CASE\n WHEN pk.column_name IS NOT NULL THEN 'PRI'\n WHEN uk.column_name IS NOT NULL THEN 'UNI'\n WHEN idx.column_name IS NOT NULL THEN 'MUL'\n ELSE ''\n END as column_key,\n CASE\n WHEN c.column_default LIKE 'nextval%' THEN 'auto_increment'\n ELSE ''\n END as extra,\n col_description(pgc.oid, c.ordinal_position) as column_comment\n FROM information_schema.tables t\n LEFT JOIN information_schema.columns c ON t.table_name = c.table_name\n AND t.table_schema = c.table_schema\n LEFT JOIN pg_class pgc ON pgc.relname = t.table_name AND pgc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = current_schema())\n LEFT JOIN (\n SELECT ku.table_name, ku.column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage ku ON tc.constraint_name = ku.constraint_name\n WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = current_schema()\n ) pk ON pk.table_name = c.table_name AND pk.column_name = c.column_name\n LEFT JOIN (\n SELECT ku.table_name, ku.column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage ku ON tc.constraint_name = ku.constraint_name\n WHERE tc.constraint_type = 'UNIQUE' AND tc.table_schema = current_schema()\n ) uk ON uk.table_name = c.table_name AND uk.column_name = c.column_name\n LEFT JOIN (\n SELECT\n t.relname as table_name,\n a.attname as column_name\n FROM pg_index i\n JOIN pg_class t ON t.oid = i.indrelid\n JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(i.indkey)\n JOIN pg_namespace n ON n.oid = t.relnamespace\n WHERE i.indisprimary = false AND i.indisunique = false AND n.nspname = current_schema()\n ) idx ON idx.table_name = c.table_name AND idx.column_name = c.column_name\n $whereClause\n ORDER BY t.table_name, c.ordinal_position\n \");\n\n $stmt->execute($params);\n $results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n $tables = [];\n foreach ($results as $row) {\n $tableName = $row['table_name'];\n\n if (!isset($tables[$tableName])) {\n $tables[$tableName] = [\n 'name' => $tableName,\n 'engine' => 'PostgreSQL',\n 'estimated_rows' => $this->getTableRowCount($tableName),\n 'comment' => $row['table_comment'],\n 'columns' => [],\n 'primary_key' => [],\n 'unique_keys' => [],\n 'indexes' => []\n ];\n }\n\n if ($row['column_name']) {\n // Map PostgreSQL types to a more readable format\n $fullType = $this->formatPostgreSQLType($row);\n\n $column = [\n 'name' => $row['column_name'],\n 'type' => $row['data_type'],\n 'full_type' => $fullType,\n 'nullable' => $row['is_nullable'] === 'YES',\n 'default' => $row['column_default'],\n 'auto_increment' => \\str_contains((string) $row['extra'], 'auto_increment'),\n 'comment' => $row['column_comment']\n ];\n\n if ($row['character_maximum_length']) {\n $column['max_length'] = $row['character_maximum_length'];\n }\n if ($row['numeric_precision']) {\n $column['precision'] = $row['numeric_precision'];\n $column['scale'] = $row['numeric_scale'];\n }\n\n $tables[$tableName]['columns'][] = $column;\n\n if ($row['column_key'] === 'PRI') {\n $tables[$tableName]['primary_key'][] = $row['column_name'];\n } elseif ($row['column_key'] === 'UNI') {\n $tables[$tableName]['unique_keys'][] = $row['column_name'];\n } elseif ($row['column_key'] === 'MUL') {\n $tables[$tableName]['indexes'][] = $row['column_name'];\n }\n }\n }\n\n return $tables;\n }\n\n private function getTableRowCount(string $tableName): string\n {\n try {\n $stmt = $this->pdo->prepare(\"\n SELECT n_tup_ins - n_tup_del as estimate\n FROM pg_stat_user_tables\n WHERE relname = $1\n \");\n $stmt->execute([$tableName]);\n $result = $stmt->fetchColumn();\n return $result !== false ? (string)$result : 'N/A';\n } catch (\\Exception) {\n return 'N/A';\n }\n }\n\n private function formatPostgreSQLType(array $row): string\n {\n $type = $row['udt_name'] ?? $row['data_type'];\n\n // Handle specific PostgreSQL types\n if ($type === 'varchar' || $type === 'character varying') {\n $type = 'character varying';\n }\n if ($row['character_maximum_length']) {\n return \"{$type}({$row['character_maximum_length']})\";\n }\n if ($row['numeric_precision'] && $row['numeric_scale']) {\n return \"{$type}({$row['numeric_precision']},{$row['numeric_scale']})\";\n }\n\n if ($row['numeric_precision']) {\n return \"{$type}({$row['numeric_precision']})\";\n }\n\n return $type;\n }\n\n private function getRelationships(): array\n {\n $whereClause = \"WHERE tc.table_schema = current_schema()\";\n $paramIndex = 1;\n $params = [];\n\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = [];\n foreach ($this->tables as $table) {\n $placeholders[] = '?';\n $params[] = $table;\n }\n $additionalPlaceholders = [];\n foreach ($this->tables as $table) {\n $additionalPlaceholders[] = '$' . $paramIndex++;\n $params[] = $table;\n }\n $whereClause .= \" AND (tc.table_name = ANY(ARRAY[\" . \\implode(',', $placeholders) . \"]) OR ccu.table_name = ANY(ARRAY[\" . \\implode(',', $additionalPlaceholders) . \"]))\";\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n tc.constraint_name,\n tc.table_name as source_table,\n kcu.column_name as source_column,\n ccu.table_name as target_table,\n ccu.column_name as target_column,\n rc.update_rule,\n rc.delete_rule\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n JOIN information_schema.constraint_column_usage ccu\n ON ccu.constraint_name = tc.constraint_name\n AND ccu.table_schema = tc.table_schema\n JOIN information_schema.referential_constraints rc\n ON tc.constraint_name = rc.constraint_name\n AND tc.table_schema = rc.constraint_schema\n $whereClause\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.table_name\n \");\n\n $stmt->execute($params);\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n private function getIndexes(): array\n {\n $whereClause = \"WHERE schemaname = current_schema() AND indexname NOT LIKE '%_pkey'\";\n $params = [];\n\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = [];\n foreach ($this->tables as $table) {\n $placeholders[] = '?';\n $params[] = $table;\n }\n $whereClause .= \" AND tablename = ANY(ARRAY[\" . \\implode(',', $placeholders) . \"])\";\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n schemaname,\n tablename,\n indexname,\n indexdef\n FROM pg_indexes\n $whereClause\n ORDER BY tablename, indexname\n \");\n\n $stmt->execute($params);\n $results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n $indexes = [];\n foreach ($results as $row) {\n // Parse column names from index definition\n \\preg_match('/\\((.*?)\\)/', (string) $row['indexdef'], $matches);\n $columnList = $matches[1] ?? '';\n $columns = \\array_map('trim', \\explode(',', $columnList));\n\n // Clean up column names (remove function calls, etc.)\n $cleanColumns = [];\n foreach ($columns as $col) {\n // Extract just the column name if it's wrapped in functions\n if (\\preg_match('/([a-zA-Z_]\\w*)/', $col, $colMatches)) {\n $cleanColumns[] = $colMatches[1];\n }\n }\n\n $indexes[] = [\n 'table' => $row['tablename'],\n 'name' => $row['indexname'],\n 'unique' => \\str_contains((string) $row['indexdef'], 'UNIQUE'),\n 'type' => $this->extractIndexType($row['indexdef']),\n 'columns' => $cleanColumns === [] ? $columns : $cleanColumns\n ];\n }\n\n return $indexes;\n }\n\n private function extractIndexType(string $indexDef): string\n {\n if (\\str_contains($indexDef, 'USING gin')) {\n return 'GIN';\n }\n if (\\str_contains($indexDef, 'USING gist')) {\n return 'GIST';\n }\n if (\\str_contains($indexDef, 'USING hash')) {\n return 'HASH';\n }\n if (\\str_contains($indexDef, 'USING brin')) {\n return 'BRIN';\n }\n return 'BTREE';\n // Default\n\n }\n\n private function getConstraints(): array\n {\n $whereClause = \"WHERE table_schema = current_schema() AND constraint_type IN ('UNIQUE', 'CHECK')\";\n $params = [];\n\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = [];\n foreach ($this->tables as $table) {\n $placeholders[] = '?';\n $params[] = $table;\n }\n $whereClause .= \" AND table_name = ANY(ARRAY[\" . \\implode(',', $placeholders) . \"])\";\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n constraint_name,\n table_name,\n constraint_type\n FROM information_schema.table_constraints\n $whereClause\n \");\n\n $stmt->execute($params);\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n private function formatForLLM(array $structure): string\n {\n $output = \"# PostgreSQL Database Schema Analysis\\n\\n\";\n $output .= \"This PostgreSQL database contains \" . \\count($structure['tables']) . \" tables with the following structure:\\n\\n\";\n\n // Tables overview\n $output .= \"## Tables Overview\\n\";\n $tableCount = \\count($structure['tables']);\n $filteredNote = $this->tables !== null ? \" (filtered to specified tables)\" : \"\";\n $output .= \"Analyzing {$tableCount} tables{$filteredNote}:\\n\";\n\n foreach ($structure['tables'] as $table) {\n $pkColumns = empty($table['primary_key']) ? 'None' : \\implode(', ', $table['primary_key']);\n $output .= \"- **{$table['name']}**: {$table['estimated_rows']} rows, Primary Key: {$pkColumns}\";\n if ($table['comment']) {\n $output .= \" - {$table['comment']}\";\n }\n $output .= \"\\n\";\n }\n $output .= \"\\n\";\n\n // Detailed table structures\n $output .= \"## Detailed Table Structures\\n\\n\";\n foreach ($structure['tables'] as $table) {\n $output .= \"### Table: `{$table['name']}`\\n\";\n if ($table['comment']) {\n $output .= \"**Description**: {$table['comment']}\\n\";\n }\n $output .= \"**Estimated Rows**: {$table['estimated_rows']}\\n\\n\";\n\n $output .= \"**Columns**:\\n\";\n foreach ($table['columns'] as $column) {\n $nullable = $column['nullable'] ? 'NULL' : 'NOT NULL';\n $autoInc = $column['auto_increment'] ? ' (SERIAL/SEQUENCE)' : '';\n $default = $column['default'] !== null ? \" DEFAULT {$column['default']}\" : '';\n\n $output .= \"- `{$column['name']}` {$column['full_type']} {$nullable}{$default}{$autoInc}\";\n if ($column['comment']) {\n $output .= \" - {$column['comment']}\";\n }\n $output .= \"\\n\";\n }\n\n if (!empty($table['primary_key'])) {\n $output .= \"\\n**Primary Key**: \" . \\implode(', ', $table['primary_key']) . \"\\n\";\n }\n\n if (!empty($table['unique_keys'])) {\n $output .= \"**Unique Keys**: \" . \\implode(', ', $table['unique_keys']) . \"\\n\";\n }\n\n $output .= \"\\n\";\n }\n\n // Relationships\n if (!empty($structure['relationships'])) {\n $output .= \"## Foreign Key Relationships\\n\\n\";\n $output .= \"Understanding these relationships is crucial for JOIN operations:\\n\\n\";\n\n foreach ($structure['relationships'] as $rel) {\n $output .= \"- `{$rel['source_table']}.{$rel['source_column']}` → `{$rel['target_table']}.{$rel['target_column']}`\";\n $output .= \" (ON DELETE {$rel['delete_rule']}, ON UPDATE {$rel['update_rule']})\\n\";\n }\n $output .= \"\\n\";\n }\n\n // Indexes for query optimization\n if (!empty($structure['indexes'])) {\n $output .= \"## Available Indexes (for Query Optimization)\\n\\n\";\n $output .= \"These indexes can significantly improve query performance:\\n\\n\";\n\n foreach ($structure['indexes'] as $index) {\n $unique = $index['unique'] ? 'UNIQUE ' : '';\n $columns = \\implode(', ', $index['columns']);\n $output .= \"- {$unique}{$index['type']} INDEX `{$index['name']}` on `{$index['table']}` ({$columns})\\n\";\n }\n $output .= \"\\n\";\n }\n\n // PostgreSQL-specific query guidelines\n $output .= \"## PostgreSQL SQL Query Generation Guidelines\\n\\n\";\n $output .= \"**Best Practices for this PostgreSQL database**:\\n\";\n $output .= \"1. Always use table aliases for better readability\\n\";\n $output .= \"2. Prefer indexed columns in WHERE clauses for better performance\\n\";\n $output .= \"3. Use appropriate JOINs based on the foreign key relationships listed above\\n\";\n $output .= \"4. Use double quotes (\\\") for identifiers if they contain special characters or are case-sensitive\\n\";\n $output .= \"5. PostgreSQL is case-sensitive for identifiers - use exact casing as shown above\\n\";\n $output .= \"6. Use \\$1, \\$2, etc. for parameterized queries in prepared statements\\n\";\n $output .= \"7. LIMIT clause syntax: `SELECT ... LIMIT n OFFSET m`\\n\";\n $output .= \"8. String comparisons are case-sensitive by default (use ILIKE for case-insensitive)\\n\";\n $output .= \"9. Use single quotes (') for string literals, not double quotes\\n\";\n $output .= \"10. PostgreSQL supports advanced features like arrays, JSON/JSONB, and full-text search\\n\";\n $output .= \"11. Use RETURNING clause for INSERT/UPDATE/DELETE to get back modified data\\n\\n\";\n\n // Common patterns\n $output .= \"**Common PostgreSQL Query Patterns**:\\n\";\n $this->addCommonPatterns($output, $structure['tables']);\n\n return $output;\n }\n\n private function addCommonPatterns(string &$output, array $tables): void\n {\n // Find tables with timestamps for temporal queries\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['timestamp without time zone', 'timestamp with time zone', 'timestamptz', 'date', 'time']) &&\n (\\str_contains(\\strtolower((string) $column['name']), 'created') ||\n \\str_contains(\\strtolower((string) $column['name']), 'updated'))) {\n $output .= \"- For temporal queries on `{$table['name']}`, use `{$column['name']}` column\\n\";\n break;\n }\n }\n }\n\n // Find potential text search columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['character varying', 'varchar', 'text', 'character']) &&\n (\\str_contains(\\strtolower((string) $column['name']), 'name') ||\n \\str_contains(\\strtolower((string) $column['name']), 'title') ||\n \\str_contains(\\strtolower((string) $column['name']), 'description'))) {\n $output .= \"- For text searches on `{$table['name']}`, consider using `{$column['name']}` with ILIKE, ~ (regex), or full-text search\\n\";\n break;\n }\n }\n }\n\n // Find JSON/JSONB columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['json', 'jsonb'])) {\n $output .= \"- Table `{$table['name']}` has {$column['type']} column `{$column['name']}` - use JSON operators like ->, ->>, @>, ? for querying\\n\";\n }\n }\n }\n\n // Find array columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\str_contains((string) $column['full_type'], '[]')) {\n $output .= \"- Table `{$table['name']}` has array column `{$column['name']}` ({$column['full_type']}) - use array operators like ANY, ALL, @>\\n\";\n }\n }\n }\n\n // Find UUID columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if ($column['type'] === 'uuid') {\n $output .= \"- Table `{$table['name']}` uses UUID for `{$column['name']}` - use gen_random_uuid() for generating new UUIDs\\n\";\n break;\n }\n }\n }\n\n $output .= \"\\n\";\n }\n}\n"], ["/neuron-ai/src/Observability/HandleToolEvents.php", "inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$agent::class.'_tools_bootstrap'] = $this->inspector\n ->startSegment(\n self::SEGMENT_TYPE.'-tools',\n \"tools_bootstrap()\"\n )\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function toolsBootstrapped(AgentInterface $agent, string $event, ToolsBootstrapped $data): void\n {\n if (\\array_key_exists($agent::class.'_tools_bootstrap', $this->segments) && $data->tools !== []) {\n $segment = $this->segments[$agent::class.'_tools_bootstrap']->end();\n $segment->addContext('Tools', \\array_reduce($data->tools, function (array $carry, ToolInterface $tool): array {\n $carry[$tool->getName()] = $tool->getDescription();\n return $carry;\n }, []));\n $segment->addContext('Guidelines', $data->guidelines);\n }\n }\n\n public function toolCalling(AgentInterface $agent, string $event, ToolCalling $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$data->tool->getName()] = $this->inspector\n ->startSegment(\n self::SEGMENT_TYPE.'-tools',\n \"tool_call( {$data->tool->getName()} )\"\n )\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function toolCalled(AgentInterface $agent, string $event, ToolCalled $data): void\n {\n if (\\array_key_exists($data->tool->getName(), $this->segments)) {\n $this->segments[$data->tool->getName()]\n ->end()\n ->addContext('Properties', $data->tool->getProperties())\n ->addContext('Inputs', $data->tool->getInputs())\n ->addContext('Output', $data->tool->getResult());\n }\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/ChromaVectorStore.php", "client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->host, '/').\"/api/v1/collections/{$this->collection}/\",\n 'headers' => [\n 'Content-Type' => 'application/json',\n ]\n ]);\n }\n\n public function addDocument(Document $document): void\n {\n $this->addDocuments([$document]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->getClient()->post('delete', [\n RequestOptions::JSON => [\n 'where' => [\n 'sourceType' => $sourceType,\n 'sourceName' => $sourceName,\n ]\n ]\n ]);\n }\n\n public function addDocuments(array $documents): void\n {\n $this->getClient()->post('upsert', [\n RequestOptions::JSON => $this->mapDocuments($documents),\n ])->getBody()->getContents();\n }\n\n public function similaritySearch(array $embedding): iterable\n {\n $response = $this->getClient()->post('query', [\n RequestOptions::JSON => [\n 'queryEmbeddings' => $embedding,\n 'nResults' => $this->topK,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n // Map the result\n $size = \\count($response['distances']);\n $result = [];\n for ($i = 0; $i < $size; $i++) {\n $document = new Document();\n $document->id = $response['ids'][$i] ?? \\uniqid();\n $document->embedding = $response['embeddings'][$i];\n $document->content = $response['documents'][$i];\n $document->sourceType = $response['metadatas'][$i]['sourceType'] ?? null;\n $document->sourceName = $response['metadatas'][$i]['sourceName'] ?? null;\n $document->score = VectorSimilarity::similarityFromDistance($response['distances'][$i]);\n\n foreach ($response['metadatas'][$i] as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName', 'score', 'embedding', 'id'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n $result[] = $document;\n }\n\n return $result;\n }\n\n /**\n * @param Document[] $documents\n */\n protected function mapDocuments(array $documents): array\n {\n $payload = [\n 'ids' => [],\n 'documents' => [],\n 'embeddings' => [],\n 'metadatas' => [],\n ];\n\n foreach ($documents as $document) {\n $payload['ids'][] = $document->getId();\n $payload['documents'][] = $document->getContent();\n $payload['embeddings'][] = $document->getEmbedding();\n $payload['metadatas'][] = [\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ];\n }\n\n return $payload;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/ElasticsearchVectorStore.php", "client->indices()->exists(['index' => $this->index]);\n $existStatusCode = $existResponse->getStatusCode();\n\n if ($existStatusCode === 200) {\n // Map vector embeddings dimension on the fly adding a document.\n $this->mapVectorDimension(\\count($document->getEmbedding()));\n return;\n }\n\n $properties = [\n 'content' => [\n 'type' => 'text',\n ],\n 'sourceType' => [\n 'type' => 'keyword',\n ],\n 'sourceName' => [\n 'type' => 'keyword',\n ]\n ];\n\n // Map metadata\n foreach (\\array_keys($document->metadata) as $name) {\n $properties[$name] = [\n 'type' => 'keyword',\n ];\n }\n\n $this->client->indices()->create([\n 'index' => $this->index,\n 'body' => [\n 'mappings' => [\n 'properties' => $properties,\n ],\n ],\n ]);\n }\n\n /**\n * @throws \\Exception\n */\n public function addDocument(Document $document): void\n {\n if ($document->embedding === []) {\n throw new \\Exception('Document embedding must be set before adding a document');\n }\n\n $this->checkIndexStatus($document);\n\n $this->client->index([\n 'index' => $this->index,\n 'body' => [\n 'embedding' => $document->getEmbedding(),\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ],\n ]);\n\n $this->client->indices()->refresh(['index' => $this->index]);\n }\n\n /**\n * @param Document[] $documents\n *\n * @throws \\Exception\n */\n public function addDocuments(array $documents): void\n {\n if ($documents === []) {\n return;\n }\n\n if (empty($documents[0]->getEmbedding())) {\n throw new \\Exception('Document embedding must be set before adding a document');\n }\n\n $this->checkIndexStatus($documents[0]);\n\n /*\n * Generate a bulk payload\n */\n $params = ['body' => []];\n foreach ($documents as $document) {\n $params['body'][] = [\n 'index' => [\n '_index' => $this->index,\n ],\n ];\n $params['body'][] = [\n 'embedding' => $document->getEmbedding(),\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ];\n }\n $this->client->bulk($params);\n $this->client->indices()->refresh(['index' => $this->index]);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->deleteByQuery([\n 'index' => $this->index,\n 'q' => \"sourceType:{$sourceType} AND sourceName:{$sourceName}\",\n 'body' => []\n ]);\n $this->client->indices()->refresh(['index' => $this->index]);\n }\n\n /**\n * {@inheritDoc}\n *\n * num_candidates are used to tune approximate kNN for speed or accuracy (see : https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html#tune-approximate-knn-for-speed-accuracy)\n * @return Document[]\n * @throws ClientResponseException\n * @throws ServerResponseException\n */\n public function similaritySearch(array $embedding): array\n {\n $searchParams = [\n 'index' => $this->index,\n 'body' => [\n 'knn' => [\n 'field' => 'embedding',\n 'query_vector' => $embedding,\n 'k' => $this->topK,\n 'num_candidates' => \\max(50, $this->topK * 4),\n ],\n 'sort' => [\n '_score' => [\n 'order' => 'desc',\n ],\n ],\n ],\n ];\n\n // Hybrid search\n if ($this->filters !== []) {\n $searchParams['body']['knn']['filter'] = $this->filters;\n }\n\n $response = $this->client->search($searchParams);\n\n return \\array_map(function (array $item): Document {\n $document = new Document($item['_source']['content']);\n //$document->embedding = $item['_source']['embedding']; // avoid carrying large data\n $document->sourceType = $item['_source']['sourceType'];\n $document->sourceName = $item['_source']['sourceName'];\n $document->score = $item['_score'];\n\n foreach ($item['_source'] as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName', 'score', 'embedding', 'id'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $response['hits']['hits']);\n }\n\n /**\n * Map vector embeddings dimension on the fly.\n */\n private function mapVectorDimension(int $dimension): void\n {\n if ($this->vectorDimSet) {\n return;\n }\n\n $response = $this->client->indices()->getFieldMapping([\n 'index' => $this->index,\n 'fields' => 'embedding',\n ]);\n\n $mappings = $response[$this->index]['mappings'];\n if (\n \\array_key_exists('embedding', $mappings)\n && $mappings['embedding']['mapping']['embedding']['dims'] === $dimension\n ) {\n return;\n }\n\n $this->client->indices()->putMapping([\n 'index' => $this->index,\n 'body' => [\n 'properties' => [\n 'embedding' => [\n 'type' => 'dense_vector',\n //'element_type' => 'float', // it's float by default\n 'dims' => $dimension,\n 'index' => true,\n 'similarity' => 'cosine',\n ],\n ],\n ],\n ]);\n\n $this->vectorDimSet = true;\n }\n\n public function withFilters(array $filters): self\n {\n $this->filters = $filters;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/MySQL/MySQLSchemaTool.php", "formatForLLM([\n 'tables' => $this->getTables(),\n 'relationships' => $this->getRelationships(),\n 'indexes' => $this->getIndexes(),\n 'constraints' => $this->getConstraints()\n ]);\n }\n\n protected function formatForLLM(array $structure): string\n {\n $output = \"# MySQL Database Schema Analysis\\n\\n\";\n $output .= \"This database contains \" . \\count($structure['tables']) . \" tables with the following structure:\\n\\n\";\n\n // Tables overview\n $output .= \"## Tables Overview\\n\";\n foreach ($structure['tables'] as $table) {\n $pkColumns = empty($table['primary_key']) ? 'None' : \\implode(', ', $table['primary_key']);\n $output .= \"- **{$table['name']}**: {$table['estimated_rows']} rows, Primary Key: {$pkColumns}\";\n if ($table['comment']) {\n $output .= \" - {$table['comment']}\";\n }\n $output .= \"\\n\";\n }\n $output .= \"\\n\";\n\n // Detailed table structures\n $output .= \"## Detailed Table Structures\\n\\n\";\n foreach ($structure['tables'] as $table) {\n $output .= \"### Table: `{$table['name']}`\\n\";\n if ($table['comment']) {\n $output .= \"**Description**: {$table['comment']}\\n\";\n }\n $output .= \"**Estimated Rows**: {$table['estimated_rows']}\\n\\n\";\n\n $output .= \"**Columns**:\\n\";\n foreach ($table['columns'] as $column) {\n $nullable = $column['nullable'] ? 'NULL' : 'NOT NULL';\n $autoInc = $column['auto_increment'] ? ' AUTO_INCREMENT' : '';\n $default = $column['default'] !== null ? \" DEFAULT '{$column['default']}'\" : '';\n\n $output .= \"- `{$column['name']}` {$column['full_type']} {$nullable}{$default}{$autoInc}\";\n if ($column['comment']) {\n $output .= \" - {$column['comment']}\";\n }\n $output .= \"\\n\";\n }\n\n if (!empty($table['primary_key'])) {\n $output .= \"\\n**Primary Key**: \" . \\implode(', ', $table['primary_key']) . \"\\n\";\n }\n\n if (!empty($table['unique_keys'])) {\n $output .= \"**Unique Keys**: \" . \\implode(', ', $table['unique_keys']) . \"\\n\";\n }\n\n $output .= \"\\n\";\n }\n\n // Relationships\n if (!empty($structure['relationships'])) {\n $output .= \"## Foreign Key Relationships\\n\\n\";\n $output .= \"Understanding these relationships is crucial for JOIN operations:\\n\\n\";\n\n foreach ($structure['relationships'] as $rel) {\n $output .= \"- `{$rel['source_table']}.{$rel['source_column']}` → `{$rel['target_table']}.{$rel['target_column']}`\";\n $output .= \" (ON DELETE {$rel['DELETE_RULE']}, ON UPDATE {$rel['UPDATE_RULE']})\\n\";\n }\n $output .= \"\\n\";\n }\n\n // Indexes for query optimization\n if (!empty($structure['indexes'])) {\n $output .= \"## Available Indexes (for Query Optimization)\\n\\n\";\n $output .= \"These indexes can significantly improve query performance:\\n\\n\";\n\n foreach ($structure['indexes'] as $index) {\n $unique = $index['unique'] ? 'UNIQUE ' : '';\n $columns = \\implode(', ', $index['columns']);\n $output .= \"- {$unique}INDEX `{$index['name']}` on `{$index['table']}` ({$columns})\\n\";\n }\n $output .= \"\\n\";\n }\n\n // Query generation guidelines\n $output .= \"## MySQL Query Generation Guidelines\\n\\n\";\n $output .= \"**Best Practices for this database**:\\n\";\n $output .= \"1. Always use table aliases for better readability\\n\";\n $output .= \"2. Prefer indexed columns in WHERE clauses for better performance\\n\";\n $output .= \"3. Use appropriate JOINs based on the foreign key relationships listed above\\n\";\n $output .= \"4. Consider the estimated row counts when writing queries - larger tables may need LIMIT clauses\\n\";\n $output .= \"5. Pay attention to nullable columns when using comparison operators\\n\\n\";\n\n // Common patterns\n $output .= \"**Common Query Patterns**:\\n\";\n $this->addCommonPatterns($output, $structure['tables']);\n\n return $output;\n }\n\n protected function getTables(): array\n {\n $whereClause = \"WHERE t.TABLE_SCHEMA = DATABASE() AND t.TABLE_TYPE = 'BASE TABLE'\";\n $params = [];\n\n // Add table filtering if specific tables are requested\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = \\str_repeat('?,', \\count($this->tables) - 1) . '?';\n $whereClause .= \" AND t.TABLE_NAME IN ($placeholders)\";\n $params = $this->tables;\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n t.TABLE_NAME,\n t.ENGINE,\n t.TABLE_ROWS,\n t.TABLE_COMMENT,\n c.COLUMN_NAME,\n c.ORDINAL_POSITION,\n c.COLUMN_DEFAULT,\n c.IS_NULLABLE,\n c.DATA_TYPE,\n c.CHARACTER_MAXIMUM_LENGTH,\n c.NUMERIC_PRECISION,\n c.NUMERIC_SCALE,\n c.COLUMN_TYPE,\n c.COLUMN_KEY,\n c.EXTRA,\n c.COLUMN_COMMENT\n FROM INFORMATION_SCHEMA.TABLES t\n LEFT JOIN INFORMATION_SCHEMA.COLUMNS c ON t.TABLE_NAME = c.TABLE_NAME\n AND t.TABLE_SCHEMA = c.TABLE_SCHEMA\n $whereClause\n ORDER BY t.TABLE_NAME, c.ORDINAL_POSITION\n \");\n\n $stmt->execute($params);\n $results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n $tables = [];\n foreach ($results as $row) {\n $tableName = $row['TABLE_NAME'];\n\n if (!isset($tables[$tableName])) {\n $tables[$tableName] = [\n 'name' => $tableName,\n 'engine' => $row['ENGINE'],\n 'estimated_rows' => $row['TABLE_ROWS'],\n 'comment' => $row['TABLE_COMMENT'],\n 'columns' => [],\n 'primary_key' => [],\n 'unique_keys' => [],\n 'indexes' => []\n ];\n }\n\n if ($row['COLUMN_NAME']) {\n $column = [\n 'name' => $row['COLUMN_NAME'],\n 'type' => $row['DATA_TYPE'],\n 'full_type' => $row['COLUMN_TYPE'],\n 'nullable' => $row['IS_NULLABLE'] === 'YES',\n 'default' => $row['COLUMN_DEFAULT'],\n 'auto_increment' => \\str_contains((string) $row['EXTRA'], 'auto_increment'),\n 'comment' => $row['COLUMN_COMMENT']\n ];\n\n // Add length/precision info for better LLM understanding\n if ($row['CHARACTER_MAXIMUM_LENGTH']) {\n $column['max_length'] = $row['CHARACTER_MAXIMUM_LENGTH'];\n }\n if ($row['NUMERIC_PRECISION']) {\n $column['precision'] = $row['NUMERIC_PRECISION'];\n $column['scale'] = $row['NUMERIC_SCALE'];\n }\n\n $tables[$tableName]['columns'][] = $column;\n\n // Track key information\n if ($row['COLUMN_KEY'] === 'PRI') {\n $tables[$tableName]['primary_key'][] = $row['COLUMN_NAME'];\n } elseif ($row['COLUMN_KEY'] === 'UNI') {\n $tables[$tableName]['unique_keys'][] = $row['COLUMN_NAME'];\n } elseif ($row['COLUMN_KEY'] === 'MUL') {\n $tables[$tableName]['indexes'][] = $row['COLUMN_NAME'];\n }\n }\n }\n\n return $tables;\n }\n\n protected function getRelationships(): array\n {\n $whereClause = \"WHERE kcu.TABLE_SCHEMA = DATABASE() AND kcu.REFERENCED_TABLE_NAME IS NOT NULL\";\n $params = [];\n\n // Add table filtering if specific tables are requested\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = \\str_repeat('?,', \\count($this->tables) - 1) . '?';\n $whereClause .= \" AND (kcu.TABLE_NAME IN ($placeholders) OR kcu.REFERENCED_TABLE_NAME IN ($placeholders))\";\n $params = \\array_merge($this->tables, $this->tables);\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n kcu.CONSTRAINT_NAME,\n kcu.TABLE_NAME as source_table,\n kcu.COLUMN_NAME as source_column,\n kcu.REFERENCED_TABLE_NAME as target_table,\n kcu.REFERENCED_COLUMN_NAME as target_column,\n rc.UPDATE_RULE,\n rc.DELETE_RULE\n FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu\n JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc\n ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME\n AND kcu.CONSTRAINT_SCHEMA = rc.CONSTRAINT_SCHEMA\n $whereClause\n ORDER BY kcu.TABLE_NAME, kcu.ORDINAL_POSITION\n \");\n\n $stmt->execute($params);\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n protected function getIndexes(): array\n {\n $stmt = $this->pdo->prepare(\"\n SELECT\n TABLE_NAME,\n INDEX_NAME,\n COLUMN_NAME,\n SEQ_IN_INDEX,\n NON_UNIQUE,\n INDEX_TYPE,\n CARDINALITY\n FROM INFORMATION_SCHEMA.STATISTICS\n WHERE TABLE_SCHEMA = DATABASE()\n AND INDEX_NAME != 'PRIMARY'\n ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX\n \");\n\n $stmt->execute();\n $results = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n $indexes = [];\n foreach ($results as $row) {\n $key = $row['TABLE_NAME'] . '.' . $row['INDEX_NAME'];\n if (!isset($indexes[$key])) {\n $indexes[$key] = [\n 'table' => $row['TABLE_NAME'],\n 'name' => $row['INDEX_NAME'],\n 'unique' => $row['NON_UNIQUE'] == 0,\n 'type' => $row['INDEX_TYPE'],\n 'columns' => []\n ];\n }\n $indexes[$key]['columns'][] = $row['COLUMN_NAME'];\n }\n\n return \\array_values($indexes);\n }\n\n protected function getConstraints(): array\n {\n $whereClause = \"WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_TYPE IN ('UNIQUE')\";\n $params = [];\n\n // Add table filtering if specific tables are requested\n if ($this->tables !== null && $this->tables !== []) {\n $placeholders = \\str_repeat('?,', \\count($this->tables) - 1) . '?';\n $whereClause .= \" AND TABLE_NAME IN ($placeholders)\";\n $params = $this->tables;\n }\n\n $stmt = $this->pdo->prepare(\"\n SELECT\n CONSTRAINT_NAME,\n TABLE_NAME,\n CONSTRAINT_TYPE\n FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS\n $whereClause\n \");\n\n $stmt->execute($params);\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n protected function addCommonPatterns(string &$output, array $tables): void\n {\n // Find tables with timestamps for temporal queries\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['timestamp', 'datetime', 'date']) &&\n (\\str_contains(\\strtolower((string) $column['name']), 'created') ||\n \\str_contains(\\strtolower((string) $column['name']), 'updated'))) {\n $output .= \"- For temporal queries on `{$table['name']}`, use `{$column['name']}` column\\n\";\n break;\n }\n }\n }\n\n // Find potential text search columns\n foreach ($tables as $table) {\n foreach ($table['columns'] as $column) {\n if (\\in_array($column['type'], ['varchar', 'text', 'longtext']) &&\n (\\str_contains(\\strtolower((string) $column['name']), 'name') ||\n \\str_contains(\\strtolower((string) $column['name']), 'title') ||\n \\str_contains(\\strtolower((string) $column['name']), 'description'))) {\n $output .= \"- For text searches on `{$table['name']}`, consider using `{$column['name']}` with LIKE or FULLTEXT\\n\";\n break;\n }\n }\n }\n\n $output .= \"\\n\";\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/AdaptiveThresholdPostProcessor.php", "1.0: Not recommended as it tends to include almost all documents.\n *\n * @param float $multiplier multiplier for MAD (higher values = more inclusive)\n */\n public function __construct(private readonly float $multiplier = 0.6)\n {\n }\n\n /**\n * Filters documents using a threshold calculated dynamically with median and MAD\n * for greater robustness against outliers.\n */\n public function process(Message $question, array $documents): array\n {\n if (\\count($documents) < 2) {\n return $documents;\n }\n\n $scores = \\array_map(fn (Document $document): float => $document->getScore(), $documents);\n $median = $this->calculateMedian($scores);\n $mad = $this->calculateMAD($scores, $median);\n\n // If MAD is zero (many equal values), don't filter\n if ($mad <= 0.0001) {\n return $documents;\n }\n\n // Threshold: median - multiplier * MAD\n $threshold = $median - ($this->multiplier * $mad);\n\n // Ensure a threshold is not negative\n $threshold = \\max(0, $threshold);\n\n return \\array_values(\\array_filter($documents, fn (Document $document): bool => $document->getScore() >= $threshold));\n }\n\n /**\n * Calculates the median of an array of values\n *\n * @param float[] $values\n */\n protected function calculateMedian(array $values): float\n {\n \\sort($values);\n $n = \\count($values);\n $mid = (int) \\floor(($n - 1) / 2);\n\n if ($n % 2 !== 0) {\n return $values[$mid];\n }\n\n return ($values[$mid] + $values[$mid + 1]) / 2.0;\n }\n\n /**\n * Calculates the Median Absolute Deviation (MAD)\n *\n * @param float[] $values\n * @param float $median The median of the values\n */\n protected function calculateMAD(array $values, float $median): float\n {\n $deviations = \\array_map(fn (float$v): float => \\abs($v - $median), $values);\n\n // MAD is the median of deviations\n return $this->calculateMedian($deviations);\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/Message.php", "role->value;\n }\n\n public function setRole(MessageRole|string $role): Message\n {\n if (!$role instanceof MessageRole) {\n $role = MessageRole::from($role);\n }\n\n $this->role = $role;\n return $this;\n }\n\n public function getContent(): mixed\n {\n return $this->content;\n }\n\n public function setContent(mixed $content): Message\n {\n $this->content = $content;\n return $this;\n }\n\n /**\n * @return array\n */\n public function getAttachments(): array\n {\n return $this->attachments;\n }\n\n public function addAttachment(Attachment $attachment): Message\n {\n $this->attachments[] = $attachment;\n return $this;\n }\n\n public function getUsage(): ?Usage\n {\n return $this->usage;\n }\n\n public function setUsage(Usage $usage): static\n {\n $this->usage = $usage;\n return $this;\n }\n\n public function addMetadata(string $key, string|array|null $value): Message\n {\n $this->meta[$key] = $value;\n return $this;\n }\n\n public function jsonSerialize(): array\n {\n $data = [\n 'role' => $this->getRole(),\n 'content' => $this->getContent()\n ];\n\n if ($this->getUsage() instanceof \\NeuronAI\\Chat\\Messages\\Usage) {\n $data['usage'] = $this->getUsage()->jsonSerialize();\n }\n\n if ($this->getAttachments() !== []) {\n $data['attachments'] = \\array_map(fn (Attachment $attachment): array => $attachment->jsonSerialize(), $this->getAttachments());\n }\n\n return \\array_merge($this->meta, $data);\n }\n}\n"], ["/neuron-ai/src/RAG/DataLoader/PdfReader.php", "setBinPath($binPath);\n }\n }\n\n public function setBinPath(string $binPath): self\n {\n if (!\\is_executable($binPath)) {\n throw new DataReaderException(\"The provided path is not executable.\");\n }\n $this->binPath = $binPath;\n return $this;\n }\n\n protected function findPdfToText(): string\n {\n if (isset($this->binPath)) {\n return $this->binPath;\n }\n\n foreach ($this->commonPaths as $path) {\n if (\\is_executable($path)) {\n return $path;\n }\n }\n\n throw new DataReaderException(\"The pdftotext binary was not found or is not executable.\");\n }\n\n public function setPdf(string $pdf): self\n {\n if (!\\is_readable($pdf)) {\n throw new DataReaderException(\"Could not read `{$pdf}`\");\n }\n\n $this->pdf = $pdf;\n\n return $this;\n }\n\n public function setOptions(array $options): self\n {\n $this->options = $this->parseOptions($options);\n\n return $this;\n }\n\n public function addOptions(array $options): self\n {\n $this->options = \\array_merge(\n $this->options,\n $this->parseOptions($options)\n );\n\n return $this;\n }\n\n protected function parseOptions(array $options): array\n {\n $mapper = function (string $content): array {\n $content = \\trim($content);\n if ('-' !== ($content[0] ?? '')) {\n $content = '-' . $content;\n }\n\n return \\explode(' ', $content, 2);\n };\n\n $reducer = fn (array $carry, array $option): array => \\array_merge($carry, $option);\n\n return \\array_reduce(\\array_map($mapper, $options), $reducer, []);\n }\n\n public function setTimeout(int $timeout): self\n {\n $this->timeout = $timeout;\n return $this;\n }\n\n public function text(): string\n {\n $process = new Process(\\array_merge([$this->findPdfToText()], $this->options, [$this->pdf, '-']));\n $process->setTimeout($this->timeout);\n $process->run();\n if (!$process->isSuccessful()) {\n throw new ProcessFailedException($process);\n }\n\n return \\trim($process->getOutput(), \" \\t\\n\\r\\0\\x0B\\x0C\");\n }\n\n /**\n * @throws \\Exception\n */\n public static function getText(\n string $filePath,\n array $options = []\n ): string {\n /** @phpstan-ignore new.static */\n $instance = new static();\n $instance->setPdf($filePath);\n\n if (\\array_key_exists('binPath', $options)) {\n $instance->setBinPath($options['binPath']);\n }\n\n if (\\array_key_exists('options', $options)) {\n $instance->setOptions($options['options']);\n }\n\n if (\\array_key_exists('timeout', $options)) {\n $instance->setTimeout($options['timeout']);\n }\n\n return $instance->text();\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Length.php", "exactly && null === $this->min && null === $this->max) {\n $this->min = $this->max = $this->exactly;\n }\n\n if (null === $this->min && null === $this->max) {\n throw new StructuredOutputException('Either option \"min\" or \"max\" must be given for validation rule \"Length\"');\n }\n\n if (\\is_null($value) && ($this->min > 0 || $this->exactly > 0)) {\n $violations[] = $this->buildMessage($name, '{name} cannot be empty');\n return;\n }\n\n if (!\\is_scalar($value) && !$value instanceof \\Stringable) {\n $violations[] = $this->buildMessage($name, '{name} must be a scalar or a stringable object');\n return;\n }\n\n $stringValue = (string) $value;\n\n $length = \\mb_strlen($stringValue);\n\n if (null !== $this->max && $length > $this->max) {\n $shouldExact = $this->min == $this->max;\n\n if ($shouldExact) {\n $violations[] = $this->buildMessage($name, '{name} must be exactly {exact} characters long', ['exact' => $this->min]);\n } else {\n $violations[] = $this->buildMessage($name, '{name} is too long. It must be at most {max} characters', ['max' => $this->max]);\n }\n }\n\n if (null !== $this->min && $length < $this->min) {\n $shouldExact = $this->min == $this->max;\n\n if ($shouldExact) {\n $violations[] = $this->buildMessage($name, '{name} must be exactly {exact} characters long', ['exact' => $this->min]);\n } else {\n $violations[] = $this->buildMessage($name, '{name} is too short. It must be at least {min} characters', ['min' => $this->min]);\n }\n }\n }\n}\n"], ["/neuron-ai/src/Chat/History/FileChatHistory.php", "directory)) {\n throw new ChatHistoryException(\"Directory '{$this->directory}' does not exist\");\n }\n\n $this->load();\n }\n\n protected function load(): void\n {\n if (\\is_file($this->getFilePath())) {\n $messages = \\json_decode(\\file_get_contents($this->getFilePath()), true) ?? [];\n $this->history = $this->deserializeMessages($messages);\n }\n }\n\n protected function getFilePath(): string\n {\n return $this->directory . \\DIRECTORY_SEPARATOR . $this->prefix.$this->key.$this->ext;\n }\n\n public function setMessages(array $messages): ChatHistoryInterface\n {\n $this->updateFile();\n return $this;\n }\n\n protected function clear(): ChatHistoryInterface\n {\n if (!\\unlink($this->getFilePath())) {\n throw new ChatHistoryException(\"Unable to delete file '{$this->getFilePath()}'\");\n }\n return $this;\n }\n\n protected function updateFile(): void\n {\n \\file_put_contents($this->getFilePath(), \\json_encode($this->jsonSerialize()), \\LOCK_EX);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/MedianTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|float|int $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n // Convert to float values and sort\n $numericData = \\array_map('floatval', $numericData);\n \\sort($numericData);\n\n $count = \\count($numericData);\n $middle = (int) \\floor($count / 2);\n\n if ($count % 2 === 0) {\n // Even number of elements - average of two middle values\n $median = ($numericData[$middle - 1] + $numericData[$middle]) / 2;\n } else {\n // Odd number of elements - middle value\n $median = $numericData[$middle];\n }\n\n return \\round($median, $this->precision);\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/QdrantVectorStore.php", "client = new Client([\n 'base_uri' => \\trim($this->collectionUrl, '/').'/',\n 'headers' => [\n 'Content-Type' => 'application/json',\n 'api-key' => $this->key,\n ]\n ]);\n }\n\n public function addDocument(Document $document): void\n {\n $this->client->put('points', [\n RequestOptions::JSON => [\n 'points' => [\n [\n 'id' => $document->getId(),\n 'payload' => [\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n 'metadata' => $document->metadata,\n ],\n 'vector' => $document->getEmbedding(),\n ]\n ]\n ]\n ]);\n }\n\n /**\n * Bulk save documents.\n *\n * @param Document[] $documents\n * @throws GuzzleException\n */\n public function addDocuments(array $documents): void\n {\n $points = \\array_map(fn (Document $document): array => [\n 'id' => $document->getId(),\n 'payload' => [\n 'content' => $document->getContent(),\n 'sourceType' => $document->getSourceType(),\n 'sourceName' => $document->getSourceName(),\n ...$document->metadata,\n ],\n 'vector' => $document->getEmbedding(),\n ], $documents);\n\n $this->client->put('points', [\n RequestOptions::JSON => ['points' => $points]\n ]);\n }\n\n /**\n * @throws GuzzleException\n */\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->client->post('points/delete', [\n RequestOptions::JSON => [\n 'wait' => true,\n 'filter' => [\n 'must' => [\n [\n 'key' => 'sourceType',\n 'match' => [\n 'value' => $sourceType,\n ]\n ],\n [\n 'key' => 'sourceName',\n 'match' => [\n 'value' => $sourceName,\n ]\n ]\n ]\n ]\n ]\n ]);\n }\n\n public function similaritySearch(array $embedding): iterable\n {\n $response = $this->client->post('points/search', [\n RequestOptions::JSON => [\n 'vector' => $embedding,\n 'limit' => $this->topK,\n 'with_payload' => true,\n 'with_vector' => true,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return \\array_map(function (array $item): Document {\n $document = new Document($item['payload']['content']);\n $document->id = $item['id'];\n $document->embedding = $item['vector'];\n $document->sourceType = $item['payload']['sourceType'];\n $document->sourceName = $item['payload']['sourceName'];\n $document->score = $item['score'];\n\n foreach ($item['payload'] as $name => $value) {\n if (!\\in_array($name, ['content', 'sourceType', 'sourceName', 'score', 'embedding', 'id'])) {\n $document->addMetadata($name, $value);\n }\n }\n\n return $document;\n }, $response['result']);\n }\n}\n"], ["/neuron-ai/src/Observability/HandleStructuredEvents.php", "inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$data->class.'-schema'] = $this->inspector->startSegment('neuron-schema-generation', \"schema_generate( {$data->class} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n protected function schemaGenerated(AgentInterface $agent, string $event, SchemaGenerated $data): void\n {\n if (\\array_key_exists($data->class.'-schema', $this->segments)) {\n $segment = $this->segments[$data->class.'-schema']->end();\n $segment->addContext('Schema', $data->schema);\n }\n }\n\n protected function extracting(AgentInterface $agent, string $event, Extracting $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $id = $this->getMessageId($data->message).'-extract';\n\n $this->segments[$id] = $this->inspector->startSegment('neuron-structured-extract', 'extract_output')\n ->setColor(self::SEGMENT_COLOR);\n }\n\n protected function extracted(AgentInterface $agent, string $event, Extracted $data): void\n {\n $id = $this->getMessageId($data->message).'-extract';\n\n if (\\array_key_exists($id, $this->segments)) {\n $segment = $this->segments[$id]->end();\n $segment->addContext(\n 'Data',\n [\n 'response' => $data->message->jsonSerialize(),\n 'json' => $data->json,\n ]\n )->addContext(\n 'Schema',\n $data->schema\n );\n unset($this->segments[$id]);\n }\n }\n\n protected function deserializing(AgentInterface $agent, string $event, Deserializing $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$data->class.'-deserialize'] = $this->inspector->startSegment('neuron-structured-deserialize', \"deserialize( {$data->class} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n protected function deserialized(AgentInterface $agent, string $event, Deserialized $data): void\n {\n $id = $data->class.'-deserialize';\n\n if (\\array_key_exists($id, $this->segments)) {\n $this->segments[$id]->end();\n }\n }\n\n protected function validating(AgentInterface $agent, string $event, Validating $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $this->segments[$data->class.'-validate'] = $this->inspector->startSegment('neuron-structured-validate', \"validate( {$data->class} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n protected function validated(AgentInterface $agent, string $event, Validated $data): void\n {\n $id = $data->class.'-validate';\n\n if (\\array_key_exists($id, $this->segments)) {\n $segment = $this->segments[$id]->end();\n $segment->addContext('Json', \\json_decode($data->json));\n if ($data->violations !== []) {\n $segment->addContext('Violations', $data->violations);\n }\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Enum.php", "values !== null && $this->values !== [] && $this->class !== null) {\n throw new StructuredOutputException('You cannot provide both \"choices\" and \"enum\" options simultaneously. Please use only one.');\n }\n\n if (($this->values === null || $this->values === []) && $this->class === null) {\n throw new StructuredOutputException('Either option \"choices\" or \"enum\" must be given for validation rule \"Enum\"');\n }\n\n if ($this->values === null || $this->values === []) {\n $this->handleEnum();\n }\n }\n\n public function validate(string $name, mixed $value, array &$violations): void\n {\n $value = $value instanceof \\BackedEnum ? $value->value : $value;\n\n if (!\\in_array($value, $this->values, true)) {\n $violations[] = $this->buildMessage($name, $this->message, ['choices' => \\implode(\", \", $this->values)]);\n }\n }\n\n /**\n * @throws StructuredOutputException\n */\n private function handleEnum(): void\n {\n if (!\\enum_exists($this->class)) {\n throw new StructuredOutputException(\"Enum '{$this->class}' does not exist.\");\n }\n\n if (!\\is_subclass_of($this->class, \\BackedEnum::class)) {\n throw new StructuredOutputException(\"Enum '{$this->class}' must implement BackedEnum.\");\n }\n\n $this->values = \\array_map(fn (\\BackedEnum $case): int|string => $case->value, $this->class::cases());\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/VoyageEmbeddingsProvider.php", "client = new Client([\n 'base_uri' => $this->baseUri,\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer ' . $key,\n ],\n ]);\n }\n\n public function embedText(string $text): array\n {\n $response = $this->client->post('', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'input' => $text,\n 'output_dimension' => $this->dimensions,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['data'][0]['embedding'];\n }\n\n public function embedDocuments(array $documents): array\n {\n $chunks = \\array_chunk($documents, 100);\n\n foreach ($chunks as $chunk) {\n $response = $this->client->post('', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'input' => \\array_map(fn (Document $document): string => $document->getContent(), $chunk),\n 'output_dimension' => $this->dimensions,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n foreach ($response['data'] as $index => $item) {\n $chunk[$index]->embedding = $item['embedding'];\n }\n }\n\n return \\array_merge(...$chunks);\n }\n}\n"], ["/neuron-ai/src/Tools/ArrayProperty.php", "validateConstraints();\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'name' => $this->name,\n 'description' => $this->description,\n 'type' => $this->type->value,\n 'items' => $this->getJsonSchema(),\n 'required' => $this->required,\n ];\n }\n\n public function getJsonSchema(): array\n {\n $schema = [\n 'type' => $this->type->value,\n ];\n\n if (!\\is_null($this->description)) {\n $schema['description'] = $this->description;\n }\n\n if ($this->items instanceof ToolPropertyInterface) {\n $schema['items'] = $this->items->getJsonSchema();\n }\n\n if ($this->minItems !== null && $this->minItems !== 0) {\n $schema['minItems'] = $this->minItems;\n }\n\n if ($this->maxItems !== null && $this->maxItems !== 0) {\n $schema['maxItems'] = $this->maxItems;\n }\n\n return $schema;\n }\n\n public function isRequired(): bool\n {\n return $this->required;\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n public function getType(): PropertyType\n {\n return $this->type;\n }\n\n public function getDescription(): ?string\n {\n return $this->description;\n }\n\n public function getItems(): ?ToolPropertyInterface\n {\n return $this->items;\n }\n\n /**\n * @throws ArrayPropertyException\n */\n protected function validateConstraints(): void\n {\n if ($this->minItems !== null && $this->minItems < 0) {\n throw new ArrayPropertyException(\"minItems must be >= 0, got {$this->minItems}\");\n }\n\n if ($this->maxItems !== null && $this->maxItems < 0) {\n throw new ArrayPropertyException(\"maxItems must be >= 0, got {$this->maxItems}\");\n }\n\n if ($this->minItems !== null && $this->maxItems !== null && $this->minItems > $this->maxItems) {\n throw new ArrayPropertyException(\n \"minItems ({$this->minItems}) cannot be greater than maxItems ({$this->maxItems})\"\n );\n }\n }\n}\n"], ["/neuron-ai/src/RAG/DataLoader/FileDataLoader.php", "\n */\n protected array $readers = [];\n\n public function __construct(protected string $path, array $readers = [])\n {\n parent::__construct();\n $this->setReaders($readers);\n }\n\n public function addReader(string $fileExtension, ReaderInterface $reader): self\n {\n $this->readers[$fileExtension] = $reader;\n return $this;\n }\n\n public function setReaders(array $readers): self\n {\n $this->readers = $readers;\n return $this;\n }\n\n public function getDocuments(): array\n {\n if (! \\file_exists($this->path)) {\n return [];\n }\n\n // If it's a directory\n if (\\is_dir($this->path)) {\n return $this->getDocumentsFromDirectory($this->path);\n }\n\n // If it's a file\n try {\n return $this->splitter->splitDocument($this->getDocument($this->getContentFromFile($this->path), $this->path));\n } catch (\\Throwable) {\n return [];\n }\n }\n\n protected function getDocumentsFromDirectory(string $directory): array\n {\n $documents = [];\n // Open the directory\n if ($handle = \\opendir($directory)) {\n // Read the directory contents\n while (($entry = \\readdir($handle)) !== false) {\n $fullPath = $directory.'/'.$entry;\n if ($entry !== '.' && $entry !== '..') {\n if (\\is_dir($fullPath)) {\n $documents = [...$documents, ...$this->getDocumentsFromDirectory($fullPath)];\n } else {\n try {\n $documents[] = $this->getDocument($this->getContentFromFile($fullPath), $entry);\n } catch (\\Throwable) {\n }\n }\n }\n }\n\n // Close the directory\n \\closedir($handle);\n }\n\n return $this->splitter->splitDocuments($documents);\n }\n\n /**\n * Transform files to plain text.\n *\n * Supported PDF and plain text files.\n *\n * @throws \\Exception\n */\n protected function getContentFromFile(string $path): string|false\n {\n $fileExtension = \\strtolower(\\pathinfo($path, \\PATHINFO_EXTENSION));\n\n if (\\array_key_exists($fileExtension, $this->readers)) {\n $reader = $this->readers[$fileExtension];\n return $reader::getText($path);\n }\n\n return TextFileReader::getText($path);\n }\n\n\n protected function getDocument(string $content, string $entry): Document\n {\n $document = new Document($content);\n $document->sourceType = 'files';\n $document->sourceName = $entry;\n\n return $document;\n }\n}\n"], ["/neuron-ai/src/Workflow/Workflow.php", "exporter = new MermaidExporter();\n\n if (\\is_null($persistence) && !\\is_null($workflowId)) {\n throw new WorkflowException('Persistence must be defined when workflowId is defined');\n }\n if (\\is_null($workflowId) && !\\is_null($persistence)) {\n throw new WorkflowException('WorkflowId must be defined when persistence is defined');\n }\n\n $this->persistence = $persistence ?? new InMemoryPersistence();\n $this->workflowId = $workflowId ?? \\uniqid('neuron_workflow_');\n }\n\n public function validate(): void\n {\n /*if ($this->getStartNode() === null) {\n throw new WorkflowException('Start node must be defined');\n }\n\n if ($this->getEndNode() === null) {\n throw new WorkflowException('End node must be defined');\n }*/\n\n if (!isset($this->getNodes()[$this->getStartNode()])) {\n throw new WorkflowException(\"Start node {$this->getStartNode()} does not exist\");\n }\n\n foreach ($this->getEndNodes() as $endNode) {\n if (!isset($this->getNodes()[$endNode])) {\n throw new WorkflowException(\"End node {$endNode} does not exist\");\n }\n }\n\n foreach ($this->getEdges() as $edge) {\n if (!isset($this->getNodes()[$edge->getFrom()])) {\n throw new WorkflowException(\"Edge from node {$edge->getFrom()} does not exist\");\n }\n\n if (!isset($this->getNodes()[$edge->getTo()])) {\n throw new WorkflowException(\"Edge to node {$edge->getTo()} does not exist\");\n }\n }\n }\n\n /**\n * @throws WorkflowInterrupt|WorkflowException|\\Throwable\n */\n protected function execute(\n string $currentNode,\n WorkflowState $state,\n bool $resuming = false,\n array|string|int $humanFeedback = []\n ): WorkflowState {\n $context = new WorkflowContext(\n $this->workflowId,\n $currentNode,\n $this->persistence,\n $state\n );\n\n if ($resuming) {\n $context->setResuming(true, [$currentNode => $humanFeedback]);\n }\n\n try {\n while (!\\in_array($currentNode, $this->getEndNodes())) {\n $node = $this->nodes[$currentNode];\n $node->setContext($context);\n\n $this->notify('workflow-node-start', new WorkflowNodeStart($currentNode, $state));\n try {\n $state = $node->run($state);\n } catch (WorkflowInterrupt $interrupt) {\n throw $interrupt;\n } catch (\\Throwable $exception) {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n $this->notify('workflow-node-end', new WorkflowNodeEnd($currentNode, $state));\n\n $nextNode = $this->findNextNode($currentNode, $state);\n\n if ($nextNode === null) {\n throw new WorkflowException(\"No valid edge found from node {$currentNode}\");\n }\n\n $currentNode = $nextNode;\n\n // Update the context before the next iteration or end node\n $context = new WorkflowContext(\n $this->workflowId,\n $currentNode,\n $this->persistence,\n $state\n );\n }\n\n $endNode = $this->nodes[$currentNode];\n $endNode->setContext($context);\n $result = $endNode->run($state);\n $this->persistence->delete($this->workflowId);\n return $result;\n\n } catch (WorkflowInterrupt $interrupt) {\n $this->persistence->save($this->workflowId, $interrupt);\n $this->notify('workflow-interrupt', $interrupt);\n throw $interrupt;\n }\n }\n\n /**\n * @throws WorkflowInterrupt|WorkflowException|\\Throwable\n */\n public function run(?WorkflowState $initialState = null): WorkflowState\n {\n $this->notify('workflow-start', new WorkflowStart($this->getNodes(), $this->getEdges()));\n try {\n $this->validate();\n } catch (WorkflowException $exception) {\n $this->notify('error', new AgentError($exception));\n throw $exception;\n }\n\n $state = $initialState ?? new WorkflowState();\n $currentNode = $this->getStartNode();\n\n $result = $this->execute($currentNode, $state);\n $this->notify('workflow-end', new WorkflowEnd($result));\n\n return $result;\n }\n\n /**\n * @throws WorkflowInterrupt|WorkflowException|\\Throwable\n */\n public function resume(array|string|int $humanFeedback): WorkflowState\n {\n $this->notify('workflow-resume', new WorkflowStart($this->getNodes(), $this->getEdges()));\n $interrupt = $this->persistence->load($this->workflowId);\n\n $state = $interrupt->getState();\n $currentNode = $interrupt->getCurrentNode();\n\n $result = $this->execute(\n $currentNode,\n $state,\n true,\n $humanFeedback\n );\n $this->notify('workflow-end', new WorkflowEnd($result));\n\n return $result;\n }\n\n /**\n * @return Node[]\n */\n protected function nodes(): array\n {\n return [];\n }\n\n /**\n * @return Edge[]\n */\n protected function edges(): array\n {\n return [];\n }\n\n public function addNode(NodeInterface $node): self\n {\n $this->nodes[$node::class] = $node;\n return $this;\n }\n\n /**\n * @param NodeInterface[] $nodes\n */\n public function addNodes(array $nodes): Workflow\n {\n foreach ($nodes as $node) {\n $this->addNode($node);\n }\n return $this;\n }\n\n /**\n * @return array\n */\n public function getNodes(): array\n {\n if ($this->nodes === []) {\n foreach ($this->nodes() as $node) {\n $this->addNode($node);\n }\n }\n\n return $this->nodes;\n }\n\n public function addEdge(Edge $edge): self\n {\n $this->edges[] = $edge;\n return $this;\n }\n\n /**\n * @param Edge[] $edges\n */\n public function addEdges(array $edges): Workflow\n {\n foreach ($edges as $edge) {\n $this->addEdge($edge);\n }\n return $this;\n }\n\n /**\n * @return Edge[]\n */\n public function getEdges(): array\n {\n if ($this->edges === []) {\n $this->edges = $this->edges();\n }\n\n return $this->edges;\n }\n\n public function setStart(string $nodeClass): Workflow\n {\n $this->startNode = $nodeClass;\n return $this;\n }\n\n public function setEnd(string $nodeClass): Workflow\n {\n $this->endNodes[] = $nodeClass;\n return $this;\n }\n\n protected function getStartNode(): string\n {\n return $this->startNode ?? $this->start();\n }\n\n protected function getEndNodes(): array\n {\n return $this->endNodes ?? $this->end();\n }\n\n protected function start(): ?string\n {\n throw new WorkflowException('Start node must be defined');\n }\n\n protected function end(): array\n {\n throw new WorkflowException('End node must be defined');\n }\n\n private function findNextNode(string $currentNode, WorkflowState $state): ?string\n {\n foreach ($this->getEdges() as $edge) {\n if ($edge->getFrom() === $currentNode && $edge->shouldExecute($state)) {\n return $edge->getTo();\n }\n }\n\n return null;\n }\n\n public function getWorkflowId(): string\n {\n return $this->workflowId;\n }\n\n public function export(): string\n {\n return $this->exporter->export($this);\n }\n\n public function setExporter(ExporterInterface $exporter): Workflow\n {\n $this->exporter = $exporter;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/MeanTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|float|int $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n // Convert to float values\n $numericData = \\array_map('floatval', $numericData);\n $mean = \\array_sum($numericData) / \\count($numericData);\n\n return \\round($mean, $this->precision);\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Json.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/NotBlank.php", "allowNull && $value === null) {\n return;\n }\n\n if (false === $value || (empty($value) && '0' != $value)) {\n $violations[] = $this->buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/Tools/ObjectProperty.php", "properties === [] && \\class_exists($this->class)) {\n $schema = (new JsonSchema())->generate($this->class);\n $this->properties = $this->buildPropertiesFromClass($schema);\n }\n }\n\n /**\n * Recursively build properties from a class schema\n *\n * @return ToolPropertyInterface[]\n * @throws \\ReflectionException\n * @throws ToolException\n * @throws ArrayPropertyException\n */\n protected function buildPropertiesFromClass(array $schema): array\n {\n $required = $schema['required'] ?? [];\n $properties = [];\n\n foreach ($schema['properties'] as $propertyName => $propertyData) {\n $isRequired = \\in_array($propertyName, $required);\n $property = $this->createPropertyFromSchema($propertyName, $propertyData, $isRequired);\n\n if ($property instanceof ToolPropertyInterface) {\n $properties[] = $property;\n }\n }\n\n return $properties;\n }\n\n /**\n * Create a property from schema data recursively\n *\n * @throws \\ReflectionException\n * @throws ToolException\n * @throws ArrayPropertyException\n */\n protected function createPropertyFromSchema(string $propertyName, array $propertyData, bool $isRequired): ?ToolPropertyInterface\n {\n $type = $propertyData['type'] ?? 'string';\n $description = $propertyData['description'] ?? null;\n\n return match ($type) {\n 'object' => $this->createObjectProperty($propertyName, $propertyData, $isRequired, $description),\n 'array' => $this->createArrayProperty($propertyName, $propertyData, $isRequired, $description),\n 'string', 'integer', 'number', 'boolean' => $this->createScalarProperty($propertyName, $propertyData, $isRequired, $description),\n default => new ToolProperty(\n $propertyName,\n PropertyType::STRING,\n $description,\n $isRequired,\n $propertyData['enum'] ?? []\n ),\n };\n }\n\n /**\n * Create an object property recursively\n *\n * @throws \\ReflectionException\n * @throws ToolException\n * @throws ArrayPropertyException\n */\n protected function createObjectProperty(string $name, array $propertyData, bool $required, ?string $description): ObjectProperty\n {\n $nestedProperties = [];\n $nestedRequired = $propertyData['required'] ?? [];\n\n // If there's a class reference in the schema, use it\n $className = $propertyData['class'] ?? null;\n\n // If no class is specified, but we have nested properties, build them recursively\n if (!$className && isset($propertyData['properties'])) {\n foreach ($propertyData['properties'] as $nestedPropertyName => $nestedPropertyData) {\n $nestedIsRequired = \\in_array($nestedPropertyName, $nestedRequired);\n $nestedProperty = $this->createPropertyFromSchema($nestedPropertyName, $nestedPropertyData, $nestedIsRequired);\n\n if ($nestedProperty instanceof ToolPropertyInterface) {\n $nestedProperties[] = $nestedProperty;\n }\n }\n }\n\n return new ObjectProperty(\n $name,\n $description,\n $required,\n $className,\n $nestedProperties\n );\n }\n\n /**\n * Create an array property with recursive item handling\n *\n * @throws \\ReflectionException\n * @throws ToolException\n * @throws ArrayPropertyException\n */\n protected function createArrayProperty(string $name, array $propertyData, bool $required, ?string $description): ArrayProperty\n {\n $items = null;\n $minItems = $propertyData['minItems'] ?? null;\n $maxItems = $propertyData['maxItems'] ?? null;\n\n // Handle array items recursively\n if (isset($propertyData['items'])) {\n $itemsData = $propertyData['items'];\n $items = $this->createPropertyFromSchema($name . '_item', $itemsData, false);\n }\n\n return new ArrayProperty(\n $name,\n $description,\n $required,\n $items,\n $minItems,\n $maxItems\n );\n }\n\n /**\n * Create a scalar property (string, integer, number, boolean)\n *\n * @throws ToolException\n */\n protected function createScalarProperty(string $name, array $propertyData, bool $required, ?string $description): ToolProperty\n {\n return new ToolProperty(\n $name,\n PropertyType::fromSchema($propertyData['type']),\n $description,\n $required,\n $propertyData['enum'] ?? []\n );\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'name' => $this->name,\n ...(\\is_null($this->description) ? [] : ['description' => $this->description]),\n 'type' => $this->type,\n 'properties' => $this->getJsonSchema(),\n 'required' => $this->required,\n ];\n }\n\n // The mapped class required properties and required properties are merged\n public function getRequiredProperties(): array\n {\n return \\array_values(\\array_filter(\\array_map(fn (\n ToolPropertyInterface $property\n ): ?string => $property->isRequired() ? $property->getName() : null, $this->properties)));\n }\n\n public function getJsonSchema(): array\n {\n $schema = [\n 'type' => $this->type->value,\n ];\n\n if (!\\is_null($this->description)) {\n $schema['description'] = $this->description;\n }\n\n $properties = \\array_reduce($this->properties, function (array $carry, ToolPropertyInterface $property) {\n $carry[$property->getName()] = $property->getJsonSchema();\n return $carry;\n }, []);\n\n if (!empty($properties)) {\n $schema['properties'] = $properties;\n $schema['required'] = $this->getRequiredProperties();\n }\n\n return $schema;\n }\n\n public function isRequired(): bool\n {\n return $this->required;\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n public function getType(): PropertyType\n {\n return $this->type;\n }\n\n public function getDescription(): ?string\n {\n return $this->description;\n }\n\n public function getProperties(): array\n {\n return $this->properties;\n }\n\n public function getClass(): ?string\n {\n return $this->class;\n }\n}\n"], ["/neuron-ai/src/Chat/History/SQLChatHistory.php", "table = $this->sanitizeTableName($table);\n $this->load();\n }\n\n protected function load(): void\n {\n $stmt = $this->pdo->prepare(\"SELECT * FROM {$this->table} WHERE thread_id = :thread_id\");\n $stmt->execute(['thread_id' => $this->thread_id]);\n $history = $stmt->fetchAll(PDO::FETCH_ASSOC);\n\n if (empty($history)) {\n $stmt = $this->pdo->prepare(\"INSERT INTO {$this->table} (thread_id, messages) VALUES (:thread_id, :messages)\");\n $stmt->execute(['thread_id' => $this->thread_id, 'messages' => '[]']);\n } else {\n $this->history = $this->deserializeMessages(\\json_decode((string) $history[0]['messages'], true));\n }\n }\n\n public function setMessages(array $messages): ChatHistoryInterface\n {\n $stmt = $this->pdo->prepare(\"UPDATE {$this->table} SET messages = :messages WHERE thread_id = :thread_id\");\n $stmt->execute(['thread_id' => $this->thread_id, 'messages' => \\json_encode($this->jsonSerialize())]);\n return $this;\n }\n\n protected function clear(): ChatHistoryInterface\n {\n $stmt = $this->pdo->prepare(\"DELETE FROM {$this->table} WHERE thread_id = :thread_id\");\n $stmt->execute(['thread_id' => $this->thread_id]);\n return $this;\n }\n\n protected function sanitizeTableName(string $tableName): string\n {\n $tableName = \\trim($tableName);\n\n // Whitelist validation\n if (!$this->tableExists($tableName)) {\n throw new ChatHistoryException('Table not allowed');\n }\n\n // Format validation as backup\n if (\\in_array(\\preg_match('/^[a-zA-Z_]\\w*$/', $tableName), [0, false], true)) {\n throw new ChatHistoryException('Invalid table name format');\n }\n\n return $tableName;\n }\n\n protected function tableExists(string $tableName): bool\n {\n $stmt = $this->pdo->prepare(\"SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :table_name\");\n $stmt->execute(['table_name' => $tableName]);\n return $stmt->fetch() !== false;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/FactorialTool.php", " 'Factorial is not defined for negative numbers.'];\n }\n\n // Handle edge cases\n if ($number === 0 || $number === 1) {\n return 1;\n }\n\n // For larger numbers, use BCMath to handle arbitrary precision\n if ($number > 20) {\n return self::calculateWithBCMath($number);\n }\n\n // For smaller numbers, use regular integer calculation\n $result = 1;\n for ($i = 2; $i <= $number; $i++) {\n $result *= $i;\n }\n\n return $result;\n }\n\n /**\n * Calculate factorial using BCMath for large numbers\n */\n private function calculateWithBCMath(int $number): float\n {\n $result = '1';\n\n for ($i = 2; $i <= $number; $i++) {\n $result = \\bcmul($result, (string)$i);\n }\n\n return (float)$result;\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/CohereRerankerPostProcessor.php", "client ?? $this->client = new Client([\n 'base_uri' => 'https://api.cohere.com/v2/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer '.$this->key,\n ],\n ]);\n }\n\n public function process(Message $question, array $documents): array\n {\n $response = $this->getClient()->post('rerank', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'query' => $question->getContent(),\n 'top_n' => $this->topN,\n 'documents' => \\array_map(fn (Document $document): string => $document->getContent(), $documents),\n ],\n ])->getBody()->getContents();\n\n $result = \\json_decode($response, true);\n\n return \\array_map(function (array $item) use ($documents): Document {\n $document = $documents[$item['index']];\n $document->setScore($item['relevance_score']);\n return $document;\n }, $result['results']);\n }\n\n public function setClient(Client $client): PostProcessorInterface\n {\n $this->client = $client;\n return $this;\n }\n}\n"], ["/neuron-ai/src/RAG/RAG.php", "chat($question);\n }\n\n /**\n * @deprecated Use \"stream\" instead\n */\n public function answerStream(Message $question): \\Generator\n {\n return $this->stream($question);\n }\n\n /**\n * @throws MissingCallbackParameter\n * @throws ToolCallableNotSet\n * @throws \\Throwable\n */\n public function chat(Message|array $messages): Message\n {\n $question = \\is_array($messages) ? \\end($messages) : $messages;\n\n $this->notify('chat-rag-start');\n\n $this->retrieval($question);\n\n $response = parent::chat($messages);\n\n $this->notify('chat-rag-stop');\n return $response;\n }\n\n public function stream(Message|array $messages): \\Generator\n {\n $question = \\is_array($messages) ? \\end($messages) : $messages;\n\n $this->notify('stream-rag-start');\n\n $this->retrieval($question);\n\n yield from parent::stream($messages);\n\n $this->notify('stream-rag-stop');\n }\n\n public function structured(Message|array $messages, ?string $class = null, int $maxRetries = 1): mixed\n {\n $question = \\is_array($messages) ? \\end($messages) : $messages;\n\n $this->notify('structured-rag-start');\n\n $this->retrieval($question);\n\n $structured = parent::structured($messages, $class, $maxRetries);\n\n $this->notify('structured-rag-stop');\n\n return $structured;\n }\n\n protected function retrieval(Message $question): void\n {\n $this->withDocumentsContext(\n $this->retrieveDocuments($question)\n );\n }\n\n /**\n * Set the system message based on the context.\n *\n * @param Document[] $documents\n */\n public function withDocumentsContext(array $documents): AgentInterface\n {\n $originalInstructions = $this->resolveInstructions();\n\n // Remove the old context to avoid infinite grow\n $newInstructions = $this->removeDelimitedContent($originalInstructions, '', '');\n\n $newInstructions .= '';\n foreach ($documents as $document) {\n $newInstructions .= \"Source Type: \".$document->getSourceType().\\PHP_EOL.\n \"Source Name: \".$document->getSourceName().\\PHP_EOL.\n \"Content: \".$document->getContent().\\PHP_EOL.\\PHP_EOL;\n }\n $newInstructions .= '';\n\n $this->withInstructions(\\trim($newInstructions));\n\n return $this;\n }\n\n /**\n * Retrieve relevant documents from the vector store.\n *\n * @return Document[]\n */\n public function retrieveDocuments(Message $question): array\n {\n $question = $this->applyPreProcessors($question);\n\n $this->notify('rag-retrieving', new Retrieving($question));\n\n $documents = $this->resolveVectorStore()->similaritySearch(\n $this->resolveEmbeddingsProvider()->embedText($question->getContent()),\n );\n\n $retrievedDocs = [];\n\n foreach ($documents as $document) {\n //md5 for removing duplicates\n $retrievedDocs[\\md5($document->getContent())] = $document;\n }\n\n $retrievedDocs = \\array_values($retrievedDocs);\n\n $this->notify('rag-retrieved', new Retrieved($question, $retrievedDocs));\n\n return $this->applyPostProcessors($question, $retrievedDocs);\n }\n\n /**\n * Apply a series of preprocessors to the asked question.\n *\n * @return Message The processed question.\n */\n protected function applyPreProcessors(Message $question): Message\n {\n foreach ($this->preProcessors() as $processor) {\n $this->notify('rag-preprocessing', new PreProcessing($processor::class, $question));\n $question = $processor->process($question);\n $this->notify('rag-preprocessed', new PreProcessed($processor::class, $question));\n }\n\n return $question;\n }\n\n /**\n * Apply a series of postprocessors to the retrieved documents.\n *\n * @param Document[] $documents The documents to process.\n * @return Document[] The processed documents.\n */\n protected function applyPostProcessors(Message $question, array $documents): array\n {\n foreach ($this->postProcessors() as $processor) {\n $this->notify('rag-postprocessing', new PostProcessing($processor::class, $question, $documents));\n $documents = $processor->process($question, $documents);\n $this->notify('rag-postprocessed', new PostProcessed($processor::class, $question, $documents));\n }\n\n return $documents;\n }\n\n /**\n * Feed the vector store with documents.\n *\n * @param Document[] $documents\n */\n public function addDocuments(array $documents, int $chunkSize = 50): void\n {\n foreach (\\array_chunk($documents, $chunkSize) as $chunk) {\n $this->resolveVectorStore()->addDocuments(\n $this->resolveEmbeddingsProvider()->embedDocuments($chunk)\n );\n }\n }\n\n /**\n * @param Document[] $documents\n */\n public function reindexBySource(array $documents, int $chunkSize = 50): void\n {\n $grouped = [];\n\n foreach ($documents as $document) {\n $key = $document->sourceType . ':' . $document->sourceName;\n\n if (!isset($grouped[$key])) {\n $grouped[$key] = [];\n }\n\n $grouped[$key][] = $document;\n }\n\n foreach (\\array_keys($grouped) as $key) {\n [$sourceType, $sourceName] = \\explode(':', $key);\n $this->resolveVectorStore()->deleteBySource($sourceType, $sourceName);\n $this->addDocuments($grouped[$key], $chunkSize);\n }\n }\n\n /**\n * @throws AgentException\n */\n public function setPreProcessors(array $preProcessors): RAG\n {\n foreach ($preProcessors as $processor) {\n if (! $processor instanceof PreProcessorInterface) {\n throw new AgentException($processor::class.\" must implement PreProcessorInterface\");\n }\n\n $this->preProcessors[] = $processor;\n }\n\n return $this;\n }\n\n /**\n * @throws AgentException\n */\n public function setPostProcessors(array $postProcessors): RAG\n {\n foreach ($postProcessors as $processor) {\n if (! $processor instanceof PostProcessorInterface) {\n throw new AgentException($processor::class.\" must implement PostProcessorInterface\");\n }\n\n $this->postProcessors[] = $processor;\n }\n\n return $this;\n }\n\n /**\n * @return PreProcessorInterface[]\n */\n protected function preProcessors(): array\n {\n return $this->preProcessors;\n }\n\n /**\n * @return PostProcessorInterface[]\n */\n protected function postProcessors(): array\n {\n return $this->postProcessors;\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Validator.php", "getProperties(\\ReflectionProperty::IS_PUBLIC) as $property) {\n // Get all attributes for this property\n $attributes = $property->getAttributes();\n\n if (empty($attributes)) {\n continue;\n }\n\n // Get the value of the property\n $name = $property->getName();\n $value = $property->isInitialized($obj) ? $property->getValue($obj) : null;\n\n // Apply all the validation rules to the value\n foreach ($attributes as $attribute) {\n $instance = $attribute->newInstance();\n\n // Perform validation\n if ($instance instanceof ValidationRuleInterface) {\n $instance->validate($name, $value, $violations);\n }\n }\n }\n\n return $violations;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/AbstractToolkit.php", "exclude = $classes;\n return $this;\n }\n\n /**\n * @param class-string[] $classes\n */\n public function only(array $classes): ToolkitInterface\n {\n $this->only = $classes;\n return $this;\n }\n\n /**\n * @return ToolInterface[]\n */\n abstract public function provide(): array;\n\n public function tools(): array\n {\n if ($this->exclude === [] && $this->only === []) {\n return $this->provide();\n }\n\n return \\array_filter(\n $this->provide(),\n fn (ToolInterface $tool): bool => !\\in_array($tool::class, $this->exclude)\n && ($this->only === [] || \\in_array($tool::class, $this->only))\n );\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Zep/ZepSearchGraphTool.php", "createUser();\n }\n\n protected function properties(): array\n {\n return [\n new ToolProperty(\n 'query',\n PropertyType::STRING,\n 'The search term to find relevant facts or nodes',\n true\n ),\n new ToolProperty(\n 'search_scope',\n PropertyType::STRING,\n 'The scope of the search to perform. Can be \"facts\" or \"nodes\"',\n false,\n ['facts', 'nodes']\n )\n ];\n }\n\n public function __invoke(string $query, string $search_scope = 'facts', int $limit = 5): array\n {\n $response = $this->getClient()->post('graph/search', [\n RequestOptions::JSON => [\n 'user_id' => $this->user_id,\n 'query' => $query,\n 'scope' => $search_scope === 'facts' ? 'edges' : 'nodes',\n 'limit' => $limit,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return match ($search_scope) {\n 'nodes' => $this->mapNodes($response['nodes']),\n default => $this->mapEdges($response['edges']),\n };\n }\n\n protected function mapEdges(array $edges): array\n {\n return \\array_map(fn (array $edge): array => [\n 'fact' => $edge['fact'],\n 'created_at' => $edge['created_at'],\n ], $edges);\n }\n\n protected function mapNodes(array $nodes): array\n {\n return \\array_map(fn (array $node): array => [\n 'name' => $node['name'],\n 'summary' => $node['summary'],\n ], $nodes);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Zep/ZepAddToGraphTool.php", "createUser();\n }\n\n protected function properties(): array\n {\n return [\n new ToolProperty(\n 'data',\n PropertyType::STRING,\n 'The search term to find relevant facts or nodes',\n true\n ),\n new ToolProperty(\n 'type',\n PropertyType::STRING,\n 'The scope of the search to perform. Can be \"facts\" or \"nodes\"',\n true,\n ['text', 'json', 'message']\n )\n ];\n }\n\n public function __invoke(string $data, string $type): string\n {\n $response = $this->getClient()->post('graph', [\n RequestOptions::JSON => [\n 'user_id' => $this->user_id,\n 'data' => $data,\n 'type' => $type,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['content'];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/PGSQL/PGSQLSelectTool.php", "validateReadOnlyQuery($query)) {\n return [\n \"error\" => \"The query was rejected for security reasons.\nIt looks like you are trying to run a write query using the read-only query tool.\"\n ];\n }\n\n $statement = $this->pdo->prepare($query);\n $statement->execute();\n\n return $statement->fetchAll(PDO::FETCH_ASSOC);\n }\n\n /**\n * Validates that the query is read-only\n *\n * @throws InvalidArgumentException if query contains write operations\n */\n private function validateReadOnlyQuery(string $query): bool\n {\n if ($query === '') {\n return false;\n }\n\n // Remove comments to avoid false positives\n $cleanQuery = $this->removeComments($query);\n\n // Check if query starts with an allowed read operation\n $isAllowed = false;\n foreach ($this->allowedPatterns as $pattern) {\n if (\\preg_match($pattern, $cleanQuery)) {\n $isAllowed = true;\n break;\n }\n }\n\n if (!$isAllowed) {\n return false;\n }\n\n // Check for forbidden write operations\n foreach ($this->forbiddenPatterns as $pattern) {\n if (\\preg_match($pattern, $cleanQuery)) {\n return false;\n }\n }\n\n // Additional security checks\n return $this->performAdditionalSecurityChecks($cleanQuery);\n }\n\n private function removeComments(string $query): string\n {\n // Remove single-line comments (-- style)\n $query = \\preg_replace('/--.*$/m', '', $query);\n\n // Remove multi-line comments (/* */ style)\n $query = \\preg_replace('/\\/\\*.*?\\*\\//s', '', (string) $query);\n\n return $query;\n }\n\n private function performAdditionalSecurityChecks(string $query): bool\n {\n // Check for semicolon followed by potential write operations\n if (\\preg_match('/;\\s*(?!$)/i', $query)) {\n // Multiple statements detected - need to validate each one\n $statements = $this->splitStatements($query);\n foreach ($statements as $statement) {\n if (\\trim((string) $statement) !== '' && !$this->validateSingleStatement(\\trim((string) $statement))) {\n return false;\n }\n }\n }\n\n // Check for function calls that might modify data\n $dangerousFunctions = [\n 'pg_exec',\n 'pg_query',\n 'system',\n 'exec',\n 'shell_exec',\n 'passthru',\n 'eval',\n ];\n\n foreach ($dangerousFunctions as $func) {\n if (\\stripos($query, $func) !== false) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Split query into individual statements\n */\n private function splitStatements(string $query): array\n {\n // Simple split on semicolons (this could be enhanced for more complex cases)\n return \\array_filter(\n \\array_map('trim', \\explode(';', $query)),\n fn (string $stmt): bool => $stmt !== ''\n );\n }\n\n /**\n * Validate a single statement\n *\n * @return bool True if statement is valid read-only operation, false otherwise\n */\n private function validateSingleStatement(string $statement): bool\n {\n $isAllowed = false;\n foreach ($this->allowedPatterns as $pattern) {\n if (\\preg_match($pattern, $statement)) {\n $isAllowed = true;\n break;\n }\n }\n\n return $isAllowed;\n }\n}\n"], ["/neuron-ai/src/Providers/HandleWithTools.php", "\n */\n protected array $tools = [];\n\n public function setTools(array $tools): AIProviderInterface\n {\n $this->tools = $tools;\n return $this;\n }\n\n public function findTool(string $name): ToolInterface\n {\n foreach ($this->tools as $tool) {\n if ($tool->getName() === $name) {\n // We return a copy to allow multiple call to the same tool.\n return clone $tool;\n }\n }\n\n throw new ProviderException(\n \"It seems the model is asking for a non-existing tool: {$name}. You could try writing more verbose tool descriptions and prompts to help the model in the task.\"\n );\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/MemoryVectorStore.php", "documents[] = $document;\n }\n\n public function addDocuments(array $documents): void\n {\n $this->documents = \\array_merge($this->documents, $documents);\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n $this->documents = \\array_filter($this->documents, fn (Document $document): bool => $document->getSourceType() !== $sourceType || $document->getSourceName() !== $sourceName);\n }\n\n public function similaritySearch(array $embedding): array\n {\n $distances = [];\n\n foreach ($this->documents as $index => $document) {\n if ($document->embedding === []) {\n throw new VectorStoreException(\"Document with the following content has no embedding: {$document->getContent()}\");\n }\n $dist = VectorSimilarity::cosineDistance($embedding, $document->getEmbedding());\n $distances[$index] = $dist;\n }\n\n \\asort($distances); // Sort by distance (ascending).\n\n $topKIndices = \\array_slice(\\array_keys($distances), 0, $this->topK, true);\n\n return \\array_reduce($topKIndices, function (array $carry, int $index) use ($distances): array {\n $document = $this->documents[$index];\n $document->setScore(VectorSimilarity::similarityFromDistance($distances[$index]));\n $carry[] = $document;\n return $carry;\n }, []);\n }\n}\n"], ["/neuron-ai/src/Observability/HandleWorkflowEvents.php", "inspector->isRecording()) {\n return;\n }\n\n if ($this->inspector->needTransaction()) {\n $this->inspector->startTransaction($workflow::class)\n ->setType('neuron-workflow')\n ->addContext('List', [\n 'nodes' => \\array_keys($data->nodes),\n 'edges' => \\array_map(fn (Edge $edge): array => [\n 'from' => $edge->getFrom(),\n 'to' => $edge->getTo(),\n 'has_condition' => $edge->hasCondition(),\n ], $data->edges)\n ]);\n } elseif ($this->inspector->canAddSegments()) {\n $this->segments[$workflow::class] = $this->inspector->startSegment('neuron-workflow', $workflow::class)\n ->setColor(self::SEGMENT_COLOR);\n }\n }\n\n public function workflowEnd(\\SplSubject $workflow, string $event, WorkflowEnd $data): void\n {\n if (\\array_key_exists($workflow::class, $this->segments)) {\n $this->segments[$workflow::class]\n ->end()\n ->addContext('State', $data->state->all());\n } elseif ($this->inspector->canAddSegments()) {\n $transaction = $this->inspector->transaction();\n $transaction->addContext('State', $data->state->all());\n $transaction->setResult('success');\n }\n }\n\n public function workflowNodeStart(\\SplSubject $workflow, string $event, WorkflowNodeStart $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $segment = $this->inspector\n ->startSegment('workflow-node', $data->node)\n ->setColor(self::SEGMENT_COLOR);\n $segment->addContext('Before', $data->state->all());\n $this->segments[$data->node] = $segment;\n }\n\n public function workflowNodeEnd(\\SplSubject $workflow, string $event, WorkflowNodeEnd $data): void\n {\n if (\\array_key_exists($data->node, $this->segments)) {\n $segment = $this->segments[$data->node]->end();\n $segment->addContext('After', $data->state->all());\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/ModeTool.php", " 'Data array cannot be empty'];\n }\n\n // Filter and validate numeric values\n $numericData = \\array_filter($numbers, fn (string|int|float $value): bool => \\is_numeric($value));\n\n if ($numericData === []) {\n return ['error' => 'Data array must contain at least one numeric value'];\n }\n\n // Convert to float values\n $numericData = \\array_map('floatval', $numericData);\n\n // Count frequency of each value\n $frequencies = \\array_count_values($numericData);\n $maxFrequency = \\max($frequencies);\n\n // Find all values with maximum frequency\n $modes = \\array_keys($frequencies, $maxFrequency);\n\n // Convert back to numeric values and sort\n $modes = \\array_map('floatval', $modes);\n \\sort($modes);\n\n return $modes;\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/JinaRerankerPostProcessor.php", "client ?? $this->client = new Client([\n 'base_uri' => 'https://api.jina.ai/v1/',\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer '.$this->key,\n ],\n ]);\n }\n\n public function process(Message $question, array $documents): array\n {\n $response = $this->getClient()->post('rerank', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'query' => $question->getContent(),\n 'top_n' => $this->topN,\n 'documents' => \\array_map(fn (Document $document): array => ['text' => $document->getContent()], $documents),\n 'return_documents' => false,\n ],\n ])->getBody()->getContents();\n\n $result = \\json_decode($response, true);\n\n return \\array_map(function (array $item) use ($documents): Document {\n $document = $documents[$item['index']];\n $document->setScore($item['relevance_score']);\n return $document;\n }, $result['results']);\n }\n\n public function setClient(Client $client): PostProcessorInterface\n {\n $this->client = $client;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Tavily/TavilySearchTool.php", " 'basic',\n 'chunks_per_source' => 3,\n 'max_results' => 1,\n ];\n\n /**\n * @param string $key Tavily API key.\n * @param array $topics Explicit the topics you want to force the Agent to perform web search.\n */\n public function __construct(\n protected string $key,\n protected array $topics = [],\n ) {\n\n parent::__construct(\n 'web_search',\n 'Use this tool to search the web for additional information '.\n ($this->topics === [] ? '' : 'about '.\\implode(', ', $this->topics).', or ').\n 'if the question is outside the scope of the context you have.'\n );\n\n }\n\n protected function properties(): array\n {\n return [\n new ToolProperty(\n 'search_query',\n PropertyType::STRING,\n 'The search query to perform web search.',\n true\n ),\n new ToolProperty(\n 'topic',\n PropertyType::STRING,\n 'Explicit the topic you want to perform the web search on.',\n false,\n ['general', 'news']\n ),\n new ToolProperty(\n 'time_range',\n PropertyType::STRING,\n '',\n false,\n ['day, week, month, year']\n ),\n new ToolProperty(\n 'days',\n PropertyType::INTEGER,\n 'Filter search results for a certain range of days up to today.',\n false,\n )\n ];\n }\n\n protected function getClient(): Client\n {\n return $this->client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function __invoke(\n string $search_query,\n ?string $topic = null,\n ?string $time_range = null,\n ?int $days = null,\n ): array {\n $topic ??= 'general';\n $time_range ??= 'day';\n $days ??= 7;\n\n $result = $this->getClient()->post('search', [\n RequestOptions::JSON => \\array_merge(\n ['topic' => $topic, 'time_range' => $time_range, 'days' => $days],\n $this->options,\n [\n 'query' => $search_query,\n ]\n )\n ])->getBody()->getContents();\n\n $result = \\json_decode($result, true);\n\n return [\n 'answer' => $result['answer'],\n 'results' => \\array_map(fn (array $item): array => [\n 'title' => $item['title'],\n 'url' => $item['url'],\n 'content' => $item['content'],\n ], $result['results']),\n ];\n }\n\n public function withOptions(array $options): self\n {\n $this->options = $options;\n return $this;\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/VectorType.php", "getVectorAsString($value);\n }\n\n public function convertToDatabaseValueSQL(mixed $sqlExpression, AbstractPlatform $platform): string\n {\n return SupportedDoctrineVectorStore::fromPlatform($platform)->convertToDatabaseValueSQL($sqlExpression);\n }\n\n public function canRequireSQLConversion(): bool\n {\n return true;\n }\n\n public function getName(): string\n {\n return self::VECTOR;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/MySQL/MySQLSelectTool.php", "validateReadOnly($query)) {\n return \"The query was rejected for security reasons.\n It looks like you are trying to run a write query using the read-only query tool.\";\n }\n\n $stmt = $this->pdo->prepare($query);\n $stmt->execute();\n return $stmt->fetchAll(PDO::FETCH_ASSOC);\n }\n\n protected function validateReadOnly(string $query): bool\n {\n // Remove comments and normalize whitespace\n $cleanQuery = $this->sanitizeQuery($query);\n\n // Check if it starts with allowed statements\n $firstKeyword = $this->getFirstKeyword($cleanQuery);\n if (!\\in_array($firstKeyword, $this->allowedStatements)) {\n return false;\n }\n\n // Check for forbidden keywords that might be in subqueries\n foreach ($this->forbiddenStatements as $forbidden) {\n if (self::containsKeyword($cleanQuery, $forbidden)) {\n return false;\n }\n }\n\n return true;\n }\n\n protected function sanitizeQuery(string $query): string\n {\n // Remove SQL comments\n $query = \\preg_replace('/--.*$/m', '', $query);\n $query = \\preg_replace('/\\/\\*.*?\\*\\//s', '', (string) $query);\n\n // Normalize whitespace\n return \\preg_replace('/\\s+/', ' ', \\trim((string) $query));\n }\n\n protected function getFirstKeyword(string $query): string\n {\n if (\\preg_match('/^\\s*(\\w+)/i', $query, $matches)) {\n return \\strtoupper($matches[1]);\n }\n return '';\n }\n\n protected function containsKeyword(string $query, string $keyword): bool\n {\n // Use word boundaries to avoid false positives\n return \\preg_match('/\\b' . \\preg_quote($keyword, '/') . '\\b/i', $query) === 1;\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IsNull.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/AbstractValidationRule.php", " $value) {\n $messageTemplate = \\str_replace('{'.$key.'}', (string) $value, $messageTemplate);\n }\n\n return \\str_replace('{name}', $name, $messageTemplate);\n }\n}\n"], ["/neuron-ai/src/Observability/HandleRagEvents.php", "inspector->canAddSegments()) {\n return;\n }\n\n $id = \\md5($data->question->getContent().$data->question->getRole());\n\n $this->segments[$id] = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-retrieval', \"vector_retrieval( {$data->question->getContent()} )\")\n ->setColor(self::SEGMENT_COLOR);\n }\n\n public function ragRetrieved(AgentInterface $agent, string $event, Retrieved $data): void\n {\n $id = \\md5($data->question->getContent().$data->question->getRole());\n\n if (\\array_key_exists($id, $this->segments)) {\n $segment = $this->segments[$id];\n $segment->addContext('Data', [\n 'question' => $data->question->getContent(),\n 'documents' => \\count($data->documents)\n ]);\n $segment->end();\n }\n }\n\n public function preProcessing(AgentInterface $agent, string $event, PreProcessing $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $segment = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-preprocessing', $data->processor)\n ->setColor(self::SEGMENT_COLOR);\n\n $segment->addContext('Original', $data->original->jsonSerialize());\n\n $this->segments[$data->processor] = $segment;\n }\n\n public function preProcessed(AgentInterface $agent, string $event, PreProcessed $data): void\n {\n if (\\array_key_exists($data->processor, $this->segments)) {\n $this->segments[$data->processor]\n ->end()\n ->addContext('Processed', $data->processed->jsonSerialize());\n }\n }\n\n public function postProcessing(AgentInterface $agent, string $event, PostProcessing $data): void\n {\n if (!$this->inspector->canAddSegments()) {\n return;\n }\n\n $segment = $this->inspector\n ->startSegment(self::SEGMENT_TYPE.'-postprocessing', $data->processor)\n ->setColor(self::SEGMENT_COLOR);\n\n $segment->addContext('Question', $data->question->jsonSerialize())\n ->addContext('Documents', $data->documents);\n\n $this->segments[$data->processor] = $segment;\n }\n\n public function postProcessed(AgentInterface $agent, string $event, PostProcessed $data): void\n {\n if (\\array_key_exists($data->processor, $this->segments)) {\n $this->segments[$data->processor]\n ->end()\n ->addContext('PostProcess', $data->documents);\n }\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/DoctrineVectorStore.php", "getConnection();\n $this->doctrineVectorStoreType = SupportedDoctrineVectorStore::fromPlatform($conn->getDatabasePlatform());\n $registeredTypes = Type::getTypesMap();\n if (!\\array_key_exists(VectorType::VECTOR, $registeredTypes)) {\n Type::addType(VectorType::VECTOR, VectorType::class);\n $conn->getDatabasePlatform()->registerDoctrineTypeMapping('vector', VectorType::VECTOR);\n }\n\n $this->doctrineVectorStoreType->addCustomisationsTo($this->entityManager);\n }\n\n public function addDocument(Document $document): void\n {\n if ($document->embedding === []) {\n throw new \\RuntimeException('document embedding must be set before adding a document');\n }\n\n $this->persistDocument($document);\n $this->entityManager->flush();\n }\n\n public function addDocuments(array $documents): void\n {\n if ($documents === []) {\n return;\n }\n foreach ($documents as $document) {\n $this->persistDocument($document);\n }\n\n $this->entityManager->flush();\n }\n\n public function deleteBySource(string $sourceType, string $sourceName): void\n {\n throw new VectorStoreException(\"Delete by source not implemented in \".self::class);\n }\n\n public function similaritySearch(array $embedding): array\n {\n $repository = $this->entityManager->getRepository($this->entityClassName);\n\n $qb = $repository\n ->createQueryBuilder('e')\n ->orderBy($this->doctrineVectorStoreType->l2DistanceName().'(e.embedding, :embeddingString)', 'ASC')\n ->setParameter('embeddingString', $this->doctrineVectorStoreType->getVectorAsString($embedding))\n ->setMaxResults($this->topK);\n\n foreach ($this->filters as $key => $value) {\n $paramName = 'where_'.$key;\n $qb->andWhere(\\sprintf('e.%s = :%s', $key, $paramName))\n ->setParameter($paramName, $value);\n }\n\n /** @var DoctrineEmbeddingEntityBase[] */\n return $qb->getQuery()->getResult();\n }\n\n private function persistDocument(Document $document): void\n {\n if ($document->embedding === []) {\n throw new \\RuntimeException('Trying to save a document in a vectorStore without embedding');\n }\n\n if (!$document instanceof DoctrineEmbeddingEntityBase) {\n throw new \\RuntimeException('Document needs to be an instance of DoctrineEmbeddingEntityBase');\n }\n\n $this->entityManager->persist($document);\n }\n\n /**\n * @return iterable\n */\n public function fetchDocumentsByChunkRange(string $sourceType, string $sourceName, int $leftIndex, int $rightIndex): iterable\n {\n $repository = $this->entityManager->getRepository($this->entityClassName);\n\n $query = $repository->createQueryBuilder('d')\n ->andWhere('d.sourceType = :sourceType')\n ->andWhere('d.sourceName = :sourceName')\n ->andWhere('d.chunkNumber >= :lower')\n ->andWhere('d.chunkNumber <= :upper')\n ->setParameter('sourceType', $sourceType)\n ->setParameter('sourceName', $sourceName)\n ->setParameter('lower', $leftIndex)\n ->setParameter('upper', $rightIndex)\n ->getQuery();\n\n return $query->toIterable();\n }\n\n public function withFilters(array $filters): VectorStoreInterface\n {\n $this->filters = $filters;\n return $this;\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IsTrue.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IsFalse.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IsNotNull.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Url.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/Email.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/IPAddress.php", "buildMessage($name, $this->message);\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Tavily/TavilyExtractTool.php", "getClient()->post('extract', [\n RequestOptions::JSON => \\array_merge(\n $this->options,\n ['urls' => [$url]]\n )\n ])->getBody()->getContents();\n\n $result = \\json_decode($result, true);\n\n return $result['results'][0];\n }\n\n\n protected function getClient(): Client\n {\n return $this->client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function withOptions(array $options): self\n {\n $this->options = $options;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Workflow/Persistence/FilePersistence.php", "directory)) {\n throw new WorkflowException(\"Directory '{$this->directory}' does not exist\");\n }\n }\n\n public function save(string $workflowId, WorkflowInterrupt $interrupt): void\n {\n \\file_put_contents($this->getFilePath($workflowId), \\json_encode($interrupt));\n }\n\n public function load(string $workflowId): WorkflowInterrupt\n {\n if (!\\is_file($this->getFilePath($workflowId))) {\n throw new WorkflowException(\"No saved workflow found for ID: {$workflowId}.\");\n }\n\n $interrupt = \\json_decode(\\file_get_contents($this->getFilePath($workflowId)), true) ?? [];\n\n return new WorkflowInterrupt(\n $interrupt['data'],\n $interrupt['currentNode'],\n new WorkflowState($interrupt['state'])\n );\n }\n\n public function delete(string $workflowId): void\n {\n if (\\file_exists($this->getFilePath($workflowId))) {\n \\unlink($this->getFilePath($workflowId));\n }\n }\n\n protected function getFilePath(string $workflowId): string\n {\n return $this->directory.\\DIRECTORY_SEPARATOR.$this->prefix.$workflowId.$this->ext;\n }\n}\n"], ["/neuron-ai/src/Observability/Observable.php", "\n */\n private array $observers = [];\n\n\n private function initEventGroup(string $event = '*'): void\n {\n /*\n * If developers attach an observer, the agent monitoring will not be attached by default.\n */\n if (!isset($this->observers['*']) && !empty($_ENV['INSPECTOR_INGESTION_KEY'])) {\n $this->observers['*'] = [\n AgentMonitoring::instance(),\n ];\n }\n\n if (!isset($this->observers[$event])) {\n $this->observers[$event] = [];\n }\n }\n\n private function getEventObservers(string $event = \"*\"): array\n {\n $this->initEventGroup($event);\n $group = $this->observers[$event];\n $all = $this->observers[\"*\"] ?? [];\n\n return \\array_merge($group, $all);\n }\n\n public function observe(SplObserver $observer, string $event = \"*\"): self\n {\n $this->attach($observer, $event);\n return $this;\n }\n\n public function attach(SplObserver $observer, string $event = \"*\"): void\n {\n $this->initEventGroup($event);\n $this->observers[$event][] = $observer;\n }\n\n public function detach(SplObserver $observer, string $event = \"*\"): void\n {\n foreach ($this->getEventObservers($event) as $key => $s) {\n if ($s === $observer) {\n unset($this->observers[$event][$key]);\n }\n }\n }\n\n public function notify(string $event = \"*\", mixed $data = null): void\n {\n // Broadcasting the '$event' event\";\n foreach ($this->getEventObservers($event) as $observer) {\n $observer->update($this, $event, $data);\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Tavily/TavilyCrawlTool.php", " false,\n 'allow_external' => false\n ];\n\n /**\n * @param string $key Tavily API key.\n */\n public function __construct(\n protected string $key,\n ) {\n parent::__construct(\n 'url_crawl',\n 'Get the entire website in markdown format.'\n );\n }\n\n protected function properties(): array\n {\n return [\n new ToolProperty(\n 'url',\n PropertyType::STRING,\n 'The URL to crawl.',\n true\n ),\n ];\n }\n\n public function __invoke(string $url): array\n {\n if (!\\filter_var($url, \\FILTER_VALIDATE_URL)) {\n throw new ToolException('Invalid URL.');\n }\n\n $result = $this->getClient()->post('crawl', [\n RequestOptions::JSON => \\array_merge(\n $this->options,\n ['url' => $url]\n )\n ])->getBody()->getContents();\n\n return \\json_decode($result, true);\n }\n\n\n protected function getClient(): Client\n {\n return $this->client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function withOptions(array $options): self\n {\n $this->options = $options;\n return $this;\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/GeminiEmbeddingsProvider.php", "client = new Client([\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'x-goog-api-key' => $this->key,\n ]\n ]);\n }\n\n public function embedText(string $text): array\n {\n $response = $this->client->post(\\trim($this->baseUri, '/').\"/{$this->model}:embedContent\", [\n RequestOptions::JSON => [\n 'content' => [\n 'parts' => [['text' => $text]]\n ],\n ...($this->config !== [] ? ['embedding_config' => $this->config] : []),\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['embedding']['values'];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/DivideTool.php", " $this->name,\n 'error' => 'Division by zero is not allowed.'\n ];\n }\n\n return $number1 / $number2;\n }\n}\n"], ["/neuron-ai/src/RAG/Document.php", "id = \\uniqid();\n }\n\n public function getId(): string|int\n {\n return $this->id;\n }\n\n public function getContent(): string\n {\n return $this->content;\n }\n\n public function getEmbedding(): array\n {\n return $this->embedding;\n }\n\n public function getSourceType(): string\n {\n return $this->sourceType;\n }\n\n public function getSourceName(): string\n {\n return $this->sourceName;\n }\n\n public function getScore(): float\n {\n return $this->score;\n }\n\n public function setScore(float $score): Document\n {\n $this->score = $score;\n return $this;\n }\n\n public function addMetadata(string $key, string|int $value): Document\n {\n $this->metadata[$key] = $value;\n return $this;\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'id' => $this->getId(),\n 'content' => $this->getContent(),\n 'embedding' => $this->getEmbedding(),\n 'sourceType' => $this->getSourceType(),\n 'sourceName' => $this->getSourceName(),\n 'score' => $this->getScore(),\n 'metadata' => $this->metadata,\n ];\n }\n}\n"], ["/neuron-ai/src/RAG/PreProcessor/QueryTransformationPreProcessor.php", "prepareMessage($question);\n\n return $this->provider\n ->systemPrompt($this->getSystemPrompt())\n ->chat([$preparedMessage]);\n }\n\n public function getSystemPrompt(): string\n {\n return $this->customPrompt ?? match ($this->transformation) {\n QueryTransformationType::REWRITING => $this->getRewritingPrompt(),\n QueryTransformationType::DECOMPOSITION => $this->getDecompositionPrompt(),\n QueryTransformationType::HYDE => $this->getHydePrompt(),\n };\n }\n\n public function setCustomPrompt(string $prompt): self\n {\n $this->customPrompt = $prompt;\n return $this;\n }\n\n public function setTransformation(QueryTransformationType $transformation): self\n {\n $this->transformation = $transformation;\n return $this;\n }\n\n public function setProvider(AIProviderInterface $provider): self\n {\n $this->provider = $provider;\n return $this;\n }\n\n protected function prepareMessage(Message $question): UserMessage\n {\n return new UserMessage('' . $question->getContent() . '');\n }\n\n protected function getRewritingPrompt(): string\n {\n return (string) new SystemPrompt(\n background: [\n 'You are an AI assistant tasked with reformulating user queries to improve retrieval in a RAG system.'\n ],\n steps: [\n 'Given the original query, rewrite it to be more specific, detailed, and likely to retrieve relevant information.',\n 'Focus on expanding vocabulary and technical terminology while preserving the original intent and meaning.',\n ],\n output: [\n 'Output only the reformulated query',\n 'Do not add temporal references, dates, or years unless they are present in the original query'\n ]\n );\n }\n\n protected function getDecompositionPrompt(): string\n {\n return (string) new SystemPrompt(\n background: [\n 'You are an AI assistant that breaks down complex queries into simpler sub-queries for comprehensive information retrieval in a RAG system.'\n ],\n steps: [\n 'Given the original complex query, decompose it into focused sub-queries.',\n 'Each sub-query should address a specific aspect of the original question.',\n 'Ensure all sub-queries together cover the full scope of the original query.',\n ],\n output: [\n 'Output each sub-query on a separate line',\n 'Use clear, specific language for each sub-query',\n 'Do not add temporal references, dates, or years unless they are present in the original query',\n ]\n );\n }\n\n protected function getHydePrompt(): string\n {\n return (string) new SystemPrompt(\n background: [\n 'You are an AI assistant that generates hypothetical answer to the user query, to improve retrieval in a RAG system.'\n ],\n steps: [\n 'Given the original query, write a hypothetical document passage that would directly answer this question.',\n 'Create content that resembles what you would expect to find in a relevant document.',\n ],\n output: [\n 'Output only the hypothetical document passage',\n 'Do not add temporal references, dates, or years unless they are present in the original query',\n 'Keep the response as concise as possible'\n ]\n );\n }\n}\n"], ["/neuron-ai/src/Providers/OpenAI/HandleStructured.php", "parameters = \\array_merge($this->parameters, [\n 'response_format' => [\n 'type' => 'json_schema',\n 'json_schema' => [\n \"name\" => \\end($tk),\n \"strict\" => false,\n \"schema\" => $response_format,\n ],\n ]\n ]);\n\n return $this->chat($messages);\n }\n}\n"], ["/neuron-ai/src/SystemPrompt.php", "background);\n\n if ($this->steps !== []) {\n $prompt .= \\PHP_EOL . \\PHP_EOL . \"# INTERNAL ASSISTANT STEPS\" . \\PHP_EOL . \\implode(\\PHP_EOL, $this->steps);\n }\n\n if ($this->output !== []) {\n $prompt .= \\PHP_EOL . \\PHP_EOL . \"# OUTPUT INSTRUCTIONS\" . \\PHP_EOL . \" - \" . \\implode(\\PHP_EOL . \" - \", $this->output);\n }\n\n if ($this->toolsUsage !== []) {\n $prompt .= \\PHP_EOL . \\PHP_EOL . \"# TOOLS USAGE RULES\" . \\PHP_EOL . \" - \" . \\implode(\\PHP_EOL . \" - \", $this->toolsUsage);\n }\n\n return $prompt;\n }\n}\n"], ["/neuron-ai/src/RAG/PostProcessor/FixedThresholdPostProcessor.php", " $document->getScore() >= $this->threshold));\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/OpenAIEmbeddingsProvider.php", "client = new Client([\n 'base_uri' => $this->baseUri,\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Authorization' => 'Bearer ' . $this->key,\n ]\n ]);\n }\n\n public function embedText(string $text): array\n {\n $response = $this->client->post('', [\n 'json' => [\n 'model' => $this->model,\n 'input' => $text,\n 'encoding_format' => 'float',\n 'dimensions' => $this->dimensions,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['data'][0]['embedding'];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Riza/RizaCodeInterpreter.php", "client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json; charset=utf-8',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function __invoke(\n string $code,\n array $args = [],\n array $env = [],\n ): mixed {\n $result = $this->getClient()->post('execute', [\n RequestOptions::JSON => [\n 'language' => $this->language,\n 'code' => $code,\n 'args' => $args,\n 'env' => $env,\n ]\n ])->getBody()->getContents();\n\n return \\json_decode($result, true);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Riza/RizaFunctionExecutor.php", "client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json; charset=utf-8',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n public function __invoke(\n string $code,\n array $input = [],\n array $env = [],\n ): mixed {\n $result = $this->getClient()->post('execute-function', [\n RequestOptions::JSON => [\n 'language' => $this->language,\n 'code' => $code,\n 'input' => $input,\n 'env' => $env,\n ]\n ])->getBody()->getContents();\n\n return \\json_decode($result, true);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/NthRootTool.php", "client = new Client(['base_uri' => \\trim($this->url, '/').'/']);\n }\n\n public function embedText(string $text): array\n {\n $response = $this->client->post('embed', [\n RequestOptions::JSON => [\n 'model' => $this->model,\n 'input' => $text,\n ...$this->parameters,\n ]\n ])->getBody()->getContents();\n\n $response = \\json_decode($response, true);\n\n return $response['embeddings'][0];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Jina/JinaUrlReader.php", "client ?? $this->client = new Client([\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n 'X-Return-Format' => 'Markdown',\n ]\n ]);\n }\n\n public function __invoke(string $url): string\n {\n if (!\\filter_var($url, \\FILTER_VALIDATE_URL)) {\n throw new ToolException('Invalid URL.');\n }\n\n return $this->getClient()->post('https://r.jina.ai/', [\n RequestOptions::JSON => [\n 'url' => $url,\n ]\n ])->getBody()->getContents();\n }\n}\n"], ["/neuron-ai/src/Providers/Deepseek/Deepseek.php", "parameters = \\array_merge($this->parameters, [\n 'response_format' => [\n 'type' => 'json_object',\n ]\n ]);\n\n $this->system .= \\PHP_EOL.\"# OUTPUT FORMAT CONSTRAINTS\".\\PHP_EOL\n .'Generate a json respecting this schema: '.\\json_encode($response_format);\n\n return $this->chat($messages);\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Zep/HandleZepClient.php", "client ?? $this->client = new Client([\n 'base_uri' => \\trim($this->url, '/').'/',\n 'headers' => [\n 'Authorization' => \"Api-Key {$this->key}\",\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ]\n ]);\n }\n\n protected function createUser(): self\n {\n // Create the user if it doesn't exist\n try {\n $this->getClient()->get('users/'.$this->user_id);\n } catch (\\Exception) {\n $this->getClient()->post('users', [\n RequestOptions::JSON => ['user_id' => $this->user_id]\n ]);\n }\n\n return $this;\n }\n}\n"], ["/neuron-ai/src/RAG/Embeddings/AbstractEmbeddingsProvider.php", " $document) {\n $documents[$index] = $this->embedDocument($document);\n }\n\n return $documents;\n }\n\n public function embedDocument(Document $document): Document\n {\n $text = $document->formattedContent ?? $document->content;\n $document->embedding = $this->embedText($text);\n\n return $document;\n }\n}\n"], ["/neuron-ai/src/Tools/ToolProperty.php", " $this->name,\n 'description' => $this->description,\n 'type' => $this->type->value,\n 'enum' => $this->enum,\n 'required' => $this->required,\n ];\n }\n\n public function isRequired(): bool\n {\n return $this->required;\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n public function getType(): PropertyType\n {\n return $this->type;\n }\n\n public function getDescription(): ?string\n {\n return $this->description;\n }\n\n public function getEnum(): array\n {\n return $this->enum;\n }\n\n public function getJsonSchema(): array\n {\n $schema = [\n 'type' => $this->type->value,\n ];\n\n if (!\\is_null($this->description)) {\n $schema['description'] = $this->description;\n }\n\n if ($this->enum !== []) {\n $schema['enum'] = $this->enum;\n }\n\n return $schema;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Jina/JinaWebSearch.php", "client ?? $this->client = new Client([\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Content-Type' => 'application/json',\n 'X-Respond-With' => 'no-content',\n ]\n ]);\n }\n\n public function __invoke(string $search_query): string\n {\n return $this->getClient()->post('https://s.jina.ai/', [\n RequestOptions::JSON => [\n 'q' => $search_query,\n ]\n ])->getBody()->getContents();\n }\n}\n"], ["/neuron-ai/src/Workflow/Exporter/MermaidExporter.php", "getEdges() as $edge) {\n $from = $this->getShortClassName($edge->getFrom());\n $to = $this->getShortClassName($edge->getTo());\n\n $output .= \" {$from} --> {$to}\\n\";\n }\n\n return $output;\n }\n\n private function getShortClassName(string $class): string\n {\n $reflection = new ReflectionClass($class);\n return $reflection->getShortName();\n }\n}\n"], ["/neuron-ai/src/RAG/Splitter/AbstractSplitter.php", "splitDocument($document));\n }\n\n return $split;\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/EqualTo.php", "reference) {\n $violations[] = $this->buildMessage($name, 'must be equal to {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/Chat/History/ChatHistoryInterface.php", "\n */\n public function getMessages(): array;\n\n public function getLastMessage(): Message|false;\n\n public function setMessages(array $messages): ChatHistoryInterface;\n\n public function flushAll(): ChatHistoryInterface;\n\n public function calculateTotalUsage(): int;\n}\n"], ["/neuron-ai/src/AgentInterface.php", " $this->type->value,\n 'content' => $this->content,\n 'content_type' => $this->contentType->value,\n 'media_type' => $this->mediaType,\n ]);\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/GreaterThan.php", "reference) || $value <= $this->reference) {\n $violations[] = $this->buildMessage($name, 'must be greater than {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/MySQL/MySQLWriteTool.php", "pdo->prepare($query)->execute();\n\n return $result\n ? \"The query has been executed successfully.\"\n : \"I'm sorry, there was an error executing the query.\";\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/GreaterThanEqual.php", "reference) || $value < $this->reference) {\n $violations[] = $this->buildMessage($name, 'must be greater than {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/PGSQL/PGSQLWriteTool.php", "pdo->prepare($query)->execute();\n\n return $result\n ? \"The query has been executed successfully.\"\n : \"I'm sorry, there was an error executing the query.\";\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/LowerThan.php", "= $this->reference) {\n $violations[] = $this->buildMessage($name, 'must be greater than {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/LowerThanEqual.php", " $this->reference) {\n $violations[] = $this->buildMessage($name, 'must be greater than {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/StructuredOutput/Validation/Rules/NotEqualTo.php", "reference) {\n $violations[] = $this->buildMessage($name, 'must not be equal to {compare}', ['compare' => \\get_debug_type($this->reference)]);\n }\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/SupportedDoctrineVectorStore.php", "inputTokens + $this->outputTokens;\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'input_tokens' => $this->inputTokens,\n 'output_tokens' => $this->outputTokens,\n ];\n }\n}\n"], ["/neuron-ai/src/Providers/HuggingFace/HuggingFace.php", "buildBaseUri();\n parent::__construct($key, $model, $parameters);\n }\n\n private function buildBaseUri(): void\n {\n $endpoint = match ($this->inferenceProvider) {\n InferenceProvider::HF_INFERENCE => \\trim($this->inferenceProvider->value, \\DIRECTORY_SEPARATOR).\\DIRECTORY_SEPARATOR.$this->model,\n default => \\trim($this->inferenceProvider->value, \\DIRECTORY_SEPARATOR),\n };\n\n $this->baseUri = \\sprintf($this->baseUri, $endpoint);\n }\n\n}\n"], ["/neuron-ai/src/Providers/Anthropic/HandleStructured.php", "system .= \\PHP_EOL.\"# OUTPUT CONSTRAINTS\".\\PHP_EOL.\n \"Your response should be a JSON string following this schema: \".\\PHP_EOL.\n \\json_encode($response_format);\n\n return $this->chat($messages);\n }\n}\n"], ["/neuron-ai/src/Chat/History/InMemoryChatHistory.php", "setBaseUrl();\n\n $this->client = new Client([\n 'base_uri' => $this->baseUri,\n 'query' => [\n 'api-version' => $this->version,\n ],\n 'headers' => [\n 'Authorization' => 'Bearer '.$this->key,\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n ],\n ]);\n }\n\n private function setBaseUrl(): void\n {\n $this->endpoint = \\preg_replace('/^https?:\\/\\/([^\\/]*)\\/?$/', '$1', $this->endpoint);\n $this->baseUri = \\sprintf($this->baseUri, $this->endpoint, $this->model);\n $this->baseUri = \\trim($this->baseUri, '/').'/';\n }\n}\n"], ["/neuron-ai/src/Workflow/WorkflowContext.php", "isResuming && isset($this->feedback[$this->currentNode])) {\n return $this->feedback[$this->currentNode];\n }\n\n throw new WorkflowInterrupt($data, $this->currentNode, $this->currentState);\n }\n\n public function setResuming(bool $resuming, array $feedback = []): void\n {\n $this->isResuming = $resuming;\n $this->feedback = $feedback;\n }\n\n public function setCurrentState(WorkflowState $state): WorkflowContext\n {\n $this->currentState = $state;\n return $this;\n }\n\n public function setCurrentNode(string $node): WorkflowContext\n {\n $this->currentNode = $node;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Agent.php", "instructions = $instructions;\n return $this;\n }\n\n public function instructions(): string\n {\n return 'Your are a helpful and friendly AI agent built with NeuronAI PHP framework.';\n }\n\n public function resolveInstructions(): string\n {\n return $this->instructions ?? $this->instructions();\n }\n\n protected function removeDelimitedContent(string $text, string $openTag, string $closeTag): string\n {\n // Escape special regex characters in the tags\n $escapedOpenTag = \\preg_quote($openTag, '/');\n $escapedCloseTag = \\preg_quote($closeTag, '/');\n\n // Create the regex pattern to match content between tags\n $pattern = '/' . $escapedOpenTag . '.*?' . $escapedCloseTag . '/s';\n\n // Remove all occurrences of the delimited content\n return \\preg_replace($pattern, '', $text);\n }\n}\n"], ["/neuron-ai/src/RAG/DataLoader/AbstractDataLoader.php", "splitter = new DelimiterTextSplitter(\n maxLength: 1000,\n separator: '.',\n wordOverlap: 0\n );\n }\n\n public static function for(...$arguments): static\n {\n /** @phpstan-ignore new.static */\n return new static(...$arguments);\n }\n\n public function withSplitter(SplitterInterface $splitter): DataLoaderInterface\n {\n $this->splitter = $splitter;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Providers/Ollama/HandleStructured.php", "parameters = \\array_merge($this->parameters, [\n 'format' => $response_format,\n ]);\n\n return $this->chat($messages);\n }\n}\n"], ["/neuron-ai/src/Chat/Messages/UserMessage.php", "id;\n }\n}\n"], ["/neuron-ai/src/Workflow/Edge.php", "from;\n }\n\n public function getTo(): string\n {\n return $this->to;\n }\n\n public function hasCondition(): bool\n {\n return $this->condition instanceof \\Closure;\n }\n\n public function shouldExecute(WorkflowState $state): bool\n {\n return $this->hasCondition() ? ($this->condition)($state) : true;\n }\n}\n"], ["/neuron-ai/src/RAG/ResolveVectorStore.php", "store = $store;\n return $this;\n }\n\n protected function vectorStore(): VectorStoreInterface\n {\n return $this->store;\n }\n\n public function resolveVectorStore(): VectorStoreInterface\n {\n if (!isset($this->store)) {\n $this->store = $this->vectorStore();\n }\n return $this->store;\n }\n}\n"], ["/neuron-ai/src/Workflow/Node.php", "context = $context;\n }\n\n protected function interrupt(array $data): mixed\n {\n if (!isset($this->context)) {\n throw new WorkflowException('WorkflowContext not set on node');\n }\n\n return $this->context->interrupt($data);\n }\n}\n"], ["/neuron-ai/src/Chat/History/TokenCounterInterface.php", "match(\\Doctrine\\ORM\\Query\\TokenType::T_IDENTIFIER);\n $parser->match(\\Doctrine\\ORM\\Query\\TokenType::T_OPEN_PARENTHESIS);\n } else {\n $parser->match(\\Doctrine\\ORM\\Query\\Lexer::T_IDENTIFIER);\n $parser->match(\\Doctrine\\ORM\\Query\\Lexer::T_OPEN_PARENTHESIS);\n }\n\n $this->vectorOne = $parser->ArithmeticFactor(); // Fix that, should be vector\n\n if (\\class_exists(\\Doctrine\\ORM\\Query\\TokenType::class)) {\n $parser->match(\\Doctrine\\ORM\\Query\\TokenType::T_COMMA);\n } else {\n $parser->match(\\Doctrine\\ORM\\Query\\Lexer::T_COMMA);\n }\n\n $this->vectorTwo = $parser->ArithmeticFactor(); // Fix that, should be vector\n\n if (\\class_exists(\\Doctrine\\ORM\\Query\\TokenType::class)) {\n $parser->match(\\Doctrine\\ORM\\Query\\TokenType::T_CLOSE_PARENTHESIS);\n } else {\n $parser->match(\\Doctrine\\ORM\\Query\\Lexer::T_CLOSE_PARENTHESIS);\n }\n }\n}\n"], ["/neuron-ai/src/ResolveProvider.php", "provider = $provider;\n return $this;\n }\n\n public function setAiProvider(AIProviderInterface $provider): AgentInterface\n {\n $this->provider = $provider;\n return $this;\n }\n\n protected function provider(): AIProviderInterface\n {\n return $this->provider;\n }\n\n /**\n * Get the current instance of the chat history.\n */\n public function resolveProvider(): AIProviderInterface\n {\n if (!isset($this->provider)) {\n $this->provider = $this->provider();\n }\n\n return $this->provider;\n }\n}\n"], ["/neuron-ai/src/Providers/AIProviderInterface.php", "embeddingsProvider = $provider;\n return $this;\n }\n\n protected function embeddings(): EmbeddingsProviderInterface\n {\n return $this->embeddingsProvider;\n }\n\n public function resolveEmbeddingsProvider(): EmbeddingsProviderInterface\n {\n if (!isset($this->embeddingsProvider)) {\n $this->embeddingsProvider = $this->embeddings();\n }\n return $this->embeddingsProvider;\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Calculator/SumTool.php", "data[$key] = $value;\n }\n\n public function get(string $key, mixed $default = null): mixed\n {\n return $this->data[$key] ?? $default;\n }\n\n public function has(string $key): bool\n {\n return \\array_key_exists($key, $this->data);\n }\n\n /**\n * Missing keys in the state are simply ignored.\n *\n * @param string[] $keys\n */\n public function only(array $keys): array\n {\n return \\array_intersect_key($this->data, \\array_flip($keys));\n }\n\n public function all(): array\n {\n return $this->data;\n }\n}\n"], ["/neuron-ai/src/Observability/Events/InferenceStop.php", "splitter->splitDocument(new Document($this->content));\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Zep/ZepLongTermMemoryToolkit.php", "key, $this->user_id),\n ZepAddToGraphTool::make($this->key, $this->user_id),\n ];\n }\n}\n"], ["/neuron-ai/src/Workflow/WorkflowInterrupt.php", "data;\n }\n\n public function getCurrentNode(): string\n {\n return $this->currentNode;\n }\n\n public function getState(): WorkflowState\n {\n return $this->state;\n }\n\n public function jsonSerialize(): array\n {\n return [\n 'data' => $this->data,\n 'currentNode' => $this->currentNode,\n 'state' => $this->state->all(),\n ];\n }\n}\n"], ["/neuron-ai/src/Observability/Events/MessageSaving.php", "\n */\n public function provide(): array\n {\n return [\n new TavilyExtractTool($this->key),\n new TavilySearchTool($this->key),\n new TavilyCrawlTool($this->key)\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/MySQL/MySQLToolkit.php", "pdo),\n MySQLSelectTool::make($this->pdo),\n MySQLWriteTool::make($this->pdo),\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/PGSQL/PGSQLToolkit.php", "pdo),\n PGSQLSelectTool::make($this->pdo),\n PGSQLWriteTool::make($this->pdo),\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Riza/RizaToolkit.php", "\n */\n public function provide(): array\n {\n return [\n new RizaCodeInterpreter($this->key),\n new RizaFunctionExecutor($this->key),\n ];\n }\n}\n"], ["/neuron-ai/src/Tools/Toolkits/Jina/JinaToolkit.php", "\n */\n public function provide(): array\n {\n return [\n new JinaWebSearch($this->key),\n new JinaUrlReader($this->key),\n ];\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/MariaDBVectorStoreType.php", "stringListOf($vector).']';\n }\n\n public function convertToDatabaseValueSQL(string $sqlExpression): string\n {\n return \\sprintf('Vec_FromText(%s)', $sqlExpression);\n }\n\n public function addCustomisationsTo(EntityManagerInterface $entityManager): void\n {\n $entityManager->getConfiguration()->addCustomStringFunction($this->l2DistanceName(), MariaDBVectorL2OperatorDql::class);\n }\n\n public function l2DistanceName(): string\n {\n return 'VEC_DISTANCE_EUCLIDEAN';\n }\n}\n"], ["/neuron-ai/src/Chat/Attachments/Document.php", "stringListOf($vector).']';\n }\n\n public function convertToDatabaseValueSQL(string $sqlExpression): string\n {\n return $sqlExpression;\n }\n\n public function addCustomisationsTo(EntityManagerInterface $entityManager): void\n {\n $entityManager->getConfiguration()->addCustomStringFunction($this->l2DistanceName(), PostgresqlVectorL2OperatorDql::class);\n }\n\n public function l2DistanceName(): string\n {\n return 'VEC_DISTANCE_EUCLIDEAN';\n }\n}\n"], ["/neuron-ai/src/Workflow/Persistence/InMemoryPersistence.php", "storage[$workflowId] = $interrupt;\n }\n\n public function load(string $workflowId): WorkflowInterrupt\n {\n return $this->storage[$workflowId] ?? throw new WorkflowException(\"No saved workflow found for ID: {$workflowId}\");\n }\n\n public function delete(string $workflowId): void\n {\n unset($this->storage[$workflowId]);\n }\n}\n"], ["/neuron-ai/src/Observability/Events/ToolCalled.php", "\n */\n public function getRequiredProperties(): array;\n\n /**\n * Define the code to be executed.\n */\n public function setCallable(callable $callback): ToolInterface;\n\n /**\n * Get the input arguments of the function call.\n */\n public function getInputs(): array;\n\n /**\n * Get the input arguments of the function call.\n */\n public function setInputs(array $inputs): ToolInterface;\n\n /**\n * The call identifier generated by the LLM.\n * @return string\n */\n public function getCallId(): ?string;\n\n\n public function setCallId(string $callId): ToolInterface;\n\n\n public function getResult(): string;\n\n /**\n * Execute the tool's logic with input parameters.\n */\n public function execute(): void;\n}\n"], ["/neuron-ai/src/Tools/Toolkits/ToolkitInterface.php", "vectorOne->dispatch($sqlWalker).', '.\n 'VEC_FROMTEXT('.\n $this->vectorTwo->dispatch($sqlWalker).\n ')'.\n ')';\n }\n}\n"], ["/neuron-ai/src/RAG/VectorStore/Doctrine/PostgresqlVectorL2OperatorDql.php", "vectorOne->dispatch($sqlWalker).', '.\n $this->vectorTwo->dispatch($sqlWalker).\n ')';\n }\n}\n"], ["/neuron-ai/src/Observability/Events/ToolsBootstrapped.php", "client = $client;\n return $this;\n }\n}\n"], ["/neuron-ai/src/Providers/MessageMapperInterface.php", " $messages\n */\n public function map(array $messages): array;\n}\n"], ["/neuron-ai/src/Observability/Events/Retrieved.php", " $violations\n */\n public function __construct(\n public string $class,\n public string $json,\n public array $violations = []\n ) {\n }\n}\n"], ["/neuron-ai/src/Observability/Events/PreProcessed.php", "withPaths([\n __DIR__ . '/src',\n __DIR__ . '/tests',\n ])\n ->withPhpSets(php81: true)\n ->withPreparedSets(\n codeQuality: true,\n deadCode: true,\n typeDeclarations: true,\n earlyReturn: true,\n strictBooleans: true,\n )\n ->withRules([\n AddReturnTypeDeclarationRector::class\n ]);\n"], ["/neuron-ai/src/RAG/DataLoader/DataLoaderInterface.php", "result;\n } elseif ($message instanceof ToolCallMessage) {\n $content = $message->toolCall->arguments;\n } else {\n continue;\n }\n \n $total += strlen((string) $content) / $this->charsPerToken;\n }\n \n $total += count($messages) * $this->extraTokensPerMessage;\n \n return (int) round($total);\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 21-28-12"}, "editdistance_info": {"edit_distance": 23.7288, "calculate_time": "2025-08-20 21:28:12", "true_code_clean": "public function count(array $messages): int\n {\n $tokenCount = 0.0;\n foreach ($messages as $message) {\n $messageChars = 0;\n $content = $message->getContent();\n if (\\is_string($content)) {\n $messageChars += \\strlen($content);\n } elseif ($content !== null) {\n $messageChars += \\strlen(\\json_encode($content));\n }\n if ($message instanceof ToolCallMessage && !\\is_array($content)) {\n $tools = $message->getTools();\n if ($tools !== []) {\n $toolsContent = \\json_encode(\\array_map(fn (ToolInterface $tool): array => $tool->jsonSerialize(), $tools));\n $messageChars += \\strlen($toolsContent);\n }\n }\n if ($message instanceof ToolCallResultMessage) {\n $tools = $message->getTools();\n foreach ($tools as $tool) {\n $serialized = $tool->jsonSerialize();\n if (isset($serialized['id'])) {\n $messageChars += \\strlen($serialized['id']);\n }\n }\n }\n $messageChars += \\strlen($message->getRole());\n $tokenCount += \\ceil($messageChars / $this->charsPerToken);\n $tokenCount += $this->extraTokensPerMessage;\n }\n return (int) \\ceil($tokenCount);\n }", "predict_code_clean": "public function count(array $messages): int\n{\n $total = 0;\n foreach ($messages as $message) {\n if ($message instanceof ToolCallResultMessage) {\n $content = $message->result;\n } elseif ($message instanceof ToolCallMessage) {\n $content = $message->toolCall->arguments;\n } else {\n continue;\n }\n $total += strlen((string) $content) / $this->charsPerToken;\n }\n $total += count($messages) * $this->extraTokensPerMessage;\n return (int) round($total);\n}"}}