{"repo_name": "ai", "file_name": "/ai/src/platform/src/Contract/JsonSchema/Attribute/With.php", "inference_info": {"prefix_code": "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\JsonSchema\\Attribute;\n\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\n\n/**\n * @author Oskar Stark \n */\n#[\\Attribute(\\Attribute::TARGET_PARAMETER)]\nfinal readonly class With\n{\n /**\n * @param list|null $enum\n * @param string|int|string[]|null $const\n */\n ", "suffix_code": "\n}\n", "middle_code": "public function __construct(\n public ?array $enum = null,\n public string|int|array|null $const = null,\n public ?string $pattern = null,\n public ?int $minLength = null,\n public ?int $maxLength = null,\n public ?int $minimum = null,\n public ?int $maximum = null,\n public ?int $multipleOf = null,\n public ?int $exclusiveMinimum = null,\n public ?int $exclusiveMaximum = null,\n public ?int $minItems = null,\n public ?int $maxItems = null,\n public ?bool $uniqueItems = null,\n public ?int $minContains = null,\n public ?int $maxContains = null,\n public ?bool $required = null,\n public ?int $minProperties = null,\n public ?int $maxProperties = null,\n public ?bool $dependentRequired = null,\n ) {\n if (\\is_array($enum)) {\n array_filter($enum, fn ($item) => \\is_string($item)) === $enum || throw new InvalidArgumentException('All enum values must be strings.');\n }\n if (\\is_string($const)) {\n '' !== trim($const) || throw new InvalidArgumentException('Const string must not be empty.');\n }\n if (\\is_string($pattern)) {\n '' !== trim($pattern) || throw new InvalidArgumentException('Pattern string must not be empty.');\n }\n if (\\is_int($minLength)) {\n $minLength >= 0 || throw new InvalidArgumentException('MinLength must be greater than or equal to 0.');\n if (\\is_int($maxLength)) {\n $maxLength >= $minLength || throw new InvalidArgumentException('MaxLength must be greater than or equal to minLength.');\n }\n }\n if (\\is_int($maxLength)) {\n $maxLength >= 0 || throw new InvalidArgumentException('MaxLength must be greater than or equal to 0.');\n }\n if (\\is_int($minimum)) {\n $minimum >= 0 || throw new InvalidArgumentException('Minimum must be greater than or equal to 0.');\n if (\\is_int($maximum)) {\n $maximum >= $minimum || throw new InvalidArgumentException('Maximum must be greater than or equal to minimum.');\n }\n }\n if (\\is_int($maximum)) {\n $maximum >= 0 || throw new InvalidArgumentException('Maximum must be greater than or equal to 0.');\n }\n if (\\is_int($multipleOf)) {\n $multipleOf >= 0 || throw new InvalidArgumentException('MultipleOf must be greater than or equal to 0.');\n }\n if (\\is_int($exclusiveMinimum)) {\n $exclusiveMinimum >= 0 || throw new InvalidArgumentException('ExclusiveMinimum must be greater than or equal to 0.');\n if (\\is_int($exclusiveMaximum)) {\n $exclusiveMaximum >= $exclusiveMinimum || throw new InvalidArgumentException('ExclusiveMaximum must be greater than or equal to exclusiveMinimum.');\n }\n }\n if (\\is_int($exclusiveMaximum)) {\n $exclusiveMaximum >= 0 || throw new InvalidArgumentException('ExclusiveMaximum must be greater than or equal to 0.');\n }\n if (\\is_int($minItems)) {\n $minItems >= 0 || throw new InvalidArgumentException('MinItems must be greater than or equal to 0.');\n if (\\is_int($maxItems)) {\n $maxItems >= $minItems || throw new InvalidArgumentException('MaxItems must be greater than or equal to minItems.');\n }\n }\n if (\\is_int($maxItems)) {\n $maxItems >= 0 || throw new InvalidArgumentException('MaxItems must be greater than or equal to 0.');\n }\n if (\\is_bool($uniqueItems)) {\n true === $uniqueItems || throw new InvalidArgumentException('UniqueItems must be true when specified.');\n }\n if (\\is_int($minContains)) {\n $minContains >= 0 || throw new InvalidArgumentException('MinContains must be greater than or equal to 0.');\n if (\\is_int($maxContains)) {\n $maxContains >= $minContains || throw new InvalidArgumentException('MaxContains must be greater than or equal to minContains.');\n }\n }\n if (\\is_int($maxContains)) {\n $maxContains >= 0 || throw new InvalidArgumentException('MaxContains must be greater than or equal to 0.');\n }\n if (\\is_int($minProperties)) {\n $minProperties >= 0 || throw new InvalidArgumentException('MinProperties must be greater than or equal to 0.');\n if (\\is_int($maxProperties)) {\n $maxProperties >= $minProperties || throw new InvalidArgumentException('MaxProperties must be greater than or equal to minProperties.');\n }\n }\n if (\\is_int($maxProperties)) {\n $maxProperties >= 0 || throw new InvalidArgumentException('MaxProperties must be greater than or equal to 0.');\n }\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/ai/src/store/src/Document/Transformer/TextSplitTransformer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Document\\Transformer;\n\nuse Symfony\\AI\\Store\\Document\\Metadata;\nuse Symfony\\AI\\Store\\Document\\TextDocument;\nuse Symfony\\AI\\Store\\Document\\TransformerInterface;\nuse Symfony\\AI\\Store\\Exception\\InvalidArgumentException;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * Splits a TextDocument into smaller chunks of specified size with optional overlap.\n * If the document's content is shorter than the specified chunk size, it returns the original document as a single chunk.\n * Overlap cannot be negative and must be less than the chunk size.\n *\n * @author Christopher Hertel \n */\nfinal readonly class TextSplitTransformer implements TransformerInterface\n{\n public const OPTION_CHUNK_SIZE = 'chunk_size';\n public const OPTION_OVERLAP = 'overlap';\n\n /**\n * @param array{chunk_size?: int, overlap?: int} $options\n */\n public function __invoke(iterable $documents, array $options = []): iterable\n {\n $chunkSize = $options[self::OPTION_CHUNK_SIZE] ?? 1000;\n $overlap = $options[self::OPTION_OVERLAP] ?? 200;\n\n if ($overlap < 0 || $overlap >= $chunkSize) {\n throw new InvalidArgumentException('Overlap must be non-negative and less than chunk size.');\n }\n\n foreach ($documents as $document) {\n if (mb_strlen($document->content) <= $chunkSize) {\n yield $document;\n\n continue;\n }\n\n $text = $document->content;\n $length = mb_strlen($text);\n $start = 0;\n\n while ($start < $length) {\n $end = min($start + $chunkSize, $length);\n $chunkText = mb_substr($text, $start, $end - $start);\n\n yield new TextDocument(Uuid::v4(), $chunkText, new Metadata([\n 'parent_id' => $document->id,\n 'text' => $chunkText,\n ...$document->metadata,\n ]));\n\n $start += ($chunkSize - $overlap);\n }\n }\n }\n}\n"], ["/ai/src/platform/src/Contract/JsonSchema/Factory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\JsonSchema;\n\nuse Symfony\\AI\\Platform\\Contract\\JsonSchema\\Attribute\\With;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\Component\\TypeInfo\\Type;\nuse Symfony\\Component\\TypeInfo\\Type\\BuiltinType;\nuse Symfony\\Component\\TypeInfo\\Type\\CollectionType;\nuse Symfony\\Component\\TypeInfo\\Type\\ObjectType;\nuse Symfony\\Component\\TypeInfo\\TypeIdentifier;\nuse Symfony\\Component\\TypeInfo\\TypeResolver\\TypeResolver;\n\n/**\n * @phpstan-type JsonSchema array{\n * type: 'object',\n * properties: array,\n * const?: string|int|list,\n * pattern?: string,\n * minLength?: int,\n * maxLength?: int,\n * minimum?: int,\n * maximum?: int,\n * multipleOf?: int,\n * exclusiveMinimum?: int,\n * exclusiveMaximum?: int,\n * minItems?: int,\n * maxItems?: int,\n * uniqueItems?: bool,\n * minContains?: int,\n * maxContains?: int,\n * required?: bool,\n * minProperties?: int,\n * maxProperties?: int,\n * dependentRequired?: bool,\n * }>,\n * required: list,\n * additionalProperties: false,\n * }\n *\n * @author Christopher Hertel \n */\nfinal readonly class Factory\n{\n private TypeResolver $typeResolver;\n\n public function __construct(\n private DescriptionParser $descriptionParser = new DescriptionParser(),\n ?TypeResolver $typeResolver = null,\n ) {\n $this->typeResolver = $typeResolver ?? TypeResolver::create();\n }\n\n /**\n * @return JsonSchema|null\n */\n public function buildParameters(string $className, string $methodName): ?array\n {\n $reflection = new \\ReflectionMethod($className, $methodName);\n\n return $this->convertTypes($reflection->getParameters());\n }\n\n /**\n * @return JsonSchema|null\n */\n public function buildProperties(string $className): ?array\n {\n $reflection = new \\ReflectionClass($className);\n\n return $this->convertTypes($reflection->getProperties());\n }\n\n /**\n * @param list<\\ReflectionProperty|\\ReflectionParameter> $elements\n *\n * @return JsonSchema|null\n */\n private function convertTypes(array $elements): ?array\n {\n if ([] === $elements) {\n return null;\n }\n\n $result = [\n 'type' => 'object',\n 'properties' => [],\n 'required' => [],\n 'additionalProperties' => false,\n ];\n\n foreach ($elements as $element) {\n $name = $element->getName();\n $type = $this->typeResolver->resolve($element);\n $schema = $this->getTypeSchema($type);\n\n if ($type->isNullable()) {\n $schema['type'] = [$schema['type'], 'null'];\n } elseif (!($element instanceof \\ReflectionParameter && $element->isOptional())) {\n $result['required'][] = $name;\n }\n\n $description = $this->descriptionParser->getDescription($element);\n if ('' !== $description) {\n $schema['description'] = $description;\n }\n\n // Check for ToolParameter attributes\n $attributes = $element->getAttributes(With::class);\n if (\\count($attributes) > 0) {\n $attributeState = array_filter((array) $attributes[0]->newInstance(), fn ($value) => null !== $value);\n $schema = array_merge($schema, $attributeState);\n }\n\n $result['properties'][$name] = $schema;\n }\n\n return $result;\n }\n\n /**\n * @return array\n */\n private function getTypeSchema(Type $type): array\n {\n switch (true) {\n case $type->isIdentifiedBy(TypeIdentifier::INT):\n return ['type' => 'integer'];\n\n case $type->isIdentifiedBy(TypeIdentifier::FLOAT):\n return ['type' => 'number'];\n\n case $type->isIdentifiedBy(TypeIdentifier::BOOL):\n return ['type' => 'boolean'];\n\n case $type->isIdentifiedBy(TypeIdentifier::ARRAY):\n \\assert($type instanceof CollectionType);\n $collectionValueType = $type->getCollectionValueType();\n\n if ($collectionValueType->isIdentifiedBy(TypeIdentifier::OBJECT)) {\n \\assert($collectionValueType instanceof ObjectType);\n\n return [\n 'type' => 'array',\n 'items' => $this->buildProperties($collectionValueType->getClassName()),\n ];\n }\n\n return [\n 'type' => 'array',\n 'items' => $this->getTypeSchema($collectionValueType),\n ];\n\n case $type->isIdentifiedBy(TypeIdentifier::OBJECT):\n if ($type instanceof BuiltinType) {\n throw new InvalidArgumentException('Cannot build schema from plain object type.');\n }\n \\assert($type instanceof ObjectType);\n if (\\in_array($type->getClassName(), ['DateTime', 'DateTimeImmutable', 'DateTimeInterface'], true)) {\n return ['type' => 'string', 'format' => 'date-time'];\n } else {\n // Recursively build the schema for an object type\n return $this->buildProperties($type->getClassName()) ?? ['type' => 'object'];\n }\n\n // no break\n case $type->isIdentifiedBy(TypeIdentifier::STRING):\n default:\n // Fallback to string for any unhandled types\n return ['type' => 'string'];\n }\n }\n}\n"], ["/ai/src/platform/src/Vector/Vector.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Vector;\n\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\n\n/**\n * @author Christopher Hertel \n */\nfinal class Vector implements VectorInterface\n{\n /**\n * @param list $data\n */\n public function __construct(\n private readonly array $data,\n private ?int $dimensions = null,\n ) {\n if (null !== $dimensions && $dimensions !== \\count($data)) {\n throw new InvalidArgumentException('Vector must have '.$dimensions.' dimensions');\n }\n\n if ([] === $data) {\n throw new InvalidArgumentException('Vector must have at least one dimension');\n }\n\n if (\\is_int($dimensions) && \\count($data) !== $dimensions) {\n throw new InvalidArgumentException('Vector must have '.$dimensions.' dimensions');\n }\n\n if (null === $this->dimensions) {\n $this->dimensions = \\count($data);\n }\n }\n\n /**\n * @return list\n */\n public function getData(): array\n {\n return $this->data;\n }\n\n public function getDimensions(): int\n {\n return $this->dimensions;\n }\n}\n"], ["/ai/src/store/src/Bridge/MariaDB/Store.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Bridge\\MariaDB;\n\nuse Doctrine\\DBAL\\Connection;\nuse Doctrine\\DBAL\\Exception as DBALException;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\nuse Symfony\\AI\\Store\\Document\\Metadata;\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\nuse Symfony\\AI\\Store\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Store\\Exception\\RuntimeException;\nuse Symfony\\AI\\Store\\InitializableStoreInterface;\nuse Symfony\\AI\\Store\\VectorStoreInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * Requires MariaDB >=11.7.\n *\n * @see https://mariadb.org/rag-with-mariadb-vector/\n *\n * @author Valtteri R \n */\nfinal readonly class Store implements VectorStoreInterface, InitializableStoreInterface\n{\n /**\n * @param string $tableName The name of the table\n * @param string $indexName The name of the vector search index\n * @param string $vectorFieldName The name of the field in the index that contains the vector\n */\n public function __construct(\n private \\PDO $connection,\n private string $tableName,\n private string $indexName,\n private string $vectorFieldName,\n ) {\n if (!\\extension_loaded('pdo')) {\n throw new RuntimeException('For using MariaDB as retrieval vector store, the PDO extension needs to be enabled.');\n }\n }\n\n public static function fromPdo(\\PDO $connection, string $tableName, string $indexName = 'embedding', string $vectorFieldName = 'embedding'): self\n {\n return new self($connection, $tableName, $indexName, $vectorFieldName);\n }\n\n /**\n * @throws RuntimeException When PDO extension is not enabled\n * @throws InvalidArgumentException When DBAL connection doesn't use PDO driver\n * @throws DBALException When DBAL operations fail (e.g., getting native connection)\n */\n public static function fromDbal(Connection $connection, string $tableName, string $indexName = 'embedding', string $vectorFieldName = 'embedding'): self\n {\n if (!class_exists(Connection::class)) {\n throw new RuntimeException('For using MariaDB as retrieval vector store, the PDO extension needs to be enabled.');\n }\n\n $pdo = $connection->getNativeConnection();\n\n if (!$pdo instanceof \\PDO) {\n throw new InvalidArgumentException('Only DBAL connections using PDO driver are supported.');\n }\n\n return self::fromPdo($pdo, $tableName, $indexName, $vectorFieldName);\n }\n\n public function add(VectorDocument ...$documents): void\n {\n $statement = $this->connection->prepare(\n \\sprintf(\n <<<'SQL'\n INSERT INTO %1$s (id, metadata, %2$s)\n VALUES (:id, :metadata, VEC_FromText(:vector))\n ON DUPLICATE KEY UPDATE metadata = :metadata, %2$s = VEC_FromText(:vector)\n SQL,\n $this->tableName,\n $this->vectorFieldName,\n ),\n );\n\n foreach ($documents as $document) {\n $operation = [\n 'id' => $document->id->toBinary(),\n 'metadata' => json_encode($document->metadata->getArrayCopy()),\n 'vector' => json_encode($document->vector->getData()),\n ];\n\n $statement->execute($operation);\n }\n }\n\n /**\n * @param array{\n * limit?: positive-int,\n * } $options\n */\n public function query(Vector $vector, array $options = [], ?float $minScore = null): array\n {\n $statement = $this->connection->prepare(\n \\sprintf(\n <<<'SQL'\n SELECT id, VEC_ToText(%1$s) embedding, metadata, VEC_DISTANCE_EUCLIDEAN(%1$s, VEC_FromText(:embedding)) AS score\n FROM %2$s\n %3$s\n ORDER BY score ASC\n LIMIT %4$d\n SQL,\n $this->vectorFieldName,\n $this->tableName,\n null !== $minScore ? \\sprintf('WHERE VEC_DISTANCE_EUCLIDEAN(%1$s, VEC_FromText(:embedding)) >= :minScore', $this->vectorFieldName) : '',\n $options['limit'] ?? 5,\n ),\n );\n\n $params = ['embedding' => json_encode($vector->getData())];\n\n if (null !== $minScore) {\n $params['minScore'] = $minScore;\n }\n\n $documents = [];\n\n $statement->execute($params);\n\n foreach ($statement->fetchAll(\\PDO::FETCH_ASSOC) as $result) {\n $documents[] = new VectorDocument(\n id: Uuid::fromBinary($result['id']),\n vector: new Vector(json_decode((string) $result['embedding'], true)),\n metadata: new Metadata(json_decode($result['metadata'] ?? '{}', true)),\n score: $result['score'],\n );\n }\n\n return $documents;\n }\n\n /**\n * @param array{dimensions?: positive-int} $options\n */\n public function initialize(array $options = []): void\n {\n if ([] !== $options && !\\array_key_exists('dimensions', $options)) {\n throw new InvalidArgumentException('The only supported option is \"dimensions\"');\n }\n\n $serverVersion = $this->connection->getAttribute(\\PDO::ATTR_SERVER_VERSION);\n\n if (!str_contains((string) $serverVersion, 'MariaDB') || version_compare($serverVersion, '11.7.0') < 0) {\n throw new InvalidArgumentException('You need MariaDB >=11.7 to use this feature');\n }\n\n $this->connection->exec(\n \\sprintf(\n <<<'SQL'\n CREATE TABLE IF NOT EXISTS %1$s (\n id BINARY(16) NOT NULL PRIMARY KEY,\n metadata JSON,\n %2$s VECTOR(%4$d) NOT NULL,\n VECTOR INDEX %3$s (%2$s)\n )\n SQL,\n $this->tableName,\n $this->vectorFieldName,\n $this->indexName,\n $options['dimensions'] ?? 1536,\n ),\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/Azure/OpenAI/GPTModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Azure\\OpenAI;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\GPT;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class GPTModelClient implements ModelClientInterface\n{\n private EventSourceHttpClient $httpClient;\n\n public function __construct(\n HttpClientInterface $httpClient,\n private string $baseUrl,\n private string $deployment,\n private string $apiVersion,\n #[\\SensitiveParameter] private string $apiKey,\n ) {\n $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n !str_starts_with($this->baseUrl, 'http://') || throw new InvalidArgumentException('The base URL must not contain the protocol.');\n !str_starts_with($this->baseUrl, 'https://') || throw new InvalidArgumentException('The base URL must not contain the protocol.');\n '' !== $deployment || throw new InvalidArgumentException('The deployment must not be empty.');\n '' !== $apiVersion || throw new InvalidArgumentException('The API version must not be empty.');\n '' !== $apiKey || throw new InvalidArgumentException('The API key must not be empty.');\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof GPT;\n }\n\n public function request(Model $model, object|array|string $payload, array $options = []): RawHttpResult\n {\n $url = \\sprintf('https://%s/openai/deployments/%s/chat/completions', $this->baseUrl, $this->deployment);\n\n return new RawHttpResult($this->httpClient->request('POST', $url, [\n 'headers' => [\n 'api-key' => $this->apiKey,\n ],\n 'query' => ['api-version' => $this->apiVersion],\n 'json' => array_merge($options, $payload),\n ]));\n }\n}\n"], ["/ai/src/platform/src/Bridge/Azure/OpenAI/EmbeddingsModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Azure\\OpenAI;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Embeddings;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class EmbeddingsModelClient implements ModelClientInterface\n{\n private EventSourceHttpClient $httpClient;\n\n public function __construct(\n HttpClientInterface $httpClient,\n private string $baseUrl,\n private string $deployment,\n private string $apiVersion,\n #[\\SensitiveParameter] private string $apiKey,\n ) {\n $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n !str_starts_with($this->baseUrl, 'http://') || throw new InvalidArgumentException('The base URL must not contain the protocol.');\n !str_starts_with($this->baseUrl, 'https://') || throw new InvalidArgumentException('The base URL must not contain the protocol.');\n '' !== $deployment || throw new InvalidArgumentException('The deployment must not be empty.');\n '' !== $apiVersion || throw new InvalidArgumentException('The API version must not be empty.');\n '' !== $apiKey || throw new InvalidArgumentException('The API key must not be empty.');\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Embeddings;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n $url = \\sprintf('https://%s/openai/deployments/%s/embeddings', $this->baseUrl, $this->deployment);\n\n return new RawHttpResult($this->httpClient->request('POST', $url, [\n 'headers' => [\n 'api-key' => $this->apiKey,\n ],\n 'query' => ['api-version' => $this->apiVersion],\n 'json' => array_merge($options, [\n 'model' => $model->getName(),\n 'input' => $payload,\n ]),\n ]));\n }\n}\n"], ["/ai/src/platform/src/Bridge/Azure/OpenAI/WhisperModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Azure\\OpenAI;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper;\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper\\Task;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class WhisperModelClient implements ModelClientInterface\n{\n private EventSourceHttpClient $httpClient;\n\n public function __construct(\n HttpClientInterface $httpClient,\n private string $baseUrl,\n private string $deployment,\n private string $apiVersion,\n #[\\SensitiveParameter] private string $apiKey,\n ) {\n $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n !str_starts_with($this->baseUrl, 'http://') || throw new InvalidArgumentException('The base URL must not contain the protocol.');\n !str_starts_with($this->baseUrl, 'https://') || throw new InvalidArgumentException('The base URL must not contain the protocol.');\n '' !== $deployment || throw new InvalidArgumentException('The deployment must not be empty.');\n '' !== $apiVersion || throw new InvalidArgumentException('The API version must not be empty.');\n '' !== $apiKey || throw new InvalidArgumentException('The API key must not be empty.');\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Whisper;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n $task = $options['task'] ?? Task::TRANSCRIPTION;\n $endpoint = Task::TRANSCRIPTION === $task ? 'transcriptions' : 'translations';\n $url = \\sprintf('https://%s/openai/deployments/%s/audio/%s', $this->baseUrl, $this->deployment, $endpoint);\n\n unset($options['task']);\n\n return new RawHttpResult($this->httpClient->request('POST', $url, [\n 'headers' => [\n 'api-key' => $this->apiKey,\n 'Content-Type' => 'multipart/form-data',\n ],\n 'query' => ['api-version' => $this->apiVersion],\n 'body' => array_merge($options, $payload),\n ]));\n }\n}\n"], ["/ai/fixtures/Tool/ToolWithToolParameterAttribute.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\AI\\Platform\\Contract\\JsonSchema\\Attribute\\With;\n\n#[AsTool('tool_with_ToolParameter_attribute', 'A tool which has a parameter with described with #[ToolParameter] attribute')]\nfinal class ToolWithToolParameterAttribute\n{\n /**\n * @param string $animal The animal given to the tool\n * @param int $numberOfArticles The number of articles given to the tool\n * @param string $infoEmail The info email given to the tool\n * @param string $locales The locales given to the tool\n * @param string $text The text given to the tool\n * @param int $number The number given to the tool\n * @param array $products The products given to the tool\n * @param string $shippingAddress The shipping address given to the tool\n */\n public function __invoke(\n #[With(enum: ['dog', 'cat', 'bird'])]\n string $animal,\n #[With(const: 42)]\n int $numberOfArticles,\n #[With(const: 'info@example.de')]\n string $infoEmail,\n #[With(const: ['de', 'en'])]\n string $locales,\n #[With(\n pattern: '^[a-zA-Z]+$',\n minLength: 1,\n maxLength: 10,\n )]\n string $text,\n #[With(\n minimum: 1,\n maximum: 10,\n multipleOf: 2,\n exclusiveMinimum: 1,\n exclusiveMaximum: 10,\n )]\n int $number,\n #[With(\n minItems: 1,\n maxItems: 10,\n uniqueItems: true,\n minContains: 1,\n maxContains: 10,\n )]\n array $products,\n #[With(\n required: true,\n minProperties: 1,\n maxProperties: 10,\n dependentRequired: true,\n )]\n string $shippingAddress,\n ): string {\n return 'Hello, World!';\n }\n}\n"], ["/ai/src/platform/src/Bridge/Albert/EmbeddingsModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Albert;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Embeddings;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Oskar Stark \n */\nfinal readonly class EmbeddingsModelClient implements ModelClientInterface\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n #[\\SensitiveParameter] private string $apiKey,\n private string $baseUrl,\n ) {\n '' !== $apiKey || throw new InvalidArgumentException('The API key must not be empty.');\n '' !== $baseUrl || throw new InvalidArgumentException('The base URL must not be empty.');\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Embeddings;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawResultInterface\n {\n return new RawHttpResult($this->httpClient->request('POST', \\sprintf('%s/embeddings', $this->baseUrl), [\n 'auth_bearer' => $this->apiKey,\n 'json' => \\is_array($payload) ? array_merge($payload, $options) : $payload,\n ]));\n }\n}\n"], ["/ai/src/platform/src/Bridge/Albert/GPTModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Albert;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\GPT;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Oskar Stark \n */\nfinal readonly class GPTModelClient implements ModelClientInterface\n{\n private EventSourceHttpClient $httpClient;\n\n public function __construct(\n HttpClientInterface $httpClient,\n #[\\SensitiveParameter] private string $apiKey,\n private string $baseUrl,\n ) {\n $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n\n '' !== $apiKey || throw new InvalidArgumentException('The API key must not be empty.');\n '' !== $baseUrl || throw new InvalidArgumentException('The base URL must not be empty.');\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof GPT;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawResultInterface\n {\n return new RawHttpResult($this->httpClient->request('POST', \\sprintf('%s/chat/completions', $this->baseUrl), [\n 'auth_bearer' => $this->apiKey,\n 'json' => \\is_array($payload) ? array_merge($payload, $options) : $payload,\n ]));\n }\n}\n"], ["/ai/src/store/src/InMemoryStore.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store;\n\nuse Symfony\\AI\\Platform\\Vector\\Vector;\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\nuse Symfony\\AI\\Store\\Exception\\InvalidArgumentException;\n\n/**\n * @author Guillaume Loulier \n */\nfinal class InMemoryStore implements VectorStoreInterface\n{\n public const COSINE_DISTANCE = 'cosine';\n public const ANGULAR_DISTANCE = 'angular';\n public const EUCLIDEAN_DISTANCE = 'euclidean';\n public const MANHATTAN_DISTANCE = 'manhattan';\n public const CHEBYSHEV_DISTANCE = 'chebyshev';\n\n /**\n * @var VectorDocument[]\n */\n private array $documents = [];\n\n public function __construct(\n private readonly string $distance = self::COSINE_DISTANCE,\n ) {\n }\n\n public function add(VectorDocument ...$documents): void\n {\n array_push($this->documents, ...$documents);\n }\n\n /**\n * @param array{\n * maxItems?: positive-int\n * } $options If maxItems is provided, only the top N results will be returned\n */\n public function query(Vector $vector, array $options = [], ?float $minScore = null): array\n {\n $strategy = match ($this->distance) {\n self::COSINE_DISTANCE => $this->cosineDistance(...),\n self::ANGULAR_DISTANCE => $this->angularDistance(...),\n self::EUCLIDEAN_DISTANCE => $this->euclideanDistance(...),\n self::MANHATTAN_DISTANCE => $this->manhattanDistance(...),\n self::CHEBYSHEV_DISTANCE => $this->chebyshevDistance(...),\n default => throw new InvalidArgumentException(\\sprintf('Unsupported distance metric \"%s\"', $this->distance)),\n };\n\n $currentEmbeddings = array_map(\n static fn (VectorDocument $vectorDocument): array => [\n 'distance' => $strategy($vectorDocument, $vector),\n 'document' => $vectorDocument,\n ],\n $this->documents,\n );\n\n usort(\n $currentEmbeddings,\n static fn (array $embedding, array $nextEmbedding): int => $embedding['distance'] <=> $nextEmbedding['distance'],\n );\n\n if (\\array_key_exists('maxItems', $options) && $options['maxItems'] < \\count($currentEmbeddings)) {\n $currentEmbeddings = \\array_slice($currentEmbeddings, 0, $options['maxItems']);\n }\n\n return array_map(\n static fn (array $embedding): VectorDocument => $embedding['document'],\n $currentEmbeddings,\n );\n }\n\n private function cosineDistance(VectorDocument $embedding, Vector $against): float\n {\n return 1 - $this->cosineSimilarity($embedding, $against);\n }\n\n private function cosineSimilarity(VectorDocument $embedding, Vector $against): float\n {\n $currentEmbeddingVectors = $embedding->vector->getData();\n\n $dotProduct = array_sum(array: array_map(\n static fn (float $a, float $b): float => $a * $b,\n $currentEmbeddingVectors,\n $against->getData(),\n ));\n\n $currentEmbeddingLength = sqrt(array_sum(array_map(\n static fn (float $value): float => $value ** 2,\n $currentEmbeddingVectors,\n )));\n\n $againstLength = sqrt(array_sum(array_map(\n static fn (float $value): float => $value ** 2,\n $against->getData(),\n )));\n\n return fdiv($dotProduct, $currentEmbeddingLength * $againstLength);\n }\n\n private function angularDistance(VectorDocument $embedding, Vector $against): float\n {\n $cosineSimilarity = $this->cosineSimilarity($embedding, $against);\n\n return fdiv(acos($cosineSimilarity), \\M_PI);\n }\n\n private function euclideanDistance(VectorDocument $embedding, Vector $against): float\n {\n return sqrt(array_sum(array_map(\n static fn (float $a, float $b): float => ($a - $b) ** 2,\n $embedding->vector->getData(),\n $against->getData(),\n )));\n }\n\n private function manhattanDistance(VectorDocument $embedding, Vector $against): float\n {\n return array_sum(array_map(\n static fn (float $a, float $b): float => abs($a - $b),\n $embedding->vector->getData(),\n $against->getData(),\n ));\n }\n\n private function chebyshevDistance(VectorDocument $embedding, Vector $against): float\n {\n $embeddingsAsPower = array_map(\n static fn (float $currentValue, float $againstValue): float => abs($currentValue - $againstValue),\n $embedding->vector->getData(),\n $against->getData(),\n );\n\n return array_reduce(\n array: $embeddingsAsPower,\n callback: static fn (float $value, float $current): float => max($value, $current),\n initial: 0.0,\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/Albert/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Albert;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Embeddings;\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\GPT;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Oskar Stark \n */\nfinal class PlatformFactory\n{\n public static function create(\n #[\\SensitiveParameter] string $apiKey,\n string $baseUrl,\n ?HttpClientInterface $httpClient = null,\n ): Platform {\n str_starts_with($baseUrl, 'https://') || throw new InvalidArgumentException('The Albert URL must start with \"https://\".');\n !str_ends_with($baseUrl, '/') || throw new InvalidArgumentException('The Albert URL must not end with a trailing slash.');\n preg_match('/\\/v\\d+$/', $baseUrl) || throw new InvalidArgumentException('The Albert URL must include an API version (e.g., /v1, /v2).');\n\n $httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n\n return new Platform(\n [\n new GPTModelClient($httpClient, $apiKey, $baseUrl),\n new EmbeddingsModelClient($httpClient, $apiKey, $baseUrl),\n ],\n [new GPT\\ResultConverter(), new Embeddings\\ResultConverter()],\n Contract::create(),\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/DallE/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\DallE;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\DallE;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @see https://platform.openai.com/docs/api-reference/images/create\n *\n * @author Denis Zunke \n */\nfinal readonly class ModelClient implements ModelClientInterface\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n #[\\SensitiveParameter]\n private string $apiKey,\n ) {\n '' !== $apiKey || throw new InvalidArgumentException('The API key must not be empty.');\n str_starts_with($apiKey, 'sk-') || throw new InvalidArgumentException('The API key must start with \"sk-\".');\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof DallE;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n return new RawHttpResult($this->httpClient->request('POST', 'https://api.openai.com/v1/images/generations', [\n 'auth_bearer' => $this->apiKey,\n 'json' => array_merge($options, [\n 'model' => $model->getName(),\n 'prompt' => $payload,\n ]),\n ]));\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenRouter/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenRouter;\n\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author rglozman\n */\nfinal readonly class ModelClient implements ModelClientInterface\n{\n private EventSourceHttpClient $httpClient;\n\n public function __construct(\n HttpClientInterface $httpClient,\n #[\\SensitiveParameter] private string $apiKey,\n ) {\n $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n '' !== $apiKey || throw new InvalidArgumentException('The API key must not be empty.');\n str_starts_with($apiKey, 'sk-') || throw new InvalidArgumentException('The API key must start with \"sk-\".');\n }\n\n public function supports(Model $model): bool\n {\n return true;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n return new RawHttpResult($this->httpClient->request('POST', 'https://openrouter.ai/api/v1/chat/completions', [\n 'auth_bearer' => $this->apiKey,\n 'json' => array_merge($options, $payload),\n ]));\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Gemini/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini\\Gemini;\n\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Gemini;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\Choice;\nuse Symfony\\AI\\Platform\\Result\\ChoiceResult;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\Result\\StreamResult;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Result\\ToolCallResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\ResponseInterface as HttpResponse;\n\n/**\n * @author Roy Garrido\n */\nfinal readonly class ResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Gemini;\n }\n\n public function convert(RawResultInterface|RawHttpResult $result, array $options = []): ResultInterface\n {\n if ($options['stream'] ?? false) {\n return new StreamResult($this->convertStream($result->getObject()));\n }\n\n $data = $result->getData();\n\n if (!isset($data['candidates'][0]['content']['parts'][0])) {\n throw new RuntimeException('Response does not contain any content');\n }\n\n /** @var Choice[] $choices */\n $choices = array_map($this->convertChoice(...), $data['candidates']);\n\n if (1 !== \\count($choices)) {\n return new ChoiceResult(...$choices);\n }\n\n if ($choices[0]->hasToolCall()) {\n return new ToolCallResult(...$choices[0]->getToolCalls());\n }\n\n return new TextResult($choices[0]->getContent());\n }\n\n private function convertStream(HttpResponse $result): \\Generator\n {\n foreach ((new EventSourceHttpClient())->stream($result) as $chunk) {\n if ($chunk->isFirst() || $chunk->isLast()) {\n continue;\n }\n\n $jsonDelta = trim($chunk->getContent());\n\n // Remove leading/trailing brackets\n if (str_starts_with($jsonDelta, '[') || str_starts_with($jsonDelta, ',')) {\n $jsonDelta = substr($jsonDelta, 1);\n }\n if (str_ends_with($jsonDelta, ']')) {\n $jsonDelta = substr($jsonDelta, 0, -1);\n }\n\n // Split in case of multiple JSON objects\n $deltas = explode(\",\\r\\n\", $jsonDelta);\n\n foreach ($deltas as $delta) {\n if ('' === $delta) {\n continue;\n }\n\n try {\n $data = json_decode($delta, true, 512, \\JSON_THROW_ON_ERROR);\n } catch (\\JsonException $e) {\n throw new RuntimeException('Failed to decode JSON response', 0, $e);\n }\n\n /** @var Choice[] $choices */\n $choices = array_map($this->convertChoice(...), $data['candidates'] ?? []);\n\n if (!$choices) {\n continue;\n }\n\n if (1 !== \\count($choices)) {\n yield new ChoiceResult(...$choices);\n continue;\n }\n\n if ($choices[0]->hasToolCall()) {\n yield new ToolCallResult(...$choices[0]->getToolCalls());\n }\n\n if ($choices[0]->hasContent()) {\n yield $choices[0]->getContent();\n }\n }\n }\n }\n\n /**\n * @param array{\n * finishReason?: string,\n * content: array{\n * parts: array{\n * functionCall?: array{\n * id: string,\n * name: string,\n * args: mixed[]\n * },\n * text?: string\n * }[]\n * }\n * } $choice\n */\n private function convertChoice(array $choice): Choice\n {\n $contentPart = $choice['content']['parts'][0] ?? [];\n\n if (isset($contentPart['functionCall'])) {\n return new Choice(toolCalls: [$this->convertToolCall($contentPart['functionCall'])]);\n }\n\n if (isset($contentPart['text'])) {\n return new Choice($contentPart['text']);\n }\n\n throw new RuntimeException(\\sprintf('Unsupported finish reason \"%s\".', $choice['finishReason']));\n }\n\n /**\n * @param array{\n * id?: string,\n * name: string,\n * args: mixed[]\n * } $toolCall\n */\n private function convertToolCall(array $toolCall): ToolCall\n {\n return new ToolCall($toolCall['id'] ?? '', $toolCall['name'], $toolCall['args']);\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/Embeddings/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\Embeddings;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Embeddings;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface as PlatformResponseFactory;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ModelClient implements PlatformResponseFactory\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n #[\\SensitiveParameter]\n private string $apiKey,\n ) {\n '' !== $apiKey || throw new InvalidArgumentException('The API key must not be empty.');\n str_starts_with($apiKey, 'sk-') || throw new InvalidArgumentException('The API key must start with \"sk-\".');\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Embeddings;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n return new RawHttpResult($this->httpClient->request('POST', 'https://api.openai.com/v1/embeddings', [\n 'auth_bearer' => $this->apiKey,\n 'json' => array_merge($options, [\n 'model' => $model->getName(),\n 'input' => $payload,\n ]),\n ]));\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/GPT/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\GPT;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\GPT;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface as PlatformResponseFactory;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ModelClient implements PlatformResponseFactory\n{\n private EventSourceHttpClient $httpClient;\n\n public function __construct(\n HttpClientInterface $httpClient,\n #[\\SensitiveParameter]\n private string $apiKey,\n ) {\n $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n '' !== $apiKey || throw new InvalidArgumentException('The API key must not be empty.');\n str_starts_with($apiKey, 'sk-') || throw new InvalidArgumentException('The API key must start with \"sk-\".');\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof GPT;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n return new RawHttpResult($this->httpClient->request('POST', 'https://api.openai.com/v1/chat/completions', [\n 'auth_bearer' => $this->apiKey,\n 'json' => array_merge($options, $payload),\n ]));\n }\n}\n"], ["/ai/src/platform/src/Message/Content/File.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message\\Content;\n\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\n\nuse function Symfony\\Component\\String\\u;\n\n/**\n * @author Christopher Hertel \n */\nreadonly class File implements ContentInterface\n{\n final public function __construct(\n private string|\\Closure $data,\n private string $format,\n private ?string $path = null,\n ) {\n }\n\n public static function fromDataUrl(string $dataUrl): static\n {\n if (!str_starts_with($dataUrl, 'data:')) {\n throw new InvalidArgumentException('Invalid audio data URL format.');\n }\n\n return new static(\n base64_decode(u($dataUrl)->after('base64,')->toString()),\n u($dataUrl)->after('data:')->before(';base64,')->toString(),\n );\n }\n\n public static function fromFile(string $path): static\n {\n if (!is_readable($path)) {\n throw new InvalidArgumentException(\\sprintf('The file \"%s\" does not exist or is not readable.', $path));\n }\n\n return new static(\n fn () => file_get_contents($path),\n mime_content_type($path),\n $path,\n );\n }\n\n public function getFormat(): string\n {\n return $this->format;\n }\n\n public function asBinary(): string\n {\n return $this->data instanceof \\Closure ? ($this->data)() : $this->data;\n }\n\n public function asBase64(): string\n {\n return base64_encode($this->asBinary());\n }\n\n public function asDataUrl(): string\n {\n return \\sprintf('data:%s;base64,%s', $this->format, $this->asBase64());\n }\n\n /**\n * @return resource|false\n */\n public function asResource()\n {\n if (null === $this->path) {\n throw new RuntimeException('You can only get a resource after creating fromFile.');\n }\n\n return fopen($this->path, 'r');\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/DallE/UrlImage.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\DallE;\n\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class UrlImage\n{\n public function __construct(\n public string $url,\n ) {\n '' !== $url || throw new InvalidArgumentException('The image url must be given.');\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace;\n\nuse Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output\\ClassificationResult;\nuse Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output\\FillMaskResult;\nuse Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output\\ImageSegmentationResult;\nuse Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output\\ObjectDetectionResult;\nuse Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output\\QuestionAnsweringResult;\nuse Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output\\SentenceSimilarityResult;\nuse Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output\\TableQuestionAnsweringResult;\nuse Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output\\TokenClassificationResult;\nuse Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output\\ZeroShotClassificationResult;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\BinaryResult;\nuse Symfony\\AI\\Platform\\Result\\ObjectResult;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\Result\\VectorResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface as PlatformResponseConverter;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ResultConverter implements PlatformResponseConverter\n{\n public function supports(Model $model): bool\n {\n return true;\n }\n\n public function convert(RawResultInterface|RawHttpResult $result, array $options = []): ResultInterface\n {\n $httpResponse = $result->getObject();\n if (503 === $httpResponse->getStatusCode()) {\n throw new RuntimeException('Service unavailable.');\n }\n\n if (404 === $httpResponse->getStatusCode()) {\n throw new InvalidArgumentException('Model, provider or task not found (404).');\n }\n\n $headers = $httpResponse->getHeaders(false);\n $contentType = $headers['content-type'][0] ?? null;\n $content = 'application/json' === $contentType ? $httpResponse->toArray(false) : $httpResponse->getContent(false);\n\n if (str_starts_with((string) $httpResponse->getStatusCode(), '4')) {\n $message = \\is_string($content) ? $content :\n (\\is_array($content['error']) ? $content['error'][0] : $content['error']);\n\n throw new InvalidArgumentException(\\sprintf('API Client Error (%d): %s', $httpResponse->getStatusCode(), $message));\n }\n\n if (200 !== $httpResponse->getStatusCode()) {\n throw new RuntimeException('Unhandled response code: '.$httpResponse->getStatusCode());\n }\n\n $task = $options['task'] ?? null;\n\n return match ($task) {\n Task::AUDIO_CLASSIFICATION, Task::IMAGE_CLASSIFICATION => new ObjectResult(\n ClassificationResult::fromArray($content)\n ),\n Task::AUTOMATIC_SPEECH_RECOGNITION => new TextResult($content['text'] ?? ''),\n Task::CHAT_COMPLETION => new TextResult($content['choices'][0]['message']['content'] ?? ''),\n Task::FEATURE_EXTRACTION => new VectorResult(new Vector($content)),\n Task::TEXT_CLASSIFICATION => new ObjectResult(ClassificationResult::fromArray(reset($content) ?? [])),\n Task::FILL_MASK => new ObjectResult(FillMaskResult::fromArray($content)),\n Task::IMAGE_SEGMENTATION => new ObjectResult(ImageSegmentationResult::fromArray($content)),\n Task::IMAGE_TO_TEXT, Task::TEXT_GENERATION => new TextResult($content[0]['generated_text'] ?? ''),\n Task::TEXT_TO_IMAGE => new BinaryResult($content, $contentType),\n Task::OBJECT_DETECTION => new ObjectResult(ObjectDetectionResult::fromArray($content)),\n Task::QUESTION_ANSWERING => new ObjectResult(QuestionAnsweringResult::fromArray($content)),\n Task::SENTENCE_SIMILARITY => new ObjectResult(SentenceSimilarityResult::fromArray($content)),\n Task::SUMMARIZATION => new TextResult($content[0]['summary_text']),\n Task::TABLE_QUESTION_ANSWERING => new ObjectResult(TableQuestionAnsweringResult::fromArray($content)),\n Task::TOKEN_CLASSIFICATION => new ObjectResult(TokenClassificationResult::fromArray($content)),\n Task::TRANSLATION => new TextResult($content[0]['translation_text'] ?? ''),\n Task::ZERO_SHOT_CLASSIFICATION => new ObjectResult(ZeroShotClassificationResult::fromArray($content)),\n\n default => throw new RuntimeException(\\sprintf('Unsupported task: %s', $task)),\n };\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/DallE/Base64Image.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\DallE;\n\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class Base64Image\n{\n public function __construct(\n public string $encodedImage,\n ) {\n '' !== $encodedImage || throw new InvalidArgumentException('The base64 encoded image generated must be given.');\n }\n}\n"], ["/ai/src/ai-bundle/src/Security/EventListener/IsGrantedToolAttributeListener.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\AIBundle\\Security\\EventListener;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Event\\ToolCallArgumentsResolved;\nuse Symfony\\AI\\AIBundle\\Security\\Attribute\\IsGrantedTool;\nuse Symfony\\Component\\ExpressionLanguage\\Expression;\nuse Symfony\\Component\\ExpressionLanguage\\ExpressionLanguage;\nuse Symfony\\Component\\Security\\Core\\Authorization\\AccessDecision;\nuse Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationCheckerInterface;\nuse Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException;\nuse Symfony\\Component\\Security\\Core\\Exception\\RuntimeException;\n\n/**\n * Checks {@see IsGrantedTool} attributes on tools just before they are called.\n *\n * @author Valtteri R \n */\nclass IsGrantedToolAttributeListener\n{\n public function __construct(\n private readonly AuthorizationCheckerInterface $authChecker,\n private ?ExpressionLanguage $expressionLanguage = null,\n ) {\n }\n\n public function __invoke(ToolCallArgumentsResolved $event): void\n {\n $tool = $event->tool;\n $class = new \\ReflectionClass($tool);\n $method = $class->getMethod($event->metadata->reference->method);\n $classAttributes = $class->getAttributes(IsGrantedTool::class);\n $methodAttributes = $method->getAttributes(IsGrantedTool::class);\n\n if (!$classAttributes && !$methodAttributes) {\n return;\n }\n\n $arguments = $event->arguments;\n\n foreach (array_merge($classAttributes, $methodAttributes) as $attr) {\n /** @var IsGrantedTool $attribute */\n $attribute = $attr->newInstance();\n $subject = null;\n\n if ($subjectRef = $attribute->subject) {\n if (\\is_array($subjectRef)) {\n foreach ($subjectRef as $refKey => $ref) {\n $subject[\\is_string($refKey) ? $refKey : (string) $ref] = $this->getIsGrantedSubject($ref, $tool, $arguments);\n }\n } else {\n $subject = $this->getIsGrantedSubject($subjectRef, $tool, $arguments);\n }\n }\n\n $accessDecision = null;\n // bc layer\n if (class_exists(AccessDecision::class)) {\n $accessDecision = new AccessDecision();\n $accessDecision->isGranted = false;\n $decision = &$accessDecision->isGranted;\n }\n\n if (!$decision = $this->authChecker->isGranted($attribute->attribute, $subject, $accessDecision)) {\n $message = $attribute->message ?: (class_exists(AccessDecision::class, false) ? $accessDecision->getMessage() : 'Access Denied.');\n\n $e = new AccessDeniedException($message, code: $attribute->exceptionCode ?? 403);\n $e->setAttributes([$attribute->attribute]);\n $e->setSubject($subject);\n if ($accessDecision && method_exists($e, 'setAccessDecision')) {\n $e->setAccessDecision($accessDecision);\n }\n\n throw $e;\n }\n }\n }\n\n /**\n * @param array $arguments\n */\n private function getIsGrantedSubject(string|Expression|\\Closure $subjectRef, object $tool, array $arguments): mixed\n {\n if ($subjectRef instanceof \\Closure) {\n return $subjectRef($arguments, $tool);\n }\n\n if ($subjectRef instanceof Expression) {\n $this->expressionLanguage ??= new ExpressionLanguage();\n\n return $this->expressionLanguage->evaluate($subjectRef, [\n 'tool' => $tool,\n 'args' => $arguments,\n ]);\n }\n\n if (!\\array_key_exists($subjectRef, $arguments)) {\n throw new RuntimeException(\\sprintf('Could not find the subject \"%s\" for the #[IsGranted] attribute. Try adding a \"$%s\" argument to your tool method.', $subjectRef, $subjectRef));\n }\n\n return $arguments[$subjectRef];\n }\n}\n"], ["/ai/src/agent/src/Memory/MemoryInputProcessor.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Memory;\n\nuse Symfony\\AI\\Agent\\Input;\nuse Symfony\\AI\\Agent\\InputProcessorInterface;\nuse Symfony\\AI\\Platform\\Message\\Message;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class MemoryInputProcessor implements InputProcessorInterface\n{\n private const MEMORY_PROMPT_MESSAGE = <<memoryProviders = $memoryProviders;\n }\n\n public function processInput(Input $input): void\n {\n $options = $input->getOptions();\n $useMemory = $options['use_memory'] ?? true;\n unset($options['use_memory']);\n $input->setOptions($options);\n\n if (false === $useMemory || 0 === \\count($this->memoryProviders)) {\n return;\n }\n\n $memory = '';\n foreach ($this->memoryProviders as $provider) {\n $memoryMessages = $provider->loadMemory($input);\n\n if (0 === \\count($memoryMessages)) {\n continue;\n }\n\n $memory .= \\PHP_EOL.\\PHP_EOL;\n $memory .= implode(\n \\PHP_EOL,\n array_map(static fn (Memory $memory): string => $memory->content, $memoryMessages),\n );\n }\n\n if ('' === $memory) {\n return;\n }\n\n $systemMessage = $input->messages->getSystemMessage()->content ?? '';\n if ('' !== $systemMessage) {\n $systemMessage .= \\PHP_EOL.\\PHP_EOL;\n }\n\n $messages = $input->messages\n ->withoutSystemMessage()\n ->prepend(Message::forSystem($systemMessage.self::MEMORY_PROMPT_MESSAGE.$memory));\n\n $input->messages = $messages;\n }\n}\n"], ["/ai/src/agent/src/Agent.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent;\n\nuse Psr\\Log\\LoggerInterface;\nuse Psr\\Log\\NullLogger;\nuse Symfony\\AI\\Agent\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Agent\\Exception\\MissingModelSupportException;\nuse Symfony\\AI\\Agent\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\PlatformInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\Contracts\\HttpClient\\Exception\\ClientExceptionInterface;\nuse Symfony\\Contracts\\HttpClient\\Exception\\HttpExceptionInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class Agent implements AgentInterface\n{\n /**\n * @var InputProcessorInterface[]\n */\n private array $inputProcessors;\n\n /**\n * @var OutputProcessorInterface[]\n */\n private array $outputProcessors;\n\n /**\n * @param InputProcessorInterface[] $inputProcessors\n * @param OutputProcessorInterface[] $outputProcessors\n */\n public function __construct(\n private PlatformInterface $platform,\n private Model $model,\n iterable $inputProcessors = [],\n iterable $outputProcessors = [],\n private LoggerInterface $logger = new NullLogger(),\n ) {\n $this->inputProcessors = $this->initializeProcessors($inputProcessors, InputProcessorInterface::class);\n $this->outputProcessors = $this->initializeProcessors($outputProcessors, OutputProcessorInterface::class);\n }\n\n /**\n * @param array $options\n *\n * @throws MissingModelSupportException When the model doesn't support audio or image inputs present in the messages\n * @throws InvalidArgumentException When the platform returns a client error (4xx) indicating invalid request parameters\n * @throws RuntimeException When the platform returns a server error (5xx) or network failure occurs\n */\n public function call(MessageBagInterface $messages, array $options = []): ResultInterface\n {\n $input = new Input($this->model, $messages, $options);\n array_map(fn (InputProcessorInterface $processor) => $processor->processInput($input), $this->inputProcessors);\n\n $model = $input->model;\n $messages = $input->messages;\n $options = $input->getOptions();\n\n if ($messages->containsAudio() && !$model->supports(Capability::INPUT_AUDIO)) {\n throw MissingModelSupportException::forAudioInput($model::class);\n }\n\n if ($messages->containsImage() && !$model->supports(Capability::INPUT_IMAGE)) {\n throw MissingModelSupportException::forImageInput($model::class);\n }\n\n try {\n $result = $this->platform->invoke($model, $messages, $options)->getResult();\n } catch (ClientExceptionInterface $e) {\n $message = $e->getMessage();\n $content = $e->getResponse()->toArray(false);\n\n $this->logger->debug($message, $content);\n\n throw new InvalidArgumentException('' === $message ? 'Invalid request to model or platform' : $message, previous: $e);\n } catch (HttpExceptionInterface $e) {\n throw new RuntimeException('Failed to request model', previous: $e);\n }\n\n $output = new Output($model, $result, $messages, $options);\n array_map(fn (OutputProcessorInterface $processor) => $processor->processOutput($output), $this->outputProcessors);\n\n return $output->result;\n }\n\n /**\n * @param InputProcessorInterface[]|OutputProcessorInterface[] $processors\n * @param class-string $interface\n *\n * @return InputProcessorInterface[]|OutputProcessorInterface[]\n */\n private function initializeProcessors(iterable $processors, string $interface): array\n {\n foreach ($processors as $processor) {\n if (!$processor instanceof $interface) {\n throw new InvalidArgumentException(\\sprintf('Processor %s must implement %s interface.', $processor::class, $interface));\n }\n\n if ($processor instanceof AgentAwareInterface) {\n $processor->setAgent($this);\n }\n }\n\n return $processors instanceof \\Traversable ? iterator_to_array($processors) : $processors;\n }\n}\n"], ["/ai/src/store/src/Bridge/MongoDB/Store.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Bridge\\MongoDB;\n\nuse MongoDB\\BSON\\Binary;\nuse MongoDB\\Client;\nuse MongoDB\\Collection;\nuse MongoDB\\Driver\\Exception\\CommandException;\nuse Psr\\Log\\LoggerInterface;\nuse Psr\\Log\\NullLogger;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\nuse Symfony\\AI\\Store\\Document\\Metadata;\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\nuse Symfony\\AI\\Store\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Store\\Exception\\RuntimeException;\nuse Symfony\\AI\\Store\\InitializableStoreInterface;\nuse Symfony\\AI\\Store\\VectorStoreInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * @see https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-overview/\n *\n * For this store you need to create a separate MongoDB Atlas Search index.\n * The index needs to be created with the following settings:\n * {\n * \"fields\": [\n * {\n * \"numDimensions\": 1536,\n * \"path\": \"vector\",\n * \"similarity\": \"euclidean\",\n * \"type\": \"vector\"\n * }\n * ]\n * }\n *\n * Note, that the `path` key needs to match the $vectorFieldName.\n *\n * For the `similarity` key you can choose between `euclidean`, `cosine` and `dotProduct`.\n * {@see https://www.mongodb.com/docs/atlas/atlas-search/field-types/knn-vector/#define-the-index-for-the-fts-field-type-type}\n *\n * @author Oskar Stark \n */\nfinal readonly class Store implements VectorStoreInterface, InitializableStoreInterface\n{\n /**\n * @param string $databaseName The name of the database\n * @param string $collectionName The name of the collection\n * @param string $indexName The name of the Atlas Search index\n * @param string $vectorFieldName The name of the field int the index that contains the vector\n * @param bool $bulkWrite Use bulk write operations\n */\n public function __construct(\n private Client $client,\n private string $databaseName,\n private string $collectionName,\n private string $indexName,\n private string $vectorFieldName = 'vector',\n private bool $bulkWrite = false,\n private LoggerInterface $logger = new NullLogger(),\n ) {\n if (!class_exists(Client::class)) {\n throw new RuntimeException('For using MongoDB Atlas as retrieval vector store, the mongodb/mongodb package is required. Try running \"composer require mongodb/mongodb\".');\n }\n }\n\n public function add(VectorDocument ...$documents): void\n {\n $operations = [];\n\n foreach ($documents as $document) {\n $operation = [\n ['_id' => $this->toBinary($document->id)], // we use binary for the id, because of storage efficiency\n array_filter([\n 'metadata' => $document->metadata->getArrayCopy(),\n $this->vectorFieldName => $document->vector->getData(),\n ]),\n ['upsert' => true], // insert if not exists\n ];\n\n if ($this->bulkWrite) {\n $operations[] = ['replaceOne' => $operation];\n continue;\n }\n\n $this->getCollection()->replaceOne(...$operation);\n }\n\n if ($this->bulkWrite) {\n $this->getCollection()->bulkWrite($operations);\n }\n }\n\n /**\n * @param array{\n * limit?: positive-int,\n * numCandidates?: positive-int,\n * filter?: array\n * } $options\n */\n public function query(Vector $vector, array $options = [], ?float $minScore = null): array\n {\n $pipeline = [\n [\n '$vectorSearch' => array_merge([\n 'index' => $this->indexName,\n 'path' => $this->vectorFieldName,\n 'queryVector' => $vector->getData(),\n 'numCandidates' => 200,\n 'limit' => 5,\n ], $options),\n ],\n [\n '$addFields' => [\n 'score' => ['$meta' => 'vectorSearchScore'],\n ],\n ],\n ];\n\n if (null !== $minScore) {\n $pipeline[] = [\n '$match' => [\n 'score' => ['$gte' => $minScore],\n ],\n ];\n }\n\n $results = $this->getCollection()->aggregate(\n $pipeline,\n ['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]\n );\n\n $documents = [];\n\n foreach ($results as $result) {\n $documents[] = new VectorDocument(\n id: $this->toUuid($result['_id']),\n vector: new Vector($result[$this->vectorFieldName]),\n metadata: new Metadata($result['metadata'] ?? []),\n score: $result['score'],\n );\n }\n\n return $documents;\n }\n\n /**\n * @param array{fields?: array} $options\n */\n public function initialize(array $options = []): void\n {\n if ([] !== $options && !\\array_key_exists('fields', $options)) {\n throw new InvalidArgumentException('The only supported option is \"fields\"');\n }\n\n try {\n $this->getCollection()->createSearchIndex(\n [\n 'fields' => array_merge([\n [\n 'numDimensions' => 1536,\n 'path' => $this->vectorFieldName,\n 'similarity' => 'euclidean',\n 'type' => 'vector',\n ],\n ], $options['fields'] ?? []),\n ],\n [\n 'name' => $this->indexName,\n 'type' => 'vectorSearch',\n ],\n );\n } catch (CommandException $e) {\n $this->logger->warning($e->getMessage());\n }\n }\n\n private function getCollection(): Collection\n {\n return $this->client->getCollection($this->databaseName, $this->collectionName);\n }\n\n private function toBinary(Uuid $uuid): Binary\n {\n return new Binary($uuid->toBinary(), Binary::TYPE_UUID);\n }\n\n private function toUuid(Binary $binary): Uuid\n {\n return Uuid::fromString($binary->getData());\n }\n}\n"], ["/ai/src/store/src/Bridge/Postgres/Store.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Bridge\\Postgres;\n\nuse Doctrine\\DBAL\\Connection;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\nuse Symfony\\AI\\Platform\\Vector\\VectorInterface;\nuse Symfony\\AI\\Store\\Document\\Metadata;\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\nuse Symfony\\AI\\Store\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Store\\InitializableStoreInterface;\nuse Symfony\\AI\\Store\\VectorStoreInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * Requires PostgreSQL with pgvector extension.\n *\n * @author Simon André \n *\n * @see https://github.com/pgvector/pgvector\n */\nfinal readonly class Store implements VectorStoreInterface, InitializableStoreInterface\n{\n public function __construct(\n private \\PDO $connection,\n private string $tableName,\n private string $vectorFieldName = 'embedding',\n ) {\n }\n\n public static function fromPdo(\\PDO $connection, string $tableName, string $vectorFieldName = 'embedding'): self\n {\n return new self($connection, $tableName, $vectorFieldName);\n }\n\n public static function fromDbal(Connection $connection, string $tableName, string $vectorFieldName = 'embedding'): self\n {\n $pdo = $connection->getNativeConnection();\n\n if (!$pdo instanceof \\PDO) {\n throw new InvalidArgumentException('Only DBAL connections using PDO driver are supported.');\n }\n\n return self::fromPdo($pdo, $tableName, $vectorFieldName);\n }\n\n public function add(VectorDocument ...$documents): void\n {\n $statement = $this->connection->prepare(\n \\sprintf(\n 'INSERT INTO %1$s (id, metadata, %2$s)\n VALUES (:id, :metadata, :vector)\n ON CONFLICT (id) DO UPDATE SET metadata = EXCLUDED.metadata, %2$s = EXCLUDED.%2$s',\n $this->tableName,\n $this->vectorFieldName,\n ),\n );\n\n foreach ($documents as $document) {\n $operation = [\n 'id' => $document->id->toRfc4122(),\n 'metadata' => json_encode($document->metadata->getArrayCopy(), \\JSON_THROW_ON_ERROR),\n 'vector' => $this->toPgvector($document->vector),\n ];\n\n $statement->execute($operation);\n }\n }\n\n /**\n * @param array $options\n * @param float|null $minScore Minimum score to filter results (optional)\n *\n * @return VectorDocument[]\n */\n public function query(Vector $vector, array $options = [], ?float $minScore = null): array\n {\n $sql = \\sprintf(\n 'SELECT id, %s AS embedding, metadata, (%s <-> :embedding) AS score\n FROM %s\n %s\n ORDER BY score ASC\n LIMIT %d',\n $this->vectorFieldName,\n $this->vectorFieldName,\n $this->tableName,\n null !== $minScore ? \"WHERE ({$this->vectorFieldName} <-> :embedding) >= :minScore\" : '',\n $options['limit'] ?? 5,\n );\n $statement = $this->connection->prepare($sql);\n\n $params = [\n 'embedding' => $this->toPgvector($vector),\n ];\n if (null !== $minScore) {\n $params['minScore'] = $minScore;\n }\n\n $statement->execute($params);\n\n $documents = [];\n foreach ($statement->fetchAll(\\PDO::FETCH_ASSOC) as $result) {\n $documents[] = new VectorDocument(\n id: Uuid::fromString($result['id']),\n vector: new Vector($this->fromPgvector($result['embedding'])),\n metadata: new Metadata(json_decode($result['metadata'] ?? '{}', true, 512, \\JSON_THROW_ON_ERROR)),\n score: $result['score'],\n );\n }\n\n return $documents;\n }\n\n /**\n * @param array{vector_type?: string, vector_size?: positive-int, index_method?: string, index_opclass?: string} $options\n *\n * Good configurations $options are:\n * - For Mistral: ['vector_size' => 1024]\n * - For Gemini: ['vector_type' => 'halfvec', 'vector_size' => 3072, 'index_method' => 'hnsw', 'index_opclass' => 'halfvec_cosine_ops']\n */\n public function initialize(array $options = []): void\n {\n $this->connection->exec('CREATE EXTENSION IF NOT EXISTS vector');\n\n $this->connection->exec(\n \\sprintf(\n 'CREATE TABLE IF NOT EXISTS %s (\n id UUID PRIMARY KEY,\n metadata JSONB,\n %s %s(%d) NOT NULL\n )',\n $this->tableName,\n $this->vectorFieldName,\n $options['vector_type'] ?? 'vector',\n $options['vector_size'] ?? 1536,\n ),\n );\n $this->connection->exec(\n \\sprintf(\n 'CREATE INDEX IF NOT EXISTS %s_%s_idx ON %s USING %s (%s %s)',\n $this->tableName,\n $this->vectorFieldName,\n $this->tableName,\n $options['index_method'] ?? 'ivfflat',\n $this->vectorFieldName,\n $options['index_opclass'] ?? 'vector_cosine_ops',\n ),\n );\n }\n\n private function toPgvector(VectorInterface $vector): string\n {\n return '['.implode(',', $vector->getData()).']';\n }\n\n /**\n * @return float[]\n */\n private function fromPgvector(string $vector): array\n {\n return json_decode($vector, true, 512, \\JSON_THROW_ON_ERROR);\n }\n}\n"], ["/ai/src/agent/src/Chat/MessageStore/CacheStore.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Chat\\MessageStore;\n\nuse Psr\\Cache\\CacheItemPoolInterface;\nuse Symfony\\AI\\Agent\\Chat\\MessageStoreInterface;\nuse Symfony\\AI\\Agent\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Message\\MessageBag;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\n\nfinal readonly class CacheStore implements MessageStoreInterface\n{\n public function __construct(\n private CacheItemPoolInterface $cache,\n private string $cacheKey,\n private int $ttl = 86400,\n ) {\n if (!interface_exists(CacheItemPoolInterface::class)) {\n throw new RuntimeException('For using the CacheStore as message store, a PSR-6 cache implementation is required. Try running \"composer require symfony/cache\" or another PSR-6 compatible cache.');\n }\n }\n\n public function save(MessageBagInterface $messages): void\n {\n $item = $this->cache->getItem($this->cacheKey);\n\n $item->set($messages);\n $item->expiresAfter($this->ttl);\n\n $this->cache->save($item);\n }\n\n public function load(): MessageBag\n {\n $item = $this->cache->getItem($this->cacheKey);\n\n return $item->isHit() ? $item->get() : new MessageBag();\n }\n\n public function clear(): void\n {\n $this->cache->deleteItem($this->cacheKey);\n }\n}\n"], ["/ai/src/store/src/Indexer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store;\n\nuse Psr\\Log\\LoggerInterface;\nuse Psr\\Log\\NullLogger;\nuse Symfony\\AI\\Store\\Document\\TextDocument;\nuse Symfony\\AI\\Store\\Document\\Vectorizer;\n\n/**\n * Converts a collection of TextDocuments into VectorDocuments and pushes them to a store implementation.\n *\n * @author Christopher Hertel \n */\nfinal readonly class Indexer\n{\n public function __construct(\n private Vectorizer $vectorizer,\n private StoreInterface $store,\n private LoggerInterface $logger = new NullLogger(),\n ) {\n }\n\n /**\n * @param TextDocument|iterable $documents\n * @param int $chunkSize number of documents to vectorize and store in one batch\n */\n public function index(TextDocument|iterable $documents, int $chunkSize = 50): void\n {\n if ($documents instanceof TextDocument) {\n $documents = [$documents];\n }\n\n $counter = 0;\n $chunk = [];\n foreach ($documents as $document) {\n $chunk[] = $document;\n ++$counter;\n\n if ($chunkSize === \\count($chunk)) {\n $this->store->add(...$this->vectorizer->vectorizeDocuments($chunk));\n $chunk = [];\n }\n }\n\n if (\\count($chunk) > 0) {\n $this->store->add(...$this->vectorizer->vectorizeDocuments($chunk));\n }\n\n $this->logger->debug(0 === $counter ? 'No documents to index' : \\sprintf('Indexed %d documents', $counter));\n }\n}\n"], ["/ai/src/store/src/Bridge/Qdrant/Store.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Bridge\\Qdrant;\n\nuse Symfony\\AI\\Platform\\Vector\\NullVector;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\nuse Symfony\\AI\\Store\\Document\\Metadata;\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\nuse Symfony\\AI\\Store\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Store\\InitializableStoreInterface;\nuse Symfony\\AI\\Store\\VectorStoreInterface;\nuse Symfony\\Component\\Uid\\Uuid;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Guillaume Loulier \n */\nfinal readonly class Store implements InitializableStoreInterface, VectorStoreInterface\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n private string $endpointUrl,\n #[\\SensitiveParameter] private string $apiKey,\n private string $collectionName,\n private int $embeddingsDimension = 1536,\n private string $embeddingsDistance = 'Cosine',\n ) {\n }\n\n public function add(VectorDocument ...$documents): void\n {\n $this->request('PUT', \\sprintf('collections/%s/points', $this->collectionName), [\n 'points' => array_map($this->convertToIndexableArray(...), $documents),\n ]);\n }\n\n /**\n * @param array{\n * limit?: positive-int,\n * offset?: positive-int\n * } $options\n */\n public function query(Vector $vector, array $options = [], ?float $minScore = null): array\n {\n $payload = [\n 'vector' => $vector->getData(),\n 'with_payload' => true,\n 'with_vector' => true,\n ];\n\n if (\\array_key_exists('limit', $options)) {\n $payload['limit'] = $options['limit'];\n }\n\n if (\\array_key_exists('offset', $options)) {\n $payload['offset'] = $options['offset'];\n }\n\n $response = $this->request('POST', \\sprintf('collections/%s/points/query', $this->collectionName), $payload);\n\n return array_map($this->convertToVectorDocument(...), $response['result']['points']);\n }\n\n public function initialize(array $options = []): void\n {\n if ([] !== $options) {\n throw new InvalidArgumentException('No supported options');\n }\n\n $collectionExistResponse = $this->request('GET', \\sprintf('collections/%s/exists', $this->collectionName));\n\n if ($collectionExistResponse['result']['exists']) {\n return;\n }\n\n $this->request('PUT', \\sprintf('collections/%s', $this->collectionName), [\n 'vectors' => [\n 'size' => $this->embeddingsDimension,\n 'distance' => $this->embeddingsDistance,\n ],\n ]);\n }\n\n /**\n * @param array $payload\n *\n * @return array\n */\n private function request(string $method, string $endpoint, array $payload = []): array\n {\n $url = \\sprintf('%s/%s', $this->endpointUrl, $endpoint);\n\n $response = $this->httpClient->request($method, $url, [\n 'headers' => [\n 'api-key' => $this->apiKey,\n ],\n 'json' => $payload,\n ]);\n\n return $response->toArray();\n }\n\n /**\n * @return array\n */\n private function convertToIndexableArray(VectorDocument $document): array\n {\n return [\n 'id' => $document->id->toRfc4122(),\n 'vector' => $document->vector->getData(),\n 'payload' => $document->metadata->getArrayCopy(),\n ];\n }\n\n /**\n * @param array $data\n */\n private function convertToVectorDocument(array $data): VectorDocument\n {\n $id = $data['id'] ?? throw new InvalidArgumentException('Missing \"id\" field in the document data');\n\n $vector = !\\array_key_exists('vector', $data) || null === $data['vector']\n ? new NullVector()\n : new Vector($data['vector']);\n\n return new VectorDocument(\n id: Uuid::fromString($id),\n vector: $vector,\n metadata: new Metadata($data['payload']),\n score: $data['score'] ?? null\n );\n }\n}\n"], ["/ai/src/store/src/Bridge/SurrealDB/Store.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Bridge\\SurrealDB;\n\nuse Symfony\\AI\\Platform\\Vector\\NullVector;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\nuse Symfony\\AI\\Store\\Document\\Metadata;\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\nuse Symfony\\AI\\Store\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Store\\Exception\\RuntimeException;\nuse Symfony\\AI\\Store\\InitializableStoreInterface;\nuse Symfony\\AI\\Store\\VectorStoreInterface;\nuse Symfony\\Component\\Uid\\Uuid;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Guillaume Loulier \n */\nfinal class Store implements InitializableStoreInterface, VectorStoreInterface\n{\n private string $authenticationToken = '';\n\n public function __construct(\n private readonly HttpClientInterface $httpClient,\n private readonly string $endpointUrl,\n #[\\SensitiveParameter] private readonly string $user,\n #[\\SensitiveParameter] private readonly string $password,\n #[\\SensitiveParameter] private readonly string $namespace,\n #[\\SensitiveParameter] private readonly string $database,\n private readonly string $table = 'vectors',\n private readonly string $vectorFieldName = '_vectors',\n private readonly string $strategy = 'cosine',\n private readonly int $embeddingsDimension = 1536,\n private readonly bool $isNamespacedUser = false,\n ) {\n }\n\n public function add(VectorDocument ...$documents): void\n {\n foreach ($documents as $document) {\n $this->request('POST', \\sprintf('key/%s', $this->table), $this->convertToIndexableArray($document));\n }\n }\n\n public function query(Vector $vector, array $options = [], ?float $minScore = null): array\n {\n $vectors = json_encode($vector->getData());\n\n $results = $this->request('POST', 'sql', \\sprintf(\n 'SELECT id, %s, _metadata, vector::similarity::%s(%s, %s) AS distance FROM %s WHERE %s <|2|> %s;',\n $this->vectorFieldName, $this->strategy, $this->vectorFieldName, $vectors, $this->table, $this->vectorFieldName, $vectors,\n ));\n\n return array_map($this->convertToVectorDocument(...), $results[0]['result']);\n }\n\n public function initialize(array $options = []): void\n {\n $this->authenticate();\n\n $this->request('POST', 'sql', \\sprintf(\n 'DEFINE INDEX %s_vectors ON %s FIELDS %s MTREE DIMENSION %d DIST %s TYPE F32',\n $this->table, $this->table, $this->vectorFieldName, $this->embeddingsDimension, $this->strategy\n ));\n }\n\n /**\n * @param array|string $payload\n *\n * @return array\n */\n private function request(string $method, string $endpoint, array|string $payload): array\n {\n $url = \\sprintf('%s/%s', $this->endpointUrl, $endpoint);\n\n $finalPayload = [\n 'json' => $payload,\n ];\n\n if (\\is_string($payload)) {\n $finalPayload = [\n 'body' => $payload,\n ];\n }\n\n $response = $this->httpClient->request($method, $url, array_merge($finalPayload, [\n 'headers' => [\n 'Accept' => 'application/json',\n 'Content-Type' => 'application/json',\n 'Surreal-NS' => $this->namespace,\n 'Surreal-DB' => $this->database,\n 'Authorization' => \\sprintf('Bearer %s', $this->authenticationToken),\n ],\n ]));\n\n return $response->toArray();\n }\n\n /**\n * @return array\n */\n private function convertToIndexableArray(VectorDocument $document): array\n {\n return [\n 'id' => $document->id->toRfc4122(),\n $this->vectorFieldName => $document->vector->getData(),\n '_metadata' => array_merge($document->metadata->getArrayCopy(), [\n '_id' => $document->id->toRfc4122(),\n ]),\n ];\n }\n\n /**\n * @param array $data\n */\n private function convertToVectorDocument(array $data): VectorDocument\n {\n $id = $data['_metadata']['_id'] ?? throw new InvalidArgumentException('Missing \"id\" field in the document data');\n\n $vector = !\\array_key_exists($this->vectorFieldName, $data) || null === $data[$this->vectorFieldName]\n ? new NullVector()\n : new Vector($data[$this->vectorFieldName]);\n\n unset($data['_metadata']['_id']);\n\n return new VectorDocument(\n id: Uuid::fromString($id),\n vector: $vector,\n metadata: new Metadata($data['_metadata']),\n );\n }\n\n private function authenticate(): void\n {\n if ('' !== $this->authenticationToken) {\n return;\n }\n\n $authenticationPayload = [\n 'user' => $this->user,\n 'pass' => $this->password,\n ];\n\n if ($this->isNamespacedUser) {\n $authenticationPayload['ns'] = $this->namespace;\n $authenticationPayload['db'] = $this->database;\n }\n\n $authenticationResponse = $this->httpClient->request('POST', \\sprintf('%s/signin', $this->endpointUrl), [\n 'headers' => [\n 'Accept' => 'application/json',\n ],\n 'json' => $authenticationPayload,\n ]);\n\n $payload = $authenticationResponse->toArray();\n\n if (!\\array_key_exists('token', $payload)) {\n throw new RuntimeException('The SurrealDB authentication response does not contain a token.');\n }\n\n $this->authenticationToken = $payload['token'];\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/GPT/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\GPT;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\GPT;\nuse Symfony\\AI\\Platform\\Exception\\ContentFilterException;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\Choice;\nuse Symfony\\AI\\Platform\\Result\\ChoiceResult;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\Result\\StreamResult;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Result\\ToolCallResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface as PlatformResponseConverter;\nuse Symfony\\Component\\HttpClient\\Chunk\\ServerSentEvent;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Component\\HttpClient\\Exception\\JsonException;\nuse Symfony\\Contracts\\HttpClient\\ResponseInterface as HttpResponse;\n\n/**\n * @author Christopher Hertel \n * @author Denis Zunke \n */\nfinal class ResultConverter implements PlatformResponseConverter\n{\n public function supports(Model $model): bool\n {\n return $model instanceof GPT;\n }\n\n public function convert(RawResultInterface|RawHttpResult $result, array $options = []): ResultInterface\n {\n if ($options['stream'] ?? false) {\n return new StreamResult($this->convertStream($result->getObject()));\n }\n\n $data = $result->getData();\n\n if (isset($data['error']['code']) && 'content_filter' === $data['error']['code']) {\n throw new ContentFilterException($data['error']['message']);\n }\n\n if (!isset($data['choices'])) {\n throw new RuntimeException('Response does not contain choices');\n }\n\n /** @var Choice[] $choices */\n $choices = array_map($this->convertChoice(...), $data['choices']);\n\n if (1 !== \\count($choices)) {\n return new ChoiceResult(...$choices);\n }\n\n if ($choices[0]->hasToolCall()) {\n return new ToolCallResult(...$choices[0]->getToolCalls());\n }\n\n return new TextResult($choices[0]->getContent());\n }\n\n private function convertStream(HttpResponse $result): \\Generator\n {\n $toolCalls = [];\n foreach ((new EventSourceHttpClient())->stream($result) as $chunk) {\n if (!$chunk instanceof ServerSentEvent || '[DONE]' === $chunk->getData()) {\n continue;\n }\n\n try {\n $data = $chunk->getArrayData();\n } catch (JsonException) {\n // try catch only needed for Symfony 6.4\n continue;\n }\n\n if ($this->streamIsToolCall($data)) {\n $toolCalls = $this->convertStreamToToolCalls($toolCalls, $data);\n }\n\n if ([] !== $toolCalls && $this->isToolCallsStreamFinished($data)) {\n yield new ToolCallResult(...array_map($this->convertToolCall(...), $toolCalls));\n }\n\n if (!isset($data['choices'][0]['delta']['content'])) {\n continue;\n }\n\n yield $data['choices'][0]['delta']['content'];\n }\n }\n\n /**\n * @param array $toolCalls\n * @param array $data\n *\n * @return array\n */\n private function convertStreamToToolCalls(array $toolCalls, array $data): array\n {\n if (!isset($data['choices'][0]['delta']['tool_calls'])) {\n return $toolCalls;\n }\n\n foreach ($data['choices'][0]['delta']['tool_calls'] as $i => $toolCall) {\n if (isset($toolCall['id'])) {\n // initialize tool call\n $toolCalls[$i] = [\n 'id' => $toolCall['id'],\n 'function' => $toolCall['function'],\n ];\n continue;\n }\n\n // add arguments delta to tool call\n $toolCalls[$i]['function']['arguments'] .= $toolCall['function']['arguments'];\n }\n\n return $toolCalls;\n }\n\n /**\n * @param array $data\n */\n private function streamIsToolCall(array $data): bool\n {\n return isset($data['choices'][0]['delta']['tool_calls']);\n }\n\n /**\n * @param array $data\n */\n private function isToolCallsStreamFinished(array $data): bool\n {\n return isset($data['choices'][0]['finish_reason']) && 'tool_calls' === $data['choices'][0]['finish_reason'];\n }\n\n /**\n * @param array{\n * index: integer,\n * message: array{\n * role: 'assistant',\n * content: ?string,\n * tool_calls: array{\n * id: string,\n * type: 'function',\n * function: array{\n * name: string,\n * arguments: string\n * },\n * },\n * refusal: ?mixed\n * },\n * logprobs: string,\n * finish_reason: 'stop'|'length'|'tool_calls'|'content_filter',\n * } $choice\n */\n private function convertChoice(array $choice): Choice\n {\n if ('tool_calls' === $choice['finish_reason']) {\n return new Choice(toolCalls: array_map([$this, 'convertToolCall'], $choice['message']['tool_calls']));\n }\n\n if (\\in_array($choice['finish_reason'], ['stop', 'length'], true)) {\n return new Choice($choice['message']['content']);\n }\n\n throw new RuntimeException(\\sprintf('Unsupported finish reason \"%s\".', $choice['finish_reason']));\n }\n\n /**\n * @param array{\n * id: string,\n * type: 'function',\n * function: array{\n * name: string,\n * arguments: string\n * }\n * } $toolCall\n */\n private function convertToolCall(array $toolCall): ToolCall\n {\n $arguments = json_decode($toolCall['function']['arguments'], true, \\JSON_THROW_ON_ERROR);\n\n return new ToolCall($toolCall['id'], $toolCall['function']['name'], $arguments);\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/Whisper/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface as BaseModelClient;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ModelClient implements BaseModelClient\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n #[\\SensitiveParameter]\n private string $apiKey,\n ) {\n '' !== $apiKey || throw new InvalidArgumentException('The API key must not be empty.');\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Whisper;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n $task = $options['task'] ?? Task::TRANSCRIPTION;\n $endpoint = Task::TRANSCRIPTION === $task ? 'transcriptions' : 'translations';\n unset($options['task']);\n\n return new RawHttpResult($this->httpClient->request('POST', \\sprintf('https://api.openai.com/v1/audio/%s', $endpoint), [\n 'auth_bearer' => $this->apiKey,\n 'headers' => ['Content-Type' => 'multipart/form-data'],\n 'body' => array_merge($options, $payload, ['model' => $model->getName()]),\n ]));\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/Anthropic/ClaudeModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock\\Anthropic;\n\nuse AsyncAws\\BedrockRuntime\\BedrockRuntimeClient;\nuse AsyncAws\\BedrockRuntime\\Input\\InvokeModelRequest;\nuse AsyncAws\\BedrockRuntime\\Result\\InvokeModelResponse;\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\Claude;\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\RawBedrockResult;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Result\\ToolCallResult;\n\n/**\n * @author Björn Altmann\n */\nfinal readonly class ClaudeModelClient implements ModelClientInterface\n{\n public function __construct(\n private BedrockRuntimeClient $bedrockRuntimeClient,\n private string $version = '2023-05-31',\n ) {\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Claude;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawBedrockResult\n {\n unset($payload['model']);\n\n if (isset($options['tools'])) {\n $options['tool_choice'] = ['type' => 'auto'];\n }\n\n if (!isset($options['anthropic_version'])) {\n $options['anthropic_version'] = 'bedrock-'.$this->version;\n }\n\n $request = [\n 'modelId' => $this->getModelId($model),\n 'contentType' => 'application/json',\n 'body' => json_encode(array_merge($options, $payload), \\JSON_THROW_ON_ERROR),\n ];\n\n return new RawBedrockResult($this->bedrockRuntimeClient->invokeModel(new InvokeModelRequest($request)));\n }\n\n public function convert(InvokeModelResponse $bedrockResponse): ToolCallResult|TextResult\n {\n $data = json_decode($bedrockResponse->getBody(), true, 512, \\JSON_THROW_ON_ERROR);\n\n if (!isset($data['content']) || [] === $data['content']) {\n throw new RuntimeException('Response does not contain any content');\n }\n\n if (!isset($data['content'][0]['text']) && !isset($data['content'][0]['type'])) {\n throw new RuntimeException('Response content does not contain any text or type');\n }\n\n $toolCalls = [];\n foreach ($data['content'] as $content) {\n if ('tool_use' === $content['type']) {\n $toolCalls[] = new ToolCall($content['id'], $content['name'], $content['input']);\n }\n }\n if ([] !== $toolCalls) {\n return new ToolCallResult(...$toolCalls);\n }\n\n return new TextResult($data['content'][0]['text']);\n }\n\n private function getModelId(Model $model): string\n {\n $configuredRegion = $this->bedrockRuntimeClient->getConfiguration()->get('region');\n $regionPrefix = substr((string) $configuredRegion, 0, 2);\n\n return $regionPrefix.'.anthropic.'.$model->getName().'-v1:0';\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/JsonRpcHandler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server;\n\nuse Psr\\Log\\LoggerInterface;\nuse Psr\\Log\\NullLogger;\nuse Symfony\\AI\\McpSdk\\Exception\\ExceptionInterface;\nuse Symfony\\AI\\McpSdk\\Exception\\HandlerNotFoundException;\nuse Symfony\\AI\\McpSdk\\Exception\\InvalidInputMessageException;\nuse Symfony\\AI\\McpSdk\\Exception\\NotFoundExceptionInterface;\nuse Symfony\\AI\\McpSdk\\Message\\Error;\nuse Symfony\\AI\\McpSdk\\Message\\Factory;\nuse Symfony\\AI\\McpSdk\\Message\\Notification;\nuse Symfony\\AI\\McpSdk\\Message\\Request;\nuse Symfony\\AI\\McpSdk\\Message\\Response;\n\n/**\n * @final\n */\nreadonly class JsonRpcHandler\n{\n /**\n * @var array\n */\n private array $requestHandlers;\n\n /**\n * @var array\n */\n private array $notificationHandlers;\n\n /**\n * @param iterable $requestHandlers\n * @param iterable $notificationHandlers\n */\n public function __construct(\n private Factory $messageFactory,\n iterable $requestHandlers,\n iterable $notificationHandlers,\n private LoggerInterface $logger = new NullLogger(),\n ) {\n $this->requestHandlers = $requestHandlers instanceof \\Traversable ? iterator_to_array($requestHandlers) : $requestHandlers;\n $this->notificationHandlers = $notificationHandlers instanceof \\Traversable ? iterator_to_array($notificationHandlers) : $notificationHandlers;\n }\n\n /**\n * @return iterable\n *\n * @throws ExceptionInterface When a handler throws an exception during message processing\n * @throws \\JsonException When JSON encoding of the response fails\n */\n public function process(string $input): iterable\n {\n $this->logger->info('Received message to process', ['message' => $input]);\n\n try {\n $messages = $this->messageFactory->create($input);\n } catch (\\JsonException $e) {\n $this->logger->warning('Failed to decode json message', ['exception' => $e]);\n\n yield $this->encodeResponse(Error::parseError($e->getMessage()));\n\n return;\n }\n\n foreach ($messages as $message) {\n if ($message instanceof InvalidInputMessageException) {\n $this->logger->warning('Failed to create message', ['exception' => $message]);\n yield $this->encodeResponse(Error::invalidRequest(0, $message->getMessage()));\n continue;\n }\n\n $this->logger->info('Decoded incoming message', ['message' => $message]);\n\n try {\n yield $message instanceof Notification\n ? $this->handleNotification($message)\n : $this->encodeResponse($this->handleRequest($message));\n } catch (\\DomainException) {\n yield null;\n } catch (NotFoundExceptionInterface $e) {\n $this->logger->warning(\\sprintf('Failed to create response: %s', $e->getMessage()), ['exception' => $e]);\n\n yield $this->encodeResponse(Error::methodNotFound($message->id, $e->getMessage()));\n } catch (\\InvalidArgumentException $e) {\n $this->logger->warning(\\sprintf('Invalid argument: %s', $e->getMessage()), ['exception' => $e]);\n\n yield $this->encodeResponse(Error::invalidParams($message->id, $e->getMessage()));\n } catch (\\Throwable $e) {\n $this->logger->critical(\\sprintf('Uncaught exception: %s', $e->getMessage()), ['exception' => $e]);\n\n yield $this->encodeResponse(Error::internalError($message->id, $e->getMessage()));\n }\n }\n }\n\n /**\n * @throws \\JsonException When JSON encoding fails\n */\n private function encodeResponse(Response|Error|null $response): ?string\n {\n if (null === $response) {\n $this->logger->warning('Response is null');\n\n return null;\n }\n\n $this->logger->info('Encoding response', ['response' => $response]);\n\n if ($response instanceof Response && [] === $response->result) {\n return json_encode($response, \\JSON_THROW_ON_ERROR | \\JSON_FORCE_OBJECT);\n }\n\n return json_encode($response, \\JSON_THROW_ON_ERROR);\n }\n\n /**\n * @throws ExceptionInterface When a notification handler throws an exception\n */\n private function handleNotification(Notification $notification): null\n {\n $handled = false;\n foreach ($this->notificationHandlers as $handler) {\n if ($handler->supports($notification)) {\n $handler->handle($notification);\n $handled = true;\n }\n }\n\n if (!$handled) {\n $this->logger->warning(\\sprintf('No handler found for \"%s\".', $notification->method), ['notification' => $notification]);\n }\n\n return null;\n }\n\n /**\n * @throws NotFoundExceptionInterface When no handler is found for the request method\n * @throws ExceptionInterface When a request handler throws an exception\n */\n private function handleRequest(Request $request): Response|Error\n {\n foreach ($this->requestHandlers as $handler) {\n if ($handler->supports($request)) {\n return $handler->createResponse($request);\n }\n }\n\n throw new HandlerNotFoundException(\\sprintf('No handler found for method \"%s\".', $request->method));\n }\n}\n"], ["/ai/src/platform/src/Bridge/Mistral/Llm/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Mistral\\Llm;\n\nuse Symfony\\AI\\Platform\\Bridge\\Mistral\\Mistral;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\Choice;\nuse Symfony\\AI\\Platform\\Result\\ChoiceResult;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\Result\\StreamResult;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Result\\ToolCallResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\nuse Symfony\\Component\\HttpClient\\Chunk\\ServerSentEvent;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Component\\HttpClient\\Exception\\JsonException;\nuse Symfony\\Contracts\\HttpClient\\ResponseInterface as HttpResponse;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Mistral;\n }\n\n /**\n * @param array $options\n */\n public function convert(RawResultInterface|RawHttpResult $result, array $options = []): ResultInterface\n {\n $httpResponse = $result->getObject();\n\n if ($options['stream'] ?? false) {\n return new StreamResult($this->convertStream($httpResponse));\n }\n\n if (200 !== $code = $httpResponse->getStatusCode()) {\n throw new RuntimeException(\\sprintf('Unexpected response code %d: %s', $code, $httpResponse->getContent(false)));\n }\n\n $data = $result->getData();\n\n if (!isset($data['choices'])) {\n throw new RuntimeException('Response does not contain choices');\n }\n\n /** @var Choice[] $choices */\n $choices = array_map($this->convertChoice(...), $data['choices']);\n\n if (1 !== \\count($choices)) {\n return new ChoiceResult(...$choices);\n }\n\n if ($choices[0]->hasToolCall()) {\n return new ToolCallResult(...$choices[0]->getToolCalls());\n }\n\n return new TextResult($choices[0]->getContent());\n }\n\n private function convertStream(HttpResponse $result): \\Generator\n {\n $toolCalls = [];\n foreach ((new EventSourceHttpClient())->stream($result) as $chunk) {\n if (!$chunk instanceof ServerSentEvent || '[DONE]' === $chunk->getData()) {\n continue;\n }\n\n try {\n $data = $chunk->getArrayData();\n } catch (JsonException) {\n // try catch only needed for Symfony 6.4\n continue;\n }\n\n if ($this->streamIsToolCall($data)) {\n $toolCalls = $this->convertStreamToToolCalls($toolCalls, $data);\n }\n\n if ([] !== $toolCalls && $this->isToolCallsStreamFinished($data)) {\n yield new ToolCallResult(...array_map($this->convertToolCall(...), $toolCalls));\n }\n\n if (!isset($data['choices'][0]['delta']['content'])) {\n continue;\n }\n\n yield $data['choices'][0]['delta']['content'];\n }\n }\n\n /**\n * @param array $toolCalls\n * @param array $data\n *\n * @return array\n */\n private function convertStreamToToolCalls(array $toolCalls, array $data): array\n {\n if (!isset($data['choices'][0]['delta']['tool_calls'])) {\n return $toolCalls;\n }\n\n foreach ($data['choices'][0]['delta']['tool_calls'] as $i => $toolCall) {\n if (isset($toolCall['id'])) {\n // initialize tool call\n $toolCalls[$i] = [\n 'id' => $toolCall['id'],\n 'function' => $toolCall['function'],\n ];\n continue;\n }\n\n // add arguments delta to tool call\n $toolCalls[$i]['function']['arguments'] .= $toolCall['function']['arguments'];\n }\n\n return $toolCalls;\n }\n\n /**\n * @param array $data\n */\n private function streamIsToolCall(array $data): bool\n {\n return isset($data['choices'][0]['delta']['tool_calls']);\n }\n\n /**\n * @param array $data\n */\n private function isToolCallsStreamFinished(array $data): bool\n {\n return isset($data['choices'][0]['finish_reason']) && 'tool_calls' === $data['choices'][0]['finish_reason'];\n }\n\n /**\n * @param array{\n * index: integer,\n * message: array{\n * role: 'assistant',\n * content: ?string,\n * tool_calls: array{\n * id: string,\n * type: 'function',\n * function: array{\n * name: string,\n * arguments: string\n * },\n * },\n * refusal: ?mixed\n * },\n * logprobs: string,\n * finish_reason: 'stop'|'length'|'tool_calls'|'content_filter',\n * } $choice\n */\n private function convertChoice(array $choice): Choice\n {\n if ('tool_calls' === $choice['finish_reason']) {\n return new Choice(toolCalls: array_map([$this, 'convertToolCall'], $choice['message']['tool_calls']));\n }\n\n if ('stop' === $choice['finish_reason']) {\n return new Choice($choice['message']['content']);\n }\n\n throw new RuntimeException(\\sprintf('Unsupported finish reason \"%s\".', $choice['finish_reason']));\n }\n\n /**\n * @param array{\n * id: string,\n * type: 'function',\n * function: array{\n * name: string,\n * arguments: string\n * }\n * } $toolCall\n */\n private function convertToolCall(array $toolCall): ToolCall\n {\n $arguments = json_decode((string) $toolCall['function']['arguments'], true, \\JSON_THROW_ON_ERROR);\n\n return new ToolCall($toolCall['id'], $toolCall['function']['name'], $arguments);\n }\n}\n"], ["/ai/src/ai-bundle/src/AIBundle.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\AIBundle;\n\nuse Symfony\\AI\\Agent\\Agent;\nuse Symfony\\AI\\Agent\\AgentInterface;\nuse Symfony\\AI\\Agent\\InputProcessor\\SystemPromptInputProcessor;\nuse Symfony\\AI\\Agent\\InputProcessorInterface;\nuse Symfony\\AI\\Agent\\OutputProcessorInterface;\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\AI\\Agent\\Toolbox\\FaultTolerantToolbox;\nuse Symfony\\AI\\Agent\\Toolbox\\Tool\\Agent as AgentTool;\nuse Symfony\\AI\\Agent\\Toolbox\\ToolFactory\\ChainFactory;\nuse Symfony\\AI\\Agent\\Toolbox\\ToolFactory\\MemoryToolFactory;\nuse Symfony\\AI\\AIBundle\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\AIBundle\\Profiler\\TraceablePlatform;\nuse Symfony\\AI\\AIBundle\\Profiler\\TraceableToolbox;\nuse Symfony\\AI\\AIBundle\\Security\\Attribute\\IsGrantedTool;\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\PlatformFactory as AnthropicPlatformFactory;\nuse Symfony\\AI\\Platform\\Bridge\\Azure\\OpenAI\\PlatformFactory as AzureOpenAIPlatformFactory;\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\PlatformFactory as GeminiPlatformFactory;\nuse Symfony\\AI\\Platform\\Bridge\\LMStudio\\PlatformFactory as LMStudioPlatformFactory;\nuse Symfony\\AI\\Platform\\Bridge\\Mistral\\PlatformFactory as MistralPlatformFactory;\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\PlatformFactory as OpenAIPlatformFactory;\nuse Symfony\\AI\\Platform\\Bridge\\OpenRouter\\PlatformFactory as OpenRouterPlatformFactory;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\AI\\Platform\\PlatformInterface;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\nuse Symfony\\AI\\Store\\Bridge\\Azure\\SearchStore as AzureSearchStore;\nuse Symfony\\AI\\Store\\Bridge\\ChromaDB\\Store as ChromaDBStore;\nuse Symfony\\AI\\Store\\Bridge\\MongoDB\\Store as MongoDBStore;\nuse Symfony\\AI\\Store\\Bridge\\Pinecone\\Store as PineconeStore;\nuse Symfony\\AI\\Store\\Document\\Vectorizer;\nuse Symfony\\AI\\Store\\Indexer;\nuse Symfony\\AI\\Store\\StoreInterface;\nuse Symfony\\AI\\Store\\VectorStoreInterface;\nuse Symfony\\Component\\Config\\Definition\\Configurator\\DefinitionConfigurator;\nuse Symfony\\Component\\DependencyInjection\\ChildDefinition;\nuse Symfony\\Component\\DependencyInjection\\ContainerBuilder;\nuse Symfony\\Component\\DependencyInjection\\ContainerInterface;\nuse Symfony\\Component\\DependencyInjection\\Definition;\nuse Symfony\\Component\\DependencyInjection\\Loader\\Configurator\\ContainerConfigurator;\nuse Symfony\\Component\\DependencyInjection\\Reference;\nuse Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle;\nuse Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationCheckerInterface;\n\nuse function Symfony\\Component\\String\\u;\n\n/**\n * @author Christopher Hertel \n */\nfinal class AIBundle extends AbstractBundle\n{\n public function configure(DefinitionConfigurator $definition): void\n {\n $definition->import('../config/options.php');\n }\n\n /**\n * @param array $config\n */\n public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void\n {\n $container->import('../config/services.php');\n\n foreach ($config['platform'] ?? [] as $type => $platform) {\n $this->processPlatformConfig($type, $platform, $builder);\n }\n $platforms = array_keys($builder->findTaggedServiceIds('ai.platform'));\n if (1 === \\count($platforms)) {\n $builder->setAlias(PlatformInterface::class, reset($platforms));\n }\n if ($builder->getParameter('kernel.debug')) {\n foreach ($platforms as $platform) {\n $traceablePlatformDefinition = (new Definition(TraceablePlatform::class))\n ->setDecoratedService($platform)\n ->setArguments([new Reference('.inner')])\n ->addTag('ai.traceable_platform');\n $suffix = u($platform)->afterLast('.')->toString();\n $builder->setDefinition('ai.traceable_platform.'.$suffix, $traceablePlatformDefinition);\n }\n }\n\n foreach ($config['agent'] as $agentName => $agent) {\n $this->processAgentConfig($agentName, $agent, $builder);\n }\n if (1 === \\count($config['agent']) && isset($agentName)) {\n $builder->setAlias(AgentInterface::class, 'ai.agent.'.$agentName);\n }\n\n foreach ($config['store'] ?? [] as $type => $store) {\n $this->processStoreConfig($type, $store, $builder);\n }\n $stores = array_keys($builder->findTaggedServiceIds('ai.store'));\n if (1 === \\count($stores)) {\n $builder->setAlias(VectorStoreInterface::class, reset($stores));\n $builder->setAlias(StoreInterface::class, reset($stores));\n }\n\n foreach ($config['indexer'] as $indexerName => $indexer) {\n $this->processIndexerConfig($indexerName, $indexer, $builder);\n }\n if (1 === \\count($config['indexer']) && isset($indexerName)) {\n $builder->setAlias(Indexer::class, 'ai.indexer.'.$indexerName);\n }\n\n $builder->registerAttributeForAutoconfiguration(AsTool::class, static function (ChildDefinition $definition, AsTool $attribute): void {\n $definition->addTag('ai.tool', [\n 'name' => $attribute->name,\n 'description' => $attribute->description,\n 'method' => $attribute->method,\n ]);\n });\n\n $builder->registerForAutoconfiguration(InputProcessorInterface::class)\n ->addTag('ai.agent.input_processor');\n $builder->registerForAutoconfiguration(OutputProcessorInterface::class)\n ->addTag('ai.agent.output_processor');\n $builder->registerForAutoconfiguration(ModelClientInterface::class)\n ->addTag('ai.platform.model_client');\n $builder->registerForAutoconfiguration(ResultConverterInterface::class)\n ->addTag('ai.platform.result_converter');\n\n if (!ContainerBuilder::willBeAvailable('symfony/security-core', AuthorizationCheckerInterface::class, ['symfony/ai-bundle'])) {\n $builder->removeDefinition('ai.security.is_granted_attribute_listener');\n $builder->registerAttributeForAutoconfiguration(\n IsGrantedTool::class,\n static fn () => throw new InvalidArgumentException('Using #[IsGrantedTool] attribute requires additional dependencies. Try running \"composer install symfony/security-core\".'),\n );\n }\n\n if (false === $builder->getParameter('kernel.debug')) {\n $builder->removeDefinition('ai.data_collector');\n $builder->removeDefinition('ai.traceable_toolbox');\n }\n }\n\n /**\n * @param array $platform\n */\n private function processPlatformConfig(string $type, array $platform, ContainerBuilder $container): void\n {\n if ('anthropic' === $type) {\n $platformId = 'ai.platform.anthropic';\n $definition = (new Definition(Platform::class))\n ->setFactory(AnthropicPlatformFactory::class.'::create')\n ->setLazy(true)\n ->addTag('proxy', ['interface' => PlatformInterface::class])\n ->setArguments([\n 0 => $platform['api_key'],\n 2 => new Reference('http_client', ContainerInterface::NULL_ON_INVALID_REFERENCE),\n 3 => new Reference('ai.platform.contract.anthropic'),\n ])\n ->addTag('ai.platform');\n\n if (isset($platform['version'])) {\n $definition->setArgument(1, $platform['version']);\n }\n\n $container->setDefinition($platformId, $definition);\n\n return;\n }\n\n if ('azure' === $type) {\n foreach ($platform as $name => $config) {\n $platformId = 'ai.platform.azure.'.$name;\n $definition = (new Definition(Platform::class))\n ->setFactory(AzureOpenAIPlatformFactory::class.'::create')\n ->setLazy(true)\n ->addTag('proxy', ['interface' => PlatformInterface::class])\n ->setArguments([\n $config['base_url'],\n $config['deployment'],\n $config['api_version'],\n $config['api_key'],\n new Reference('http_client', ContainerInterface::NULL_ON_INVALID_REFERENCE),\n new Reference('ai.platform.contract.default'),\n ])\n ->addTag('ai.platform');\n\n $container->setDefinition($platformId, $definition);\n }\n\n return;\n }\n\n if ('gemini' === $type) {\n $platformId = 'ai.platform.gemini';\n $definition = (new Definition(Platform::class))\n ->setFactory(GeminiPlatformFactory::class.'::create')\n ->setLazy(true)\n ->addTag('proxy', ['interface' => PlatformInterface::class])\n ->setArguments([\n $platform['api_key'],\n new Reference('http_client', ContainerInterface::NULL_ON_INVALID_REFERENCE),\n new Reference('ai.platform.contract.google'),\n ])\n ->addTag('ai.platform');\n\n $container->setDefinition($platformId, $definition);\n\n return;\n }\n\n if ('openai' === $type) {\n $platformId = 'ai.platform.openai';\n $definition = (new Definition(Platform::class))\n ->setFactory(OpenAIPlatformFactory::class.'::create')\n ->setLazy(true)\n ->addTag('proxy', ['interface' => PlatformInterface::class])\n ->setArguments([\n $platform['api_key'],\n new Reference('http_client', ContainerInterface::NULL_ON_INVALID_REFERENCE),\n new Reference('ai.platform.contract.openai'),\n ])\n ->addTag('ai.platform');\n\n $container->setDefinition($platformId, $definition);\n\n return;\n }\n\n if ('openrouter' === $type) {\n $platformId = 'ai.platform.openrouter';\n $definition = (new Definition(Platform::class))\n ->setFactory(OpenRouterPlatformFactory::class.'::create')\n ->setLazy(true)\n ->addTag('proxy', ['interface' => PlatformInterface::class])\n ->setArguments([\n $platform['api_key'],\n new Reference('http_client', ContainerInterface::NULL_ON_INVALID_REFERENCE),\n new Reference('ai.platform.contract.default'),\n ])\n ->addTag('ai.platform');\n\n $container->setDefinition($platformId, $definition);\n\n return;\n }\n\n if ('mistral' === $type) {\n $platformId = 'ai.platform.mistral';\n $definition = (new Definition(Platform::class))\n ->setFactory(MistralPlatformFactory::class.'::create')\n ->setLazy(true)\n ->addTag('proxy', ['interface' => PlatformInterface::class])\n ->setArguments([\n $platform['api_key'],\n new Reference('http_client', ContainerInterface::NULL_ON_INVALID_REFERENCE),\n new Reference('ai.platform.contract.default'),\n ])\n ->addTag('ai.platform');\n\n $container->setDefinition($platformId, $definition);\n\n return;\n }\n\n if ('lmstudio' === $type) {\n $platformId = 'symfony_ai.platform.lmstudio';\n $definition = (new Definition(Platform::class))\n ->setFactory(LMStudioPlatformFactory::class.'::create')\n ->setLazy(true)\n ->addTag('proxy', ['interface' => PlatformInterface::class])\n ->setArguments([\n $platform['host_url'],\n new Reference('http_client', ContainerInterface::NULL_ON_INVALID_REFERENCE),\n new Reference('ai.platform.contract.default'),\n ])\n ->addTag('symfony_ai.platform');\n\n $container->setDefinition($platformId, $definition);\n\n return;\n }\n\n throw new InvalidArgumentException(\\sprintf('Platform \"%s\" is not supported for configuration via bundle at this point.', $type));\n }\n\n /**\n * @param array $config\n */\n private function processAgentConfig(string $name, array $config, ContainerBuilder $container): void\n {\n // MODEL\n ['class' => $modelClass, 'name' => $modelName, 'options' => $options] = $config['model'];\n\n if (!is_a($modelClass, Model::class, true)) {\n throw new InvalidArgumentException(\\sprintf('\"%s\" class is not extending Symfony\\AI\\Platform\\Model.', $modelClass));\n }\n\n $modelDefinition = new Definition($modelClass);\n if (null !== $modelName) {\n $modelDefinition->setArgument(0, $modelName);\n }\n if ([] !== $options) {\n $modelDefinition->setArgument(1, $options);\n }\n $modelDefinition->addTag('ai.model.language_model');\n $container->setDefinition('ai.agent.'.$name.'.model', $modelDefinition);\n\n // AGENT\n $agentDefinition = (new Definition(Agent::class))\n ->setArgument(0, new Reference($config['platform']))\n ->setArgument(1, new Reference('ai.agent.'.$name.'.model'));\n\n $inputProcessors = [];\n $outputProcessors = [];\n\n // TOOL & PROCESSOR\n if ($config['tools']['enabled']) {\n // Create specific toolbox and process if tools are explicitly defined\n if ([] !== $config['tools']['services']) {\n $memoryFactoryDefinition = new ChildDefinition('ai.tool_factory.abstract');\n $memoryFactoryDefinition->setClass(MemoryToolFactory::class);\n $container->setDefinition('ai.toolbox.'.$name.'.memory_factory', $memoryFactoryDefinition);\n $chainFactoryDefinition = new Definition(ChainFactory::class, [\n [new Reference('ai.toolbox.'.$name.'.memory_factory'), new Reference('ai.tool_factory')],\n ]);\n $container->setDefinition('ai.toolbox.'.$name.'.chain_factory', $chainFactoryDefinition);\n\n $tools = [];\n foreach ($config['tools']['services'] as $tool) {\n if (isset($tool['agent'])) {\n $tool['name'] ??= $tool['agent'];\n $tool['service'] = \\sprintf('ai.agent.%s', $tool['agent']);\n }\n $reference = new Reference($tool['service']);\n // We use the memory factory in case method, description and name are set\n if (isset($tool['name'], $tool['description'])) {\n if (isset($tool['agent'])) {\n $agentWrapperDefinition = new Definition(AgentTool::class, [$reference]);\n $container->setDefinition('ai.toolbox.'.$name.'.agent_wrapper.'.$tool['name'], $agentWrapperDefinition);\n $reference = new Reference('ai.toolbox.'.$name.'.agent_wrapper.'.$tool['name']);\n }\n $memoryFactoryDefinition->addMethodCall('addTool', [$reference, $tool['name'], $tool['description'], $tool['method'] ?? '__invoke']);\n }\n $tools[] = $reference;\n }\n\n $toolboxDefinition = (new ChildDefinition('ai.toolbox.abstract'))\n ->replaceArgument(0, $tools)\n ->replaceArgument(1, new Reference('ai.toolbox.'.$name.'.chain_factory'));\n $container->setDefinition('ai.toolbox.'.$name, $toolboxDefinition);\n\n if ($config['fault_tolerant_toolbox']) {\n $faultTolerantToolboxDefinition = (new Definition('ai.fault_tolerant_toolbox.'.$name))\n ->setClass(FaultTolerantToolbox::class)\n ->setArguments([new Reference('.inner')])\n ->setDecoratedService('ai.toolbox.'.$name);\n $container->setDefinition('ai.fault_tolerant_toolbox.'.$name, $faultTolerantToolboxDefinition);\n }\n\n if ($container->getParameter('kernel.debug')) {\n $traceableToolboxDefinition = (new Definition('ai.traceable_toolbox.'.$name))\n ->setClass(TraceableToolbox::class)\n ->setArguments([new Reference('.inner')])\n ->setDecoratedService('ai.toolbox.'.$name)\n ->addTag('ai.traceable_toolbox');\n $container->setDefinition('ai.traceable_toolbox.'.$name, $traceableToolboxDefinition);\n }\n\n $toolProcessorDefinition = (new ChildDefinition('ai.tool.agent_processor.abstract'))\n ->replaceArgument(0, new Reference('ai.toolbox.'.$name));\n $container->setDefinition('ai.tool.agent_processor.'.$name, $toolProcessorDefinition);\n\n $inputProcessors[] = new Reference('ai.tool.agent_processor.'.$name);\n $outputProcessors[] = new Reference('ai.tool.agent_processor.'.$name);\n } else {\n $inputProcessors[] = new Reference('ai.tool.agent_processor');\n $outputProcessors[] = new Reference('ai.tool.agent_processor');\n }\n }\n\n // STRUCTURED OUTPUT\n if ($config['structured_output']) {\n $inputProcessors[] = new Reference('ai.agent.structured_output_processor');\n $outputProcessors[] = new Reference('ai.agent.structured_output_processor');\n }\n\n // SYSTEM PROMPT\n if (\\is_string($config['system_prompt'])) {\n $systemPromptInputProcessorDefinition = new Definition(SystemPromptInputProcessor::class, [\n $config['system_prompt'],\n $config['include_tools'] ? new Reference('ai.toolbox.'.$name) : null,\n new Reference('logger', ContainerInterface::IGNORE_ON_INVALID_REFERENCE),\n ]);\n\n $inputProcessors[] = $systemPromptInputProcessorDefinition;\n }\n\n $agentDefinition\n ->setArgument(2, $inputProcessors)\n ->setArgument(3, $outputProcessors)\n ->setArgument(4, new Reference('logger', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))\n ;\n\n $container->setDefinition('ai.agent.'.$name, $agentDefinition);\n }\n\n /**\n * @param array $stores\n */\n private function processStoreConfig(string $type, array $stores, ContainerBuilder $container): void\n {\n if ('azure_search' === $type) {\n foreach ($stores as $name => $store) {\n $arguments = [\n new Reference('http_client'),\n $store['endpoint'],\n $store['api_key'],\n $store['index_name'],\n $store['api_version'],\n ];\n\n if (\\array_key_exists('vector_field', $store)) {\n $arguments[5] = $store['vector_field'];\n }\n\n $definition = new Definition(AzureSearchStore::class);\n $definition\n ->addTag('ai.store')\n ->setArguments($arguments);\n\n $container->setDefinition('ai.store.'.$type.'.'.$name, $definition);\n }\n }\n\n if ('chroma_db' === $type) {\n foreach ($stores as $name => $store) {\n $definition = new Definition(ChromaDBStore::class);\n $definition\n ->setArguments([\n new Reference($store['client']),\n $store['collection'],\n ])\n ->addTag('ai.store');\n\n $container->setDefinition('ai.store.'.$type.'.'.$name, $definition);\n }\n }\n\n if ('mongodb' === $type) {\n foreach ($stores as $name => $store) {\n $arguments = [\n new Reference($store['client']),\n $store['database'],\n $store['collection'],\n $store['index_name'],\n ];\n\n if (\\array_key_exists('vector_field', $store)) {\n $arguments[4] = $store['vector_field'];\n }\n\n if (\\array_key_exists('bulk_write', $store)) {\n $arguments[5] = $store['bulk_write'];\n }\n\n $definition = new Definition(MongoDBStore::class);\n $definition\n ->addTag('ai.store')\n ->setArguments($arguments);\n\n $container->setDefinition('ai.store.'.$type.'.'.$name, $definition);\n }\n }\n\n if ('pinecone' === $type) {\n foreach ($stores as $name => $store) {\n $arguments = [\n new Reference($store['client']),\n $store['namespace'],\n ];\n\n if (\\array_key_exists('filter', $store)) {\n $arguments[2] = $store['filter'];\n }\n\n if (\\array_key_exists('top_k', $store)) {\n $arguments[3] = $store['top_k'];\n }\n\n $definition = new Definition(PineconeStore::class);\n $definition\n ->addTag('ai.store')\n ->setArguments($arguments);\n\n $container->setDefinition('ai.store.'.$type.'.'.$name, $definition);\n }\n }\n }\n\n /**\n * @param array $config\n */\n private function processIndexerConfig(int|string $name, array $config, ContainerBuilder $container): void\n {\n ['class' => $modelClass, 'name' => $modelName, 'options' => $options] = $config['model'];\n\n if (!is_a($modelClass, Model::class, true)) {\n throw new InvalidArgumentException(\\sprintf('\"%s\" class is not extending Symfony\\AI\\Platform\\Model.', $modelClass));\n }\n\n $modelDefinition = (new Definition((string) $modelClass));\n if (null !== $modelName) {\n $modelDefinition->setArgument(0, $modelName);\n }\n if ([] !== $options) {\n $modelDefinition->setArgument(1, $options);\n }\n\n $modelDefinition->addTag('ai.model.embeddings_model');\n $container->setDefinition('ai.indexer.'.$name.'.model', $modelDefinition);\n\n $vectorizerDefinition = new Definition(Vectorizer::class, [\n new Reference($config['platform']),\n new Reference('ai.indexer.'.$name.'.model'),\n ]);\n $container->setDefinition('ai.indexer.'.$name.'.vectorizer', $vectorizerDefinition);\n\n $definition = new Definition(Indexer::class, [\n new Reference('ai.indexer.'.$name.'.vectorizer'),\n new Reference($config['store']),\n new Reference('logger', ContainerInterface::IGNORE_ON_INVALID_REFERENCE),\n ]);\n\n $container->setDefinition('ai.indexer.'.$name, $definition);\n }\n}\n"], ["/ai/src/store/src/Bridge/Meilisearch/Store.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Bridge\\Meilisearch;\n\nuse Symfony\\AI\\Platform\\Vector\\NullVector;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\nuse Symfony\\AI\\Store\\Document\\Metadata;\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\nuse Symfony\\AI\\Store\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Store\\InitializableStoreInterface;\nuse Symfony\\AI\\Store\\VectorStoreInterface;\nuse Symfony\\Component\\Uid\\Uuid;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Guillaume Loulier \n */\nfinal readonly class Store implements InitializableStoreInterface, VectorStoreInterface\n{\n /**\n * @param string $embedder The name of the embedder where vectors are stored\n * @param string $vectorFieldName The name of the field int the index that contains the vector\n */\n public function __construct(\n private HttpClientInterface $httpClient,\n private string $endpointUrl,\n #[\\SensitiveParameter] private string $apiKey,\n private string $indexName,\n private string $embedder = 'default',\n private string $vectorFieldName = '_vectors',\n private int $embeddingsDimension = 1536,\n ) {\n }\n\n public function add(VectorDocument ...$documents): void\n {\n $this->request('PUT', \\sprintf('indexes/%s/documents', $this->indexName), array_map(\n $this->convertToIndexableArray(...), $documents)\n );\n }\n\n public function query(Vector $vector, array $options = [], ?float $minScore = null): array\n {\n $result = $this->request('POST', \\sprintf('indexes/%s/search', $this->indexName), [\n 'vector' => $vector->getData(),\n 'showRankingScore' => true,\n 'retrieveVectors' => true,\n 'hybrid' => [\n 'embedder' => $this->embedder,\n 'semanticRatio' => 1.0,\n ],\n ]);\n\n return array_map($this->convertToVectorDocument(...), $result['hits']);\n }\n\n public function initialize(array $options = []): void\n {\n if ([] !== $options) {\n throw new InvalidArgumentException('No supported options');\n }\n\n $this->request('POST', 'indexes', [\n 'uid' => $this->indexName,\n 'primaryKey' => 'id',\n ]);\n\n $this->request('PATCH', \\sprintf('indexes/%s/settings', $this->indexName), [\n 'embedders' => [\n $this->embedder => [\n 'source' => 'userProvided',\n 'dimensions' => $this->embeddingsDimension,\n ],\n ],\n ]);\n }\n\n /**\n * @param array $payload\n *\n * @return array\n */\n private function request(string $method, string $endpoint, array $payload): array\n {\n $url = \\sprintf('%s/%s', $this->endpointUrl, $endpoint);\n $result = $this->httpClient->request($method, $url, [\n 'headers' => [\n 'Authorization' => \\sprintf('Bearer %s', $this->apiKey),\n ],\n 'json' => $payload,\n ]);\n\n return $result->toArray();\n }\n\n /**\n * @return array\n */\n private function convertToIndexableArray(VectorDocument $document): array\n {\n return array_merge([\n 'id' => $document->id->toRfc4122(),\n $this->vectorFieldName => [\n $this->embedder => [\n 'embeddings' => $document->vector->getData(),\n 'regenerate' => false,\n ],\n ],\n ], $document->metadata->getArrayCopy());\n }\n\n /**\n * @param array $data\n */\n private function convertToVectorDocument(array $data): VectorDocument\n {\n $id = $data['id'] ?? throw new InvalidArgumentException('Missing \"id\" field in the document data');\n $vector = !\\array_key_exists($this->vectorFieldName, $data) || null === $data[$this->vectorFieldName]\n ? new NullVector() : new Vector($data[$this->vectorFieldName][$this->embedder]['embeddings']);\n $score = $data['_rankingScore'] ?? null;\n\n unset($data['id'], $data[$this->vectorFieldName], $data['_rankingScore']);\n\n return new VectorDocument(Uuid::fromString($id), $vector, new Metadata($data), $score);\n }\n}\n"], ["/ai/src/store/src/Bridge/ChromaDB/Store.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Bridge\\ChromaDB;\n\nuse Codewithkyrian\\ChromaDB\\Client;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\nuse Symfony\\AI\\Store\\Document\\Metadata;\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\nuse Symfony\\AI\\Store\\Exception\\RuntimeException;\nuse Symfony\\AI\\Store\\VectorStoreInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class Store implements VectorStoreInterface\n{\n public function __construct(\n private Client $client,\n private string $collectionName,\n ) {\n if (!class_exists(Client::class)) {\n throw new RuntimeException('For using the ChromaDB as retrieval vector store, the codewithkyrian/chromadb-php package is required. Try running \"composer require codewithkyrian/chromadb-php\".');\n }\n }\n\n public function add(VectorDocument ...$documents): void\n {\n $ids = [];\n $vectors = [];\n $metadata = [];\n foreach ($documents as $document) {\n $ids[] = (string) $document->id;\n $vectors[] = $document->vector->getData();\n $metadata[] = $document->metadata->getArrayCopy();\n }\n\n $collection = $this->client->getOrCreateCollection($this->collectionName);\n $collection->add($ids, $vectors, $metadata);\n }\n\n public function query(Vector $vector, array $options = [], ?float $minScore = null): array\n {\n $collection = $this->client->getOrCreateCollection($this->collectionName);\n $queryResponse = $collection->query(\n queryEmbeddings: [$vector->getData()],\n nResults: 4,\n );\n\n $documents = [];\n for ($i = 0; $i < \\count($queryResponse->metadatas[0]); ++$i) {\n $documents[] = new VectorDocument(\n id: Uuid::fromString($queryResponse->ids[0][$i]),\n vector: new Vector($queryResponse->embeddings[0][$i]),\n metadata: new Metadata($queryResponse->metadatas[0][$i]),\n );\n }\n\n return $documents;\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic;\n\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\Result\\StreamResult;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Result\\ToolCallResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\nuse Symfony\\Component\\HttpClient\\Chunk\\ServerSentEvent;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Component\\HttpClient\\Exception\\JsonException;\nuse Symfony\\Contracts\\HttpClient\\ResponseInterface as HttpResponse;\n\n/**\n * @author Christopher Hertel \n */\nclass ResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Claude;\n }\n\n public function convert(RawHttpResult|RawResultInterface $result, array $options = []): ResultInterface\n {\n if ($options['stream'] ?? false) {\n return new StreamResult($this->convertStream($result->getObject()));\n }\n\n $data = $result->getData();\n\n if (!isset($data['content']) || [] === $data['content']) {\n throw new RuntimeException('Response does not contain any content');\n }\n\n $toolCalls = [];\n foreach ($data['content'] as $content) {\n if ('tool_use' === $content['type']) {\n $toolCalls[] = new ToolCall($content['id'], $content['name'], $content['input']);\n }\n }\n\n if (!isset($data['content'][0]['text']) && [] === $toolCalls) {\n throw new RuntimeException('Response content does not contain any text nor tool calls.');\n }\n\n if ([] !== $toolCalls) {\n return new ToolCallResult(...$toolCalls);\n }\n\n return new TextResult($data['content'][0]['text']);\n }\n\n private function convertStream(HttpResponse $result): \\Generator\n {\n foreach ((new EventSourceHttpClient())->stream($result) as $chunk) {\n if (!$chunk instanceof ServerSentEvent || '[DONE]' === $chunk->getData()) {\n continue;\n }\n\n try {\n $data = $chunk->getArrayData();\n } catch (JsonException) {\n // try catch only needed for Symfony 6.4\n continue;\n }\n\n if ('content_block_delta' != $data['type'] || !isset($data['delta']['text'])) {\n continue;\n }\n\n yield $data['delta']['text'];\n }\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/ResourceChain.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Resource\\CollectionInterface;\nuse Symfony\\AI\\McpSdk\\Capability\\Resource\\IdentifierInterface;\nuse Symfony\\AI\\McpSdk\\Capability\\Resource\\MetadataInterface;\nuse Symfony\\AI\\McpSdk\\Capability\\Resource\\ResourceRead;\nuse Symfony\\AI\\McpSdk\\Capability\\Resource\\ResourceReaderInterface;\nuse Symfony\\AI\\McpSdk\\Capability\\Resource\\ResourceReadResult;\nuse Symfony\\AI\\McpSdk\\Exception\\InvalidCursorException;\nuse Symfony\\AI\\McpSdk\\Exception\\ResourceNotFoundException;\nuse Symfony\\AI\\McpSdk\\Exception\\ResourceReadException;\n\n/**\n * A collection of resources. All resources need to implement IdentifierInterface.\n */\nclass ResourceChain implements CollectionInterface, ResourceReaderInterface\n{\n public function __construct(\n /**\n * @var IdentifierInterface[]\n */\n private readonly array $items,\n ) {\n }\n\n public function getMetadata(int $count, ?string $lastIdentifier = null): iterable\n {\n $found = null === $lastIdentifier;\n foreach ($this->items as $item) {\n if (!$item instanceof MetadataInterface) {\n continue;\n }\n\n if (false === $found) {\n $found = $item->getUri() === $lastIdentifier;\n continue;\n }\n\n yield $item;\n if (--$count <= 0) {\n break;\n }\n }\n\n if (!$found) {\n throw new InvalidCursorException($lastIdentifier);\n }\n }\n\n public function read(ResourceRead $input): ResourceReadResult\n {\n foreach ($this->items as $item) {\n if ($item instanceof ResourceReaderInterface && $input->uri === $item->getUri()) {\n try {\n return $item->read($input);\n } catch (\\Throwable $e) {\n throw new ResourceReadException($input, $e);\n }\n }\n }\n\n throw new ResourceNotFoundException($input);\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/ToolChain.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Tool\\CollectionInterface;\nuse Symfony\\AI\\McpSdk\\Capability\\Tool\\IdentifierInterface;\nuse Symfony\\AI\\McpSdk\\Capability\\Tool\\MetadataInterface;\nuse Symfony\\AI\\McpSdk\\Capability\\Tool\\ToolCall;\nuse Symfony\\AI\\McpSdk\\Capability\\Tool\\ToolCallResult;\nuse Symfony\\AI\\McpSdk\\Capability\\Tool\\ToolExecutorInterface;\nuse Symfony\\AI\\McpSdk\\Exception\\InvalidCursorException;\nuse Symfony\\AI\\McpSdk\\Exception\\ToolExecutionException;\nuse Symfony\\AI\\McpSdk\\Exception\\ToolNotFoundException;\n\n/**\n * A collection of tools. All tools need to implement IdentifierInterface.\n */\nclass ToolChain implements ToolExecutorInterface, CollectionInterface\n{\n public function __construct(\n /**\n * @var IdentifierInterface[] $items\n */\n private readonly iterable $items,\n ) {\n }\n\n public function getMetadata(int $count, ?string $lastIdentifier = null): iterable\n {\n $found = null === $lastIdentifier;\n foreach ($this->items as $item) {\n if (!$item instanceof MetadataInterface) {\n continue;\n }\n\n if (false === $found) {\n $found = $item->getName() === $lastIdentifier;\n continue;\n }\n\n yield $item;\n if (--$count <= 0) {\n break;\n }\n }\n\n if (!$found) {\n throw new InvalidCursorException($lastIdentifier);\n }\n }\n\n public function call(ToolCall $input): ToolCallResult\n {\n foreach ($this->items as $item) {\n if ($item instanceof ToolExecutorInterface && $input->name === $item->getName()) {\n try {\n return $item->call($input);\n } catch (\\Throwable $e) {\n throw new ToolExecutionException($input, $e);\n }\n }\n }\n\n throw new ToolNotFoundException($input);\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/PromptChain.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Prompt\\CollectionInterface;\nuse Symfony\\AI\\McpSdk\\Capability\\Prompt\\IdentifierInterface;\nuse Symfony\\AI\\McpSdk\\Capability\\Prompt\\MetadataInterface;\nuse Symfony\\AI\\McpSdk\\Capability\\Prompt\\PromptGet;\nuse Symfony\\AI\\McpSdk\\Capability\\Prompt\\PromptGetResult;\nuse Symfony\\AI\\McpSdk\\Capability\\Prompt\\PromptGetterInterface;\nuse Symfony\\AI\\McpSdk\\Exception\\InvalidCursorException;\nuse Symfony\\AI\\McpSdk\\Exception\\PromptGetException;\nuse Symfony\\AI\\McpSdk\\Exception\\PromptNotFoundException;\n\n/**\n * A collection of prompts. All prompts need to implement IdentifierInterface.\n */\nclass PromptChain implements PromptGetterInterface, CollectionInterface\n{\n public function __construct(\n /**\n * @var IdentifierInterface[]\n */\n private readonly array $items,\n ) {\n }\n\n public function getMetadata(int $count, ?string $lastIdentifier = null): iterable\n {\n $found = null === $lastIdentifier;\n foreach ($this->items as $item) {\n if (!$item instanceof MetadataInterface) {\n continue;\n }\n\n if (false === $found) {\n $found = $item->getName() === $lastIdentifier;\n continue;\n }\n\n yield $item;\n if (--$count <= 0) {\n break;\n }\n }\n\n if (!$found) {\n throw new InvalidCursorException($lastIdentifier);\n }\n }\n\n public function get(PromptGet $input): PromptGetResult\n {\n foreach ($this->items as $item) {\n if ($item instanceof PromptGetterInterface && $input->name === $item->getName()) {\n try {\n return $item->get($input);\n } catch (\\Throwable $e) {\n throw new PromptGetException($input, $e);\n }\n }\n }\n\n throw new PromptNotFoundException($input);\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace;\n\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface as PlatformModelClient;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ModelClient implements PlatformModelClient\n{\n private EventSourceHttpClient $httpClient;\n\n public function __construct(\n HttpClientInterface $httpClient,\n private string $provider,\n #[\\SensitiveParameter]\n private string $apiKey,\n ) {\n $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n }\n\n public function supports(Model $model): bool\n {\n return true;\n }\n\n /**\n * The difference in HuggingFace here is that we treat the payload as the options for the request not only the body.\n */\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n // Extract task from options if provided\n $task = $options['task'] ?? null;\n unset($options['task']);\n\n return new RawHttpResult($this->httpClient->request('POST', $this->getUrl($model, $task), [\n 'auth_bearer' => $this->apiKey,\n ...$this->getPayload($payload, $options),\n ]));\n }\n\n private function getUrl(Model $model, ?string $task): string\n {\n $endpoint = Task::FEATURE_EXTRACTION === $task ? 'pipeline/feature-extraction' : 'models';\n $url = \\sprintf('https://router.huggingface.co/%s/%s/%s', $this->provider, $endpoint, $model->getName());\n\n if (Task::CHAT_COMPLETION === $task) {\n $url .= '/v1/chat/completions';\n }\n\n return $url;\n }\n\n /**\n * @param array $payload\n * @param array $options\n *\n * @return array\n */\n private function getPayload(array|string $payload, array $options): array\n {\n // Expect JSON input if string or not\n if (\\is_string($payload) || !(isset($payload['body']) || isset($payload['json']))) {\n $payload = ['json' => ['inputs' => $payload]];\n\n if ([] !== $options) {\n $payload['json']['parameters'] = $options;\n }\n }\n\n // Merge options into JSON payload\n if (isset($payload['json'])) {\n $payload['json'] = array_merge($payload['json'], $options);\n }\n\n $payload['headers'] ??= ['Content-Type' => 'application/json'];\n\n return $payload;\n }\n}\n"], ["/ai/src/agent/src/InputProcessor/ModelOverrideInputProcessor.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\InputProcessor;\n\nuse Symfony\\AI\\Agent\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Agent\\Input;\nuse Symfony\\AI\\Agent\\InputProcessorInterface;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ModelOverrideInputProcessor implements InputProcessorInterface\n{\n public function processInput(Input $input): void\n {\n $options = $input->getOptions();\n\n if (!\\array_key_exists('model', $options)) {\n return;\n }\n\n if (!$options['model'] instanceof Model) {\n throw new InvalidArgumentException(\\sprintf('Option \"model\" must be an instance of %s.', Model::class));\n }\n\n $input->model = $options['model'];\n }\n}\n"], ["/ai/src/agent/src/StructuredOutput/AgentProcessor.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\StructuredOutput;\n\nuse Symfony\\AI\\Agent\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Agent\\Exception\\MissingModelSupportException;\nuse Symfony\\AI\\Agent\\Input;\nuse Symfony\\AI\\Agent\\InputProcessorInterface;\nuse Symfony\\AI\\Agent\\Output;\nuse Symfony\\AI\\Agent\\OutputProcessorInterface;\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Result\\ObjectResult;\nuse Symfony\\Component\\PropertyInfo\\Extractor\\PhpDocExtractor;\nuse Symfony\\Component\\PropertyInfo\\PropertyInfoExtractor;\nuse Symfony\\Component\\Serializer\\Encoder\\JsonEncoder;\nuse Symfony\\Component\\Serializer\\Normalizer\\ArrayDenormalizer;\nuse Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer;\nuse Symfony\\Component\\Serializer\\Serializer;\nuse Symfony\\Component\\Serializer\\SerializerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class AgentProcessor implements InputProcessorInterface, OutputProcessorInterface\n{\n private string $outputStructure;\n\n public function __construct(\n private readonly ResponseFormatFactoryInterface $responseFormatFactory = new ResponseFormatFactory(),\n private ?SerializerInterface $serializer = null,\n ) {\n if (null === $this->serializer) {\n $propertyInfo = new PropertyInfoExtractor([], [new PhpDocExtractor()]);\n $normalizers = [new ObjectNormalizer(propertyTypeExtractor: $propertyInfo), new ArrayDenormalizer()];\n $this->serializer = new Serializer($normalizers, [new JsonEncoder()]);\n }\n }\n\n /**\n * @throws MissingModelSupportException When structured output is requested but the model doesn't support it\n * @throws InvalidArgumentException When streaming is enabled with structured output (incompatible options)\n */\n public function processInput(Input $input): void\n {\n $options = $input->getOptions();\n\n if (!isset($options['output_structure'])) {\n return;\n }\n\n if (!$input->model->supports(Capability::OUTPUT_STRUCTURED)) {\n throw MissingModelSupportException::forStructuredOutput($input->model::class);\n }\n\n if (true === ($options['stream'] ?? false)) {\n throw new InvalidArgumentException('Streamed responses are not supported for structured output');\n }\n\n $options['response_format'] = $this->responseFormatFactory->create($options['output_structure']);\n\n $this->outputStructure = $options['output_structure'];\n unset($options['output_structure']);\n\n $input->setOptions($options);\n }\n\n public function processOutput(Output $output): void\n {\n $options = $output->options;\n\n if ($output->result instanceof ObjectResult) {\n return;\n }\n\n if (!isset($options['response_format'])) {\n return;\n }\n\n if (!isset($this->outputStructure)) {\n $output->result = new ObjectResult(json_decode($output->result->getContent(), true));\n\n return;\n }\n\n $originalResult = $output->result;\n $output->result = new ObjectResult(\n $this->serializer->deserialize($output->result->getContent(), $this->outputStructure, 'json')\n );\n\n if ($originalResult->getMetadata()->count() > 0) {\n $output->result->getMetadata()->set($originalResult->getMetadata()->all());\n }\n\n if (!empty($originalResult->getRawResult())) {\n $output->result->setRawResult($originalResult->getRawResult());\n }\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk;\n\nuse Psr\\Log\\LoggerInterface;\nuse Psr\\Log\\NullLogger;\nuse Symfony\\AI\\McpSdk\\Server\\JsonRpcHandler;\nuse Symfony\\AI\\McpSdk\\Server\\TransportInterface;\n\nfinal readonly class Server\n{\n public function __construct(\n private JsonRpcHandler $jsonRpcHandler,\n private LoggerInterface $logger = new NullLogger(),\n ) {\n }\n\n public function connect(TransportInterface $transport): void\n {\n $transport->initialize();\n $this->logger->info('Transport initialized');\n\n while ($transport->isConnected()) {\n foreach ($transport->receive() as $message) {\n if (null === $message) {\n continue;\n }\n\n try {\n foreach ($this->jsonRpcHandler->process($message) as $response) {\n if (null === $response) {\n continue;\n }\n\n $transport->send($response);\n }\n } catch (\\JsonException $e) {\n $this->logger->error('Failed to encode response to JSON', [\n 'message' => $message,\n 'exception' => $e,\n ]);\n continue;\n }\n }\n\n usleep(1000);\n }\n\n $transport->close();\n $this->logger->info('Transport closed');\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/TokenOutputProcessor.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI;\n\nuse Symfony\\AI\\Agent\\Output;\nuse Symfony\\AI\\Agent\\OutputProcessorInterface;\nuse Symfony\\AI\\Platform\\Result\\StreamResult;\nuse Symfony\\Contracts\\HttpClient\\ResponseInterface;\n\n/**\n * @author Denis Zunke \n */\nfinal class TokenOutputProcessor implements OutputProcessorInterface\n{\n public function processOutput(Output $output): void\n {\n if ($output->result instanceof StreamResult) {\n // Streams have to be handled manually as the tokens are part of the streamed chunks\n return;\n }\n\n $rawResponse = $output->result->getRawResult()?->getObject();\n if (!$rawResponse instanceof ResponseInterface) {\n return;\n }\n\n $metadata = $output->result->getMetadata();\n\n $metadata->add(\n 'remaining_tokens',\n (int) $rawResponse->getHeaders(false)['x-ratelimit-remaining-tokens'][0],\n );\n\n $content = $rawResponse->toArray(false);\n\n if (!\\array_key_exists('usage', $content)) {\n return;\n }\n\n $metadata->add('prompt_tokens', $content['usage']['prompt_tokens'] ?? null);\n $metadata->add('completion_tokens', $content['usage']['completion_tokens'] ?? null);\n $metadata->add('total_tokens', $content['usage']['total_tokens'] ?? null);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Contract/ToolNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Gemini;\nuse Symfony\\AI\\Platform\\Contract\\JsonSchema\\Factory;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\n\n/**\n * @author Valtteri R \n *\n * @phpstan-import-type JsonSchema from Factory\n */\nfinal class ToolNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return Tool::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Gemini;\n }\n\n /**\n * @param Tool $data\n *\n * @return array{\n * name: string,\n * description: string,\n * parameters: JsonSchema|array{type: 'object'}\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'description' => $data->description,\n 'name' => $data->name,\n 'parameters' => $data->parameters ? $this->removeAdditionalProperties($data->parameters) : null,\n ];\n }\n\n /**\n * @template T of array\n *\n * @phpstan-param T $data\n *\n * @phpstan-return T\n */\n private function removeAdditionalProperties(array $data): array\n {\n unset($data['additionalProperties']); // not supported by Gemini\n\n foreach ($data as &$value) {\n if (\\is_array($value)) {\n $value = $this->removeAdditionalProperties($value);\n }\n }\n\n return $data;\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/Anthropic/ClaudeResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock\\Anthropic;\n\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\Claude;\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\RawBedrockResult;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Result\\ToolCallResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\n\n/**\n * @author Björn Altmann\n */\nfinal readonly class ClaudeResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Claude;\n }\n\n public function convert(RawResultInterface|RawBedrockResult $result, array $options = []): ToolCallResult|TextResult\n {\n $data = $result->getData();\n\n if (!isset($data['content']) || [] === $data['content']) {\n throw new RuntimeException('Response does not contain any content');\n }\n\n if (!isset($data['content'][0]['text']) && !isset($data['content'][0]['type'])) {\n throw new RuntimeException('Response content does not contain any text or type');\n }\n\n $toolCalls = [];\n foreach ($data['content'] as $content) {\n if ('tool_use' === $content['type']) {\n $toolCalls[] = new ToolCall($content['id'], $content['name'], $content['input']);\n }\n }\n if ([] !== $toolCalls) {\n return new ToolCallResult(...$toolCalls);\n }\n\n return new TextResult($data['content'][0]['text']);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Mistral/TokenOutputProcessor.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Mistral;\n\nuse Symfony\\AI\\Agent\\Output;\nuse Symfony\\AI\\Agent\\OutputProcessorInterface;\nuse Symfony\\AI\\Platform\\Result\\StreamResult;\nuse Symfony\\Contracts\\HttpClient\\ResponseInterface;\n\n/**\n * @author Quentin Fahrner \n */\nfinal class TokenOutputProcessor implements OutputProcessorInterface\n{\n public function processOutput(Output $output): void\n {\n if ($output->result instanceof StreamResult) {\n // Streams have to be handled manually as the tokens are part of the streamed chunks\n return;\n }\n\n $rawResponse = $output->result->getRawResult()?->getObject();\n if (!$rawResponse instanceof ResponseInterface) {\n return;\n }\n\n $metadata = $output->result->getMetadata();\n\n $metadata->add(\n 'remaining_tokens_minute',\n (int) $rawResponse->getHeaders(false)['x-ratelimit-limit-tokens-minute'][0],\n );\n\n $metadata->add(\n 'remaining_tokens_month',\n (int) $rawResponse->getHeaders(false)['x-ratelimit-limit-tokens-month'][0],\n );\n\n $content = $rawResponse->toArray(false);\n\n if (!\\array_key_exists('usage', $content)) {\n return;\n }\n\n $metadata->add('prompt_tokens', $content['usage']['prompt_tokens'] ?? null);\n $metadata->add('completion_tokens', $content['usage']['completion_tokens'] ?? null);\n $metadata->add('total_tokens', $content['usage']['total_tokens'] ?? null);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Meta/LlamaPromptConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Meta;\n\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Message\\AssistantMessage;\nuse Symfony\\AI\\Platform\\Message\\Content\\ImageUrl;\nuse Symfony\\AI\\Platform\\Message\\Content\\Text;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Message\\SystemMessage;\nuse Symfony\\AI\\Platform\\Message\\UserMessage;\n\n/**\n * @author Oskar Stark \n */\nfinal class LlamaPromptConverter\n{\n public function convertToPrompt(MessageBagInterface $messageBag): string\n {\n $messages = [];\n\n /** @var UserMessage|SystemMessage|AssistantMessage $message */\n foreach ($messageBag->getMessages() as $message) {\n $messages[] = self::convertMessage($message);\n }\n\n $messages = array_filter($messages, fn ($message) => '' !== $message);\n\n return trim(implode(\\PHP_EOL.\\PHP_EOL, $messages)).\\PHP_EOL.\\PHP_EOL.'<|start_header_id|>assistant<|end_header_id|>';\n }\n\n public function convertMessage(UserMessage|SystemMessage|AssistantMessage $message): string\n {\n if ($message instanceof SystemMessage) {\n return trim(<<<|start_header_id|>system<|end_header_id|>\n\n {$message->content}<|eot_id|>\n SYSTEM);\n }\n\n if ($message instanceof AssistantMessage) {\n if ('' === $message->content || null === $message->content) {\n return '';\n }\n\n return trim(<<{$message->getRole()->value}<|end_header_id|>\n\n {$message->content}<|eot_id|>\n ASSISTANT);\n }\n\n // Handling of UserMessage\n $count = \\count($message->content);\n\n $contentParts = [];\n if ($count > 1) {\n foreach ($message->content as $value) {\n if ($value instanceof Text) {\n $contentParts[] = $value->text;\n }\n\n if ($value instanceof ImageUrl) {\n $contentParts[] = $value->url;\n }\n }\n } elseif (1 === $count) {\n $value = $message->content[0];\n if ($value instanceof Text) {\n $contentParts[] = $value->text;\n }\n\n if ($value instanceof ImageUrl) {\n $contentParts[] = $value->url;\n }\n } else {\n throw new RuntimeException('Unsupported message type.');\n }\n\n $content = implode(\\PHP_EOL, $contentParts);\n\n return trim(<<{$message->getRole()->value}<|end_header_id|>\n\n {$content}<|eot_id|>\n USER);\n }\n}\n"], ["/ai/src/store/src/Document/TextDocument.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Document;\n\nuse Symfony\\AI\\Store\\Exception\\InvalidArgumentException;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class TextDocument\n{\n public function __construct(\n public Uuid $id,\n public string $content,\n public Metadata $metadata = new Metadata(),\n ) {\n '' !== trim($this->content) || throw new InvalidArgumentException('The content shall not be an empty string');\n }\n}\n"], ["/ai/src/store/src/Document/Loader/TextFileLoader.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Document\\Loader;\n\nuse Symfony\\AI\\Store\\Document\\LoaderInterface;\nuse Symfony\\AI\\Store\\Document\\Metadata;\nuse Symfony\\AI\\Store\\Document\\TextDocument;\nuse Symfony\\AI\\Store\\Exception\\RuntimeException;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class TextFileLoader implements LoaderInterface\n{\n public function __invoke(string $source, array $options = []): iterable\n {\n if (!is_file($source)) {\n throw new RuntimeException(\\sprintf('File \"%s\" does not exist.', $source));\n }\n\n $content = file_get_contents($source);\n\n if (false === $content) {\n throw new RuntimeException(\\sprintf('Unable to read file \"%s\"', $source));\n }\n\n yield new TextDocument(Uuid::v4(), trim($content), new Metadata([\n 'source' => $source,\n ]));\n }\n}\n"], ["/ai/src/platform/src/Bridge/Replicate/LlamaModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Replicate;\n\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\Llama;\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class LlamaModelClient implements ModelClientInterface\n{\n public function __construct(\n private Client $client,\n ) {\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Llama;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n $model instanceof Llama || throw new InvalidArgumentException(\\sprintf('The model must be an instance of \"%s\".', Llama::class));\n\n return new RawHttpResult(\n $this->client->request(\\sprintf('meta/meta-%s', $model->getName()), 'predictions', $payload)\n );\n }\n}\n"], ["/ai/src/platform/src/Message/Message.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message;\n\nuse Symfony\\AI\\Platform\\Message\\Content\\ContentInterface;\nuse Symfony\\AI\\Platform\\Message\\Content\\Text;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\n\n/**\n * @author Christopher Hertel \n * @author Denis Zunke \n */\nfinal readonly class Message\n{\n // Disabled by default, just a bridge to the specific messages\n private function __construct()\n {\n }\n\n public static function forSystem(\\Stringable|string $content): SystemMessage\n {\n return new SystemMessage($content instanceof \\Stringable ? (string) $content : $content);\n }\n\n /**\n * @param ?ToolCall[] $toolCalls\n */\n public static function ofAssistant(?string $content = null, ?array $toolCalls = null): AssistantMessage\n {\n return new AssistantMessage($content, $toolCalls);\n }\n\n public static function ofUser(\\Stringable|string|ContentInterface ...$content): UserMessage\n {\n $content = array_map(\n static fn (\\Stringable|string|ContentInterface $entry) => $entry instanceof ContentInterface ? $entry : (\\is_string($entry) ? new Text($entry) : new Text((string) $entry)),\n $content,\n );\n\n return new UserMessage(...$content);\n }\n\n public static function ofToolCall(ToolCall $toolCall, string $content): ToolCallMessage\n {\n return new ToolCallMessage($toolCall, $content);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/Nova/NovaModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova;\n\nuse AsyncAws\\BedrockRuntime\\BedrockRuntimeClient;\nuse AsyncAws\\BedrockRuntime\\Input\\InvokeModelRequest;\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\RawBedrockResult;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\n\n/**\n * @author Björn Altmann\n */\nclass NovaModelClient implements ModelClientInterface\n{\n public function __construct(\n private readonly BedrockRuntimeClient $bedrockRuntimeClient,\n ) {\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Nova;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawBedrockResult\n {\n $modelOptions = [];\n if (isset($options['tools'])) {\n $modelOptions['toolConfig']['tools'] = $options['tools'];\n }\n\n if (isset($options['temperature'])) {\n $modelOptions['inferenceConfig']['temperature'] = $options['temperature'];\n }\n\n if (isset($options['max_tokens'])) {\n $modelOptions['inferenceConfig']['maxTokens'] = $options['max_tokens'];\n }\n\n $request = [\n 'modelId' => $this->getModelId($model),\n 'contentType' => 'application/json',\n 'body' => json_encode(array_merge($payload, $modelOptions), \\JSON_THROW_ON_ERROR),\n ];\n\n return new RawBedrockResult($this->bedrockRuntimeClient->invokeModel(new InvokeModelRequest($request)));\n }\n\n private function getModelId(Model $model): string\n {\n $configuredRegion = $this->bedrockRuntimeClient->getConfiguration()->get('region');\n $regionPrefix = substr((string) $configuredRegion, 0, 2);\n\n return $regionPrefix.'.amazon.'.$model->getName().'-v1:0';\n }\n}\n"], ["/ai/src/agent/src/Toolbox/ToolFactory/ChainFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\ToolFactory;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Exception\\ToolException;\nuse Symfony\\AI\\Agent\\Toolbox\\ToolFactoryInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ChainFactory implements ToolFactoryInterface\n{\n /**\n * @var list\n */\n private array $factories;\n\n /**\n * @param iterable $factories\n */\n public function __construct(iterable $factories)\n {\n $this->factories = $factories instanceof \\Traversable ? iterator_to_array($factories) : $factories;\n }\n\n public function getTool(string $reference): iterable\n {\n $invalid = 0;\n foreach ($this->factories as $factory) {\n try {\n yield from $factory->getTool($reference);\n } catch (ToolException) {\n ++$invalid;\n continue;\n }\n\n // If the factory does not throw an exception, we don't need to check the others\n return;\n }\n\n if ($invalid === \\count($this->factories)) {\n throw ToolException::invalidReference($reference);\n }\n }\n}\n"], ["/ai/src/store/src/Bridge/Pinecone/Store.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Bridge\\Pinecone;\n\nuse Probots\\Pinecone\\Client;\nuse Probots\\Pinecone\\Resources\\Data\\VectorResource;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\nuse Symfony\\AI\\Store\\Document\\Metadata;\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\nuse Symfony\\AI\\Store\\Exception\\RuntimeException;\nuse Symfony\\AI\\Store\\VectorStoreInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class Store implements VectorStoreInterface\n{\n /**\n * @param array $filter\n */\n public function __construct(\n private Client $pinecone,\n private ?string $namespace = null,\n private array $filter = [],\n private int $topK = 3,\n ) {\n if (!class_exists(Client::class)) {\n throw new RuntimeException('For using the Pinecone as retrieval vector store, the probots-io/pinecone-php package is required. Try running \"composer require probots-io/pinecone-php\".');\n }\n }\n\n public function add(VectorDocument ...$documents): void\n {\n $vectors = [];\n foreach ($documents as $document) {\n $vectors[] = [\n 'id' => (string) $document->id,\n 'values' => $document->vector->getData(),\n 'metadata' => $document->metadata->getArrayCopy(),\n ];\n }\n\n if ([] === $vectors) {\n return;\n }\n\n $this->getVectors()->upsert($vectors, $this->namespace);\n }\n\n public function query(Vector $vector, array $options = [], ?float $minScore = null): array\n {\n $result = $this->getVectors()->query(\n vector: $vector->getData(),\n namespace: $options['namespace'] ?? $this->namespace,\n filter: $options['filter'] ?? $this->filter,\n topK: $options['topK'] ?? $this->topK,\n includeValues: true,\n );\n\n $documents = [];\n foreach ($result->json()['matches'] as $match) {\n $documents[] = new VectorDocument(\n id: Uuid::fromString($match['id']),\n vector: new Vector($match['values']),\n metadata: new Metadata($match['metadata']),\n score: $match['score'],\n );\n }\n\n return $documents;\n }\n\n private function getVectors(): VectorResource\n {\n return $this->pinecone->data()->vectors();\n }\n}\n"], ["/ai/src/platform/src/Bridge/TransformersPHP/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\TransformersPHP;\n\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\n\nuse function Codewithkyrian\\Transformers\\Pipelines\\pipeline;\n\nfinal readonly class ModelClient implements ModelClientInterface\n{\n public function supports(Model $model): bool\n {\n return true;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawPipelineResult\n {\n if (null === $task = $options['task'] ?? null) {\n throw new InvalidArgumentException('The task option is required.');\n }\n\n $pipeline = pipeline(\n $task,\n $model->getName(),\n $options['quantized'] ?? true,\n $options['config'] ?? null,\n $options['cacheDir'] ?? null,\n $options['revision'] ?? 'main',\n $options['modelFilename'] ?? null,\n );\n\n return new RawPipelineResult(new PipelineExecution($pipeline, $payload));\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/DallE/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\DallE;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\DallE;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\n\n/**\n * @see https://platform.openai.com/docs/api-reference/images/create\n *\n * @author Denis Zunke \n */\nfinal readonly class ResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof DallE;\n }\n\n public function convert(RawResultInterface $result, array $options = []): ResultInterface\n {\n $result = $result->getData();\n\n if (!isset($result['data'][0])) {\n throw new RuntimeException('No image generated.');\n }\n\n $images = [];\n foreach ($result['data'] as $image) {\n if ('url' === $options['response_format']) {\n $images[] = new UrlImage($image['url']);\n\n continue;\n }\n\n $images[] = new Base64Image($image['b64_json']);\n }\n\n return new ImageResult($image['revised_prompt'] ?? null, ...$images);\n }\n}\n"], ["/ai/src/platform/src/Result/ChoiceResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ChoiceResult extends BaseResult\n{\n /**\n * @var Choice[]\n */\n private readonly array $choices;\n\n public function __construct(Choice ...$choices)\n {\n if ([] === $choices) {\n throw new InvalidArgumentException('Result must have at least one choice.');\n }\n\n $this->choices = $choices;\n }\n\n /**\n * @return Choice[]\n */\n public function getContent(): array\n {\n return $this->choices;\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Toolbox.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox;\n\nuse Psr\\Log\\LoggerInterface;\nuse Psr\\Log\\NullLogger;\nuse Symfony\\AI\\Agent\\Toolbox\\Event\\ToolCallArgumentsResolved;\nuse Symfony\\AI\\Agent\\Toolbox\\Exception\\ToolExecutionException;\nuse Symfony\\AI\\Agent\\Toolbox\\Exception\\ToolNotFoundException;\nuse Symfony\\AI\\Agent\\Toolbox\\ToolFactory\\ReflectionToolFactory;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\nuse Symfony\\Contracts\\EventDispatcher\\EventDispatcherInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class Toolbox implements ToolboxInterface\n{\n /**\n * List of executable tools.\n *\n * @var list\n */\n private readonly array $tools;\n\n /**\n * List of tool metadata objects.\n *\n * @var Tool[]\n */\n private array $map;\n\n /**\n * @param iterable $tools\n */\n public function __construct(\n iterable $tools,\n private readonly ToolFactoryInterface $toolFactory = new ReflectionToolFactory(),\n private readonly ToolCallArgumentResolver $argumentResolver = new ToolCallArgumentResolver(),\n private readonly LoggerInterface $logger = new NullLogger(),\n private readonly ?EventDispatcherInterface $eventDispatcher = null,\n ) {\n $this->tools = $tools instanceof \\Traversable ? iterator_to_array($tools) : $tools;\n }\n\n public function getTools(): array\n {\n if (isset($this->map)) {\n return $this->map;\n }\n\n $map = [];\n foreach ($this->tools as $tool) {\n foreach ($this->toolFactory->getTool($tool::class) as $metadata) {\n $map[] = $metadata;\n }\n }\n\n return $this->map = $map;\n }\n\n public function execute(ToolCall $toolCall): mixed\n {\n $metadata = $this->getMetadata($toolCall);\n $tool = $this->getExecutable($metadata);\n\n try {\n $this->logger->debug(\\sprintf('Executing tool \"%s\".', $toolCall->name), $toolCall->arguments);\n\n $arguments = $this->argumentResolver->resolveArguments($metadata, $toolCall);\n $this->eventDispatcher?->dispatch(new ToolCallArgumentsResolved($tool, $metadata, $arguments));\n\n $result = $tool->{$metadata->reference->method}(...$arguments);\n } catch (\\Throwable $e) {\n $this->logger->warning(\\sprintf('Failed to execute tool \"%s\".', $toolCall->name), ['exception' => $e]);\n throw ToolExecutionException::executionFailed($toolCall, $e);\n }\n\n return $result;\n }\n\n private function getMetadata(ToolCall $toolCall): Tool\n {\n foreach ($this->getTools() as $metadata) {\n if ($metadata->name === $toolCall->name) {\n return $metadata;\n }\n }\n\n throw ToolNotFoundException::notFoundForToolCall($toolCall);\n }\n\n private function getExecutable(Tool $metadata): object\n {\n foreach ($this->tools as $tool) {\n if ($tool instanceof $metadata->reference->class) {\n return $tool;\n }\n }\n\n throw ToolNotFoundException::notFoundForReference($metadata->reference);\n }\n}\n"], ["/ai/src/platform/src/Result/BinaryResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\n\n/**\n * @author Christopher Hertel \n */\nfinal class BinaryResult extends BaseResult\n{\n public function __construct(\n public string $data,\n public ?string $mimeType = null,\n ) {\n }\n\n public function getContent(): string\n {\n return $this->data;\n }\n\n public function toBase64(): string\n {\n return base64_encode($this->data);\n }\n\n public function toDataUri(): string\n {\n if (null === $this->mimeType) {\n throw new RuntimeException('Mime type is not set.');\n }\n\n return 'data:'.$this->mimeType.';base64,'.$this->toBase64();\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Tool/Brave.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\AI\\Platform\\Contract\\JsonSchema\\Attribute\\With;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\n#[AsTool('brave_search', 'Tool that searches the web using Brave Search')]\nfinal readonly class Brave\n{\n /**\n * @param array $options See https://api-dashboard.search.brave.com/app/documentation/web-search/query#WebSearchAPIQueryParameters\n */\n public function __construct(\n private HttpClientInterface $httpClient,\n #[\\SensitiveParameter]\n private string $apiKey,\n private array $options = [],\n ) {\n }\n\n /**\n * @param string $query the search query term\n * @param int $count The number of search results returned in response.\n * Combine this parameter with offset to paginate search results.\n * @param int $offset The number of search results to skip before returning results.\n * In order to paginate results use this parameter together with count.\n *\n * @return array\n */\n public function __invoke(\n #[With(maximum: 500)]\n string $query,\n int $count = 20,\n #[With(minimum: 0, maximum: 9)]\n int $offset = 0,\n ): array {\n $result = $this->httpClient->request('GET', 'https://api.search.brave.com/res/v1/web/search', [\n 'headers' => ['X-Subscription-Token' => $this->apiKey],\n 'query' => array_merge($this->options, [\n 'q' => $query,\n 'count' => $count,\n 'offset' => $offset,\n ]),\n ]);\n\n $data = $result->toArray();\n\n return array_map(static function (array $result) {\n return ['title' => $result['title'], 'description' => $result['description'], 'url' => $result['url']];\n }, $data['web']['results'] ?? []);\n }\n}\n"], ["/ai/src/platform/src/Result/ToolCallResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\nuse Symfony\\AI\\Platform\\Exception\\InvalidArgumentException;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ToolCallResult extends BaseResult\n{\n /**\n * @var ToolCall[]\n */\n private readonly array $toolCalls;\n\n public function __construct(ToolCall ...$toolCalls)\n {\n if ([] === $toolCalls) {\n throw new InvalidArgumentException('Response must have at least one tool call.');\n }\n\n $this->toolCalls = $toolCalls;\n }\n\n /**\n * @return ToolCall[]\n */\n public function getContent(): array\n {\n return $this->toolCalls;\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Tool/Wikipedia.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\n#[AsTool('wikipedia_search', description: 'Searches Wikipedia for a given query', method: 'search')]\n#[AsTool('wikipedia_article', description: 'Retrieves a Wikipedia article by its title', method: 'article')]\nfinal readonly class Wikipedia\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n private string $locale = 'en',\n ) {\n }\n\n /**\n * @param string $query The query to search for on Wikipedia\n */\n public function search(string $query): string\n {\n $result = $this->execute([\n 'action' => 'query',\n 'format' => 'json',\n 'list' => 'search',\n 'srsearch' => $query,\n ], $this->locale);\n\n $titles = array_map(fn (array $item) => $item['title'], $result['query']['search']);\n\n if ([] === $titles) {\n return 'No articles were found on Wikipedia.';\n }\n\n $result = 'Articles with the following titles were found on Wikipedia:'.\\PHP_EOL;\n foreach ($titles as $title) {\n $result .= ' - '.$title.\\PHP_EOL;\n }\n\n return $result.\\PHP_EOL.'Use the title of the article with tool \"wikipedia_article\" to load the content.';\n }\n\n /**\n * @param string $title The title of the article to load from Wikipedia\n */\n public function article(string $title): string\n {\n $response = $this->execute([\n 'action' => 'query',\n 'format' => 'json',\n 'prop' => 'extracts|info|pageimages',\n 'titles' => $title,\n 'explaintext' => true,\n 'redirects' => true,\n ], $this->locale);\n\n $article = current($response['query']['pages']);\n\n if (\\array_key_exists('missing', $article)) {\n return \\sprintf('No article with title \"%s\" was found on Wikipedia.', $title);\n }\n\n $result = '';\n if (\\array_key_exists('redirects', $response['query'])) {\n foreach ($response['query']['redirects'] as $redirect) {\n $result .= \\sprintf('The article \"%s\" redirects to article \"%s\".', $redirect['from'], $redirect['to']).\\PHP_EOL;\n }\n $result .= \\PHP_EOL;\n }\n\n return $result.'This is the content of article \"'.$article['title'].'\":'.\\PHP_EOL.$article['extract'];\n }\n\n /**\n * @param array $query\n *\n * @return array\n */\n private function execute(array $query, ?string $locale = null): array\n {\n $url = \\sprintf('https://%s.wikipedia.org/w/api.php', $locale ?? $this->locale);\n $response = $this->httpClient->request('GET', $url, ['query' => $query]);\n\n return $response->toArray();\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/Nova/NovaResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova;\n\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\RawBedrockResult;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Result\\ToolCallResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\n\n/**\n * @author Björn Altmann\n */\nclass NovaResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Nova;\n }\n\n public function convert(RawResultInterface|RawBedrockResult $result, array $options = []): ToolCallResult|TextResult\n {\n $data = $result->getData();\n\n if (!isset($data['output']) || [] === $data['output']) {\n throw new RuntimeException('Response does not contain any content');\n }\n\n if (!isset($data['output']['message']['content'][0]['text'])) {\n throw new RuntimeException('Response content does not contain any text');\n }\n\n $toolCalls = [];\n foreach ($data['output']['message']['content'] as $content) {\n if (isset($content['toolUse'])) {\n $toolCalls[] = new ToolCall($content['toolUse']['toolUseId'], $content['toolUse']['name'], $content['toolUse']['input']);\n }\n }\n if ([] !== $toolCalls) {\n return new ToolCallResult(...$toolCalls);\n }\n\n return new TextResult($data['output']['message']['content'][0]['text']);\n }\n}\n"], ["/ai/src/platform/src/InMemoryPlatform.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform;\n\nuse Symfony\\AI\\Platform\\Result\\InMemoryRawResult;\nuse Symfony\\AI\\Platform\\Result\\ResultPromise;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\n\n/**\n * A fake implementation of PlatformInterface that returns fixed or callable responses.\n *\n * Useful for unit or integration testing without real API calls.\n *\n * @author Ramy Hakam \n */\nclass InMemoryPlatform implements PlatformInterface\n{\n /**\n * The mock result can be a string or a callable that returns a string.\n * If it's a closure, it receives the model, input, and optionally options as parameters like a real platform call.\n */\n public function __construct(private readonly \\Closure|string $mockResult)\n {\n }\n\n public function invoke(Model $model, array|string|object $input, array $options = []): ResultPromise\n {\n $resultText = $this->mockResult instanceof \\Closure\n ? ($this->mockResult)($model, $input, $options)\n : $this->mockResult;\n\n $textResult = new TextResult($resultText);\n\n return new ResultPromise(\n static fn () => $textResult,\n rawResult: new InMemoryRawResult(\n ['text' => $resultText],\n (object) ['text' => $resultText],\n ),\n options: $options\n );\n }\n}\n"], ["/ai/src/store/src/Bridge/Azure/SearchStore.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Bridge\\Azure;\n\nuse Symfony\\AI\\Platform\\Vector\\NullVector;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\nuse Symfony\\AI\\Store\\Document\\Metadata;\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\nuse Symfony\\AI\\Store\\VectorStoreInterface;\nuse Symfony\\Component\\Uid\\Uuid;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class SearchStore implements VectorStoreInterface\n{\n /**\n * @param string $vectorFieldName The name of the field int the index that contains the vector\n */\n public function __construct(\n private HttpClientInterface $httpClient,\n private string $endpointUrl,\n #[\\SensitiveParameter] private string $apiKey,\n private string $indexName,\n private string $apiVersion,\n private string $vectorFieldName = 'vector',\n ) {\n }\n\n public function add(VectorDocument ...$documents): void\n {\n $this->request('index', [\n 'value' => array_map([$this, 'convertToIndexableArray'], $documents),\n ]);\n }\n\n public function query(Vector $vector, array $options = [], ?float $minScore = null): array\n {\n $result = $this->request('search', [\n 'vectorQueries' => [$this->buildVectorQuery($vector)],\n ]);\n\n return array_map([$this, 'convertToVectorDocument'], $result['value']);\n }\n\n /**\n * @param array $payload\n *\n * @return array\n */\n private function request(string $endpoint, array $payload): array\n {\n $url = \\sprintf('%s/indexes/%s/docs/%s', $this->endpointUrl, $this->indexName, $endpoint);\n $result = $this->httpClient->request('POST', $url, [\n 'headers' => [\n 'api-key' => $this->apiKey,\n ],\n 'query' => ['api-version' => $this->apiVersion],\n 'json' => $payload,\n ]);\n\n return $result->toArray();\n }\n\n /**\n * @return array\n */\n private function convertToIndexableArray(VectorDocument $document): array\n {\n return array_merge([\n 'id' => $document->id,\n $this->vectorFieldName => $document->vector->getData(),\n ], $document->metadata->getArrayCopy());\n }\n\n /**\n * @param array $data\n */\n private function convertToVectorDocument(array $data): VectorDocument\n {\n return new VectorDocument(\n id: Uuid::fromString($data['id']),\n vector: !\\array_key_exists($this->vectorFieldName, $data) || null === $data[$this->vectorFieldName]\n ? new NullVector()\n : new Vector($data[$this->vectorFieldName]),\n metadata: new Metadata($data),\n );\n }\n\n /**\n * @return array{\n * kind: 'vector',\n * vector: float[],\n * exhaustive: true,\n * fields: non-empty-string,\n * weight: float,\n * k: int,\n * }\n */\n private function buildVectorQuery(Vector $vector): array\n {\n return [\n 'kind' => 'vector',\n 'vector' => $vector->getData(),\n 'exhaustive' => true,\n 'fields' => $this->vectorFieldName,\n 'weight' => 0.5,\n 'k' => 5,\n ];\n }\n}\n"], ["/ai/src/platform/src/Contract/JsonSchema/DescriptionParser.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\JsonSchema;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class DescriptionParser\n{\n public function getDescription(\\ReflectionProperty|\\ReflectionParameter $reflector): string\n {\n if ($reflector instanceof \\ReflectionProperty) {\n return $this->fromProperty($reflector);\n }\n\n return $this->fromParameter($reflector);\n }\n\n private function fromProperty(\\ReflectionProperty $property): string\n {\n $comment = $property->getDocComment();\n\n if (\\is_string($comment) && preg_match('/@var\\s+[a-zA-Z\\\\\\\\]+\\s+((.*)(?=\\*)|.*)/', $comment, $matches)) {\n return trim($matches[1]);\n }\n\n $class = $property->getDeclaringClass();\n if ($class->hasMethod('__construct')) {\n return $this->fromParameter(\n new \\ReflectionParameter([$class->getName(), '__construct'], $property->getName())\n );\n }\n\n return '';\n }\n\n private function fromParameter(\\ReflectionParameter $parameter): string\n {\n $comment = $parameter->getDeclaringFunction()->getDocComment();\n if (!$comment) {\n return '';\n }\n\n if (preg_match('/@param\\s+\\S+\\s+\\$'.preg_quote($parameter->getName(), '/').'\\s+((.*)(?=\\*)|.*)/', $comment, $matches)) {\n return trim($matches[1]);\n }\n\n return '';\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/Nova/Nova.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova;\n\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Björn Altmann\n */\nfinal class Nova extends Model\n{\n public const MICRO = 'nova-micro';\n public const LITE = 'nova-lite';\n public const PRO = 'nova-pro';\n public const PREMIER = 'nova-premier';\n\n /**\n * @param array $options The default options for the model usage\n */\n public function __construct(\n string $name = self::PRO,\n array $options = ['temperature' => 1.0, 'max_tokens' => 1000],\n ) {\n $capabilities = [\n Capability::INPUT_MESSAGES,\n Capability::OUTPUT_TEXT,\n Capability::TOOL_CALLING,\n ];\n\n if (self::MICRO !== $name) {\n $capabilities[] = Capability::INPUT_IMAGE;\n }\n\n parent::__construct($name, $capabilities, $options);\n }\n}\n"], ["/ai/src/ai-bundle/src/Profiler/TraceablePlatform.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\AIBundle\\Profiler;\n\nuse Symfony\\AI\\Platform\\Message\\Content\\File;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\PlatformInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultPromise;\nuse Symfony\\AI\\Platform\\Result\\StreamResult;\n\n/**\n * @author Christopher Hertel \n *\n * @phpstan-type PlatformCallData array{\n * model: Model,\n * input: array|string|object,\n * options: array,\n * result: ResultPromise,\n * }\n */\nfinal class TraceablePlatform implements PlatformInterface\n{\n /**\n * @var PlatformCallData[]\n */\n public array $calls = [];\n /**\n * @var \\WeakMap\n */\n public \\WeakMap $resultCache;\n\n public function __construct(\n private readonly PlatformInterface $platform,\n ) {\n $this->resultCache = new \\WeakMap();\n }\n\n public function invoke(Model $model, array|string|object $input, array $options = []): ResultPromise\n {\n $resultPromise = $this->platform->invoke($model, $input, $options);\n\n if ($input instanceof File) {\n $input = $input::class.': '.$input->getFormat();\n }\n\n if ($options['stream'] ?? false) {\n $originalStream = $resultPromise->asStream();\n $resultPromise = new ResultPromise(fn () => $this->createTraceableStreamResult($originalStream), $resultPromise->getRawResult(), $options);\n }\n\n $this->calls[] = [\n 'model' => $model,\n 'input' => \\is_object($input) ? clone $input : $input,\n 'options' => $options,\n 'result' => $resultPromise,\n ];\n\n return $resultPromise;\n }\n\n private function createTraceableStreamResult(\\Generator $originalStream): StreamResult\n {\n return $result = new StreamResult((function () use (&$result, $originalStream) {\n $this->resultCache[$result] = '';\n foreach ($originalStream as $chunk) {\n yield $chunk;\n if (\\is_string($chunk)) {\n $this->resultCache[$result] .= $chunk;\n }\n }\n })());\n }\n}\n"], ["/ai/src/agent/src/Toolbox/AgentProcessor.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox;\n\nuse Symfony\\AI\\Agent\\AgentAwareInterface;\nuse Symfony\\AI\\Agent\\AgentAwareTrait;\nuse Symfony\\AI\\Agent\\Exception\\MissingModelSupportException;\nuse Symfony\\AI\\Agent\\Input;\nuse Symfony\\AI\\Agent\\InputProcessorInterface;\nuse Symfony\\AI\\Agent\\Output;\nuse Symfony\\AI\\Agent\\OutputProcessorInterface;\nuse Symfony\\AI\\Agent\\Toolbox\\Event\\ToolCallsExecuted;\nuse Symfony\\AI\\Agent\\Toolbox\\StreamResult as ToolboxStreamResponse;\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Message\\AssistantMessage;\nuse Symfony\\AI\\Platform\\Message\\Message;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\Result\\StreamResult as GenericStreamResponse;\nuse Symfony\\AI\\Platform\\Result\\ToolCallResult;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\nuse Symfony\\Contracts\\EventDispatcher\\EventDispatcherInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class AgentProcessor implements InputProcessorInterface, OutputProcessorInterface, AgentAwareInterface\n{\n use AgentAwareTrait;\n\n public function __construct(\n private readonly ToolboxInterface $toolbox,\n private readonly ToolResultConverter $resultConverter = new ToolResultConverter(),\n private readonly ?EventDispatcherInterface $eventDispatcher = null,\n private readonly bool $keepToolMessages = false,\n ) {\n }\n\n public function processInput(Input $input): void\n {\n if (!$input->model->supports(Capability::TOOL_CALLING)) {\n throw MissingModelSupportException::forToolCalling($input->model::class);\n }\n\n $toolMap = $this->toolbox->getTools();\n if ([] === $toolMap) {\n return;\n }\n\n $options = $input->getOptions();\n // only filter tool map if list of strings is provided as option\n if (isset($options['tools']) && $this->isFlatStringArray($options['tools'])) {\n $toolMap = array_values(array_filter($toolMap, fn (Tool $tool) => \\in_array($tool->name, $options['tools'], true)));\n }\n\n $options['tools'] = $toolMap;\n $input->setOptions($options);\n }\n\n public function processOutput(Output $output): void\n {\n if ($output->result instanceof GenericStreamResponse) {\n $output->result = new ToolboxStreamResponse(\n $output->result->getContent(),\n $this->handleToolCallsCallback($output),\n );\n\n return;\n }\n\n if (!$output->result instanceof ToolCallResult) {\n return;\n }\n\n $output->result = $this->handleToolCallsCallback($output)($output->result);\n }\n\n /**\n * @param array $tools\n */\n private function isFlatStringArray(array $tools): bool\n {\n return array_reduce($tools, fn (bool $carry, mixed $item) => $carry && \\is_string($item), true);\n }\n\n private function handleToolCallsCallback(Output $output): \\Closure\n {\n return function (ToolCallResult $result, ?AssistantMessage $streamedAssistantResponse = null) use ($output): ResultInterface {\n $messages = $this->keepToolMessages ? $output->messages : clone $output->messages;\n\n if (null !== $streamedAssistantResponse && '' !== $streamedAssistantResponse->content) {\n $messages->add($streamedAssistantResponse);\n }\n\n do {\n $toolCalls = $result->getContent();\n $messages->add(Message::ofAssistant(toolCalls: $toolCalls));\n\n $results = [];\n foreach ($toolCalls as $toolCall) {\n $result = $this->toolbox->execute($toolCall);\n $results[] = new ToolResult($toolCall, $result);\n $messages->add(Message::ofToolCall($toolCall, $this->resultConverter->convert($result)));\n }\n\n $event = new ToolCallsExecuted(...$results);\n $this->eventDispatcher?->dispatch($event);\n\n $result = $event->hasResponse() ? $event->result : $this->agent->call($messages, $output->options);\n } while ($result instanceof ToolCallResult);\n\n return $result;\n };\n }\n}\n"], ["/ai/src/agent/src/InputProcessor/SystemPromptInputProcessor.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\InputProcessor;\n\nuse Psr\\Log\\LoggerInterface;\nuse Psr\\Log\\NullLogger;\nuse Symfony\\AI\\Agent\\Input;\nuse Symfony\\AI\\Agent\\InputProcessorInterface;\nuse Symfony\\AI\\Agent\\Toolbox\\ToolboxInterface;\nuse Symfony\\AI\\Platform\\Message\\Message;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class SystemPromptInputProcessor implements InputProcessorInterface\n{\n /**\n * @param \\Stringable|string $systemPrompt the system prompt to prepend to the input messages\n * @param ToolboxInterface|null $toolbox the tool box to be used to append the tool definitions to the system prompt\n */\n public function __construct(\n private \\Stringable|string $systemPrompt,\n private ?ToolboxInterface $toolbox = null,\n private LoggerInterface $logger = new NullLogger(),\n ) {\n }\n\n public function processInput(Input $input): void\n {\n $messages = $input->messages;\n\n if (null !== $messages->getSystemMessage()) {\n $this->logger->debug('Skipping system prompt injection since MessageBag already contains a system message.');\n\n return;\n }\n\n $message = (string) $this->systemPrompt;\n\n if ($this->toolbox instanceof ToolboxInterface\n && [] !== $this->toolbox->getTools()\n ) {\n $this->logger->debug('Append tool definitions to system prompt.');\n\n $tools = implode(\\PHP_EOL.\\PHP_EOL, array_map(\n fn (Tool $tool) => <<name}\n {$tool->description}\n TOOL,\n $this->toolbox->getTools()\n ));\n\n $message = <<systemPrompt}\n\n # Available tools\n\n {$tools}\n PROMPT;\n }\n\n $input->messages = $messages->prepend(Message::forSystem($message));\n }\n}\n"], ["/ai/src/ai-bundle/src/Security/Attribute/IsGrantedTool.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\AIBundle\\Security\\Attribute;\n\nuse Symfony\\AI\\Platform\\Tool\\Tool;\nuse Symfony\\Component\\ExpressionLanguage\\Expression;\n\n/**\n * Checks if user has permission to access to some tool resource using security roles and voters.\n *\n * @see https://symfony.com/doc/current/security.html#roles\n *\n * @author Valtteri R \n */\n#[\\Attribute(\\Attribute::IS_REPEATABLE | \\Attribute::TARGET_CLASS | \\Attribute::TARGET_METHOD)]\nfinal class IsGrantedTool\n{\n /**\n * @param string|Expression $attribute The attribute that will be checked against a given authentication token and optional subject\n * @param array|string|Expression|\\Closure(array, Tool):mixed|null $subject An optional subject - e.g. the current object being voted on\n * @param string|null $message A custom message when access is not granted\n * @param int|null $exceptionCode If set, will add the exception code to thrown exception\n */\n public function __construct(\n public string|Expression $attribute,\n public array|string|Expression|\\Closure|null $subject = null,\n public ?string $message = null,\n public ?int $exceptionCode = null,\n ) {\n }\n}\n"], ["/ai/src/agent/src/Toolbox/ToolCallArgumentResolver.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Exception\\ToolException;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\nuse Symfony\\Component\\Serializer\\Normalizer\\ArrayDenormalizer;\nuse Symfony\\Component\\Serializer\\Normalizer\\DateTimeNormalizer;\nuse Symfony\\Component\\Serializer\\Normalizer\\DenormalizerInterface;\nuse Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer;\nuse Symfony\\Component\\Serializer\\Serializer;\nuse Symfony\\Component\\TypeInfo\\Type\\CollectionType;\nuse Symfony\\Component\\TypeInfo\\TypeResolver\\TypeResolver;\n\n/**\n * @author Valtteri R \n */\nfinal readonly class ToolCallArgumentResolver\n{\n private TypeResolver $typeResolver;\n\n public function __construct(\n private DenormalizerInterface $denormalizer = new Serializer([new DateTimeNormalizer(), new ObjectNormalizer(), new ArrayDenormalizer()]),\n ?TypeResolver $typeResolver = null,\n ) {\n $this->typeResolver = $typeResolver ?? TypeResolver::create();\n }\n\n /**\n * @return array\n *\n * @throws ToolException When a mandatory tool parameter is missing from the tool call arguments\n */\n public function resolveArguments(Tool $metadata, ToolCall $toolCall): array\n {\n $method = new \\ReflectionMethod($metadata->reference->class, $metadata->reference->method);\n\n /** @var array $parameters */\n $parameters = array_column($method->getParameters(), null, 'name');\n $arguments = [];\n\n foreach ($parameters as $name => $reflectionParameter) {\n if (!\\array_key_exists($name, $toolCall->arguments)) {\n if (!$reflectionParameter->isOptional()) {\n throw new ToolException(\\sprintf('Parameter \"%s\" is mandatory for tool \"%s\".', $name, $toolCall->name));\n }\n continue;\n }\n\n $value = $toolCall->arguments[$name];\n $parameterType = $this->typeResolver->resolve($reflectionParameter);\n $dimensions = '';\n while ($parameterType instanceof CollectionType) {\n $dimensions .= '[]';\n $parameterType = $parameterType->getCollectionValueType();\n }\n\n $parameterType .= $dimensions;\n\n if ($this->denormalizer->supportsDenormalization($value, $parameterType)) {\n $value = $this->denormalizer->denormalize($value, $parameterType);\n }\n\n $arguments[$name] = $value;\n }\n\n return $arguments;\n }\n}\n"], ["/ai/src/platform/src/Vector/NullVector.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Vector;\n\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\n\n/**\n * @author Oskar Stark \n */\nfinal class NullVector implements VectorInterface\n{\n public function getData(): array\n {\n throw new RuntimeException('getData() method cannot be called on a NullVector.');\n }\n\n public function getDimensions(): int\n {\n throw new RuntimeException('getDimensions() method cannot be called on a NullVector.');\n }\n}\n"], ["/ai/src/platform/src/Platform.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform;\n\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultPromise;\n\n/**\n * @author Christopher Hertel \n */\nfinal class Platform implements PlatformInterface\n{\n /**\n * @var ModelClientInterface[]\n */\n private readonly array $modelClients;\n\n /**\n * @var ResultConverterInterface[]\n */\n private readonly array $resultConverters;\n\n /**\n * @param iterable $modelClients\n * @param iterable $resultConverters\n */\n public function __construct(\n iterable $modelClients,\n iterable $resultConverters,\n private ?Contract $contract = null,\n ) {\n $this->contract = $contract ?? Contract::create();\n $this->modelClients = $modelClients instanceof \\Traversable ? iterator_to_array($modelClients) : $modelClients;\n $this->resultConverters = $resultConverters instanceof \\Traversable ? iterator_to_array($resultConverters) : $resultConverters;\n }\n\n public function invoke(Model $model, array|string|object $input, array $options = []): ResultPromise\n {\n $payload = $this->contract->createRequestPayload($model, $input);\n $options = array_merge($model->getOptions(), $options);\n\n if (isset($options['tools'])) {\n $options['tools'] = $this->contract->createToolOption($options['tools'], $model);\n }\n\n $result = $this->doInvoke($model, $payload, $options);\n\n return $this->convertResult($model, $result, $options);\n }\n\n /**\n * @param array $payload\n * @param array $options\n */\n private function doInvoke(Model $model, array|string $payload, array $options = []): RawResultInterface\n {\n foreach ($this->modelClients as $modelClient) {\n if ($modelClient->supports($model)) {\n return $modelClient->request($model, $payload, $options);\n }\n }\n\n throw new RuntimeException(\\sprintf('No ModelClient registered for model \"%s\" with given input.', $model::class));\n }\n\n /**\n * @param array $options\n */\n private function convertResult(Model $model, RawResultInterface $result, array $options): ResultPromise\n {\n foreach ($this->resultConverters as $resultConverter) {\n if ($resultConverter->supports($model)) {\n return new ResultPromise($resultConverter->convert(...), $result, $options);\n }\n }\n\n throw new RuntimeException(\\sprintf('No ResultConverter registered for model \"%s\" with given input.', $model::class));\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Contract/ToolCallMessageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Gemini;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\ToolCallMessage;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Valtteri R \n */\nfinal class ToolCallMessageNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return ToolCallMessage::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Gemini;\n }\n\n /**\n * @param ToolCallMessage $data\n *\n * @return array{\n * functionResponse: array{\n * id: string,\n * name: string,\n * response: array\n * }\n * }[]\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n $resultContent = json_validate($data->content) ? json_decode($data->content, true) : $data->content;\n\n return [[\n 'functionResponse' => array_filter([\n 'id' => $data->toolCall->id,\n 'name' => $data->toolCall->name,\n 'response' => \\is_array($resultContent) ? $resultContent : [\n 'rawResponse' => $resultContent, // Gemini expects the response to be an object, but not everyone uses objects as their responses.\n ],\n ]),\n ]];\n }\n}\n"], ["/ai/src/agent/src/Toolbox/ToolResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox;\n\nuse Symfony\\Component\\Serializer\\Encoder\\JsonEncoder;\nuse Symfony\\Component\\Serializer\\Normalizer\\DateTimeNormalizer;\nuse Symfony\\Component\\Serializer\\Normalizer\\JsonSerializableNormalizer;\nuse Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer;\nuse Symfony\\Component\\Serializer\\Serializer;\nuse Symfony\\Component\\Serializer\\SerializerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ToolResultConverter\n{\n public function __construct(\n private SerializerInterface $serializer = new Serializer([new JsonSerializableNormalizer(), new DateTimeNormalizer(), new ObjectNormalizer()], [new JsonEncoder()]),\n ) {\n }\n\n public function convert(mixed $result): ?string\n {\n if (null === $result || \\is_string($result)) {\n return $result;\n }\n\n if ($result instanceof \\Stringable) {\n return (string) $result;\n }\n\n return $this->serializer->serialize($result, 'json');\n }\n}\n"], ["/ai/src/agent/src/Memory/EmbeddingProvider.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Memory;\n\nuse Symfony\\AI\\Agent\\Input;\nuse Symfony\\AI\\Platform\\Message\\Content\\ContentInterface;\nuse Symfony\\AI\\Platform\\Message\\Content\\Text;\nuse Symfony\\AI\\Platform\\Message\\MessageInterface;\nuse Symfony\\AI\\Platform\\Message\\UserMessage;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\PlatformInterface;\nuse Symfony\\AI\\Store\\VectorStoreInterface;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class EmbeddingProvider implements MemoryProviderInterface\n{\n public function __construct(\n private PlatformInterface $platform,\n private Model $model,\n private VectorStoreInterface $vectorStore,\n ) {\n }\n\n public function loadMemory(Input $input): array\n {\n $messages = $input->messages->getMessages();\n /** @var MessageInterface|null $userMessage */\n $userMessage = $messages[array_key_last($messages)] ?? null;\n\n if (!$userMessage instanceof UserMessage) {\n return [];\n }\n\n $userMessageTextContent = array_filter(\n $userMessage->content,\n static fn (ContentInterface $content): bool => $content instanceof Text,\n );\n\n if (0 === \\count($userMessageTextContent)) {\n return [];\n }\n\n $userMessageTextContent = array_shift($userMessageTextContent);\n\n $vectors = $this->platform->invoke($this->model, $userMessageTextContent->text)->asVectors();\n $foundEmbeddingContent = $this->vectorStore->query($vectors[0]);\n if (0 === \\count($foundEmbeddingContent)) {\n return [];\n }\n\n $content = '## Dynamic memories fitting user message'.\\PHP_EOL.\\PHP_EOL;\n foreach ($foundEmbeddingContent as $document) {\n $content .= json_encode($document->metadata);\n }\n\n return [new Memory($content)];\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/RequestHandler/ToolListHandler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\RequestHandler;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Tool\\CollectionInterface;\nuse Symfony\\AI\\McpSdk\\Message\\Request;\nuse Symfony\\AI\\McpSdk\\Message\\Response;\n\nfinal class ToolListHandler extends BaseRequestHandler\n{\n public function __construct(\n private readonly CollectionInterface $collection,\n private readonly int $pageSize = 20,\n ) {\n }\n\n public function createResponse(Request $message): Response\n {\n $nextCursor = null;\n $tools = [];\n\n $metadataList = $this->collection->getMetadata(\n $this->pageSize,\n $message->params['cursor'] ?? null\n );\n\n foreach ($metadataList as $tool) {\n $nextCursor = $tool->getName();\n $inputSchema = $tool->getInputSchema();\n $tools[] = [\n 'name' => $tool->getName(),\n 'description' => $tool->getDescription(),\n 'inputSchema' => [] === $inputSchema ? [\n 'type' => 'object',\n '$schema' => 'http://json-schema.org/draft-07/schema#',\n ] : $inputSchema,\n ];\n }\n\n $result = [\n 'tools' => $tools,\n ];\n\n if (null !== $nextCursor && \\count($tools) === $this->pageSize) {\n $result['nextCursor'] = $nextCursor;\n }\n\n return new Response($message->id, $result);\n }\n\n protected function supportedMethod(): string\n {\n return 'tools/list';\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Contract/AssistantMessageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Gemini;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\AssistantMessage;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nfinal class AssistantMessageNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return AssistantMessage::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Gemini;\n }\n\n /**\n * @param AssistantMessage $data\n *\n * @return array{array{text: string}}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n $normalized = [];\n\n if (isset($data->content)) {\n $normalized['text'] = $data->content;\n }\n\n if (isset($data->toolCalls[0])) {\n $normalized['functionCall'] = [\n 'id' => $data->toolCalls[0]->id,\n 'name' => $data->toolCalls[0]->name,\n ];\n\n if ($data->toolCalls[0]->arguments) {\n $normalized['functionCall']['args'] = $data->toolCalls[0]->arguments;\n }\n }\n\n return [$normalized];\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/GPT.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI;\n\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n * @author Oskar Stark \n */\nclass GPT extends Model\n{\n public const GPT_35_TURBO = 'gpt-3.5-turbo';\n public const GPT_35_TURBO_INSTRUCT = 'gpt-3.5-turbo-instruct';\n public const GPT_4 = 'gpt-4';\n public const GPT_4_TURBO = 'gpt-4-turbo';\n public const GPT_4O = 'gpt-4o';\n public const GPT_4O_MINI = 'gpt-4o-mini';\n public const GPT_4O_AUDIO = 'gpt-4o-audio-preview';\n public const O1_MINI = 'o1-mini';\n public const O1_PREVIEW = 'o1-preview';\n public const O3_MINI = 'o3-mini';\n public const O3_MINI_HIGH = 'o3-mini-high';\n public const GPT_45_PREVIEW = 'gpt-4.5-preview';\n public const GPT_41 = 'gpt-4.1';\n public const GPT_41_MINI = 'gpt-4.1-mini';\n public const GPT_41_NANO = 'gpt-4.1-nano';\n\n private const IMAGE_SUPPORTING = [\n self::GPT_4_TURBO,\n self::GPT_4O,\n self::GPT_4O_MINI,\n self::O1_MINI,\n self::O1_PREVIEW,\n self::O3_MINI,\n self::GPT_45_PREVIEW,\n self::GPT_41,\n self::GPT_41_MINI,\n self::GPT_41_NANO,\n ];\n\n private const STRUCTURED_OUTPUT_SUPPORTING = [\n self::GPT_4O,\n self::GPT_4O_MINI,\n self::O3_MINI,\n self::GPT_45_PREVIEW,\n self::GPT_41,\n self::GPT_41_MINI,\n self::GPT_41_NANO,\n ];\n\n /**\n * @param array $options The default options for the model usage\n */\n public function __construct(\n string $name = self::GPT_4O,\n array $options = ['temperature' => 1.0],\n ) {\n $capabilities = [\n Capability::INPUT_MESSAGES,\n Capability::OUTPUT_TEXT,\n Capability::OUTPUT_STREAMING,\n Capability::TOOL_CALLING,\n ];\n\n if (self::GPT_4O_AUDIO === $name) {\n $capabilities[] = Capability::INPUT_AUDIO;\n }\n\n if (\\in_array($name, self::IMAGE_SUPPORTING, true)) {\n $capabilities[] = Capability::INPUT_IMAGE;\n }\n\n if (\\in_array($name, self::STRUCTURED_OUTPUT_SUPPORTING, true)) {\n $capabilities[] = Capability::OUTPUT_STRUCTURED;\n }\n\n parent::__construct($name, $capabilities, $options);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Mistral/Embeddings/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Mistral\\Embeddings;\n\nuse Symfony\\AI\\Platform\\Bridge\\Mistral\\Embeddings;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\VectorResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Embeddings;\n }\n\n public function convert(RawResultInterface|RawHttpResult $result, array $options = []): VectorResult\n {\n $httpResponse = $result->getObject();\n\n if (200 !== $httpResponse->getStatusCode()) {\n throw new RuntimeException(\\sprintf('Unexpected response code %d: %s', $httpResponse->getStatusCode(), $httpResponse->getContent(false)));\n }\n\n $data = $result->getData();\n\n if (!isset($data['data'])) {\n throw new RuntimeException('Response does not contain data');\n }\n\n return new VectorResult(\n ...array_map(\n static fn (array $item): Vector => new Vector($item['embedding']),\n $data['data']\n ),\n );\n }\n}\n"], ["/ai/src/store/src/Document/Vectorizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Document;\n\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\PlatformInterface;\n\n/**\n * The Vectorizer encapsulates the logic to convert a collection of TextDocuments into VectorDocuments. It checks for\n * the model's capabilities to handle batch processing or handles it with HttpClient's concurrency feature.\n */\nfinal readonly class Vectorizer\n{\n public function __construct(\n private PlatformInterface $platform,\n private Model $model,\n ) {\n }\n\n /**\n * @param TextDocument[] $documents\n *\n * @return VectorDocument[]\n */\n public function vectorizeDocuments(array $documents): array\n {\n if ($this->model->supports(Capability::INPUT_MULTIPLE)) {\n $result = $this->platform->invoke($this->model, array_map(fn (TextDocument $document) => $document->content, $documents));\n\n $vectors = $result->asVectors();\n } else {\n $results = [];\n foreach ($documents as $document) {\n $results[] = $this->platform->invoke($this->model, $document->content);\n }\n\n $vectors = [];\n foreach ($results as $result) {\n $vectors = array_merge($vectors, $result->asVectors());\n }\n }\n\n $vectorDocuments = [];\n foreach ($documents as $i => $document) {\n $vectorDocuments[] = new VectorDocument($document->id, $vectors[$i], $document->metadata);\n }\n\n return $vectorDocuments;\n }\n}\n"], ["/ai/src/platform/src/Result/RawResultAwareTrait.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\nuse Symfony\\AI\\Platform\\Result\\Exception\\RawResultAlreadySetException;\n\n/**\n * @author Denis Zunke \n */\ntrait RawResultAwareTrait\n{\n protected ?RawResultInterface $rawResult = null;\n\n public function setRawResult(RawResultInterface $rawResult): void\n {\n if (isset($this->rawResult)) {\n throw new RawResultAlreadySetException();\n }\n\n $this->rawResult = $rawResult;\n }\n\n public function getRawResult(): ?RawResultInterface\n {\n return $this->rawResult;\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenRouter/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenRouter;\n\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\n\n/**\n * @author rglozman\n */\nfinal readonly class ResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return true;\n }\n\n public function convert(RawResultInterface $result, array $options = []): ResultInterface\n {\n $data = $result->getData();\n\n if (!isset($data['choices'][0]['message'])) {\n throw new RuntimeException('Response does not contain message');\n }\n\n if (!isset($data['choices'][0]['message']['content'])) {\n throw new RuntimeException('Message does not contain content');\n }\n\n return new TextResult($data['choices'][0]['message']['content']);\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/RequestHandler/PromptListHandler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\RequestHandler;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Prompt\\CollectionInterface;\nuse Symfony\\AI\\McpSdk\\Message\\Request;\nuse Symfony\\AI\\McpSdk\\Message\\Response;\n\nfinal class PromptListHandler extends BaseRequestHandler\n{\n public function __construct(\n private readonly CollectionInterface $collection,\n private readonly int $pageSize = 20,\n ) {\n }\n\n public function createResponse(Request $message): Response\n {\n $nextCursor = null;\n $prompts = [];\n\n $metadataList = $this->collection->getMetadata(\n $this->pageSize,\n $message->params['cursor'] ?? null\n );\n\n foreach ($metadataList as $metadata) {\n $nextCursor = $metadata->getName();\n $result = [\n 'name' => $metadata->getName(),\n ];\n\n $description = $metadata->getDescription();\n if (null !== $description) {\n $result['description'] = $description;\n }\n\n $arguments = [];\n foreach ($metadata->getArguments() as $data) {\n $argument = [\n 'name' => $data['name'],\n 'required' => $data['required'] ?? false,\n ];\n\n if (isset($data['description'])) {\n $argument['description'] = $data['description'];\n }\n $arguments[] = $argument;\n }\n\n if ([] !== $arguments) {\n $result['arguments'] = $arguments;\n }\n\n $prompts[] = $result;\n }\n\n $result = [\n 'prompts' => $prompts,\n ];\n\n if (null !== $nextCursor && \\count($prompts) === $this->pageSize) {\n $result['nextCursor'] = $nextCursor;\n }\n\n return new Response($message->id, $result);\n }\n\n protected function supportedMethod(): string\n {\n return 'prompts/list';\n }\n}\n"], ["/ai/src/agent/src/Toolbox/ToolFactory/ReflectionToolFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\ToolFactory;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\AI\\Agent\\Toolbox\\Exception\\ToolException;\n\n/**\n * Metadata factory that uses reflection in combination with `#[AsTool]` attribute to extract metadata from tools.\n *\n * @author Christopher Hertel \n */\nfinal class ReflectionToolFactory extends AbstractToolFactory\n{\n /**\n * @param class-string $reference\n */\n public function getTool(string $reference): iterable\n {\n if (!class_exists($reference)) {\n throw ToolException::invalidReference($reference);\n }\n\n $reflectionClass = new \\ReflectionClass($reference);\n $attributes = $reflectionClass->getAttributes(AsTool::class);\n\n if ([] === $attributes) {\n throw ToolException::missingAttribute($reference);\n }\n\n foreach ($attributes as $attribute) {\n yield $this->convertAttribute($reference, $attribute->newInstance());\n }\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Tool/OpenMeteo.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\AI\\Platform\\Contract\\JsonSchema\\Attribute\\With;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\n#[AsTool(name: 'weather_current', description: 'get current weather for a location', method: 'current')]\n#[AsTool(name: 'weather_forecast', description: 'get weather forecast for a location', method: 'forecast')]\nfinal readonly class OpenMeteo\n{\n private const WMO_CODES = [\n 0 => 'Clear',\n 1 => 'Mostly Clear',\n 2 => 'Partly Cloudy',\n 3 => 'Overcast',\n 45 => 'Fog',\n 48 => 'Icy Fog',\n 51 => 'Light Drizzle',\n 53 => 'Drizzle',\n 55 => 'Heavy Drizzle',\n 56 => 'Light Freezing Drizzle',\n 57 => 'Freezing Drizzle',\n 61 => 'Light Rain',\n 63 => 'Rain',\n 65 => 'Heavy Rain',\n 66 => 'Light Freezing Rain',\n 67 => 'Freezing Rain',\n 71 => 'Light Snow',\n 73 => 'Snow',\n 75 => 'Heavy Snow',\n 77 => 'Snow Grains',\n 80 => 'Light Showers',\n 81 => 'Showers',\n 82 => 'Heavy Showers',\n 85 => 'Light Snow Showers',\n 86 => 'Snow Showers',\n 95 => 'Thunderstorm',\n 96 => 'Light Thunderstorm with Hail',\n 99 => 'Thunderstorm with Hail',\n ];\n\n public function __construct(\n private HttpClientInterface $httpClient,\n ) {\n }\n\n /**\n * @param float $latitude the latitude of the location\n * @param float $longitude the longitude of the location\n *\n * @return array{\n * weather: string,\n * time: string,\n * temperature: string,\n * wind_speed: string,\n * }\n */\n public function current(float $latitude, float $longitude): array\n {\n $result = $this->httpClient->request('GET', 'https://api.open-meteo.com/v1/forecast', [\n 'query' => [\n 'latitude' => $latitude,\n 'longitude' => $longitude,\n 'current' => 'weather_code,temperature_2m,wind_speed_10m',\n ],\n ]);\n\n $data = $result->toArray();\n\n return [\n 'weather' => self::WMO_CODES[$data['current']['weather_code']] ?? 'Unknown',\n 'time' => $data['current']['time'],\n 'temperature' => $data['current']['temperature_2m'].$data['current_units']['temperature_2m'],\n 'wind_speed' => $data['current']['wind_speed_10m'].$data['current_units']['wind_speed_10m'],\n ];\n }\n\n /**\n * @param float $latitude the latitude of the location\n * @param float $longitude the longitude of the location\n * @param int $days the number of days to forecast\n *\n * @return array{\n * weather: string,\n * time: string,\n * temperature_min: string,\n * temperature_max: string,\n * }[]\n */\n public function forecast(\n float $latitude,\n float $longitude,\n #[With(minimum: 1, maximum: 16)]\n int $days = 7,\n ): array {\n $result = $this->httpClient->request('GET', 'https://api.open-meteo.com/v1/forecast', [\n 'query' => [\n 'latitude' => $latitude,\n 'longitude' => $longitude,\n 'daily' => 'weather_code,temperature_2m_max,temperature_2m_min',\n 'forecast_days' => $days,\n ],\n ]);\n\n $data = $result->toArray();\n $forecast = [];\n for ($i = 0; $i < $days; ++$i) {\n $forecast[] = [\n 'weather' => self::WMO_CODES[$data['daily']['weather_code'][$i]] ?? 'Unknown',\n 'time' => $data['daily']['time'][$i],\n 'temperature_min' => $data['daily']['temperature_2m_min'][$i].$data['daily_units']['temperature_2m_min'],\n 'temperature_max' => $data['daily']['temperature_2m_max'][$i].$data['daily_units']['temperature_2m_max'],\n ];\n }\n\n return $forecast;\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/RequestHandler/ResourceListHandler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\RequestHandler;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Resource\\CollectionInterface;\nuse Symfony\\AI\\McpSdk\\Message\\Request;\nuse Symfony\\AI\\McpSdk\\Message\\Response;\n\nfinal class ResourceListHandler extends BaseRequestHandler\n{\n public function __construct(\n private readonly CollectionInterface $collection,\n private readonly int $pageSize = 20,\n ) {\n }\n\n public function createResponse(Request $message): Response\n {\n $nextCursor = null;\n $resources = [];\n\n $metadataList = $this->collection->getMetadata(\n $this->pageSize,\n $message->params['cursor'] ?? null\n );\n\n foreach ($metadataList as $metadata) {\n $nextCursor = $metadata->getUri();\n $result = [\n 'uri' => $metadata->getUri(),\n 'name' => $metadata->getName(),\n ];\n\n $description = $metadata->getDescription();\n if (null !== $description) {\n $result['description'] = $description;\n }\n\n $mimeType = $metadata->getMimeType();\n if (null !== $mimeType) {\n $result['mimeType'] = $mimeType;\n }\n\n $size = $metadata->getSize();\n if (null !== $size) {\n $result['size'] = $size;\n }\n\n $resources[] = $result;\n }\n\n $result = [\n 'resources' => $resources,\n ];\n\n if (null !== $nextCursor && \\count($resources) === $this->pageSize) {\n $result['nextCursor'] = $nextCursor;\n }\n\n return new Response($message->id, $result);\n }\n\n protected function supportedMethod(): string\n {\n return 'resources/list';\n }\n}\n"], ["/ai/src/store/src/Document/Transformer/ChunkDelayTransformer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Document\\Transformer;\n\nuse Symfony\\AI\\Store\\Document\\TransformerInterface;\nuse Symfony\\Component\\Clock\\ClockInterface;\n\n/**\n * This transformer splits the batch of documents into chunks and delays in-between with x seconds, which is useful\n * when indexing a lot of documents and facing API rate limits.\n *\n * @author Christopher Hertel \n */\nfinal readonly class ChunkDelayTransformer implements TransformerInterface\n{\n public const OPTION_CHUNK_SIZE = 'chunk_size';\n public const OPTION_DELAY = 'delay';\n\n public function __construct(\n private ClockInterface $clock,\n ) {\n }\n\n /**\n * @param array{chunk_size?: int, delay?: int} $options\n */\n public function __invoke(iterable $documents, array $options = []): iterable\n {\n $chunkSize = $options[self::OPTION_CHUNK_SIZE] ?? 50;\n $delay = $options[self::OPTION_DELAY] ?? 10;\n\n $counter = 0;\n foreach ($documents as $document) {\n yield $document;\n ++$counter;\n\n if ($chunkSize === $counter && 0 !== $delay) {\n $this->clock->sleep($delay);\n }\n }\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/Claude.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic;\n\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nclass Claude extends Model\n{\n public const HAIKU_3 = 'claude-3-haiku-20240307';\n public const HAIKU_35 = 'claude-3-5-haiku-latest';\n public const SONNET_3 = 'claude-3-sonnet-20240229';\n public const SONNET_35 = 'claude-3-5-sonnet-latest';\n public const SONNET_37 = 'claude-3-7-sonnet-latest';\n public const SONNET_4 = 'claude-sonnet-4-20250514';\n public const SONNET_4_0 = 'claude-sonnet-4-0';\n public const OPUS_3 = 'claude-3-opus-20240229';\n public const OPUS_4 = 'claude-opus-4-20250514';\n public const OPUS_4_0 = 'claude-opus-4-0';\n\n /**\n * @param array $options The default options for the model usage\n */\n public function __construct(\n string $name = self::SONNET_37,\n array $options = ['temperature' => 1.0, 'max_tokens' => 1000],\n ) {\n $capabilities = [\n Capability::INPUT_MESSAGES,\n Capability::INPUT_IMAGE,\n Capability::OUTPUT_TEXT,\n Capability::OUTPUT_STREAMING,\n Capability::TOOL_CALLING,\n ];\n\n parent::__construct($name, $capabilities, $options);\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Tool/SimilaritySearch.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\PlatformInterface;\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\nuse Symfony\\AI\\Store\\VectorStoreInterface;\n\n/**\n * @author Christopher Hertel \n */\n#[AsTool('similarity_search', description: 'Searches for documents similar to a query or sentence.')]\nfinal class SimilaritySearch\n{\n /**\n * @var VectorDocument[]\n */\n public array $usedDocuments = [];\n\n public function __construct(\n private readonly PlatformInterface $platform,\n private readonly Model $model,\n private readonly VectorStoreInterface $vectorStore,\n ) {\n }\n\n /**\n * @param string $searchTerm string used for similarity search\n */\n public function __invoke(string $searchTerm): string\n {\n $vectors = $this->platform->invoke($this->model, $searchTerm)->asVectors();\n $this->usedDocuments = $this->vectorStore->query($vectors[0]);\n\n if ([] === $this->usedDocuments) {\n return 'No results found';\n }\n\n $result = 'Found documents with following information:'.\\PHP_EOL;\n foreach ($this->usedDocuments as $document) {\n $result .= json_encode($document->metadata);\n }\n\n return $result;\n }\n}\n"], ["/ai/src/platform/src/Result/ResultInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\nuse Symfony\\AI\\Platform\\Result\\Exception\\RawResultAlreadySetException;\nuse Symfony\\AI\\Platform\\Result\\Metadata\\Metadata;\n\n/**\n * @author Christopher Hertel \n * @author Denis Zunke \n */\ninterface ResultInterface\n{\n /**\n * @return string|iterable|object|null\n */\n public function getContent(): string|iterable|object|null;\n\n public function getMetadata(): Metadata;\n\n public function getRawResult(): ?RawResultInterface;\n\n /**\n * @throws RawResultAlreadySetException if the result is tried to be set more than once\n */\n public function setRawResult(RawResultInterface $rawResult): void;\n}\n"], ["/ai/src/agent/src/Toolbox/Tool/Crawler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Tool;\n\nuse Symfony\\AI\\Agent\\Exception\\RuntimeException;\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\Component\\DomCrawler\\Crawler as DomCrawler;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\n#[AsTool('crawler', 'A tool that crawls one page of a website and returns the visible text of it.')]\nfinal readonly class Crawler\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n ) {\n if (!class_exists(DomCrawler::class)) {\n throw new RuntimeException('For using the Crawler tool, the symfony/dom-crawler package is required. Try running \"composer require symfony/dom-crawler\".');\n }\n }\n\n /**\n * @param string $url the URL of the page to crawl\n */\n public function __invoke(string $url): string\n {\n $result = $this->httpClient->request('GET', $url);\n\n return (new DomCrawler($result->getContent()))->filter('body')->text();\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/Nova/Contract/UserMessageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\Nova;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Message\\Content\\Image;\nuse Symfony\\AI\\Platform\\Message\\Content\\Text;\nuse Symfony\\AI\\Platform\\Message\\UserMessage;\nuse Symfony\\AI\\Platform\\Model;\n\nuse function Symfony\\Component\\String\\u;\n\n/**\n * @author Christopher Hertel \n */\nfinal class UserMessageNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return UserMessage::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Nova;\n }\n\n /**\n * @param UserMessage $data\n *\n * @return array{\n * role: 'user',\n * content: array\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n $array = ['role' => $data->getRole()->value];\n\n foreach ($data->content as $value) {\n $contentPart = [];\n if ($value instanceof Text) {\n $contentPart['text'] = $value->text;\n } elseif ($value instanceof Image) {\n $contentPart['image']['format'] = u($value->getFormat())->replace('image/', '')->replace('jpg', 'jpeg')->toString();\n $contentPart['image']['source']['bytes'] = $value->asBase64();\n } else {\n throw new RuntimeException('Unsupported message type.');\n }\n $array['content'][] = $contentPart;\n }\n\n return $array;\n }\n}\n"], ["/ai/src/platform/src/Result/ResultPromise.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\nuse Symfony\\AI\\Platform\\Exception\\UnexpectedResultTypeException;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ResultPromise\n{\n private bool $isConverted = false;\n private ResultInterface $convertedResult;\n\n /**\n * @param array $options\n */\n public function __construct(\n private readonly \\Closure $resultConverter,\n private readonly RawResultInterface $rawResult,\n private readonly array $options = [],\n ) {\n }\n\n public function getResult(): ResultInterface\n {\n return $this->await();\n }\n\n public function getRawResult(): RawResultInterface\n {\n return $this->rawResult;\n }\n\n public function await(): ResultInterface\n {\n if (!$this->isConverted) {\n $this->convertedResult = ($this->resultConverter)($this->rawResult, $this->options);\n\n if (null === $this->convertedResult->getRawResult()) {\n // Fallback to set the raw result when it was not handled by the ResultConverter itself\n $this->convertedResult->setRawResult($this->rawResult);\n }\n\n $this->isConverted = true;\n }\n\n return $this->convertedResult;\n }\n\n public function asText(): string\n {\n return $this->as(TextResult::class)->getContent();\n }\n\n public function asObject(): object\n {\n return $this->as(ObjectResult::class)->getContent();\n }\n\n public function asBinary(): string\n {\n return $this->as(BinaryResult::class)->getContent();\n }\n\n public function asBase64(): string\n {\n $result = $this->as(BinaryResult::class);\n\n \\assert($result instanceof BinaryResult);\n\n return $result->toDataUri();\n }\n\n /**\n * @return Vector[]\n */\n public function asVectors(): array\n {\n return $this->as(VectorResult::class)->getContent();\n }\n\n public function asStream(): \\Generator\n {\n yield from $this->as(StreamResult::class)->getContent();\n }\n\n /**\n * @return ToolCall[]\n */\n public function asToolCalls(): array\n {\n return $this->as(ToolCallResult::class)->getContent();\n }\n\n /**\n * @param class-string $type\n */\n private function as(string $type): ResultInterface\n {\n $result = $this->getResult();\n\n if (!$result instanceof $type) {\n throw new UnexpectedResultTypeException($type, $result::class);\n }\n\n return $result;\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Embeddings.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini;\n\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Embeddings\\TaskType;\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Valtteri R \n */\nclass Embeddings extends Model\n{\n /** Supported dimensions: 3072, 1536, or 768 */\n public const GEMINI_EMBEDDING_EXP_03_07 = 'gemini-embedding-exp-03-07';\n /** Fixed 768 dimensions */\n public const TEXT_EMBEDDING_004 = 'text-embedding-004';\n /** Fixed 768 dimensions */\n public const EMBEDDING_001 = 'embedding-001';\n\n /**\n * @param array{dimensions?: int, task_type?: TaskType|string} $options\n */\n public function __construct(string $name = self::GEMINI_EMBEDDING_EXP_03_07, array $options = [])\n {\n parent::__construct($name, [Capability::INPUT_MULTIPLE], $options);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Mistral/Mistral.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Mistral;\n\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nfinal class Mistral extends Model\n{\n public const CODESTRAL = 'codestral-latest';\n public const CODESTRAL_MAMBA = 'open-codestral-mamba';\n public const MISTRAL_LARGE = 'mistral-large-latest';\n public const MISTRAL_SMALL = 'mistral-small-latest';\n public const MISTRAL_NEMO = 'open-mistral-nemo';\n public const MISTRAL_SABA = 'mistral-saba-latest';\n public const MINISTRAL_3B = 'mistral-3b-latest';\n public const MINISTRAL_8B = 'mistral-8b-latest';\n public const PIXSTRAL_LARGE = 'pixstral-large-latest';\n public const PIXSTRAL = 'pixstral-12b-latest';\n\n /**\n * @param array $options\n */\n public function __construct(\n string $name = self::MISTRAL_LARGE,\n array $options = [],\n ) {\n $capabilities = [\n Capability::INPUT_MESSAGES,\n Capability::OUTPUT_TEXT,\n Capability::OUTPUT_STREAMING,\n Capability::OUTPUT_STRUCTURED,\n ];\n\n if (\\in_array($name, [self::PIXSTRAL, self::PIXSTRAL_LARGE, self::MISTRAL_SMALL], true)) {\n $capabilities[] = Capability::INPUT_IMAGE;\n }\n\n if (\\in_array($name, [\n self::CODESTRAL,\n self::MISTRAL_LARGE,\n self::MISTRAL_SMALL,\n self::MISTRAL_NEMO,\n self::MINISTRAL_3B,\n self::MINISTRAL_8B,\n self::PIXSTRAL,\n self::PIXSTRAL_LARGE,\n ], true)) {\n $capabilities[] = Capability::TOOL_CALLING;\n }\n\n parent::__construct($name, $capabilities, $options);\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/RequestHandler/ToolCallHandler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\RequestHandler;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Tool\\ToolCall;\nuse Symfony\\AI\\McpSdk\\Capability\\Tool\\ToolExecutorInterface;\nuse Symfony\\AI\\McpSdk\\Exception\\ExceptionInterface;\nuse Symfony\\AI\\McpSdk\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\McpSdk\\Message\\Error;\nuse Symfony\\AI\\McpSdk\\Message\\Request;\nuse Symfony\\AI\\McpSdk\\Message\\Response;\n\nfinal class ToolCallHandler extends BaseRequestHandler\n{\n public function __construct(\n private readonly ToolExecutorInterface $toolExecutor,\n ) {\n }\n\n public function createResponse(Request $message): Response|Error\n {\n $name = $message->params['name'];\n $arguments = $message->params['arguments'] ?? [];\n\n try {\n $result = $this->toolExecutor->call(new ToolCall(uniqid('', true), $name, $arguments));\n } catch (ExceptionInterface) {\n return Error::internalError($message->id, 'Error while executing tool');\n }\n\n $content = match ($result->type) {\n 'text' => [\n 'type' => 'text',\n 'text' => $result->result,\n ],\n 'image', 'audio' => [\n 'type' => $result->type,\n 'data' => $result->result,\n 'mimeType' => $result->mimeType,\n ],\n 'resource' => [\n 'type' => 'resource',\n 'resource' => [\n 'uri' => $result->uri,\n 'mimeType' => $result->mimeType,\n 'text' => $result->result,\n ],\n ],\n // TODO better exception\n default => throw new InvalidArgumentException('Unsupported tool result type: '.$result->type),\n };\n\n return new Response($message->id, [\n 'content' => [$content], // TODO: allow multiple `ToolCallResult`s in the future\n 'isError' => $result->isError,\n ]);\n }\n\n protected function supportedMethod(): string\n {\n return 'tools/call';\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic;\n\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ModelClient implements ModelClientInterface\n{\n private EventSourceHttpClient $httpClient;\n\n public function __construct(\n HttpClientInterface $httpClient,\n #[\\SensitiveParameter] private string $apiKey,\n private string $version = '2023-06-01',\n ) {\n $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Claude;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n if (isset($options['tools'])) {\n $options['tool_choice'] = ['type' => 'auto'];\n }\n\n return new RawHttpResult($this->httpClient->request('POST', 'https://api.anthropic.com/v1/messages', [\n 'headers' => [\n 'x-api-key' => $this->apiKey,\n 'anthropic-version' => $this->version,\n ],\n 'json' => array_merge($options, $payload),\n ]));\n }\n}\n"], ["/ai/src/platform/src/Contract/Normalizer/ModelContractNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\Normalizer;\n\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Christopher Hertel \n */\nabstract class ModelContractNormalizer implements NormalizerInterface\n{\n /**\n * @return class-string\n */\n abstract protected function supportedDataClass(): string;\n\n abstract protected function supportsModel(Model $model): bool;\n\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n if (!is_a($data, $this->supportedDataClass(), true)) {\n return false;\n }\n\n if (isset($context[Contract::CONTEXT_MODEL]) && $context[Contract::CONTEXT_MODEL] instanceof Model) {\n return $this->supportsModel($context[Contract::CONTEXT_MODEL]);\n }\n\n return false;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n $this->supportedDataClass() => true,\n ];\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Tool/YouTubeTranscriber.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Tool;\n\nuse MrMySQL\\YoutubeTranscript\\TranscriptListFetcher;\nuse Symfony\\AI\\Agent\\Exception\\LogicException;\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\Component\\HttpClient\\Psr18Client;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\n#[AsTool('youtube_transcript', 'Fetches the transcript of a YouTube video')]\nfinal readonly class YouTubeTranscriber\n{\n public function __construct(\n private HttpClientInterface $client,\n ) {\n if (!class_exists(TranscriptListFetcher::class)) {\n throw new LogicException('For using the YouTube transcription tool, the mrmysql/youtube-transcript package is required. Try running \"composer require mrmysql/youtube-transcript\".');\n }\n }\n\n /**\n * @param string $videoId The ID of the YouTube video\n */\n public function __invoke(string $videoId): string\n {\n $psr18Client = new Psr18Client($this->client);\n $fetcher = new TranscriptListFetcher($psr18Client, $psr18Client, $psr18Client);\n\n $list = $fetcher->fetch($videoId);\n $transcript = $list->findTranscript($list->getAvailableLanguageCodes());\n\n return array_reduce($transcript->fetch(), function (string $carry, array $item): string {\n return $carry.\\PHP_EOL.$item['text'];\n }, '');\n }\n}\n"], ["/ai/src/agent/src/Memory/StaticMemoryProvider.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Memory;\n\nuse Symfony\\AI\\Agent\\Input;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class StaticMemoryProvider implements MemoryProviderInterface\n{\n /**\n * @var array\n */\n private array $memory;\n\n public function __construct(string ...$memory)\n {\n $this->memory = $memory;\n }\n\n public function loadMemory(Input $input): array\n {\n if (0 === \\count($this->memory)) {\n return [];\n }\n\n $content = '## Static Memory'.\\PHP_EOL;\n\n foreach ($this->memory as $memory) {\n $content .= \\PHP_EOL.'- '.$memory;\n }\n\n return [new Memory($content)];\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Tool/Tavily.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * Tool integration of tavily.com.\n *\n * @author Christopher Hertel \n */\n#[AsTool('tavily_search', description: 'search for information on the internet', method: 'search')]\n#[AsTool('tavily_extract', description: 'fetch content from websites', method: 'extract')]\nfinal readonly class Tavily\n{\n /**\n * @param array $options\n */\n public function __construct(\n private HttpClientInterface $httpClient,\n private string $apiKey,\n private array $options = ['include_images' => false],\n ) {\n }\n\n /**\n * @param string $query The search query to use\n */\n public function search(string $query): string\n {\n $result = $this->httpClient->request('POST', 'https://api.tavily.com/search', [\n 'json' => array_merge($this->options, [\n 'query' => $query,\n 'api_key' => $this->apiKey,\n ]),\n ]);\n\n return $result->getContent();\n }\n\n /**\n * @param string[] $urls URLs to fetch information from\n */\n public function extract(array $urls): string\n {\n $result = $this->httpClient->request('POST', 'https://api.tavily.com/extract', [\n 'json' => [\n 'urls' => $urls,\n 'api_key' => $this->apiKey,\n ],\n ]);\n\n return $result->getContent();\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic;\n\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\Contract\\AnthropicContract;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class PlatformFactory\n{\n public static function create(\n #[\\SensitiveParameter]\n string $apiKey,\n string $version = '2023-06-01',\n ?HttpClientInterface $httpClient = null,\n ?Contract $contract = null,\n ): Platform {\n $httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n\n return new Platform(\n [new ModelClient($httpClient, $apiKey, $version)],\n [new ResultConverter()],\n $contract ?? AnthropicContract::create(),\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Gemini/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini\\Gemini;\n\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Gemini;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\Exception\\TransportExceptionInterface;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Roy Garrido\n */\nfinal readonly class ModelClient implements ModelClientInterface\n{\n private EventSourceHttpClient $httpClient;\n\n public function __construct(\n HttpClientInterface $httpClient,\n #[\\SensitiveParameter] private string $apiKey,\n ) {\n $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Gemini;\n }\n\n /**\n * @throws TransportExceptionInterface When the HTTP request fails due to network issues\n */\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n $url = \\sprintf(\n 'https://generativelanguage.googleapis.com/v1beta/models/%s:%s',\n $model->getName(),\n $options['stream'] ?? false ? 'streamGenerateContent' : 'generateContent',\n );\n\n if (isset($options['response_format']['json_schema']['schema'])) {\n $options['responseMimeType'] = 'application/json';\n $options['responseJsonSchema'] = $options['response_format']['json_schema']['schema'];\n unset($options['response_format']);\n }\n\n $generationConfig = ['generationConfig' => $options];\n unset($generationConfig['generationConfig']['stream']);\n unset($generationConfig['generationConfig']['tools']);\n unset($generationConfig['generationConfig']['server_tools']);\n\n if (isset($options['tools'])) {\n $generationConfig['tools'][] = ['functionDeclarations' => $options['tools']];\n unset($options['tools']);\n }\n\n foreach ($options['server_tools'] ?? [] as $tool => $params) {\n if (!$params) {\n continue;\n }\n\n $generationConfig['tools'][] = [$tool => true === $params ? new \\ArrayObject() : $params];\n }\n\n return new RawHttpResult($this->httpClient->request('POST', $url, [\n 'headers' => [\n 'x-goog-api-key' => $this->apiKey,\n ],\n 'json' => array_merge($generationConfig, $payload),\n ]));\n }\n}\n"], ["/ai/src/mcp-sdk/src/Message/Error.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Message;\n\nfinal readonly class Error implements \\JsonSerializable\n{\n public const INVALID_REQUEST = -32600;\n public const METHOD_NOT_FOUND = -32601;\n public const INVALID_PARAMS = -32602;\n public const INTERNAL_ERROR = -32603;\n public const PARSE_ERROR = -32700;\n public const RESOURCE_NOT_FOUND = -32002;\n\n public function __construct(\n public string|int $id,\n public int $code,\n public string $message,\n ) {\n }\n\n public static function invalidRequest(string|int $id, string $message = 'Invalid Request'): self\n {\n return new self($id, self::INVALID_REQUEST, $message);\n }\n\n public static function methodNotFound(string|int $id, string $message = 'Method not found'): self\n {\n return new self($id, self::METHOD_NOT_FOUND, $message);\n }\n\n public static function invalidParams(string|int $id, string $message = 'Invalid params'): self\n {\n return new self($id, self::INVALID_PARAMS, $message);\n }\n\n public static function internalError(string|int $id, string $message = 'Internal error'): self\n {\n return new self($id, self::INTERNAL_ERROR, $message);\n }\n\n public static function parseError(string|int $id, string $message = 'Parse error'): self\n {\n return new self($id, self::PARSE_ERROR, $message);\n }\n\n /**\n * @return array{\n * jsonrpc: string,\n * id: string|int,\n * error: array{code: int, message: string}\n * }\n */\n public function jsonSerialize(): array\n {\n return [\n 'jsonrpc' => '2.0',\n 'id' => $this->id,\n 'error' => [\n 'code' => $this->code,\n 'message' => $this->message,\n ],\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/Meta/LlamaModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock\\Meta;\n\nuse AsyncAws\\BedrockRuntime\\BedrockRuntimeClient;\nuse AsyncAws\\BedrockRuntime\\Input\\InvokeModelRequest;\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\RawBedrockResult;\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\Llama;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\n\n/**\n * @author Björn Altmann\n */\nclass LlamaModelClient implements ModelClientInterface\n{\n public function __construct(\n private readonly BedrockRuntimeClient $bedrockRuntimeClient,\n ) {\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Llama;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawBedrockResult\n {\n return new RawBedrockResult($this->bedrockRuntimeClient->invokeModel(new InvokeModelRequest([\n 'modelId' => $this->getModelId($model),\n 'contentType' => 'application/json',\n 'body' => json_encode($payload, \\JSON_THROW_ON_ERROR),\n ])));\n }\n\n private function getModelId(Model $model): string\n {\n $configuredRegion = $this->bedrockRuntimeClient->getConfiguration()->get('region');\n $regionPrefix = substr((string) $configuredRegion, 0, 2);\n $modifiedModelName = str_replace('llama-3', 'llama3', $model->getName());\n\n return $regionPrefix.'.meta.'.str_replace('.', '-', $modifiedModelName).'-v1:0';\n }\n}\n"], ["/ai/src/mcp-sdk/src/Message/Factory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Message;\n\nuse Symfony\\AI\\McpSdk\\Exception\\InvalidInputMessageException;\n\nfinal class Factory\n{\n /**\n * @return iterable\n *\n * @throws \\JsonException When the input string is not valid JSON\n */\n public function create(string $input): iterable\n {\n $data = json_decode($input, true, flags: \\JSON_THROW_ON_ERROR);\n\n if ('{' === $input[0]) {\n $data = [$data];\n }\n\n foreach ($data as $message) {\n if (!isset($message['method'])) {\n yield new InvalidInputMessageException('Invalid JSON-RPC request, missing \"method\".');\n } elseif (str_starts_with((string) $message['method'], 'notifications/')) {\n yield Notification::from($message);\n } else {\n yield Request::from($message);\n }\n }\n }\n}\n"], ["/ai/src/platform/src/Bridge/Replicate/Client.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Replicate;\n\nuse Symfony\\Component\\Clock\\ClockInterface;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\nuse Symfony\\Contracts\\HttpClient\\ResponseInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class Client\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n private ClockInterface $clock,\n #[\\SensitiveParameter] private string $apiKey,\n ) {\n }\n\n /**\n * @param string $model The model name on Replicate, e.g. \"meta/meta-llama-3.1-405b-instruct\"\n * @param array $body\n */\n public function request(string $model, string $endpoint, array $body): ResponseInterface\n {\n $url = \\sprintf('https://api.replicate.com/v1/models/%s/%s', $model, $endpoint);\n\n $response = $this->httpClient->request('POST', $url, [\n 'headers' => ['Content-Type' => 'application/json'],\n 'auth_bearer' => $this->apiKey,\n 'json' => ['input' => $body],\n ]);\n $data = $response->toArray();\n\n while (!\\in_array($data['status'], ['succeeded', 'failed', 'canceled'], true)) {\n $this->clock->sleep(1); // we need to wait until the prediction is ready\n\n $response = $this->getResponse($data['id']);\n $data = $response->toArray();\n }\n\n return $response;\n }\n\n private function getResponse(string $id): ResponseInterface\n {\n $url = \\sprintf('https://api.replicate.com/v1/predictions/%s', $id);\n\n return $this->httpClient->request('GET', $url, [\n 'headers' => ['Content-Type' => 'application/json'],\n 'auth_bearer' => $this->apiKey,\n ]);\n }\n}\n"], ["/ai/src/agent/src/Toolbox/ToolFactory/AbstractToolFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\ToolFactory;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\AI\\Agent\\Toolbox\\Exception\\ToolConfigurationException;\nuse Symfony\\AI\\Agent\\Toolbox\\ToolFactoryInterface;\nuse Symfony\\AI\\Platform\\Contract\\JsonSchema\\Factory;\nuse Symfony\\AI\\Platform\\Tool\\ExecutionReference;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\n\n/**\n * @author Christopher Hertel \n */\nabstract class AbstractToolFactory implements ToolFactoryInterface\n{\n public function __construct(\n private readonly Factory $factory = new Factory(),\n ) {\n }\n\n protected function convertAttribute(string $className, AsTool $attribute): Tool\n {\n try {\n return new Tool(\n new ExecutionReference($className, $attribute->method),\n $attribute->name,\n $attribute->description,\n $this->factory->buildParameters($className, $attribute->method)\n );\n } catch (\\ReflectionException $e) {\n throw ToolConfigurationException::invalidMethod($className, $attribute->method, $e);\n }\n }\n}\n"], ["/ai/src/agent/src/Toolbox/ToolFactory/MemoryToolFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\ToolFactory;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\AI\\Agent\\Toolbox\\Exception\\ToolException;\n\n/**\n * @author Christopher Hertel \n */\nfinal class MemoryToolFactory extends AbstractToolFactory\n{\n /**\n * @var array\n */\n private array $tools = [];\n\n public function addTool(string|object $class, string $name, string $description, string $method = '__invoke'): self\n {\n $className = \\is_object($class) ? $class::class : $class;\n $this->tools[$className][] = new AsTool($name, $description, $method);\n\n return $this;\n }\n\n /**\n * @param class-string $reference\n */\n public function getTool(string $reference): iterable\n {\n if (!isset($this->tools[$reference])) {\n throw ToolException::invalidReference($reference);\n }\n\n foreach ($this->tools[$reference] as $tool) {\n yield $this->convertAttribute($reference, $tool);\n }\n }\n}\n"], ["/ai/src/platform/src/Bridge/Azure/Meta/LlamaResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Azure\\Meta;\n\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\Llama;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class LlamaResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Llama;\n }\n\n public function convert(RawResultInterface $result, array $options = []): TextResult\n {\n $data = $result->getData();\n\n if (!isset($data['choices'][0]['message']['content'])) {\n throw new RuntimeException('Response does not contain output');\n }\n\n return new TextResult($data['choices'][0]['message']['content']);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock;\n\nuse AsyncAws\\BedrockRuntime\\BedrockRuntimeClient;\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\Contract as AnthropicContract;\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\Anthropic\\ClaudeModelClient;\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\Anthropic\\ClaudeResultConverter;\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\Meta\\LlamaModelClient;\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\Meta\\LlamaResultConverter;\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\Contract as NovaContract;\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\NovaModelClient;\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\NovaResultConverter;\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\Contract as LlamaContract;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Platform;\n\n/**\n * @author Björn Altmann\n */\nfinal readonly class PlatformFactory\n{\n public static function create(\n BedrockRuntimeClient $bedrockRuntimeClient = new BedrockRuntimeClient(),\n ?Contract $contract = null,\n ): Platform {\n if (!class_exists(BedrockRuntimeClient::class)) {\n throw new RuntimeException('For using the Bedrock platform, the async-aws/bedrock-runtime package is required. Try running \"composer require async-aws/bedrock-runtime\".');\n }\n\n return new Platform(\n [\n new ClaudeModelClient($bedrockRuntimeClient),\n new LlamaModelClient($bedrockRuntimeClient),\n new NovaModelClient($bedrockRuntimeClient),\n ],\n [\n new ClaudeResultConverter(),\n new LlamaResultConverter(),\n new NovaResultConverter(),\n ],\n $contract ?? Contract::create(\n new AnthropicContract\\AssistantMessageNormalizer(),\n new AnthropicContract\\DocumentNormalizer(),\n new AnthropicContract\\DocumentUrlNormalizer(),\n new AnthropicContract\\ImageNormalizer(),\n new AnthropicContract\\ImageUrlNormalizer(),\n new AnthropicContract\\MessageBagNormalizer(),\n new AnthropicContract\\ToolCallMessageNormalizer(),\n new AnthropicContract\\ToolNormalizer(),\n new LlamaContract\\MessageBagNormalizer(),\n new NovaContract\\AssistantMessageNormalizer(),\n new NovaContract\\MessageBagNormalizer(),\n new NovaContract\\ToolCallMessageNormalizer(),\n new NovaContract\\ToolNormalizer(),\n new NovaContract\\UserMessageNormalizer(),\n )\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Embeddings/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini\\Embeddings;\n\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Embeddings;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Valtteri R \n */\nfinal readonly class ModelClient implements ModelClientInterface\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n #[\\SensitiveParameter]\n private string $apiKey,\n ) {\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Embeddings;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n $url = \\sprintf('https://generativelanguage.googleapis.com/v1beta/models/%s:%s', $model->getName(), 'batchEmbedContents');\n $modelOptions = $model->getOptions();\n\n return new RawHttpResult($this->httpClient->request('POST', $url, [\n 'headers' => [\n 'x-goog-api-key' => $this->apiKey,\n ],\n 'json' => [\n 'requests' => array_map(\n static fn (string $text) => array_filter([\n 'model' => 'models/'.$model->getName(),\n 'content' => ['parts' => [['text' => $text]]],\n 'outputDimensionality' => $modelOptions['dimensions'] ?? null,\n 'taskType' => $modelOptions['task_type'] ?? null,\n 'title' => $options['title'] ?? null,\n ]),\n \\is_array($payload) ? $payload : [$payload],\n ),\n ],\n ]));\n }\n}\n"], ["/ai/src/platform/src/Contract/Normalizer/ToolNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\Normalizer;\n\nuse Symfony\\AI\\Platform\\Contract\\JsonSchema\\Factory;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @phpstan-import-type JsonSchema from Factory\n *\n * @author Christopher Hertel \n */\nclass ToolNormalizer implements NormalizerInterface\n{\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n return $data instanceof Tool;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n Tool::class => true,\n ];\n }\n\n /**\n * @param Tool $data\n *\n * @return array{\n * type: 'function',\n * function: array{\n * name: string,\n * description: string,\n * parameters?: JsonSchema\n * }\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n $function = [\n 'name' => $data->name,\n 'description' => $data->description,\n ];\n\n if (isset($data->parameters)) {\n $function['parameters'] = $data->parameters;\n }\n\n return [\n 'type' => 'function',\n 'function' => $function,\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/Voyage/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Voyage;\n\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\Result\\VectorResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Voyage;\n }\n\n public function convert(RawResultInterface $result, array $options = []): ResultInterface\n {\n $result = $result->getData();\n\n if (!isset($result['data'])) {\n throw new RuntimeException('Response does not contain embedding data');\n }\n\n $vectors = array_map(fn (array $data) => new Vector($data['embedding']), $result['data']);\n\n return new VectorResult($vectors[0]);\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/Transport/Sse/StreamTransport.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\Transport\\Sse;\n\nuse Symfony\\AI\\McpSdk\\Server\\TransportInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\nfinal readonly class StreamTransport implements TransportInterface\n{\n public function __construct(\n private string $messageEndpoint,\n private StoreInterface $store,\n private Uuid $id,\n ) {\n }\n\n public function initialize(): void\n {\n ignore_user_abort(true);\n $this->flushEvent('endpoint', $this->messageEndpoint);\n }\n\n public function isConnected(): bool\n {\n return 0 === connection_aborted();\n }\n\n public function receive(): \\Generator\n {\n yield $this->store->pop($this->id);\n }\n\n public function send(string $data): void\n {\n $this->flushEvent('message', $data);\n }\n\n public function close(): void\n {\n $this->store->remove($this->id);\n }\n\n private function flushEvent(string $event, string $data): void\n {\n echo \\sprintf('event: %s', $event).\\PHP_EOL;\n echo \\sprintf('data: %s', $data).\\PHP_EOL;\n echo \\PHP_EOL;\n if (false !== ob_get_length()) {\n ob_flush();\n }\n flush();\n }\n}\n"], ["/ai/src/agent/src/Chat/MessageStore/SessionStore.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Chat\\MessageStore;\n\nuse Symfony\\AI\\Agent\\Chat\\MessageStoreInterface;\nuse Symfony\\AI\\Agent\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Message\\MessageBag;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\Component\\HttpFoundation\\RequestStack;\nuse Symfony\\Component\\HttpFoundation\\Session\\SessionInterface;\n\nfinal readonly class SessionStore implements MessageStoreInterface\n{\n private SessionInterface $session;\n\n public function __construct(\n RequestStack $requestStack,\n private string $sessionKey = 'messages',\n ) {\n if (!class_exists(RequestStack::class)) {\n throw new RuntimeException('For using the SessionStore as message store, the symfony/http-foundation package is required. Try running \"composer require symfony/http-foundation\".');\n }\n $this->session = $requestStack->getSession();\n }\n\n public function save(MessageBagInterface $messages): void\n {\n $this->session->set($this->sessionKey, $messages);\n }\n\n public function load(): MessageBagInterface\n {\n return $this->session->get($this->sessionKey, new MessageBag());\n }\n\n public function clear(): void\n {\n $this->session->remove($this->sessionKey);\n }\n}\n"], ["/ai/src/platform/src/Contract/Normalizer/Message/UserMessageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\Normalizer\\Message;\n\nuse Symfony\\AI\\Platform\\Message\\Content\\Text;\nuse Symfony\\AI\\Platform\\Message\\UserMessage;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareInterface;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareTrait;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class UserMessageNormalizer implements NormalizerInterface, NormalizerAwareInterface\n{\n use NormalizerAwareTrait;\n\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n return $data instanceof UserMessage;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n UserMessage::class => true,\n ];\n }\n\n /**\n * @param UserMessage $data\n *\n * @return array{role: 'assistant', content: string}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n $array = ['role' => $data->getRole()->value];\n\n if (1 === \\count($data->content) && $data->content[0] instanceof Text) {\n $array['content'] = $data->content[0]->text;\n\n return $array;\n }\n\n $array['content'] = $this->normalizer->normalize($data->content, $format, $context);\n\n return $array;\n }\n}\n"], ["/ai/src/platform/src/Bridge/TransformersPHP/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\TransformersPHP;\n\nuse Codewithkyrian\\Transformers\\Transformers;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Platform;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class PlatformFactory\n{\n public static function create(): Platform\n {\n if (!class_exists(Transformers::class)) {\n throw new RuntimeException('For using the TransformersPHP with FFI to run models in PHP, the codewithkyrian/transformers package is required. Try running \"composer require codewithkyrian/transformers\".');\n }\n\n return new Platform([new ModelClient()], [new ResultConverter()]);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Ollama/LlamaResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Ollama;\n\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\Llama;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class LlamaResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Llama;\n }\n\n public function convert(RawResultInterface $result, array $options = []): ResultInterface\n {\n $data = $result->getData();\n\n if (!isset($data['message'])) {\n throw new RuntimeException('Response does not contain message');\n }\n\n if (!isset($data['message']['content'])) {\n throw new RuntimeException('Message does not contain content');\n }\n\n return new TextResult($data['message']['content']);\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/Transport/Sse/Store/CachePoolStore.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\Transport\\Sse\\Store;\n\nuse Psr\\Cache\\CacheItemPoolInterface;\nuse Symfony\\AI\\McpSdk\\Server\\Transport\\Sse\\StoreInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\nfinal readonly class CachePoolStore implements StoreInterface\n{\n public function __construct(\n private CacheItemPoolInterface $cachePool,\n ) {\n }\n\n public function push(Uuid $id, string $message): void\n {\n $item = $this->cachePool->getItem($this->getCacheKey($id));\n\n $messages = $item->isHit() ? $item->get() : [];\n $messages[] = $message;\n $item->set($messages);\n\n $this->cachePool->save($item);\n }\n\n public function pop(Uuid $id): ?string\n {\n $item = $this->cachePool->getItem($this->getCacheKey($id));\n\n if (!$item->isHit()) {\n return null;\n }\n\n $messages = $item->get();\n $message = array_shift($messages);\n\n $item->set($messages);\n $this->cachePool->save($item);\n\n return $message;\n }\n\n public function remove(Uuid $id): void\n {\n $this->cachePool->deleteItem($this->getCacheKey($id));\n }\n\n private function getCacheKey(Uuid $id): string\n {\n return 'message_'.$id->toRfc4122();\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Gemini.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini;\n\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Roy Garrido\n */\nclass Gemini extends Model\n{\n public const GEMINI_2_FLASH = 'gemini-2.0-flash';\n public const GEMINI_2_PRO = 'gemini-2.0-pro-exp-02-05';\n public const GEMINI_2_FLASH_LITE = 'gemini-2.0-flash-lite-preview-02-05';\n public const GEMINI_2_FLASH_THINKING = 'gemini-2.0-flash-thinking-exp-01-21';\n public const GEMINI_1_5_FLASH = 'gemini-1.5-flash';\n\n /**\n * @param array $options The default options for the model usage\n */\n public function __construct(string $name = self::GEMINI_2_PRO, array $options = ['temperature' => 1.0])\n {\n $capabilities = [\n Capability::INPUT_MESSAGES,\n Capability::INPUT_IMAGE,\n Capability::INPUT_AUDIO,\n Capability::INPUT_PDF,\n Capability::OUTPUT_STREAMING,\n Capability::OUTPUT_STRUCTURED,\n Capability::TOOL_CALLING,\n ];\n\n parent::__construct($name, $capabilities, $options);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Replicate/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Replicate;\n\nuse Symfony\\AI\\Platform\\Bridge\\Replicate\\Contract\\LlamaMessageBagNormalizer;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\Clock\\Clock;\nuse Symfony\\Component\\HttpClient\\HttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class PlatformFactory\n{\n public static function create(\n #[\\SensitiveParameter]\n string $apiKey,\n ?HttpClientInterface $httpClient = null,\n ?Contract $contract = null,\n ): Platform {\n return new Platform(\n [new LlamaModelClient(new Client($httpClient ?? HttpClient::create(), new Clock(), $apiKey))],\n [new LlamaResultConverter()],\n $contract ?? Contract::create(new LlamaMessageBagNormalizer()),\n );\n }\n}\n"], ["/ai/src/mcp-sdk/src/Message/Request.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Message;\n\nfinal readonly class Request implements \\JsonSerializable, \\Stringable\n{\n /**\n * @param array|null $params\n */\n public function __construct(\n public int|string $id,\n public string $method,\n public ?array $params = null,\n ) {\n }\n\n /**\n * @param array{id: string|int, method: string, params?: array} $data\n */\n public static function from(array $data): self\n {\n return new self(\n $data['id'],\n $data['method'],\n $data['params'] ?? null,\n );\n }\n\n /**\n * @return array{jsonrpc: string, id: string|int, method: string, params: array|null}\n */\n public function jsonSerialize(): array\n {\n return [\n 'jsonrpc' => '2.0',\n 'id' => $this->id,\n 'method' => $this->method,\n 'params' => $this->params,\n ];\n }\n\n public function __toString(): string\n {\n return \\sprintf('%s: %s', $this->id, $this->method);\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/RequestHandler/PromptGetHandler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\RequestHandler;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Prompt\\PromptGet;\nuse Symfony\\AI\\McpSdk\\Capability\\Prompt\\PromptGetterInterface;\nuse Symfony\\AI\\McpSdk\\Exception\\ExceptionInterface;\nuse Symfony\\AI\\McpSdk\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\McpSdk\\Message\\Error;\nuse Symfony\\AI\\McpSdk\\Message\\Request;\nuse Symfony\\AI\\McpSdk\\Message\\Response;\n\nfinal class PromptGetHandler extends BaseRequestHandler\n{\n public function __construct(\n private readonly PromptGetterInterface $getter,\n ) {\n }\n\n public function createResponse(Request $message): Response|Error\n {\n $name = $message->params['name'];\n $arguments = $message->params['arguments'] ?? [];\n\n try {\n $result = $this->getter->get(new PromptGet(uniqid('', true), $name, $arguments));\n } catch (ExceptionInterface) {\n return Error::internalError($message->id, 'Error while handling prompt');\n }\n\n $messages = [];\n foreach ($result->messages as $resultMessage) {\n $content = match ($resultMessage->type) {\n 'text' => [\n 'type' => 'text',\n 'text' => $resultMessage->result,\n ],\n 'image', 'audio' => [\n 'type' => $resultMessage->type,\n 'data' => $resultMessage->result,\n 'mimeType' => $resultMessage->mimeType,\n ],\n 'resource' => [\n 'type' => 'resource',\n 'resource' => [\n 'uri' => $resultMessage->uri,\n 'mimeType' => $resultMessage->mimeType,\n 'text' => $resultMessage->result,\n ],\n ],\n // TODO better exception\n default => throw new InvalidArgumentException('Unsupported PromptGet result type: '.$resultMessage->type),\n };\n\n $messages[] = [\n 'role' => $resultMessage->role,\n 'content' => $content,\n ];\n }\n\n return new Response($message->id, [\n 'description' => $result->description,\n 'messages' => $messages,\n ]);\n }\n\n protected function supportedMethod(): string\n {\n return 'prompts/get';\n }\n}\n"], ["/ai/src/mcp-bundle/src/McpBundle.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpBundle;\n\nuse Symfony\\AI\\McpBundle\\Command\\McpCommand;\nuse Symfony\\AI\\McpBundle\\Controller\\McpController;\nuse Symfony\\AI\\McpBundle\\Routing\\RouteLoader;\nuse Symfony\\AI\\McpSdk\\Capability\\Tool\\IdentifierInterface;\nuse Symfony\\AI\\McpSdk\\Server\\NotificationHandlerInterface;\nuse Symfony\\AI\\McpSdk\\Server\\RequestHandlerInterface;\nuse Symfony\\Component\\Config\\Definition\\Configurator\\DefinitionConfigurator;\nuse Symfony\\Component\\DependencyInjection\\ContainerBuilder;\nuse Symfony\\Component\\DependencyInjection\\Loader\\Configurator\\ContainerConfigurator;\nuse Symfony\\Component\\DependencyInjection\\Reference;\nuse Symfony\\Component\\HttpKernel\\Bundle\\AbstractBundle;\n\nfinal class McpBundle extends AbstractBundle\n{\n public function configure(DefinitionConfigurator $definition): void\n {\n $definition->import('../config/options.php');\n }\n\n /**\n * @param array $config\n */\n public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void\n {\n $container->import('../config/services.php');\n\n $builder->setParameter('mcp.app', $config['app']);\n $builder->setParameter('mcp.version', $config['version']);\n\n if (isset($config['client_transports'])) {\n $this->configureClient($config['client_transports'], $builder);\n }\n\n $builder\n ->registerForAutoconfiguration(IdentifierInterface::class)\n ->addTag('mcp.tool')\n ;\n }\n\n /**\n * @param array{stdio: bool, sse: bool} $transports\n */\n private function configureClient(array $transports, ContainerBuilder $container): void\n {\n if (!$transports['stdio'] && !$transports['sse']) {\n return;\n }\n\n $container->registerForAutoconfiguration(NotificationHandlerInterface::class)\n ->addTag('mcp.server.notification_handler');\n $container->registerForAutoconfiguration(RequestHandlerInterface::class)\n ->addTag('mcp.server.request_handler');\n\n if ($transports['stdio']) {\n $container->register('mcp.server.command', McpCommand::class)\n ->setArguments([\n new Reference('mcp.server'),\n ])\n ->addTag('console.command');\n }\n\n if ($transports['sse']) {\n $container->register('mcp.server.controller', McpController::class)\n ->setArguments([\n new Reference('mcp.server'),\n new Reference('mcp.server.sse.store.cache_pool'),\n new Reference('router'),\n ])\n ->setPublic(true)\n ->addTag('controller.service_arguments');\n }\n\n $container->register('mcp.server.route_loader', RouteLoader::class)\n ->setArgument(0, $transports['sse'])\n ->addTag('routing.route_loader');\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/Embeddings/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\Embeddings;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Embeddings;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\VectorResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Embeddings;\n }\n\n public function convert(RawResultInterface $result, array $options = []): VectorResult\n {\n $data = $result->getData();\n\n if (!isset($data['data'])) {\n throw new RuntimeException('Response does not contain data');\n }\n\n return new VectorResult(\n ...array_map(\n static fn (array $item): Vector => new Vector($item['embedding']),\n $data['data']\n ),\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Embeddings/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini\\Embeddings;\n\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Embeddings;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\VectorResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\n\n/**\n * @author Valtteri R \n */\nfinal readonly class ResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Embeddings;\n }\n\n public function convert(RawResultInterface $result, array $options = []): VectorResult\n {\n $data = $result->getData();\n\n if (!isset($data['embeddings'])) {\n throw new RuntimeException('Response does not contain data');\n }\n\n return new VectorResult(\n ...array_map(\n static fn (array $item): Vector => new Vector($item['values']),\n $data['embeddings'],\n ),\n );\n }\n}\n"], ["/ai/src/platform/src/Contract/Normalizer/Result/ToolCallNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\Normalizer\\Result;\n\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ToolCallNormalizer implements NormalizerInterface\n{\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n return $data instanceof ToolCall;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n ToolCall::class => true,\n ];\n }\n\n /**\n * @param ToolCall $data\n *\n * @return array{\n * id: string,\n * type: 'function',\n * function: array{\n * name: string,\n * arguments: string\n * }\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'id' => $data->id,\n 'type' => 'function',\n 'function' => [\n 'name' => $data->name,\n 'arguments' => json_encode($data->arguments),\n ],\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/LMStudio/Embeddings/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\LMStudio\\Embeddings;\n\nuse Symfony\\AI\\Platform\\Bridge\\LMStudio\\Embeddings;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\VectorResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\nuse Symfony\\AI\\Platform\\Vector\\Vector;\n\n/**\n * @author Christopher Hertel \n * @author André Lubian \n */\nfinal class ResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Embeddings;\n }\n\n public function convert(RawResultInterface $result, array $options = []): VectorResult\n {\n $data = $result->getData();\n\n if (!isset($data['data'])) {\n throw new RuntimeException('Response does not contain data');\n }\n\n return new VectorResult(\n ...array_map(\n static fn (array $item): Vector => new Vector($item['embedding']),\n $data['data']\n ),\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/DallE/ImageResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\DallE;\n\nuse Symfony\\AI\\Platform\\Result\\BaseResult;\n\n/**\n * @author Denis Zunke \n */\nclass ImageResult extends BaseResult\n{\n /** @var list */\n private readonly array $images;\n\n public function __construct(\n public ?string $revisedPrompt = null, // Only string on Dall-E 3 usage\n Base64Image|UrlImage ...$images,\n ) {\n $this->images = array_values($images);\n }\n\n /**\n * @return list\n */\n public function getContent(): array\n {\n return $this->images;\n }\n}\n"], ["/ai/src/mcp-sdk/src/Message/Notification.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Message;\n\nfinal readonly class Notification implements \\JsonSerializable, \\Stringable\n{\n /**\n * @param array|null $params\n */\n public function __construct(\n public string $method,\n public ?array $params = null,\n ) {\n }\n\n /**\n * @param array{method: string, params?: array} $data\n */\n public static function from(array $data): self\n {\n return new self(\n $data['method'],\n $data['params'] ?? null,\n );\n }\n\n /**\n * @return array{jsonrpc: string, method: string, params: array|null}\n */\n public function jsonSerialize(): array\n {\n return [\n 'jsonrpc' => '2.0',\n 'method' => $this->method,\n 'params' => $this->params,\n ];\n }\n\n public function __toString(): string\n {\n return \\sprintf('%s', $this->method);\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/Transport/Stdio/SymfonyConsoleTransport.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\Transport\\Stdio;\n\nuse Symfony\\AI\\McpSdk\\Server\\TransportInterface;\nuse Symfony\\Component\\Console\\Input\\InputInterface;\nuse Symfony\\Component\\Console\\Input\\StreamableInputInterface;\nuse Symfony\\Component\\Console\\Output\\OutputInterface;\n\n/**\n * Heavily inspired by https://jolicode.com/blog/mcp-the-open-protocol-that-turns-llm-chatbots-into-intelligent-agents.\n */\nfinal class SymfonyConsoleTransport implements TransportInterface\n{\n private string $buffer = '';\n\n public function __construct(\n private readonly InputInterface $input,\n private readonly OutputInterface $output,\n ) {\n }\n\n public function initialize(): void\n {\n }\n\n public function isConnected(): bool\n {\n return true;\n }\n\n public function receive(): \\Generator\n {\n $stream = $this->input instanceof StreamableInputInterface ? $this->input->getStream() ?? \\STDIN : \\STDIN;\n $line = fgets($stream);\n if (false === $line) {\n return;\n }\n $this->buffer .= \\STDIN === $stream ? rtrim($line).\\PHP_EOL : $line;\n if (str_contains($this->buffer, \\PHP_EOL)) {\n $lines = explode(\\PHP_EOL, $this->buffer);\n $this->buffer = array_pop($lines);\n\n yield from $lines;\n }\n }\n\n public function send(string $data): void\n {\n $this->output->writeln($data);\n }\n\n public function close(): void\n {\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper\\AudioNormalizer;\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper\\ModelClient as WhisperModelClient;\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper\\ResultConverter as WhisperResponseConverter;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class PlatformFactory\n{\n public static function create(\n #[\\SensitiveParameter]\n string $apiKey,\n ?HttpClientInterface $httpClient = null,\n ?Contract $contract = null,\n ): Platform {\n $httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n\n return new Platform(\n [\n new GPT\\ModelClient($httpClient, $apiKey),\n new Embeddings\\ModelClient($httpClient, $apiKey),\n new DallE\\ModelClient($httpClient, $apiKey),\n new WhisperModelClient($httpClient, $apiKey),\n ],\n [\n new GPT\\ResultConverter(),\n new Embeddings\\ResultConverter(),\n new DallE\\ResultConverter(),\n new WhisperResponseConverter(),\n ],\n $contract ?? Contract::create(new AudioNormalizer()),\n );\n }\n}\n"], ["/ai/src/platform/src/Message/UserMessage.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message;\n\nuse Symfony\\AI\\Platform\\Message\\Content\\Audio;\nuse Symfony\\AI\\Platform\\Message\\Content\\ContentInterface;\nuse Symfony\\AI\\Platform\\Message\\Content\\Image;\nuse Symfony\\AI\\Platform\\Message\\Content\\ImageUrl;\nuse Symfony\\Component\\Uid\\AbstractUid;\nuse Symfony\\Component\\Uid\\TimeBasedUidInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class UserMessage implements MessageInterface\n{\n /**\n * @var list\n */\n public array $content;\n\n public AbstractUid&TimeBasedUidInterface $id;\n\n public function __construct(\n ContentInterface ...$content,\n ) {\n $this->content = $content;\n $this->id = Uuid::v7();\n }\n\n public function getRole(): Role\n {\n return Role::User;\n }\n\n public function getId(): AbstractUid&TimeBasedUidInterface\n {\n return $this->id;\n }\n\n public function hasAudioContent(): bool\n {\n foreach ($this->content as $content) {\n if ($content instanceof Audio) {\n return true;\n }\n }\n\n return false;\n }\n\n public function hasImageContent(): bool\n {\n foreach ($this->content as $content) {\n if ($content instanceof Image || $content instanceof ImageUrl) {\n return true;\n }\n }\n\n return false;\n }\n}\n"], ["/ai/src/platform/src/Bridge/LMStudio/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\LMStudio;\n\nuse Symfony\\AI\\Platform\\Bridge\\LMStudio\\Embeddings\\ModelClient;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author André Lubian \n */\nclass PlatformFactory\n{\n public static function create(\n string $hostUrl = 'http://localhost:1234',\n ?HttpClientInterface $httpClient = null,\n ?Contract $contract = null,\n ): Platform {\n $httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n\n return new Platform(\n [\n new ModelClient($httpClient, $hostUrl),\n new Completions\\ModelClient($httpClient, $hostUrl),\n ],\n [\n new Embeddings\\ResultConverter(),\n new Completions\\ResultConverter(),\n ], $contract);\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/ZeroShotClassificationResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ZeroShotClassificationResult\n{\n /**\n * @param array $labels\n * @param array $scores\n */\n public function __construct(\n public array $labels,\n public array $scores,\n public ?string $sequence = null,\n ) {\n }\n\n /**\n * @param array{labels: array, scores: array, sequence?: string} $data\n */\n public static function fromArray(array $data): self\n {\n return new self(\n $data['labels'],\n $data['scores'],\n $data['sequence'] ?? null,\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace;\n\nuse Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Contract\\FileNormalizer;\nuse Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Contract\\MessageBagNormalizer;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class PlatformFactory\n{\n public static function create(\n #[\\SensitiveParameter]\n string $apiKey,\n string $provider = Provider::HF_INFERENCE,\n ?HttpClientInterface $httpClient = null,\n ?Contract $contract = null,\n ): Platform {\n $httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n\n return new Platform(\n [new ModelClient($httpClient, $provider, $apiKey)],\n [new ResultConverter()],\n $contract ?? Contract::create(\n new FileNormalizer(),\n new MessageBagNormalizer(),\n ),\n );\n }\n}\n"], ["/ai/src/ai-bundle/src/Profiler/DataCollector.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\AIBundle\\Profiler;\n\nuse Symfony\\AI\\Agent\\Toolbox\\ToolboxInterface;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\nuse Symfony\\Bundle\\FrameworkBundle\\DataCollector\\AbstractDataCollector;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\HttpKernel\\DataCollector\\LateDataCollectorInterface;\n\n/**\n * @author Christopher Hertel \n *\n * @phpstan-import-type PlatformCallData from TraceablePlatform\n * @phpstan-import-type ToolCallData from TraceableToolbox\n */\nfinal class DataCollector extends AbstractDataCollector implements LateDataCollectorInterface\n{\n /**\n * @var TraceablePlatform[]\n */\n private readonly array $platforms;\n\n /**\n * @var TraceableToolbox[]\n */\n private readonly array $toolboxes;\n\n /**\n * @param TraceablePlatform[] $platforms\n * @param TraceableToolbox[] $toolboxes\n */\n public function __construct(\n iterable $platforms,\n private readonly ToolboxInterface $defaultToolBox,\n iterable $toolboxes,\n ) {\n $this->platforms = $platforms instanceof \\Traversable ? iterator_to_array($platforms) : $platforms;\n $this->toolboxes = $toolboxes instanceof \\Traversable ? iterator_to_array($toolboxes) : $toolboxes;\n }\n\n public function collect(Request $request, Response $response, ?\\Throwable $exception = null): void\n {\n $this->lateCollect();\n }\n\n public function lateCollect(): void\n {\n $this->data = [\n 'tools' => $this->defaultToolBox->getTools(),\n 'platform_calls' => array_merge(...array_map($this->awaitCallResults(...), $this->platforms)),\n 'tool_calls' => array_merge(...array_map(fn (TraceableToolbox $toolbox) => $toolbox->calls, $this->toolboxes)),\n ];\n }\n\n public static function getTemplate(): string\n {\n return '@AI/data_collector.html.twig';\n }\n\n /**\n * @return PlatformCallData[]\n */\n public function getPlatformCalls(): array\n {\n return $this->data['platform_calls'] ?? [];\n }\n\n /**\n * @return Tool[]\n */\n public function getTools(): array\n {\n return $this->data['tools'] ?? [];\n }\n\n /**\n * @return ToolCallData[]\n */\n public function getToolCalls(): array\n {\n return $this->data['tool_calls'] ?? [];\n }\n\n /**\n * @return array{\n * model: Model,\n * input: array|string|object,\n * options: array,\n * result: string|iterable|object|null\n * }[]\n */\n private function awaitCallResults(TraceablePlatform $platform): array\n {\n $calls = $platform->calls;\n foreach ($calls as $key => $call) {\n $result = $call['result']->await();\n\n if (isset($platform->resultCache[$result])) {\n $call['result'] = $platform->resultCache[$result];\n } else {\n $call['result'] = $result->getContent();\n }\n\n $calls[$key] = $call;\n }\n\n return $calls;\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Contract/MessageBagNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Gemini;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Message\\Role;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareInterface;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareTrait;\n\n/**\n * @author Christopher Hertel \n */\nfinal class MessageBagNormalizer extends ModelContractNormalizer implements NormalizerAwareInterface\n{\n use NormalizerAwareTrait;\n\n protected function supportedDataClass(): string\n {\n return MessageBagInterface::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Gemini;\n }\n\n /**\n * @param MessageBagInterface $data\n *\n * @return array{\n * contents: list\n * }>,\n * system_instruction?: array{parts: array{text: string}[]}\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n $array = ['contents' => []];\n\n if (null !== $systemMessage = $data->getSystemMessage()) {\n $array['system_instruction'] = [\n 'parts' => [['text' => $systemMessage->content]],\n ];\n }\n\n foreach ($data->withoutSystemMessage()->getMessages() as $message) {\n $array['contents'][] = [\n 'role' => $message->getRole()->equals(Role::Assistant) ? 'model' : 'user',\n 'parts' => $this->normalizer->normalize($message, $format, $context),\n ];\n }\n\n return $array;\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenRouter/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenRouter;\n\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Contract\\AssistantMessageNormalizer;\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Contract\\MessageBagNormalizer;\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Contract\\UserMessageNormalizer;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author rglozman\n */\nfinal class PlatformFactory\n{\n public static function create(\n #[\\SensitiveParameter]\n string $apiKey,\n ?HttpClientInterface $httpClient = null,\n ?Contract $contract = null,\n ): Platform {\n $httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n\n return new Platform(\n [new ModelClient($httpClient, $apiKey)],\n [new ResultConverter()],\n $contract ?? Contract::create(\n new AssistantMessageNormalizer(),\n new MessageBagNormalizer(),\n new UserMessageNormalizer(),\n ),\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/ObjectDetectionResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ObjectDetectionResult\n{\n /**\n * @param DetectedObject[] $objects\n */\n public function __construct(\n public array $objects,\n ) {\n }\n\n /**\n * @param array $data\n */\n public static function fromArray(array $data): self\n {\n return new self(array_map(\n fn (array $item) => new DetectedObject(\n $item['label'],\n $item['score'],\n $item['box']['xmin'],\n $item['box']['ymin'],\n $item['box']['xmax'],\n $item['box']['ymax'],\n ),\n $data,\n ));\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/ApiClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace;\n\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\Component\\HttpClient\\HttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ApiClient\n{\n public function __construct(\n private ?HttpClientInterface $httpClient = null,\n ) {\n $this->httpClient = $httpClient ?? HttpClient::create();\n }\n\n /**\n * @return Model[]\n */\n public function models(?string $provider, ?string $task): array\n {\n $result = $this->httpClient->request('GET', 'https://huggingface.co/api/models', [\n 'query' => [\n 'inference_provider' => $provider,\n 'pipeline_tag' => $task,\n ],\n ]);\n\n return array_map(fn (array $model) => new Model($model['id']), $result->toArray());\n }\n}\n"], ["/ai/src/platform/src/Message/MessageBag.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message;\n\n/**\n * @final\n *\n * @author Christopher Hertel \n */\nclass MessageBag implements MessageBagInterface\n{\n /**\n * @var list\n */\n private array $messages;\n\n public function __construct(MessageInterface ...$messages)\n {\n $this->messages = array_values($messages);\n }\n\n public function add(MessageInterface $message): void\n {\n $this->messages[] = $message;\n }\n\n /**\n * @return list\n */\n public function getMessages(): array\n {\n return $this->messages;\n }\n\n public function getSystemMessage(): ?SystemMessage\n {\n foreach ($this->messages as $message) {\n if ($message instanceof SystemMessage) {\n return $message;\n }\n }\n\n return null;\n }\n\n public function with(MessageInterface $message): self\n {\n $messages = clone $this;\n $messages->add($message);\n\n return $messages;\n }\n\n public function merge(MessageBagInterface $messageBag): self\n {\n $messages = clone $this;\n $messages->messages = array_merge($messages->messages, $messageBag->getMessages());\n\n return $messages;\n }\n\n public function withoutSystemMessage(): self\n {\n $messages = clone $this;\n $messages->messages = array_values(array_filter(\n $messages->messages,\n static fn (MessageInterface $message) => !$message instanceof SystemMessage,\n ));\n\n return $messages;\n }\n\n public function prepend(MessageInterface $message): self\n {\n $messages = clone $this;\n $messages->messages = array_merge([$message], $messages->messages);\n\n return $messages;\n }\n\n public function containsAudio(): bool\n {\n foreach ($this->messages as $message) {\n if ($message instanceof UserMessage && $message->hasAudioContent()) {\n return true;\n }\n }\n\n return false;\n }\n\n public function containsImage(): bool\n {\n foreach ($this->messages as $message) {\n if ($message instanceof UserMessage && $message->hasImageContent()) {\n return true;\n }\n }\n\n return false;\n }\n\n public function count(): int\n {\n return \\count($this->messages);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Mistral/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Mistral;\n\nuse Symfony\\AI\\Platform\\Bridge\\Mistral\\Contract\\ToolNormalizer;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class PlatformFactory\n{\n public static function create(\n #[\\SensitiveParameter]\n string $apiKey,\n ?HttpClientInterface $httpClient = null,\n ?Contract $contract = null,\n ): Platform {\n $httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n\n return new Platform(\n [new Embeddings\\ModelClient($httpClient, $apiKey), new Llm\\ModelClient($httpClient, $apiKey)],\n [new Embeddings\\ResultConverter(), new Llm\\ResultConverter()],\n $contract ?? Contract::create(new ToolNormalizer()),\n );\n }\n}\n"], ["/ai/src/platform/src/Contract/Normalizer/Message/AssistantMessageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\Normalizer\\Message;\n\nuse Symfony\\AI\\Platform\\Message\\AssistantMessage;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareInterface;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareTrait;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class AssistantMessageNormalizer implements NormalizerInterface, NormalizerAwareInterface\n{\n use NormalizerAwareTrait;\n\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n return $data instanceof AssistantMessage;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n AssistantMessage::class => true,\n ];\n }\n\n /**\n * @param AssistantMessage $data\n *\n * @return array{role: 'assistant', content?: string, tool_calls?: array>}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n $array = [\n 'role' => $data->getRole()->value,\n ];\n\n if (null !== $data->content) {\n $array['content'] = $data->content;\n }\n\n if ($data->hasToolCalls()) {\n $array['tool_calls'] = $this->normalizer->normalize($data->toolCalls, $format, $context);\n }\n\n return $array;\n }\n}\n"], ["/ai/src/agent/src/StructuredOutput/ResponseFormatFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\StructuredOutput;\n\nuse Symfony\\AI\\Platform\\Contract\\JsonSchema\\Factory;\n\nuse function Symfony\\Component\\String\\u;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ResponseFormatFactory implements ResponseFormatFactoryInterface\n{\n public function __construct(\n private Factory $schemaFactory = new Factory(),\n ) {\n }\n\n public function create(string $responseClass): array\n {\n return [\n 'type' => 'json_schema',\n 'json_schema' => [\n 'name' => u($responseClass)->afterLast('\\\\')->toString(),\n 'schema' => $this->schemaFactory->buildProperties($responseClass),\n 'strict' => true,\n ],\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/Azure/OpenAI/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Azure\\OpenAI;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Embeddings;\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\GPT;\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper;\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper\\AudioNormalizer;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class PlatformFactory\n{\n public static function create(\n string $baseUrl,\n string $deployment,\n string $apiVersion,\n #[\\SensitiveParameter]\n string $apiKey,\n ?HttpClientInterface $httpClient = null,\n ?Contract $contract = null,\n ): Platform {\n $httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n $embeddingsModelClient = new EmbeddingsModelClient($httpClient, $baseUrl, $deployment, $apiVersion, $apiKey);\n $GPTModelClient = new GPTModelClient($httpClient, $baseUrl, $deployment, $apiVersion, $apiKey);\n $whisperModelClient = new WhisperModelClient($httpClient, $baseUrl, $deployment, $apiVersion, $apiKey);\n\n return new Platform(\n [$GPTModelClient, $embeddingsModelClient, $whisperModelClient],\n [new GPT\\ResultConverter(), new Embeddings\\ResultConverter(), new Whisper\\ResultConverter()],\n $contract ?? Contract::create(new AudioNormalizer()),\n );\n }\n}\n"], ["/ai/fixtures/Movies.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures;\n\nfinal readonly class Movies\n{\n /**\n * @return array\n */\n public static function all(): array\n {\n return [\n ['title' => 'Inception', 'description' => 'A skilled thief is given a chance at redemption if he can successfully perform inception, the act of planting an idea in someone\\'s subconscious.', 'director' => 'Christopher Nolan'],\n ['title' => 'The Matrix', 'description' => 'A hacker discovers the world he lives in is a simulated reality and joins a rebellion to overthrow its controllers.', 'director' => 'The Wachowskis'],\n ['title' => 'The Godfather', 'description' => 'The aging patriarch of an organized crime dynasty transfers control of his empire to his reluctant son.', 'director' => 'Francis Ford Coppola'],\n ['title' => 'Notting Hill', 'description' => 'A British bookseller meets and falls in love with a famous American actress, navigating the challenges of fame and romance.', 'director' => 'Roger Michell'],\n ['title' => 'WALL-E', 'description' => 'A small waste-collecting robot inadvertently embarks on a space journey that will decide the fate of mankind.', 'director' => 'Andrew Stanton'],\n ['title' => 'Spirited Away', 'description' => 'A young girl enters a mysterious world of spirits and must find a way to rescue her parents and return home.', 'director' => 'Hayao Miyazaki'],\n ['title' => 'Jurassic Park', 'description' => 'During a preview tour, a theme park suffers a major power breakdown that allows its cloned dinosaur exhibits to run amok.', 'director' => 'Steven Spielberg'],\n ['title' => 'Interstellar', 'description' => 'A team of explorers travel through a wormhole in space in an attempt to ensure humanity\\'s survival.', 'director' => 'Christopher Nolan'],\n ['title' => 'The Shawshank Redemption', 'description' => 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', 'director' => 'Frank Darabont'],\n ['title' => 'Gladiator', 'description' => 'A former Roman General sets out to exact vengeance against the corrupt emperor who murdered his family and sent him into slavery.', 'director' => 'Ridley Scott'],\n ];\n }\n}\n"], ["/ai/src/agent/src/Toolbox/StreamResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox;\n\nuse Symfony\\AI\\Platform\\Message\\Message;\nuse Symfony\\AI\\Platform\\Result\\BaseResult;\nuse Symfony\\AI\\Platform\\Result\\ToolCallResult;\n\n/**\n * @author Denis Zunke \n */\nfinal class StreamResult extends BaseResult\n{\n public function __construct(\n private readonly \\Generator $generator,\n private readonly \\Closure $handleToolCallsCallback,\n ) {\n }\n\n public function getContent(): \\Generator\n {\n $streamedResult = '';\n foreach ($this->generator as $value) {\n if ($value instanceof ToolCallResult) {\n yield from ($this->handleToolCallsCallback)($value, Message::ofAssistant($streamedResult))->getContent();\n\n break;\n }\n\n $streamedResult .= $value;\n\n yield $value;\n }\n }\n}\n"], ["/ai/src/platform/src/Bridge/TransformersPHP/PipelineExecution.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\TransformersPHP;\n\nuse Codewithkyrian\\Transformers\\Pipelines\\Pipeline;\n\n/**\n * @author Christopher Hertel \n */\nfinal class PipelineExecution\n{\n /**\n * @var array|null\n */\n private ?array $result = null;\n\n /**\n * @param array|string $input\n */\n public function __construct(\n private readonly Pipeline $pipeline,\n private readonly array|string $input,\n ) {\n }\n\n /**\n * @return array\n */\n public function getResult(): array\n {\n if (null === $this->result) {\n $this->result = ($this->pipeline)($this->input);\n }\n\n return $this->result;\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini;\n\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Contract\\GeminiContract;\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Embeddings\\ModelClient as EmbeddingsModelClient;\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Embeddings\\ResultConverter as EmbeddingsResultConverter;\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Gemini\\ModelClient as GeminiModelClient;\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Gemini\\ResultConverter as GeminiResultConverter;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Roy Garrido\n */\nfinal readonly class PlatformFactory\n{\n public static function create(\n #[\\SensitiveParameter]\n string $apiKey,\n ?HttpClientInterface $httpClient = null,\n ?Contract $contract = null,\n ): Platform {\n $httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n\n return new Platform(\n [new EmbeddingsModelClient($httpClient, $apiKey), new GeminiModelClient($httpClient, $apiKey)],\n [new EmbeddingsResultConverter(), new GeminiResultConverter()],\n $contract ?? GeminiContract::create(),\n );\n }\n}\n"], ["/ai/fixtures/Tool/ToolException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\n\n#[AsTool('tool_exception', description: 'This tool is broken', method: 'bar')]\nfinal class ToolException\n{\n public function bar(): string\n {\n throw new \\Exception('Tool error.');\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/Meta/LlamaResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock\\Meta;\n\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\RawBedrockResult;\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\Llama;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\n\n/**\n * @author Björn Altmann\n */\nclass LlamaResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Llama;\n }\n\n public function convert(RawResultInterface|RawBedrockResult $result, array $options = []): TextResult\n {\n $data = $result->getData();\n\n if (!isset($data['generation'])) {\n throw new RuntimeException('Response does not contain any content');\n }\n\n return new TextResult($data['generation']);\n }\n}\n"], ["/ai/src/platform/src/Contract/Normalizer/Message/MessageBagNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\Normalizer\\Message;\n\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareInterface;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareTrait;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class MessageBagNormalizer implements NormalizerInterface, NormalizerAwareInterface\n{\n use NormalizerAwareTrait;\n\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n return $data instanceof MessageBagInterface;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n MessageBagInterface::class => true,\n ];\n }\n\n /**\n * @param MessageBagInterface $data\n *\n * @return array{\n * messages: array,\n * model?: string,\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n $array = [\n 'messages' => $this->normalizer->normalize($data->getMessages(), $format, $context),\n ];\n\n if (isset($context[Contract::CONTEXT_MODEL]) && $context[Contract::CONTEXT_MODEL] instanceof Model) {\n $array['model'] = $context[Contract::CONTEXT_MODEL]->getName();\n }\n\n return $array;\n }\n}\n"], ["/ai/src/platform/src/Bridge/Mistral/Embeddings/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Mistral\\Embeddings;\n\nuse Symfony\\AI\\Platform\\Bridge\\Mistral\\Embeddings;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ModelClient implements ModelClientInterface\n{\n private EventSourceHttpClient $httpClient;\n\n public function __construct(\n HttpClientInterface $httpClient,\n #[\\SensitiveParameter]\n private string $apiKey,\n ) {\n $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Embeddings;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n return new RawHttpResult($this->httpClient->request('POST', 'https://api.mistral.ai/v1/embeddings', [\n 'auth_bearer' => $this->apiKey,\n 'headers' => [\n 'Content-Type' => 'application/json',\n ],\n 'json' => array_merge($options, [\n 'model' => $model->getName(),\n 'input' => $payload,\n ]),\n ]));\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Tool/SerpApi.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\n#[AsTool(name: 'serpapi', description: 'search for information on the internet')]\nfinal readonly class SerpApi\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n private string $apiKey,\n ) {\n }\n\n /**\n * @param string $query The search query to use\n */\n public function __invoke(string $query): string\n {\n $result = $this->httpClient->request('GET', 'https://serpapi.com/search', [\n 'query' => [\n 'q' => $query,\n 'api_key' => $this->apiKey,\n ],\n ]);\n\n return \\sprintf('Results for \"%s\" are \"%s\".', $query, $this->extractBestResponse($result->toArray()));\n }\n\n /**\n * @param array $results\n */\n private function extractBestResponse(array $results): string\n {\n return implode('. ', array_map(fn ($story) => $story['title'], $results['organic_results']));\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/Contract/MessageBagNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\Claude;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareInterface;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareTrait;\n\n/**\n * @author Christopher Hertel \n */\nfinal class MessageBagNormalizer extends ModelContractNormalizer implements NormalizerAwareInterface\n{\n use NormalizerAwareTrait;\n\n protected function supportedDataClass(): string\n {\n return MessageBagInterface::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Claude;\n }\n\n /**\n * @param MessageBagInterface $data\n *\n * @return array{\n * messages: array,\n * model?: string,\n * system?: string,\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n $array = [\n 'messages' => $this->normalizer->normalize($data->withoutSystemMessage()->getMessages(), $format, $context),\n ];\n\n if (null !== $system = $data->getSystemMessage()) {\n $array['system'] = $system->content;\n }\n\n if (isset($context[Contract::CONTEXT_MODEL]) && $context[Contract::CONTEXT_MODEL] instanceof Model) {\n $array['model'] = $context[Contract::CONTEXT_MODEL]->getName();\n }\n\n return $array;\n }\n}\n"], ["/ai/src/platform/src/Contract.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform;\n\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\AssistantMessageNormalizer;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\Content\\AudioNormalizer;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\Content\\ImageNormalizer;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\Content\\ImageUrlNormalizer;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\Content\\TextNormalizer;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\MessageBagNormalizer;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\SystemMessageNormalizer;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\ToolCallMessageNormalizer;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\UserMessageNormalizer;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\Result\\ToolCallNormalizer;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ToolNormalizer;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\nuse Symfony\\Component\\Serializer\\Normalizer\\AbstractObjectNormalizer;\nuse Symfony\\Component\\Serializer\\Normalizer\\JsonSerializableNormalizer;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\nuse Symfony\\Component\\Serializer\\Serializer;\n\n/**\n * @author Christopher Hertel \n */\nreadonly class Contract\n{\n public const CONTEXT_MODEL = 'model';\n\n final public function __construct(\n protected NormalizerInterface $normalizer,\n ) {\n }\n\n public static function create(NormalizerInterface ...$normalizer): self\n {\n // Messages\n $normalizer[] = new MessageBagNormalizer();\n $normalizer[] = new AssistantMessageNormalizer();\n $normalizer[] = new SystemMessageNormalizer();\n $normalizer[] = new ToolCallMessageNormalizer();\n $normalizer[] = new UserMessageNormalizer();\n\n // Message Content\n $normalizer[] = new AudioNormalizer();\n $normalizer[] = new ImageNormalizer();\n $normalizer[] = new ImageUrlNormalizer();\n $normalizer[] = new TextNormalizer();\n\n // Options\n $normalizer[] = new ToolNormalizer();\n\n // Result\n $normalizer[] = new ToolCallNormalizer();\n\n // JsonSerializable objects as extension point to library interfaces\n $normalizer[] = new JsonSerializableNormalizer();\n\n return new self(\n new Serializer($normalizer),\n );\n }\n\n /**\n * @param object|array|string $input\n *\n * @return array|string\n */\n final public function createRequestPayload(Model $model, object|array|string $input): string|array\n {\n return $this->normalizer->normalize($input, context: [self::CONTEXT_MODEL => $model]);\n }\n\n /**\n * @param Tool[] $tools\n *\n * @return array\n */\n final public function createToolOption(array $tools, Model $model): array\n {\n return $this->normalizer->normalize($tools, context: [\n self::CONTEXT_MODEL => $model,\n AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true,\n ]);\n }\n}\n"], ["/ai/src/platform/src/Bridge/LMStudio/Completions.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\LMStudio;\n\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author André Lubian \n */\nclass Completions extends Model\n{\n public const DEFAULT_CAPABILITIES = [\n Capability::INPUT_MESSAGES,\n Capability::OUTPUT_TEXT,\n Capability::OUTPUT_STREAMING,\n ];\n\n public function __construct(\n string $name,\n array $options = ['temperature' => 0.7],\n array $capabilities = self::DEFAULT_CAPABILITIES,\n ) {\n parent::__construct($name, $capabilities, $options);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Replicate/LlamaResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Replicate;\n\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\Llama;\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class LlamaResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Llama;\n }\n\n public function convert(RawResultInterface $result, array $options = []): ResultInterface\n {\n $data = $result->getData();\n\n if (!isset($data['output'])) {\n throw new RuntimeException('Response does not contain output');\n }\n\n return new TextResult(implode('', $data['output']));\n }\n}\n"], ["/ai/src/store/src/Document/LoaderInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Document;\n\n/**\n * @author Christopher Hertel \n */\ninterface LoaderInterface\n{\n /**\n * @param string $source Identifier for the loader to load the documents from, e.g. file path, folder, or URL.\n * @param array $options loader specific set of options to control the loading process\n *\n * @return iterable iterable of TextDocuments loaded from the source\n */\n public function __invoke(string $source, array $options = []): iterable;\n}\n"], ["/ai/src/platform/src/Bridge/Mistral/Llm/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Mistral\\Llm;\n\nuse Symfony\\AI\\Platform\\Bridge\\Mistral\\Mistral;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ModelClient implements ModelClientInterface\n{\n private EventSourceHttpClient $httpClient;\n\n public function __construct(\n HttpClientInterface $httpClient,\n #[\\SensitiveParameter]\n private string $apiKey,\n ) {\n $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Mistral;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n return new RawHttpResult($this->httpClient->request('POST', 'https://api.mistral.ai/v1/chat/completions', [\n 'auth_bearer' => $this->apiKey,\n 'headers' => [\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json',\n ],\n 'json' => array_merge($options, $payload),\n ]));\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/Nova/Contract/AssistantMessageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\Nova;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\AssistantMessage;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\n\n/**\n * @author Christopher Hertel \n */\nfinal class AssistantMessageNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return AssistantMessage::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Nova;\n }\n\n /**\n * @param AssistantMessage $data\n *\n * @return array{\n * role: 'assistant',\n * content: array\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n if ($data->hasToolCalls()) {\n return [\n 'role' => 'assistant',\n 'content' => array_map(static function (ToolCall $toolCall) {\n return [\n 'toolUse' => [\n 'toolUseId' => $toolCall->id,\n 'name' => $toolCall->name,\n 'input' => [] !== $toolCall->arguments ? $toolCall->arguments : new \\stdClass(),\n ],\n ];\n }, $data->toolCalls),\n ];\n }\n\n return [\n 'role' => 'assistant',\n 'content' => [['text' => $data->content]],\n ];\n }\n}\n"], ["/ai/fixtures/Tool/ToolOptionalParam.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\n\n#[AsTool('tool_optional_param', 'A tool with one optional parameter', method: 'bar')]\nfinal class ToolOptionalParam\n{\n /**\n * @param string $text The text given to the tool\n * @param int $number A number given to the tool\n */\n public function bar(string $text, int $number = 3): string\n {\n return \\sprintf('%s says \"%d\".', $text, $number);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Replicate/Contract/LlamaMessageBagNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Replicate\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\Llama;\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\LlamaPromptConverter;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Message\\SystemMessage;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nfinal class LlamaMessageBagNormalizer extends ModelContractNormalizer\n{\n public function __construct(\n private readonly LlamaPromptConverter $promptConverter = new LlamaPromptConverter(),\n ) {\n }\n\n protected function supportedDataClass(): string\n {\n return MessageBagInterface::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Llama;\n }\n\n /**\n * @param MessageBagInterface $data\n *\n * @return array{system: string, prompt: string}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'system' => $this->promptConverter->convertMessage($data->getSystemMessage() ?? new SystemMessage('')),\n 'prompt' => $this->promptConverter->convertToPrompt($data->withoutSystemMessage()),\n ];\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/RequestHandler/InitializeHandler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\RequestHandler;\n\nuse Symfony\\AI\\McpSdk\\Message\\Request;\nuse Symfony\\AI\\McpSdk\\Message\\Response;\n\nfinal class InitializeHandler extends BaseRequestHandler\n{\n public function __construct(\n private readonly string $name = 'app',\n private readonly string $version = 'dev',\n ) {\n }\n\n public function createResponse(Request $message): Response\n {\n return new Response($message->id, [\n 'protocolVersion' => '2025-03-26',\n 'capabilities' => [\n 'prompts' => ['listChanged' => false],\n 'tools' => ['listChanged' => false],\n 'resources' => ['listChanged' => false, 'subscribe' => false],\n ],\n 'serverInfo' => ['name' => $this->name, 'version' => $this->version],\n ]);\n }\n\n protected function supportedMethod(): string\n {\n return 'initialize';\n }\n}\n"], ["/ai/src/platform/src/Message/AssistantMessage.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message;\n\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\Component\\Uid\\AbstractUid;\nuse Symfony\\Component\\Uid\\TimeBasedUidInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class AssistantMessage implements MessageInterface\n{\n public AbstractUid&TimeBasedUidInterface $id;\n\n /**\n * @param ?ToolCall[] $toolCalls\n */\n public function __construct(\n public ?string $content = null,\n public ?array $toolCalls = null,\n ) {\n $this->id = Uuid::v7();\n }\n\n public function getRole(): Role\n {\n return Role::Assistant;\n }\n\n public function getId(): AbstractUid&TimeBasedUidInterface\n {\n return $this->id;\n }\n\n public function hasToolCalls(): bool\n {\n return null !== $this->toolCalls && [] !== $this->toolCalls;\n }\n}\n"], ["/ai/src/platform/src/Bridge/Voyage/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Voyage;\n\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class PlatformFactory\n{\n public static function create(\n #[\\SensitiveParameter]\n string $apiKey,\n ?HttpClientInterface $httpClient = null,\n ?Contract $contract = null,\n ): Platform {\n $httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n\n return new Platform([new ModelClient($httpClient, $apiKey)], [new ResultConverter()], $contract);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Azure/Meta/LlamaModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Azure\\Meta;\n\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\Llama;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class LlamaModelClient implements ModelClientInterface\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n private string $baseUrl,\n #[\\SensitiveParameter] private string $apiKey,\n ) {\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Llama;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n $url = \\sprintf('https://%s/chat/completions', $this->baseUrl);\n\n return new RawHttpResult($this->httpClient->request('POST', $url, [\n 'headers' => [\n 'Content-Type' => 'application/json',\n 'Authorization' => $this->apiKey,\n ],\n 'json' => array_merge($options, $payload),\n ]));\n }\n}\n"], ["/ai/fixtures/StructuredOutput/UserWithConstructor.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\StructuredOutput;\n\nfinal class UserWithConstructor\n{\n /**\n * @param string $name The name of the user in lowercase\n */\n public function __construct(\n public int $id,\n public string $name,\n public \\DateTimeInterface $createdAt,\n public bool $isActive,\n public ?int $age = null,\n ) {\n }\n}\n"], ["/ai/src/platform/src/Bridge/Ollama/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Ollama;\n\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class PlatformFactory\n{\n public static function create(\n string $hostUrl = 'http://localhost:11434',\n ?HttpClientInterface $httpClient = null,\n ?Contract $contract = null,\n ): Platform {\n $httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n\n return new Platform([new LlamaModelClient($httpClient, $hostUrl)], [new LlamaResultConverter()], $contract);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Contract/UserMessageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Gemini\\Gemini;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\Content\\File;\nuse Symfony\\AI\\Platform\\Message\\Content\\Text;\nuse Symfony\\AI\\Platform\\Message\\UserMessage;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nfinal class UserMessageNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return UserMessage::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Gemini;\n }\n\n /**\n * @param UserMessage $data\n *\n * @return list\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n $parts = [];\n foreach ($data->content as $content) {\n if ($content instanceof Text) {\n $parts[] = ['text' => $content->text];\n }\n if ($content instanceof File) {\n $parts[] = ['inline_data' => [\n 'mime_type' => $content->getFormat(),\n 'data' => $content->asBase64(),\n ]];\n }\n }\n\n return $parts;\n }\n}\n"], ["/ai/src/platform/src/Bridge/Azure/Meta/PlatformFactory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Azure\\Meta;\n\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Platform;\nuse Symfony\\Component\\HttpClient\\HttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class PlatformFactory\n{\n public static function create(\n string $baseUrl,\n #[\\SensitiveParameter]\n string $apiKey,\n ?HttpClientInterface $httpClient = null,\n ?Contract $contract = null,\n ): Platform {\n $modelClient = new LlamaModelClient($httpClient ?? HttpClient::create(), $baseUrl, $apiKey);\n\n return new Platform([$modelClient], [new LlamaResultConverter()], $contract);\n }\n}\n"], ["/ai/src/platform/src/Bridge/LMStudio/Completions/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\LMStudio\\Completions;\n\nuse Symfony\\AI\\Platform\\Bridge\\LMStudio\\Completions;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface as PlatformResponseFactory;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Component\\HttpClient\\EventSourceHttpClient;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author André Lubian \n */\nfinal readonly class ModelClient implements PlatformResponseFactory\n{\n private EventSourceHttpClient $httpClient;\n\n public function __construct(\n HttpClientInterface $httpClient,\n private string $hostUrl,\n ) {\n $this->httpClient = $httpClient instanceof EventSourceHttpClient ? $httpClient : new EventSourceHttpClient($httpClient);\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Completions;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n return new RawHttpResult($this->httpClient->request('POST', \\sprintf('%s/v1/chat/completions', $this->hostUrl), [\n 'json' => array_merge($options, $payload),\n ]));\n }\n}\n"], ["/ai/src/platform/src/Contract/Normalizer/Message/ToolCallMessageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\Normalizer\\Message;\n\nuse Symfony\\AI\\Platform\\Message\\ToolCallMessage;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareInterface;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareTrait;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ToolCallMessageNormalizer implements NormalizerInterface, NormalizerAwareInterface\n{\n use NormalizerAwareTrait;\n\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n return $data instanceof ToolCallMessage;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n ToolCallMessage::class => true,\n ];\n }\n\n /**\n * @return array{\n * role: 'tool',\n * content: string,\n * tool_call_id: string,\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'role' => $data->getRole()->value,\n 'content' => $this->normalizer->normalize($data->content, $format, $context),\n 'tool_call_id' => $data->toolCall->id,\n ];\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Tool/ToolCallResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Tool;\n\nfinal readonly class ToolCallResult\n{\n public function __construct(\n public string $result,\n /**\n * @var \"text\"|\"image\"|\"audio\"|\"resource\"|non-empty-string\n */\n public string $type = 'text',\n public string $mimeType = 'text/plan',\n public bool $isError = false,\n public ?string $uri = null,\n ) {\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/Nova/Contract/ToolNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\Nova;\nuse Symfony\\AI\\Platform\\Contract\\JsonSchema\\Factory;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\n\n/**\n * @phpstan-import-type JsonSchema from Factory\n *\n * @author Christopher Hertel \n */\nclass ToolNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return Tool::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Nova;\n }\n\n /**\n * @param Tool $data\n *\n * @return array{\n * toolSpec: array{\n * name: string,\n * description: string,\n * inputSchema: array{\n * json: JsonSchema|array{type: 'object'}\n * }\n * }\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'toolSpec' => [\n 'name' => $data->name,\n 'description' => $data->description,\n 'inputSchema' => [\n 'json' => $data->parameters ?? new \\stdClass(),\n ],\n ],\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/Voyage/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Voyage;\n\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ModelClient implements ModelClientInterface\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n #[\\SensitiveParameter] private string $apiKey,\n ) {\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Voyage;\n }\n\n public function request(Model $model, object|string|array $payload, array $options = []): RawHttpResult\n {\n return new RawHttpResult($this->httpClient->request('POST', 'https://api.voyageai.com/v1/embeddings', [\n 'auth_bearer' => $this->apiKey,\n 'json' => [\n 'model' => $model->getName(),\n 'input' => $payload,\n ],\n ]));\n }\n}\n"], ["/ai/src/platform/src/Result/Exception/RawResultAlreadySetException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result\\Exception;\n\nuse Symfony\\AI\\Platform\\Exception\\RuntimeException;\n\n/**\n * @author Denis Zunke \n */\nfinal class RawResultAlreadySetException extends RuntimeException\n{\n public function __construct()\n {\n parent::__construct('The raw result was already set.');\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Exception/ToolException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Exception;\n\nuse Symfony\\AI\\Agent\\Exception\\InvalidArgumentException;\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ToolException extends InvalidArgumentException implements ExceptionInterface\n{\n public static function invalidReference(mixed $reference): self\n {\n return new self(\\sprintf('The reference \"%s\" is not a valid tool.', $reference));\n }\n\n public static function missingAttribute(string $className): self\n {\n return new self(\\sprintf('The class \"%s\" is not a tool, please add %s attribute.', $className, AsTool::class));\n }\n}\n"], ["/ai/src/platform/src/Contract/Normalizer/Message/Content/AudioNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\Content;\n\nuse Symfony\\AI\\Platform\\Message\\Content\\Audio;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class AudioNormalizer implements NormalizerInterface\n{\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n return $data instanceof Audio;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n Audio::class => true,\n ];\n }\n\n /**\n * @param Audio $data\n *\n * @return array{type: 'input_audio', input_audio: array{\n * data: string,\n * format: 'mp3'|'wav'|string,\n * }}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'type' => 'input_audio',\n 'input_audio' => [\n 'data' => $data->asBase64(),\n 'format' => match ($data->getFormat()) {\n 'audio/mpeg' => 'mp3',\n 'audio/wav' => 'wav',\n default => $data->getFormat(),\n },\n ],\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/Contract/ImageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\Claude;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\Content\\Image;\nuse Symfony\\AI\\Platform\\Model;\n\nuse function Symfony\\Component\\String\\u;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ImageNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return Image::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Claude;\n }\n\n /**\n * @param Image $data\n *\n * @return array{type: 'image', source: array{type: 'base64', media_type: string, data: string}}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'type' => 'image',\n 'source' => [\n 'type' => 'base64',\n 'media_type' => u($data->getFormat())->replace('jpg', 'jpeg')->toString(),\n 'data' => $data->asBase64(),\n ],\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Embeddings/TaskType.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini\\Embeddings;\n\nenum TaskType: string\n{\n /** Unset value, which will default to one of the other enum values. */\n public const TaskTypeUnspecified = 'TASK_TYPE_UNSPECIFIED';\n /** Specifies the given text is a query in a search/retrieval setting. */\n public const RetrievalQuery = 'RETRIEVAL_QUERY';\n /** Specifies the given text is a document from the corpus being searched. */\n public const RetrievalDocument = 'RETRIEVAL_DOCUMENT';\n /** Specifies the given text will be used for STS. */\n public const SemanticSimilarity = 'SEMANTIC_SIMILARITY';\n /** Specifies that the given text will be classified. */\n public const Classification = 'CLASSIFICATION';\n /** Specifies that the embeddings will be used for clustering. */\n public const Clustering = 'CLUSTERING';\n /** Specifies that the given text will be used for question answering. */\n public const QuestionAnswering = 'QUESTION_ANSWERING';\n /** Specifies that the given text will be used for fact verification. */\n public const FactVerification = 'FACT_VERIFICATION';\n /** Specifies that the given text will be used for code retrieval. */\n public const CodeRetrievalQuery = 'CODE_RETRIEVAL_QUERY';\n}\n"], ["/ai/src/platform/src/Bridge/Meta/Llama.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Meta;\n\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nclass Llama extends Model\n{\n public const V3_3_70B_INSTRUCT = 'llama-3.3-70B-Instruct';\n public const V3_2_90B_VISION_INSTRUCT = 'llama-3.2-90b-vision-instruct';\n public const V3_2_11B_VISION_INSTRUCT = 'llama-3.2-11b-vision-instruct';\n public const V3_2_3B = 'llama-3.2-3b';\n public const V3_2_3B_INSTRUCT = 'llama-3.2-3b-instruct';\n public const V3_2_1B = 'llama-3.2-1b';\n public const V3_2_1B_INSTRUCT = 'llama-3.2-1b-instruct';\n public const V3_1_405B_INSTRUCT = 'llama-3.1-405b-instruct';\n public const V3_1_70B = 'llama-3.1-70b';\n public const V3_1_70B_INSTRUCT = 'llama-3-70b-instruct';\n public const V3_1_8B = 'llama-3.1-8b';\n public const V3_1_8B_INSTRUCT = 'llama-3.1-8b-instruct';\n public const V3_70B = 'llama-3-70b';\n public const V3_8B_INSTRUCT = 'llama-3-8b-instruct';\n public const V3_8B = 'llama-3-8b';\n\n /**\n * @param array $options\n */\n public function __construct(string $name = self::V3_1_405B_INSTRUCT, array $options = [])\n {\n $capabilities = [\n Capability::INPUT_MESSAGES,\n Capability::OUTPUT_TEXT,\n ];\n\n parent::__construct($name, $capabilities, $options);\n }\n}\n"], ["/ai/src/platform/src/Bridge/LMStudio/Embeddings/ModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\LMStudio\\Embeddings;\n\nuse Symfony\\AI\\Platform\\Bridge\\LMStudio\\Embeddings;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface as PlatformResponseFactory;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n * @author André Lubian \n */\nfinal readonly class ModelClient implements PlatformResponseFactory\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n private string $hostUrl,\n ) {\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Embeddings;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n return new RawHttpResult($this->httpClient->request('POST', \\sprintf('%s/v1/embeddings', $this->hostUrl), [\n 'json' => array_merge($options, [\n 'model' => $model->getName(),\n 'input' => $payload,\n ]),\n ]));\n }\n}\n"], ["/ai/fixtures/Tool/ToolMultiple.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\n\n#[AsTool('tool_hello_world', 'Function to say hello', method: 'hello')]\n#[AsTool('tool_required_params', 'Function to say a number', method: 'bar')]\nfinal class ToolMultiple\n{\n /**\n * @param string $world The world to say hello to\n */\n public function hello(string $world): string\n {\n return \\sprintf('Hello \"%s\".', $world);\n }\n\n /**\n * @param string $text The text given to the tool\n * @param int $number A number given to the tool\n */\n public function bar(string $text, int $number): string\n {\n return \\sprintf('%s says \"%d\".', $text, $number);\n }\n}\n"], ["/ai/src/platform/src/Bridge/TransformersPHP/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\TransformersPHP;\n\nuse Codewithkyrian\\Transformers\\Pipelines\\Task;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\ObjectResult;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\n\nfinal readonly class ResultConverter implements ResultConverterInterface\n{\n public function supports(Model $model): bool\n {\n return true;\n }\n\n public function convert(RawResultInterface $result, array $options = []): TextResult|ObjectResult\n {\n $data = $result->getData();\n\n if (Task::Text2TextGeneration === $options['task']) {\n $result = reset($data);\n\n return new TextResult($result['generated_text']);\n }\n\n return new ObjectResult($data);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/Contract/AssistantMessageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\Claude;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\AssistantMessage;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareInterface;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareTrait;\n\n/**\n * @author Christopher Hertel \n */\nfinal class AssistantMessageNormalizer extends ModelContractNormalizer implements NormalizerAwareInterface\n{\n use NormalizerAwareTrait;\n\n protected function supportedDataClass(): string\n {\n return AssistantMessage::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Claude;\n }\n\n /**\n * @param AssistantMessage $data\n *\n * @return array{\n * role: 'assistant',\n * content: list\n * }>\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'role' => 'assistant',\n 'content' => array_map(static function (ToolCall $toolCall) {\n return [\n 'type' => 'tool_use',\n 'id' => $toolCall->id,\n 'name' => $toolCall->name,\n 'input' => [] !== $toolCall->arguments ? $toolCall->arguments : new \\stdClass(),\n ];\n }, $data->toolCalls),\n ];\n }\n}\n"], ["/ai/src/mcp-sdk/src/Message/Response.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Message;\n\nfinal readonly class Response implements \\JsonSerializable\n{\n /**\n * @param array $result\n */\n public function __construct(\n public string|int $id,\n public array $result = [],\n ) {\n }\n\n /**\n * @return array{jsonrpc: string, id: string|int, result: array}\n */\n public function jsonSerialize(): array\n {\n return [\n 'jsonrpc' => '2.0',\n 'id' => $this->id,\n 'result' => $this->result,\n ];\n }\n}\n"], ["/ai/src/platform/src/Contract/Normalizer/Message/SystemMessageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\Normalizer\\Message;\n\nuse Symfony\\AI\\Platform\\Message\\SystemMessage;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class SystemMessageNormalizer implements NormalizerInterface\n{\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n return $data instanceof SystemMessage;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n SystemMessage::class => true,\n ];\n }\n\n /**\n * @param SystemMessage $data\n *\n * @return array{role: 'system', content: string}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'role' => $data->getRole()->value,\n 'content' => $data->content,\n ];\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/RequestHandler/ResourceReadHandler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\RequestHandler;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Resource\\ResourceRead;\nuse Symfony\\AI\\McpSdk\\Capability\\Resource\\ResourceReaderInterface;\nuse Symfony\\AI\\McpSdk\\Exception\\ExceptionInterface;\nuse Symfony\\AI\\McpSdk\\Exception\\ResourceNotFoundException;\nuse Symfony\\AI\\McpSdk\\Message\\Error;\nuse Symfony\\AI\\McpSdk\\Message\\Request;\nuse Symfony\\AI\\McpSdk\\Message\\Response;\n\nfinal class ResourceReadHandler extends BaseRequestHandler\n{\n public function __construct(\n private readonly ResourceReaderInterface $reader,\n ) {\n }\n\n public function createResponse(Request $message): Response|Error\n {\n $uri = $message->params['uri'];\n\n try {\n $result = $this->reader->read(new ResourceRead(uniqid('', true), $uri));\n } catch (ResourceNotFoundException $e) {\n return new Error($message->id, Error::RESOURCE_NOT_FOUND, $e->getMessage());\n } catch (ExceptionInterface) {\n return Error::internalError($message->id, 'Error while reading resource');\n }\n\n return new Response($message->id, [\n 'contents' => [\n [\n 'uri' => $result->uri,\n 'mimeType' => $result->mimeType,\n $result->type => $result->result,\n ],\n ],\n ]);\n }\n\n protected function supportedMethod(): string\n {\n return 'resources/read';\n }\n}\n"], ["/ai/src/store/src/Document/TransformerInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Document;\n\n/**\n * A Transformer is designed to mutate a stream of TextDocuments with the purpose of preparing them for indexing.\n * It can reduce or expand the number of documents, modify their content or metadata.\n * It should not act blocking, but is expected to iterate over incoming documents and yield prepared ones.\n *\n * @author Christopher Hertel \n */\ninterface TransformerInterface\n{\n /**\n * @param iterable $documents\n * @param array $options\n *\n * @return iterable\n */\n public function __invoke(iterable $documents, array $options = []): iterable;\n}\n"], ["/ai/src/platform/src/Result/Metadata/MetadataAwareTrait.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result\\Metadata;\n\n/**\n * @author Denis Zunke \n */\ntrait MetadataAwareTrait\n{\n private ?Metadata $metadata = null;\n\n public function getMetadata(): Metadata\n {\n return $this->metadata ??= new Metadata();\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Exception/ToolNotFoundException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Exception;\n\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Tool\\ExecutionReference;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ToolNotFoundException extends \\RuntimeException implements ExceptionInterface\n{\n public ?ToolCall $toolCall = null;\n\n public static function notFoundForToolCall(ToolCall $toolCall): self\n {\n $exception = new self(\\sprintf('Tool not found for call: %s.', $toolCall->name));\n $exception->toolCall = $toolCall;\n\n return $exception;\n }\n\n public static function notFoundForReference(ExecutionReference $reference): self\n {\n return new self(\\sprintf('Tool not found for reference: %s::%s.', $reference->class, $reference->method));\n }\n}\n"], ["/ai/src/platform/src/Bridge/Ollama/LlamaModelClient.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Ollama;\n\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\Llama;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\ModelClientInterface;\nuse Symfony\\AI\\Platform\\Result\\RawHttpResult;\nuse Symfony\\Contracts\\HttpClient\\HttpClientInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class LlamaModelClient implements ModelClientInterface\n{\n public function __construct(\n private HttpClientInterface $httpClient,\n private string $hostUrl,\n ) {\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Llama;\n }\n\n public function request(Model $model, array|string $payload, array $options = []): RawHttpResult\n {\n // Revert Ollama's default streaming behavior\n $options['stream'] ??= false;\n\n return new RawHttpResult($this->httpClient->request('POST', \\sprintf('%s/api/chat', $this->hostUrl), [\n 'headers' => ['Content-Type' => 'application/json'],\n 'json' => array_merge($options, $payload),\n ]));\n }\n}\n"], ["/ai/src/platform/src/Contract/Normalizer/Message/Content/ImageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\Content;\n\nuse Symfony\\AI\\Platform\\Message\\Content\\Image;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ImageNormalizer implements NormalizerInterface\n{\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n return $data instanceof Image;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n Image::class => true,\n ];\n }\n\n /**\n * @param Image $data\n *\n * @return array{type: 'image_url', image_url: array{url: string}}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'type' => 'image_url',\n 'image_url' => ['url' => $data->asDataUrl()],\n ];\n }\n}\n"], ["/ai/src/platform/src/Contract/Normalizer/Message/Content/ImageUrlNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\Content;\n\nuse Symfony\\AI\\Platform\\Message\\Content\\ImageUrl;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ImageUrlNormalizer implements NormalizerInterface\n{\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n return $data instanceof ImageUrl;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n ImageUrl::class => true,\n ];\n }\n\n /**\n * @param ImageUrl $data\n *\n * @return array{type: 'image_url', image_url: array{url: string}}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'type' => 'image_url',\n 'image_url' => ['url' => $data->url],\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/Whisper/AudioNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper;\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\AI\\Platform\\Message\\Content\\Audio;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class AudioNormalizer implements NormalizerInterface\n{\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n return $data instanceof Audio && $context[Contract::CONTEXT_MODEL] instanceof Whisper;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n Audio::class => true,\n ];\n }\n\n /**\n * @param Audio $data\n *\n * @return array{model: string, file: resource}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'model' => $context[Contract::CONTEXT_MODEL]->getName(),\n 'file' => $data->asResource(),\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/DallE.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI;\n\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Denis Zunke \n */\nclass DallE extends Model\n{\n public const DALL_E_2 = 'dall-e-2';\n public const DALL_E_3 = 'dall-e-3';\n\n /** @param array $options The default options for the model usage */\n public function __construct(string $name = self::DALL_E_2, array $options = [])\n {\n $capabilities = [\n Capability::INPUT_TEXT,\n Capability::OUTPUT_IMAGE,\n ];\n\n parent::__construct($name, $capabilities, $options);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/Nova/Contract/MessageBagNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\Nova;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareInterface;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareTrait;\n\n/**\n * @author Christopher Hertel \n */\nfinal class MessageBagNormalizer extends ModelContractNormalizer implements NormalizerAwareInterface\n{\n use NormalizerAwareTrait;\n\n protected function supportedDataClass(): string\n {\n return MessageBagInterface::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Nova;\n }\n\n /**\n * @param MessageBagInterface $data\n *\n * @return array{\n * messages: array>,\n * system?: array,\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n $array = [];\n\n if ($data->getSystemMessage()) {\n $array['system'][]['text'] = $data->getSystemMessage()->content;\n }\n\n $array['messages'] = $this->normalizer->normalize($data->withoutSystemMessage()->getMessages(), $format, $context);\n\n return $array;\n }\n}\n"], ["/ai/src/platform/src/Bridge/Meta/Contract/MessageBagNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Meta\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\Llama;\nuse Symfony\\AI\\Platform\\Bridge\\Meta\\LlamaPromptConverter;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nfinal class MessageBagNormalizer extends ModelContractNormalizer\n{\n public function __construct(\n private readonly LlamaPromptConverter $promptConverter = new LlamaPromptConverter(),\n ) {\n }\n\n protected function supportedDataClass(): string\n {\n return MessageBagInterface::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Llama;\n }\n\n /**\n * @param MessageBagInterface $data\n *\n * @return array{prompt: string}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'prompt' => $this->promptConverter->convertToPrompt($data),\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Contract/MessageBagNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Contract;\n\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareInterface;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareTrait;\n\n/**\n * @author Christopher Hertel \n */\nclass MessageBagNormalizer extends ModelContractNormalizer implements NormalizerAwareInterface\n{\n use NormalizerAwareTrait;\n\n protected function supportedDataClass(): string\n {\n return MessageBagInterface::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return true;\n }\n\n /**\n * @param MessageBagInterface $data\n *\n * @return array{\n * headers: array<'Content-Type', 'application/json'>,\n * json: array{messages: array}\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'headers' => ['Content-Type' => 'application/json'],\n 'json' => [\n 'messages' => $this->normalizer->normalize($data->getMessages(), $format, $context),\n ],\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/FillMaskResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal class FillMaskResult\n{\n /**\n * @param MaskFill[] $fills\n */\n public function __construct(\n public array $fills,\n ) {\n }\n\n /**\n * @param array $data\n */\n public static function fromArray(array $data): self\n {\n return new self(array_map(\n fn (array $item) => new MaskFill(\n $item['token'],\n $item['token_str'],\n $item['sequence'],\n $item['score'],\n ),\n $data,\n ));\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/TokenClassificationResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal class TokenClassificationResult\n{\n /**\n * @param Token[] $tokens\n */\n public function __construct(\n public array $tokens,\n ) {\n }\n\n /**\n * @param array $data\n */\n public static function fromArray(array $data): self\n {\n return new self(array_map(\n fn (array $item) => new Token(\n $item['entity_group'],\n $item['score'],\n $item['word'],\n $item['start'],\n $item['end'],\n ),\n $data,\n ));\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/Contract/AnthropicContract.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic\\Contract;\n\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class AnthropicContract extends Contract\n{\n public static function create(NormalizerInterface ...$normalizer): Contract\n {\n return parent::create(\n new AssistantMessageNormalizer(),\n new DocumentNormalizer(),\n new DocumentUrlNormalizer(),\n new ImageNormalizer(),\n new ImageUrlNormalizer(),\n new MessageBagNormalizer(),\n new ToolCallMessageNormalizer(),\n new ToolNormalizer(),\n ...$normalizer,\n );\n }\n}\n"], ["/ai/src/platform/src/Result/Metadata/Metadata.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result\\Metadata;\n\n/**\n * @implements \\IteratorAggregate\n * @implements \\ArrayAccess\n *\n * @author Denis Zunke \n */\nclass Metadata implements \\JsonSerializable, \\Countable, \\IteratorAggregate, \\ArrayAccess\n{\n /**\n * @var array\n */\n private array $metadata = [];\n\n /**\n * @param array $metadata\n */\n public function __construct(array $metadata = [])\n {\n $this->set($metadata);\n }\n\n /**\n * @return array\n */\n public function all(): array\n {\n return $this->metadata;\n }\n\n /**\n * @param array $metadata\n */\n public function set(array $metadata): void\n {\n $this->metadata = $metadata;\n }\n\n public function add(string $key, mixed $value): void\n {\n $this->metadata[$key] = $value;\n }\n\n public function has(string $key): bool\n {\n return \\array_key_exists($key, $this->metadata);\n }\n\n public function get(string $key, mixed $default = null): mixed\n {\n return $this->metadata[$key] ?? $default;\n }\n\n public function remove(string $key): void\n {\n unset($this->metadata[$key]);\n }\n\n /**\n * @return array\n */\n public function jsonSerialize(): array\n {\n return $this->all();\n }\n\n public function count(): int\n {\n return \\count($this->metadata);\n }\n\n public function getIterator(): \\Traversable\n {\n return new \\ArrayIterator($this->metadata);\n }\n\n public function offsetExists(mixed $offset): bool\n {\n return $this->has((string) $offset);\n }\n\n public function offsetGet(mixed $offset): mixed\n {\n return $this->get((string) $offset);\n }\n\n public function offsetSet(mixed $offset, mixed $value): void\n {\n $this->add((string) $offset, $value);\n }\n\n public function offsetUnset(mixed $offset): void\n {\n $this->remove((string) $offset);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/Contract/ToolNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\Claude;\nuse Symfony\\AI\\Platform\\Contract\\JsonSchema\\Factory;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\n\n/**\n * @phpstan-import-type JsonSchema from Factory\n *\n * @author Christopher Hertel \n */\nclass ToolNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return Tool::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Claude;\n }\n\n /**\n * @param Tool $data\n *\n * @return array{\n * name: string,\n * description: string,\n * input_schema: JsonSchema|array{type: 'object'}\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'name' => $data->name,\n 'description' => $data->description,\n 'input_schema' => $data->parameters ?? ['type' => 'object'],\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/Gemini/Contract/GeminiContract.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Gemini\\Contract;\n\nuse Symfony\\AI\\Platform\\Contract;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class GeminiContract extends Contract\n{\n public static function create(NormalizerInterface ...$normalizer): Contract\n {\n return parent::create(\n new AssistantMessageNormalizer(),\n new MessageBagNormalizer(),\n new ToolNormalizer(),\n new ToolCallMessageNormalizer(),\n new UserMessageNormalizer(),\n ...$normalizer,\n );\n }\n}\n"], ["/ai/src/platform/src/Contract/Normalizer/Message/Content/TextNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Contract\\Normalizer\\Message\\Content;\n\nuse Symfony\\AI\\Platform\\Message\\Content\\Text;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class TextNormalizer implements NormalizerInterface\n{\n public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool\n {\n return $data instanceof Text;\n }\n\n public function getSupportedTypes(?string $format): array\n {\n return [\n Text::class => true,\n ];\n }\n\n /**\n * @param Text $data\n *\n * @return array{type: 'text', text: string}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return ['type' => 'text', 'text' => $data->text];\n }\n}\n"], ["/ai/fixtures/Tool/ToolArray.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\n\n#[AsTool('tool_array', 'A tool with array parameters')]\nfinal class ToolArray\n{\n /**\n * @param string[] $urls\n * @param list $ids\n */\n public function __invoke(array $urls, array $ids): string\n {\n return 'Hello world!';\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Tool/Agent.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Tool;\n\nuse Symfony\\AI\\Agent\\AgentInterface;\nuse Symfony\\AI\\Platform\\Message\\Message;\nuse Symfony\\AI\\Platform\\Message\\MessageBag;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class Agent\n{\n public function __construct(\n private AgentInterface $agent,\n ) {\n }\n\n /**\n * @param string $message the message to pass to the chain\n */\n public function __invoke(string $message): string\n {\n $result = $this->agent->call(new MessageBag(Message::ofUser($message)));\n\n \\assert($result instanceof TextResult);\n\n return $result->getContent();\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Exception/ToolConfigurationException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Exception;\n\nuse Symfony\\AI\\Agent\\Exception\\InvalidArgumentException;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ToolConfigurationException extends InvalidArgumentException implements ExceptionInterface\n{\n public static function invalidMethod(string $toolClass, string $methodName, \\ReflectionException $previous): self\n {\n return new self(\\sprintf('Method \"%s\" not found in tool \"%s\".', $methodName, $toolClass), previous: $previous);\n }\n}\n"], ["/ai/src/mcp-bundle/src/Controller/McpController.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpBundle\\Controller;\n\nuse Symfony\\AI\\McpSdk\\Server;\nuse Symfony\\AI\\McpSdk\\Server\\Transport\\Sse\\Store\\CachePoolStore;\nuse Symfony\\AI\\McpSdk\\Server\\Transport\\Sse\\StreamTransport;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\HttpFoundation\\StreamedResponse;\nuse Symfony\\Component\\Routing\\Generator\\UrlGeneratorInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\nfinal readonly class McpController\n{\n public function __construct(\n private Server $server,\n private CachePoolStore $store,\n private UrlGeneratorInterface $urlGenerator,\n ) {\n }\n\n public function sse(): StreamedResponse\n {\n $id = Uuid::v4();\n $endpoint = $this->urlGenerator->generate('_mcp_messages', ['id' => $id], UrlGeneratorInterface::ABSOLUTE_URL);\n $transport = new StreamTransport($endpoint, $this->store, $id);\n\n return new StreamedResponse(fn () => $this->server->connect($transport), headers: [\n 'Content-Type' => 'text/event-stream',\n 'Cache-Control' => 'no-cache',\n 'X-Accel-Buffering' => 'no',\n ]);\n }\n\n public function messages(Request $request, Uuid $id): Response\n {\n $this->store->push($id, $request->getContent());\n\n return new Response();\n }\n}\n"], ["/ai/fixtures/SomeStructure.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures;\n\nfinal class SomeStructure\n{\n public function __construct(?string $some = null)\n {\n if (null !== $some) {\n $this->some = $some;\n }\n }\n\n public string $some;\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/Embeddings.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI;\n\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nclass Embeddings extends Model\n{\n public const TEXT_ADA_002 = 'text-embedding-ada-002';\n public const TEXT_3_LARGE = 'text-embedding-3-large';\n public const TEXT_3_SMALL = 'text-embedding-3-small';\n\n /**\n * @param array $options\n */\n public function __construct(string $name = self::TEXT_3_SMALL, array $options = [])\n {\n parent::__construct($name, [], $options);\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/ClassificationResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ClassificationResult\n{\n /**\n * @param Classification[] $classifications\n */\n public function __construct(\n public array $classifications,\n ) {\n }\n\n /**\n * @param array $data\n */\n public static function fromArray(array $data): self\n {\n return new self(\n array_map(fn (array $item) => new Classification($item['label'], $item['score']), $data)\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/Contract/ToolCallMessageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\Claude;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\ToolCallMessage;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareInterface;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareTrait;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ToolCallMessageNormalizer extends ModelContractNormalizer implements NormalizerAwareInterface\n{\n use NormalizerAwareTrait;\n\n protected function supportedDataClass(): string\n {\n return ToolCallMessage::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Claude;\n }\n\n /**\n * @param ToolCallMessage $data\n *\n * @return array{\n * role: 'user',\n * content: list\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'role' => 'user',\n 'content' => [\n [\n 'type' => 'tool_result',\n 'tool_use_id' => $data->toolCall->id,\n 'content' => $data->content,\n ],\n ],\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/ImageSegmentationResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ImageSegmentationResult\n{\n /**\n * @param ImageSegment[] $segments\n */\n public function __construct(\n public array $segments,\n ) {\n }\n\n /**\n * @param array $data\n */\n public static function fromArray(array $data): self\n {\n return new self(\n array_map(fn (array $item) => new ImageSegment($item['label'], $item['score'], $item['mask']), $data)\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/Contract/DocumentUrlNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\Claude;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\Content\\DocumentUrl;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nfinal class DocumentUrlNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return DocumentUrl::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Claude;\n }\n\n /**\n * @param DocumentUrl $data\n *\n * @return array{type: 'document', source: array{type: 'url', url: string}}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'type' => 'document',\n 'source' => [\n 'type' => 'url',\n 'url' => $data->url,\n ],\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/Contract/ImageUrlNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\Claude;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\Content\\Image;\nuse Symfony\\AI\\Platform\\Message\\Content\\ImageUrl;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ImageUrlNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return ImageUrl::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Claude;\n }\n\n /**\n * @param ImageUrl $data\n *\n * @return array{type: 'image', source: array{type: 'url', url: string}}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'type' => 'image',\n 'source' => [\n 'type' => 'url',\n 'url' => $data->url,\n ],\n ];\n }\n}\n"], ["/ai/src/mcp-bundle/src/Command/McpCommand.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpBundle\\Command;\n\nuse Symfony\\AI\\McpSdk\\Server;\nuse Symfony\\AI\\McpSdk\\Server\\Transport\\Stdio\\SymfonyConsoleTransport;\nuse Symfony\\Component\\Console\\Attribute\\AsCommand;\nuse Symfony\\Component\\Console\\Command\\Command;\nuse Symfony\\Component\\Console\\Input\\InputInterface;\nuse Symfony\\Component\\Console\\Output\\OutputInterface;\n\n#[AsCommand('mcp:server', 'Starts an MCP server')]\nclass McpCommand extends Command\n{\n public function __construct(\n private readonly Server $server,\n ) {\n parent::__construct();\n }\n\n protected function execute(InputInterface $input, OutputInterface $output): int\n {\n $this->server->connect(\n new SymfonyConsoleTransport($input, $output)\n );\n\n return Command::SUCCESS;\n }\n}\n"], ["/ai/src/platform/src/Result/ToolCall.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ToolCall implements \\JsonSerializable\n{\n /**\n * @param array $arguments\n */\n public function __construct(\n public string $id,\n public string $name,\n public array $arguments = [],\n ) {\n }\n\n /**\n * @return array{\n * id: string,\n * type: 'function',\n * function: array{\n * name: string,\n * arguments: string\n * }\n * }\n */\n public function jsonSerialize(): array\n {\n return [\n 'id' => $this->id,\n 'type' => 'function',\n 'function' => [\n 'name' => $this->name,\n 'arguments' => json_encode($this->arguments),\n ],\n ];\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Tool/Clock.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\Component\\Clock\\Clock as SymfonyClock;\nuse Symfony\\Component\\Clock\\ClockInterface;\n\n/**\n * @author Christopher Hertel \n */\n#[AsTool('clock', description: 'Provides the current date and time.')]\nfinal readonly class Clock\n{\n public function __construct(\n private ClockInterface $clock = new SymfonyClock(),\n ) {\n }\n\n public function __invoke(): string\n {\n return \\sprintf(\n 'Current date is %s (YYYY-MM-DD) and the time is %s (HH:MM:SS).',\n $this->clock->now()->format('Y-m-d'),\n $this->clock->now()->format('H:i:s'),\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/Nova/Contract/ToolCallMessageNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Bedrock\\Nova\\Nova;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\ToolCallMessage;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareInterface;\nuse Symfony\\Component\\Serializer\\Normalizer\\NormalizerAwareTrait;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ToolCallMessageNormalizer extends ModelContractNormalizer implements NormalizerAwareInterface\n{\n use NormalizerAwareTrait;\n\n protected function supportedDataClass(): string\n {\n return ToolCallMessage::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Nova;\n }\n\n /**\n * @param ToolCallMessage $data\n *\n * @return array{\n * role: 'user',\n * content: array,\n * }\n * }>\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'role' => 'user',\n 'content' => [\n [\n 'toolResult' => [\n 'toolUseId' => $data->toolCall->id,\n 'content' => [['json' => $data->content]],\n ],\n ],\n ],\n ];\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Exception/ToolExecutionException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Exception;\n\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ToolExecutionException extends \\RuntimeException implements ExceptionInterface\n{\n public ?ToolCall $toolCall = null;\n\n public static function executionFailed(ToolCall $toolCall, \\Throwable $previous): self\n {\n $exception = new self(\\sprintf('Execution of tool \"%s\" failed with error: %s', $toolCall->name, $previous->getMessage()), previous: $previous);\n $exception->toolCall = $toolCall;\n\n return $exception;\n }\n}\n"], ["/ai/src/platform/src/Tool/Tool.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Tool;\n\nuse Symfony\\AI\\Platform\\Contract\\JsonSchema\\Factory;\n\n/**\n * @phpstan-import-type JsonSchema from Factory\n *\n * @author Christopher Hertel \n */\nfinal readonly class Tool\n{\n /**\n * @param JsonSchema|null $parameters\n */\n public function __construct(\n public ExecutionReference $reference,\n public string $name,\n public string $description,\n public ?array $parameters = null,\n ) {\n }\n}\n"], ["/ai/src/mcp-sdk/src/Exception/PromptGetException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Exception;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Prompt\\PromptGet;\n\nfinal class PromptGetException extends \\RuntimeException implements ExceptionInterface\n{\n public function __construct(\n public readonly PromptGet $promptGet,\n ?\\Throwable $previous = null,\n ) {\n parent::__construct(\\sprintf('Handling prompt \"%s\" failed with error: %s', $promptGet->name, $previous->getMessage()), previous: $previous);\n }\n}\n"], ["/ai/src/mcp-sdk/src/Exception/ResourceReadException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Exception;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Resource\\ResourceRead;\n\nfinal class ResourceReadException extends \\RuntimeException implements ExceptionInterface\n{\n public function __construct(\n public readonly ResourceRead $readRequest,\n ?\\Throwable $previous = null,\n ) {\n parent::__construct(\\sprintf('Reading resource \"%s\" failed with error: %s', $readRequest->uri, $previous?->getMessage() ?? ''), previous: $previous);\n }\n}\n"], ["/ai/src/agent/src/Toolbox/FaultTolerantToolbox.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Exception\\ToolExecutionException;\nuse Symfony\\AI\\Agent\\Toolbox\\Exception\\ToolNotFoundException;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\n\n/**\n * Catches exceptions thrown by the inner tool box and returns error messages for the LLM instead.\n *\n * @author Christopher Hertel \n */\nfinal readonly class FaultTolerantToolbox implements ToolboxInterface\n{\n public function __construct(\n private ToolboxInterface $innerToolbox,\n ) {\n }\n\n public function getTools(): array\n {\n return $this->innerToolbox->getTools();\n }\n\n public function execute(ToolCall $toolCall): mixed\n {\n try {\n return $this->innerToolbox->execute($toolCall);\n } catch (ToolExecutionException $e) {\n return \\sprintf('An error occurred while executing tool \"%s\".', $e->toolCall->name);\n } catch (ToolNotFoundException) {\n $names = array_map(fn (Tool $metadata) => $metadata->name, $this->getTools());\n\n return \\sprintf('Tool \"%s\" was not found, please use one of these: %s', $toolCall->name, implode(', ', $names));\n }\n }\n}\n"], ["/ai/src/mcp-sdk/src/Exception/ToolExecutionException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Exception;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Tool\\ToolCall;\n\nfinal class ToolExecutionException extends \\RuntimeException implements ExceptionInterface\n{\n public function __construct(\n public readonly ToolCall $toolCall,\n ?\\Throwable $previous = null,\n ) {\n parent::__construct(\\sprintf('Execution of tool \"%s\" failed with error: %s', $toolCall->name, $previous?->getMessage() ?? ''), previous: $previous);\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/TableQuestionAnsweringResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class TableQuestionAnsweringResult\n{\n /**\n * @param array $cells\n * @param array $aggregator\n */\n public function __construct(\n public string $answer,\n public array $cells = [],\n public array $aggregator = [],\n ) {\n }\n\n /**\n * @param array{answer: string, cells?: array, aggregator?: array} $data\n */\n public static function fromArray(array $data): self\n {\n return new self(\n $data['answer'],\n $data['cells'] ?? [],\n $data['aggregator'] ?? [],\n );\n }\n}\n"], ["/ai/src/agent/src/Exception/MissingModelSupportException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Exception;\n\n/**\n * @author Christopher Hertel \n */\nfinal class MissingModelSupportException extends RuntimeException\n{\n private function __construct(string $model, string $support)\n {\n parent::__construct(\\sprintf('Model \"%s\" does not support \"%s\".', $model, $support));\n }\n\n public static function forToolCalling(string $model): self\n {\n return new self($model, 'tool calling');\n }\n\n public static function forAudioInput(string $model): self\n {\n return new self($model, 'audio input');\n }\n\n public static function forImageInput(string $model): self\n {\n return new self($model, 'image input');\n }\n\n public static function forStructuredOutput(string $model): self\n {\n return new self($model, 'structured output');\n }\n}\n"], ["/ai/src/store/src/Document/VectorDocument.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Document;\n\nuse Symfony\\AI\\Platform\\Vector\\VectorInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class VectorDocument\n{\n public function __construct(\n public Uuid $id,\n public VectorInterface $vector,\n public Metadata $metadata = new Metadata(),\n public ?float $score = null,\n ) {\n }\n}\n"], ["/ai/src/platform/src/Result/Choice.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class Choice\n{\n /**\n * @param ToolCall[] $toolCalls\n */\n public function __construct(\n private ?string $content = null,\n private array $toolCalls = [],\n ) {\n }\n\n public function getContent(): ?string\n {\n return $this->content;\n }\n\n public function hasContent(): bool\n {\n return null !== $this->content;\n }\n\n /**\n * @return ToolCall[]\n */\n public function getToolCalls(): array\n {\n return $this->toolCalls;\n }\n\n public function hasToolCall(): bool\n {\n return [] !== $this->toolCalls;\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Resource/CollectionInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Resource;\n\nuse Symfony\\AI\\McpSdk\\Exception\\InvalidCursorException;\n\ninterface CollectionInterface\n{\n /**\n * @param int $count the number of metadata items to return\n *\n * @return iterable\n *\n * @throws InvalidCursorException if no item with $lastIdentifier was found\n */\n public function getMetadata(int $count, ?string $lastIdentifier = null): iterable;\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Tool/CollectionInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Tool;\n\nuse Symfony\\AI\\McpSdk\\Exception\\InvalidCursorException;\n\ninterface CollectionInterface\n{\n /**\n * @param int $count the number of metadata items to return\n *\n * @return iterable\n *\n * @throws InvalidCursorException if no item with $lastIdentifier was found\n */\n public function getMetadata(int $count, ?string $lastIdentifier = null): iterable;\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Prompt/CollectionInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Prompt;\n\nuse Symfony\\AI\\McpSdk\\Exception\\InvalidCursorException;\n\ninterface CollectionInterface\n{\n /**\n * @param int $count the number of metadata items to return\n *\n * @return iterable\n *\n * @throws InvalidCursorException if no item with $lastIdentifier was found\n */\n public function getMetadata(int $count, ?string $lastIdentifier = null): iterable;\n}\n"], ["/ai/src/mcp-bundle/src/Routing/RouteLoader.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpBundle\\Routing;\n\nuse Symfony\\Component\\Routing\\Route;\nuse Symfony\\Component\\Routing\\RouteCollection;\n\nfinal readonly class RouteLoader\n{\n public function __construct(\n private bool $sseTransportEnabled,\n ) {\n }\n\n public function __invoke(): RouteCollection\n {\n if (!$this->sseTransportEnabled) {\n return new RouteCollection();\n }\n\n $collection = new RouteCollection();\n\n $collection->add('_mcp_sse', new Route('/_mcp/sse', ['_controller' => ['mcp.server.controller', 'sse']], methods: ['GET']));\n $collection->add('_mcp_messages', new Route('/_mcp/messages/{id}', ['_controller' => ['mcp.server.controller', 'messages']], methods: ['POST']));\n\n return $collection;\n }\n}\n"], ["/ai/fixtures/Tool/ToolRequiredParams.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\n\n#[AsTool('tool_required_params', 'A tool with required parameters', method: 'bar')]\nfinal class ToolRequiredParams\n{\n /**\n * @param string $text The text given to the tool\n * @param int $number A number given to the tool\n */\n public function bar(string $text, int $number): string\n {\n return \\sprintf('%s says \"%d\".', $text, $number);\n }\n}\n"], ["/ai/fixtures/Tool/ToolNoAttribute1.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nfinal class ToolNoAttribute1\n{\n /**\n * @param string $name the name of the person\n * @param int $years the age of the person\n */\n public function __invoke(string $name, int $years): string\n {\n return \\sprintf('Happy Birthday, %s! You are %d years old.', $name, $years);\n }\n}\n"], ["/ai/src/platform/src/Bridge/Anthropic/Contract/DocumentNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Anthropic\\Contract;\n\nuse Symfony\\AI\\Platform\\Bridge\\Anthropic\\Claude;\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\Content\\Document;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nclass DocumentNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return Document::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return $model instanceof Claude;\n }\n\n /**\n * @param Document $data\n *\n * @return array{type: 'document', source: array{type: 'base64', media_type: string, data: string}}\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'type' => 'document',\n 'source' => [\n 'type' => 'base64',\n 'media_type' => $data->getFormat(),\n 'data' => $data->asBase64(),\n ],\n ];\n }\n}\n"], ["/ai/src/agent/src/AgentInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent;\n\nuse Symfony\\AI\\Agent\\Exception\\ExceptionInterface;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\n\n/**\n * @author Denis Zunke \n */\ninterface AgentInterface\n{\n /**\n * @param array $options\n *\n * @throws ExceptionInterface When the agent encounters an error (e.g., unsupported model capabilities, invalid arguments, network failures, or processor errors)\n */\n public function call(MessageBagInterface $messages, array $options = []): ResultInterface;\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Contract/FileNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Contract;\n\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ModelContractNormalizer;\nuse Symfony\\AI\\Platform\\Message\\Content\\File;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nclass FileNormalizer extends ModelContractNormalizer\n{\n protected function supportedDataClass(): string\n {\n return File::class;\n }\n\n protected function supportsModel(Model $model): bool\n {\n return true;\n }\n\n /**\n * @param File $data\n *\n * @return array{\n * headers: array<'Content-Type', string>,\n * body: string\n * }\n */\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n return [\n 'headers' => ['Content-Type' => $data->getFormat()],\n 'body' => $data->asBinary(),\n ];\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/DetectedObject.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class DetectedObject\n{\n public function __construct(\n public string $label,\n public float $score,\n public float $xmin,\n public float $ymin,\n public float $xmax,\n public float $ymax,\n ) {\n }\n}\n"], ["/ai/fixtures/StructuredOutput/User.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\StructuredOutput;\n\nfinal class User\n{\n public int $id;\n /**\n * @var string The name of the user in lowercase\n */\n public string $name;\n public \\DateTimeInterface $createdAt;\n public bool $isActive;\n public ?int $age = null;\n}\n"], ["/ai/src/store/src/Document/Transformer/ChainTransformer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Document\\Transformer;\n\nuse Symfony\\AI\\Store\\Document\\TransformerInterface;\n\nfinal readonly class ChainTransformer implements TransformerInterface\n{\n /**\n * @var TransformerInterface[]\n */\n private array $transformers;\n\n /**\n * @param iterable $transformers\n */\n public function __construct(iterable $transformers)\n {\n $this->transformers = $transformers instanceof \\Traversable ? iterator_to_array($transformers) : $transformers;\n }\n\n public function __invoke(iterable $documents, array $options = []): iterable\n {\n foreach ($this->transformers as $transformer) {\n $documents = $transformer($documents, $options);\n }\n\n return $documents;\n }\n}\n"], ["/ai/src/store/src/VectorStoreInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store;\n\nuse Symfony\\AI\\Platform\\Vector\\Vector;\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\n\n/**\n * @author Christopher Hertel \n */\ninterface VectorStoreInterface extends StoreInterface\n{\n /**\n * @param array $options\n *\n * @return VectorDocument[]\n */\n public function query(Vector $vector, array $options = [], ?float $minScore = null): array;\n}\n"], ["/ai/src/platform/src/Bridge/Bedrock/RawBedrockResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Bedrock;\n\nuse AsyncAws\\BedrockRuntime\\Result\\InvokeModelResponse;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class RawBedrockResult implements RawResultInterface\n{\n public function __construct(\n private InvokeModelResponse $invokeModelResponse,\n ) {\n }\n\n public function getData(): array\n {\n return json_decode($this->invokeModelResponse->getBody(), true, 512, \\JSON_THROW_ON_ERROR);\n }\n\n public function getObject(): InvokeModelResponse\n {\n return $this->invokeModelResponse;\n }\n}\n"], ["/ai/src/ai-bundle/src/Profiler/TraceableToolbox.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\AIBundle\\Profiler;\n\nuse Symfony\\AI\\Agent\\Toolbox\\ToolboxInterface;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\n\n/**\n * @author Christopher Hertel \n *\n * @phpstan-type ToolCallData array{\n * call: ToolCall,\n * result: string,\n * }\n */\nfinal class TraceableToolbox implements ToolboxInterface\n{\n /**\n * @var ToolCallData[]\n */\n public array $calls = [];\n\n public function __construct(\n private readonly ToolboxInterface $toolbox,\n ) {\n }\n\n public function getTools(): array\n {\n return $this->toolbox->getTools();\n }\n\n public function execute(ToolCall $toolCall): mixed\n {\n $result = $this->toolbox->execute($toolCall);\n\n $this->calls[] = [\n 'call' => $toolCall,\n 'result' => $result,\n ];\n\n return $result;\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Prompt/PromptGetResultMessages.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Prompt;\n\nfinal readonly class PromptGetResultMessages\n{\n public function __construct(\n public string $role,\n public string $result,\n /**\n * @var \"text\"|\"image\"|\"audio\"|\"resource\"|non-empty-string\n */\n public string $type = 'text',\n public string $mimeType = 'text/plan',\n public ?string $uri = null,\n ) {\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/QuestionAnsweringResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class QuestionAnsweringResult\n{\n public function __construct(\n public string $answer,\n public int $startIndex,\n public int $endIndex,\n public float $score,\n ) {\n }\n\n /**\n * @param array{answer: string, start: int, end: int, score: float} $data\n */\n public static function fromArray(array $data): self\n {\n return new self(\n $data['answer'],\n $data['start'],\n $data['end'],\n $data['score'],\n );\n }\n}\n"], ["/ai/src/platform/src/Bridge/Mistral/Contract/ToolNormalizer.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Mistral\\Contract;\n\nuse Symfony\\AI\\Platform\\Contract\\Normalizer\\ToolNormalizer as BaseToolNormalizer;\n\n/**\n * @author Christopher Hertel \n */\nclass ToolNormalizer extends BaseToolNormalizer\n{\n public function normalize(mixed $data, ?string $format = null, array $context = []): array\n {\n $array = parent::normalize($data, $format, $context);\n\n $array['function']['parameters'] ??= ['type' => 'object'];\n\n return $array;\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/Whisper.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI;\n\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nclass Whisper extends Model\n{\n public const WHISPER_1 = 'whisper-1';\n\n /**\n * @param array $options\n */\n public function __construct(string $name = self::WHISPER_1, array $options = [])\n {\n $capabilities = [\n Capability::INPUT_AUDIO,\n Capability::OUTPUT_TEXT,\n ];\n\n parent::__construct($name, $capabilities, $options);\n }\n}\n"], ["/ai/src/platform/src/Message/ToolCallMessage.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message;\n\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\Component\\Uid\\AbstractUid;\nuse Symfony\\Component\\Uid\\TimeBasedUidInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class ToolCallMessage implements MessageInterface\n{\n public AbstractUid&TimeBasedUidInterface $id;\n\n public function __construct(\n public ToolCall $toolCall,\n public string $content,\n ) {\n $this->id = Uuid::v7();\n }\n\n public function getRole(): Role\n {\n return Role::ToolCall;\n }\n\n public function getId(): AbstractUid&TimeBasedUidInterface\n {\n return $this->id;\n }\n}\n"], ["/ai/fixtures/Tool/ToolMisconfigured.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\n\n#[AsTool('tool_misconfigured', description: 'This tool is misconfigured, see method', method: 'foo')]\nfinal class ToolMisconfigured\n{\n public function bar(): string\n {\n return 'Wrong Config Attribute';\n }\n}\n"], ["/ai/src/platform/src/Model.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform;\n\n/**\n * @author Christopher Hertel \n */\nclass Model\n{\n /**\n * @param Capability[] $capabilities\n * @param array $options\n */\n public function __construct(\n private readonly string $name,\n private readonly array $capabilities = [],\n private readonly array $options = [],\n ) {\n }\n\n public function getName(): string\n {\n return $this->name;\n }\n\n /**\n * @return Capability[]\n */\n public function getCapabilities(): array\n {\n return $this->capabilities;\n }\n\n public function supports(Capability $capability): bool\n {\n return \\in_array($capability, $this->capabilities, true);\n }\n\n /**\n * @return array\n */\n public function getOptions(): array\n {\n return $this->options;\n }\n}\n"], ["/ai/src/agent/src/Chat.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent;\n\nuse Symfony\\AI\\Agent\\Chat\\MessageStoreInterface;\nuse Symfony\\AI\\Platform\\Message\\AssistantMessage;\nuse Symfony\\AI\\Platform\\Message\\Message;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Message\\UserMessage;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\n\nfinal readonly class Chat implements ChatInterface\n{\n public function __construct(\n private AgentInterface $agent,\n private MessageStoreInterface $store,\n ) {\n }\n\n public function initiate(MessageBagInterface $messages): void\n {\n $this->store->clear();\n $this->store->save($messages);\n }\n\n public function submit(UserMessage $message): AssistantMessage\n {\n $messages = $this->store->load();\n\n $messages->add($message);\n $result = $this->agent->call($messages);\n\n \\assert($result instanceof TextResult);\n\n $assistantMessage = Message::ofAssistant($result->getContent());\n $messages->add($assistantMessage);\n\n $this->store->save($messages);\n\n return $assistantMessage;\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Tool/ToolExecutorInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Tool;\n\nuse Symfony\\AI\\McpSdk\\Exception\\ToolExecutionException;\nuse Symfony\\AI\\McpSdk\\Exception\\ToolNotFoundException;\n\ninterface ToolExecutorInterface\n{\n /**\n * @throws ToolExecutionException if the tool execution fails\n * @throws ToolNotFoundException if the tool is not found\n */\n public function call(ToolCall $input): ToolCallResult;\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/SentenceSimilarityResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class SentenceSimilarityResult\n{\n /**\n * @param array $similarities\n */\n public function __construct(\n public array $similarities,\n ) {\n }\n\n /**\n * @param array $data\n */\n public static function fromArray(array $data): self\n {\n return new self($data);\n }\n}\n"], ["/ai/src/platform/src/Message/Content/Text.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message\\Content;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class Text implements ContentInterface\n{\n public function __construct(\n public string $text,\n ) {\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Attribute/AsTool.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Attribute;\n\n/**\n * @author Christopher Hertel \n */\n#[\\Attribute(\\Attribute::TARGET_CLASS | \\Attribute::IS_REPEATABLE)]\nfinal readonly class AsTool\n{\n public function __construct(\n public string $name,\n public string $description,\n public string $method = '__invoke',\n ) {\n }\n}\n"], ["/ai/fixtures/Tool/ToolArrayMultidimensional.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\nuse Symfony\\AI\\Fixtures\\SomeStructure;\n\n#[AsTool('tool_array_multidimensional', 'A tool with multidimensional array parameters')]\nfinal class ToolArrayMultidimensional\n{\n /**\n * @param float[][] $vectors\n * @param array> $sequences\n * @param SomeStructure[][] $objects\n */\n public function __invoke(array $vectors, array $sequences, array $objects): string\n {\n return 'Hello world!';\n }\n}\n"], ["/ai/src/agent/src/Toolbox/ToolboxInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Exception\\ToolExecutionException;\nuse Symfony\\AI\\Agent\\Toolbox\\Exception\\ToolNotFoundException;\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\n\n/**\n * @author Christopher Hertel \n */\ninterface ToolboxInterface\n{\n /**\n * @return Tool[]\n */\n public function getTools(): array;\n\n /**\n * @throws ToolExecutionException if the tool execution fails\n * @throws ToolNotFoundException if the tool is not found\n */\n public function execute(ToolCall $toolCall): mixed;\n}\n"], ["/ai/fixtures/Tool/ToolWrong.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nfinal class ToolWrong\n{\n /**\n * @param string $text The text given to the tool\n * @param int $number A number given to the tool\n */\n public function bar(string $text, int $number): string\n {\n return \\sprintf('%s says \"%d\".', $text, $number);\n }\n}\n"], ["/ai/src/platform/src/Message/SystemMessage.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message;\n\nuse Symfony\\Component\\Uid\\AbstractUid;\nuse Symfony\\Component\\Uid\\TimeBasedUidInterface;\nuse Symfony\\Component\\Uid\\Uuid;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class SystemMessage implements MessageInterface\n{\n public AbstractUid&TimeBasedUidInterface $id;\n\n public function __construct(public string $content)\n {\n $this->id = Uuid::v7();\n }\n\n public function getRole(): Role\n {\n return Role::System;\n }\n\n public function getId(): AbstractUid&TimeBasedUidInterface\n {\n return $this->id;\n }\n}\n"], ["/ai/src/platform/src/Bridge/Mistral/Embeddings.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Mistral;\n\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nfinal class Embeddings extends Model\n{\n public const MISTRAL_EMBED = 'mistral-embed';\n\n /**\n * @param array $options\n */\n public function __construct(\n string $name = self::MISTRAL_EMBED,\n array $options = [],\n ) {\n parent::__construct($name, [Capability::INPUT_MULTIPLE], $options);\n }\n}\n"], ["/ai/fixtures/Tool/ToolDate.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\n\n#[AsTool('tool_date', 'A tool with date parameter')]\nfinal class ToolDate\n{\n /**\n * @param \\DateTimeImmutable $date The date\n */\n public function __invoke(\\DateTimeImmutable $date): string\n {\n return \\sprintf('Weekday: %s', $date->format('l'));\n }\n}\n"], ["/ai/src/platform/src/Exception/InvalidArgumentException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Exception;\n\n/**\n * @author Oskar Stark \n */\nclass InvalidArgumentException extends \\InvalidArgumentException implements ExceptionInterface\n{\n}\n"], ["/ai/src/store/src/Exception/InvalidArgumentException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Exception;\n\n/**\n * @author Oskar Stark \n */\nclass InvalidArgumentException extends \\InvalidArgumentException implements ExceptionInterface\n{\n}\n"], ["/ai/src/agent/src/Exception/InvalidArgumentException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Exception;\n\n/**\n * @author Oskar Stark \n */\nclass InvalidArgumentException extends \\InvalidArgumentException implements ExceptionInterface\n{\n}\n"], ["/ai/fixtures/Tool/ToolNoAttribute2.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nfinal class ToolNoAttribute2\n{\n /**\n * @param int $id the ID of the product\n * @param int $amount the number of products\n */\n public function buy(int $id, int $amount): string\n {\n return \\sprintf('You bought %d of product %d.', $amount, $id);\n }\n\n /**\n * @param string $orderId the ID of the order\n */\n public function cancel(string $orderId): string\n {\n return \\sprintf('You canceled order %s.', $orderId);\n }\n}\n"], ["/ai/src/platform/src/Exception/ContentFilterException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Exception;\n\n/**\n * @author Oskar Stark \n */\nclass ContentFilterException extends InvalidArgumentException\n{\n}\n"], ["/ai/src/mcp-sdk/src/Exception/InvalidCursorException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Exception;\n\nfinal class InvalidCursorException extends \\InvalidArgumentException implements ExceptionInterface\n{\n public function __construct(\n public readonly string $cursor,\n ) {\n parent::__construct(\\sprintf('Invalid value for pagination parameter \"cursor\": \"%s\"', $cursor));\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Resource/MetadataInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Resource;\n\ninterface MetadataInterface extends IdentifierInterface\n{\n public function getName(): string;\n\n public function getDescription(): ?string;\n\n public function getMimeType(): ?string;\n\n /**\n * Size in bytes.\n */\n public function getSize(): ?int;\n}\n"], ["/ai/src/platform/src/Bridge/LMStudio/Completions/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\LMStudio\\Completions;\n\nuse Symfony\\AI\\Platform\\Bridge\\LMStudio\\Completions;\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\GPT\\ResultConverter as OpenAIResponseConverter;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\ResultConverterInterface;\n\n/**\n * @author André Lubian \n */\nfinal class ResultConverter implements ResultConverterInterface\n{\n public function __construct(\n private readonly OpenAIResponseConverter $gptResponseConverter = new OpenAIResponseConverter(),\n ) {\n }\n\n public function supports(Model $model): bool\n {\n return $model instanceof Completions;\n }\n\n public function convert(RawResultInterface $result, array $options = []): ResultInterface\n {\n return $this->gptResponseConverter->convert($result, $options);\n }\n}\n"], ["/ai/src/mcp-sdk/src/Exception/ResourceNotFoundException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Exception;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Resource\\ResourceRead;\n\nfinal class ResourceNotFoundException extends \\RuntimeException implements NotFoundExceptionInterface\n{\n public function __construct(\n public readonly ResourceRead $readRequest,\n ) {\n parent::__construct(\\sprintf('Resource not found for uri: \"%s\"', $readRequest->uri));\n }\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/Whisper/ResultConverter.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper;\n\nuse Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\nuse Symfony\\AI\\Platform\\Result\\TextResult;\nuse Symfony\\AI\\Platform\\ResultConverterInterface as BaseResponseConverter;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ResultConverter implements BaseResponseConverter\n{\n public function supports(Model $model): bool\n {\n return $model instanceof Whisper;\n }\n\n public function convert(RawResultInterface $result, array $options = []): ResultInterface\n {\n $data = $result->getData();\n\n return new TextResult($data['text']);\n }\n}\n"], ["/ai/src/mcp-sdk/src/Exception/ToolNotFoundException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Exception;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Tool\\ToolCall;\n\nfinal class ToolNotFoundException extends \\RuntimeException implements NotFoundExceptionInterface\n{\n public function __construct(\n public readonly ToolCall $toolCall,\n ) {\n parent::__construct(\\sprintf('Tool not found for call: \"%s\"', $toolCall->name));\n }\n}\n"], ["/ai/src/mcp-sdk/src/Exception/PromptNotFoundException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Exception;\n\nuse Symfony\\AI\\McpSdk\\Capability\\Prompt\\PromptGet;\n\nfinal class PromptNotFoundException extends \\RuntimeException implements NotFoundExceptionInterface\n{\n public function __construct(\n public readonly PromptGet $promptGet,\n ) {\n parent::__construct(\\sprintf('Prompt not found for name: \"%s\"', $promptGet->name));\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/ImageSegment.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ImageSegment\n{\n public function __construct(\n public string $label,\n public ?float $score,\n public string $mask,\n ) {\n }\n}\n"], ["/ai/src/platform/src/Exception/UnexpectedResultTypeException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Exception;\n\nclass UnexpectedResultTypeException extends RuntimeException\n{\n public function __construct(string $expectedType, string $actualType)\n {\n parent::__construct(\\sprintf(\n 'Unexpected response type: expected \"%s\", got \"%s\".',\n $expectedType,\n $actualType\n ));\n }\n}\n"], ["/ai/src/platform/src/Result/InMemoryRawResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\n/**\n * A fake implementation of RawResultInterface that returns fixed data.\n *\n * @author Ramy Hakam \n */\nfinal readonly class InMemoryRawResult implements RawResultInterface\n{\n /**\n * @param array $data\n */\n public function __construct(\n private array $data = [],\n private object $object = new \\stdClass(),\n ) {\n }\n\n public function getData(): array\n {\n return $this->data;\n }\n\n public function getObject(): object\n {\n return $this->object;\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/RequestHandler/PingHandler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\RequestHandler;\n\nuse Symfony\\AI\\McpSdk\\Message\\Request;\nuse Symfony\\AI\\McpSdk\\Message\\Response;\n\nfinal class PingHandler extends BaseRequestHandler\n{\n public function createResponse(Request $message): Response\n {\n return new Response($message->id, []);\n }\n\n protected function supportedMethod(): string\n {\n return 'ping';\n }\n}\n"], ["/ai/src/agent/src/Input.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent;\n\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nfinal class Input\n{\n /**\n * @param array $options\n */\n public function __construct(\n public Model $model,\n public MessageBagInterface $messages,\n private array $options,\n ) {\n }\n\n /**\n * @return array\n */\n public function getOptions(): array\n {\n return $this->options;\n }\n\n /**\n * @param array $options\n */\n public function setOptions(array $options): void\n {\n $this->options = $options;\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Tool/ToolCall.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Tool;\n\nfinal readonly class ToolCall\n{\n /**\n * @param array $arguments\n */\n public function __construct(\n public string $id,\n public string $name,\n public array $arguments = [],\n ) {\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Prompt/PromptGet.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Prompt;\n\nfinal readonly class PromptGet\n{\n /**\n * @param array $arguments\n */\n public function __construct(\n public string $id,\n public string $name,\n public array $arguments = [],\n ) {\n }\n}\n"], ["/ai/src/agent/src/Chat/MessageStore/InMemoryStore.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Chat\\MessageStore;\n\nuse Symfony\\AI\\Agent\\Chat\\MessageStoreInterface;\nuse Symfony\\AI\\Platform\\Message\\MessageBag;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\n\nfinal class InMemoryStore implements MessageStoreInterface\n{\n private MessageBagInterface $messages;\n\n public function save(MessageBagInterface $messages): void\n {\n $this->messages = $messages;\n }\n\n public function load(): MessageBagInterface\n {\n return $this->messages ?? new MessageBag();\n }\n\n public function clear(): void\n {\n $this->messages = new MessageBag();\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Prompt/PromptGetResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Prompt;\n\nfinal readonly class PromptGetResult\n{\n /**\n * @param list $messages\n */\n public function __construct(\n public string $description,\n public array $messages = [],\n ) {\n }\n}\n"], ["/ai/src/agent/src/Memory/Memory.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Memory;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class Memory\n{\n public function __construct(public string $content)\n {\n }\n}\n"], ["/ai/fixtures/Tool/ToolWithoutDocs.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\n\n#[AsTool('tool_without_docs', 'A tool with required parameters', method: 'bar')]\nfinal class ToolWithoutDocs\n{\n public function bar(string $text, int $number): string\n {\n return \\sprintf('%s says \"%d\".', $text, $number);\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Resource/ResourceReadResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Resource;\n\nfinal readonly class ResourceReadResult\n{\n public function __construct(\n public string $result,\n public string $uri,\n\n /**\n * @var \"text\"|\"blob\"\n */\n public string $type = 'text',\n public string $mimeType = 'text/plain',\n ) {\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Event/ToolCallsExecuted.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Event;\n\nuse Symfony\\AI\\Agent\\Toolbox\\ToolResult;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ToolCallsExecuted\n{\n /**\n * @var ToolResult[]\n */\n public readonly array $toolResults;\n public ResultInterface $result;\n\n public function __construct(ToolResult ...$toolResults)\n {\n $this->toolResults = $toolResults;\n }\n\n public function hasResponse(): bool\n {\n return isset($this->result);\n }\n}\n"], ["/ai/src/agent/src/StructuredOutput/ResponseFormatFactoryInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\StructuredOutput;\n\n/**\n * @author Oskar Stark \n */\ninterface ResponseFormatFactoryInterface\n{\n /**\n * @param class-string $responseClass\n *\n * @return array{\n * type: 'json_schema',\n * json_schema: array{\n * name: string,\n * schema: array,\n * strict: true,\n * }\n * }\n */\n public function create(string $responseClass): array;\n}\n"], ["/ai/src/agent/src/Output.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent;\n\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Model;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal class Output\n{\n /**\n * @param array $options\n */\n public function __construct(\n public readonly Model $model,\n public ResultInterface $result,\n public readonly MessageBagInterface $messages,\n public readonly array $options,\n ) {\n }\n}\n"], ["/ai/src/platform/src/Bridge/Voyage/Voyage.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\Voyage;\n\nuse Symfony\\AI\\Platform\\Capability;\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author Christopher Hertel \n */\nclass Voyage extends Model\n{\n public const V3 = 'voyage-3';\n public const V3_LITE = 'voyage-3-lite';\n public const FINANCE_2 = 'voyage-finance-2';\n public const MULTILINGUAL_2 = 'voyage-multilingual-2';\n public const LAW_2 = 'voyage-law-2';\n public const CODE_2 = 'voyage-code-2';\n\n /**\n * @param array $options\n */\n public function __construct(string $name = self::V3, array $options = [])\n {\n parent::__construct($name, [Capability::INPUT_MULTIPLE], $options);\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/Token.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class Token\n{\n public function __construct(\n public string $entityGroup,\n public float $score,\n public string $word,\n public int $start,\n public int $end,\n ) {\n }\n}\n"], ["/ai/fixtures/StructuredOutput/MathReasoning.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\StructuredOutput;\n\nfinal class MathReasoning\n{\n /**\n * @param Step[] $steps\n */\n public function __construct(\n public array $steps,\n public string $finalAnswer,\n ) {\n }\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/MaskFill.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class MaskFill\n{\n public function __construct(\n public int $token,\n public string $tokenStr,\n public string $sequence,\n public float $score,\n ) {\n }\n}\n"], ["/ai/src/platform/src/Result/ObjectResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ObjectResult extends BaseResult\n{\n /**\n * @param object|array $structuredOutput\n */\n public function __construct(\n private readonly object|array $structuredOutput,\n ) {\n }\n\n /**\n * @return object|array\n */\n public function getContent(): object|array\n {\n return $this->structuredOutput;\n }\n}\n"], ["/ai/src/agent/src/Toolbox/Event/ToolCallArgumentsResolved.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Event;\n\nuse Symfony\\AI\\Platform\\Tool\\Tool;\n\n/**\n * Dispatched after the arguments are denormalized, just before invoking the tool.\n *\n * @author Valtteri R \n */\nfinal readonly class ToolCallArgumentsResolved\n{\n /**\n * @param array $arguments\n */\n public function __construct(\n public object $tool,\n public Tool $metadata,\n public array $arguments,\n ) {\n }\n}\n"], ["/ai/src/platform/src/Tool/ExecutionReference.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Tool;\n\n/**\n * @author Christopher Hertel \n */\nfinal class ExecutionReference\n{\n public function __construct(\n public string $class,\n public string $method = '__invoke',\n ) {\n }\n}\n"], ["/ai/src/platform/src/Message/MessageBagInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message;\n\n/**\n * @author Oskar Stark \n */\ninterface MessageBagInterface extends \\Countable\n{\n public function add(MessageInterface $message): void;\n\n /**\n * @return list\n */\n public function getMessages(): array;\n\n public function getSystemMessage(): ?SystemMessage;\n\n public function with(MessageInterface $message): self;\n\n public function merge(self $messageBag): self;\n\n public function withoutSystemMessage(): self;\n\n public function prepend(MessageInterface $message): self;\n\n public function containsAudio(): bool;\n\n public function containsImage(): bool;\n}\n"], ["/ai/fixtures/Tool/ToolNoParams.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\Tool;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Attribute\\AsTool;\n\n#[AsTool('tool_no_params', 'A tool without parameters')]\nfinal class ToolNoParams\n{\n public function __invoke(): string\n {\n return 'Hello world!';\n }\n}\n"], ["/ai/src/agent/src/Memory/MemoryProviderInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Memory;\n\nuse Symfony\\AI\\Agent\\Input;\n\n/**\n * @author Denis Zunke \n */\ninterface MemoryProviderInterface\n{\n /**\n * @return list\n */\n public function loadMemory(Input $input): array;\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Output/Classification.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace\\Output;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class Classification\n{\n public function __construct(\n public string $label,\n public float $score,\n ) {\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Resource/ResourceRead.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Resource;\n\nfinal readonly class ResourceRead\n{\n public function __construct(\n public string $id,\n public string $uri,\n ) {\n }\n}\n"], ["/ai/fixtures/StructuredOutput/Step.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Fixtures\\StructuredOutput;\n\nfinal class Step\n{\n public function __construct(\n public string $explanation,\n public string $output,\n ) {\n }\n}\n"], ["/ai/src/mcp-sdk/src/Server/NotificationHandler/BaseNotificationHandler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\NotificationHandler;\n\nuse Symfony\\AI\\McpSdk\\Message\\Notification;\nuse Symfony\\AI\\McpSdk\\Server\\NotificationHandlerInterface;\n\nabstract class BaseNotificationHandler implements NotificationHandlerInterface\n{\n public function supports(Notification $message): bool\n {\n return $message->method === \\sprintf('notifications/%s', $this->supportedNotification());\n }\n\n abstract protected function supportedNotification(): string;\n}\n"], ["/ai/src/mcp-sdk/src/Exception/InvalidArgumentException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Exception;\n\n/**\n * @author Christopher Hertel \n */\nclass InvalidArgumentException extends \\InvalidArgumentException implements ExceptionInterface\n{\n}\n"], ["/ai/src/platform/src/Result/TextResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\n/**\n * @author Christopher Hertel \n */\nfinal class TextResult extends BaseResult\n{\n public function __construct(\n private readonly string $content,\n ) {\n }\n\n public function getContent(): string\n {\n return $this->content;\n }\n}\n"], ["/ai/src/ai-bundle/src/Exception/InvalidArgumentException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\AIBundle\\Exception;\n\n/**\n * @author Christopher Hertel \n */\nclass InvalidArgumentException extends \\InvalidArgumentException implements ExceptionInterface\n{\n}\n"], ["/ai/src/platform/src/Result/RawHttpResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\nuse Symfony\\Contracts\\HttpClient\\ResponseInterface;\n\n/**\n * @author Christopher Hertel response->toArray(false);\n }\n\n public function getObject(): ResponseInterface\n {\n return $this->response;\n }\n}\n"], ["/ai/src/agent/src/Toolbox/ToolResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox;\n\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ToolResult\n{\n public function __construct(\n public ToolCall $toolCall,\n public mixed $result,\n ) {\n }\n}\n"], ["/ai/src/platform/src/Bridge/TransformersPHP/RawPipelineResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\TransformersPHP;\n\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class RawPipelineResult implements RawResultInterface\n{\n public function __construct(\n private PipelineExecution $pipelineExecution,\n ) {\n }\n\n public function getData(): array\n {\n return $this->pipelineExecution->getResult();\n }\n\n public function getObject(): PipelineExecution\n {\n return $this->pipelineExecution;\n }\n}\n"], ["/ai/src/platform/src/Result/StreamResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\n/**\n * @author Christopher Hertel \n */\nfinal class StreamResult extends BaseResult\n{\n public function __construct(\n private readonly \\Generator $generator,\n ) {\n }\n\n public function getContent(): \\Generator\n {\n yield from $this->generator;\n }\n}\n"], ["/ai/src/platform/src/Result/VectorResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\nuse Symfony\\AI\\Platform\\Vector\\Vector;\n\n/**\n * @author Christopher Hertel \n */\nfinal class VectorResult extends BaseResult\n{\n /**\n * @var Vector[]\n */\n private readonly array $vectors;\n\n public function __construct(Vector ...$vector)\n {\n $this->vectors = $vector;\n }\n\n /**\n * @return Vector[]\n */\n public function getContent(): array\n {\n return $this->vectors;\n }\n}\n"], ["/ai/src/store/src/InitializableStoreInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store;\n\n/**\n * @author Oskar Stark \n */\ninterface InitializableStoreInterface extends StoreInterface\n{\n /**\n * @param array $options\n */\n public function initialize(array $options = []): void;\n}\n"], ["/ai/src/agent/src/ChatInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent;\n\nuse Symfony\\AI\\Agent\\Exception\\ExceptionInterface;\nuse Symfony\\AI\\Platform\\Message\\AssistantMessage;\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\nuse Symfony\\AI\\Platform\\Message\\UserMessage;\n\ninterface ChatInterface\n{\n public function initiate(MessageBagInterface $messages): void;\n\n /**\n * @throws ExceptionInterface When the chat submission fails due to agent errors\n */\n public function submit(UserMessage $message): AssistantMessage;\n}\n"], ["/ai/src/platform/src/Message/Content/ImageUrl.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message\\Content;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class ImageUrl implements ContentInterface\n{\n public function __construct(\n public string $url,\n ) {\n }\n}\n"], ["/ai/src/platform/src/Message/Content/DocumentUrl.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message\\Content;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class DocumentUrl implements ContentInterface\n{\n public function __construct(\n public string $url,\n ) {\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Resource/ResourceReaderInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Resource;\n\nuse Symfony\\AI\\McpSdk\\Exception\\ResourceNotFoundException;\nuse Symfony\\AI\\McpSdk\\Exception\\ResourceReadException;\n\ninterface ResourceReaderInterface\n{\n /**\n * @throws ResourceReadException if the resource execution fails\n * @throws ResourceNotFoundException if the resource is not found\n */\n public function read(ResourceRead $input): ResourceReadResult;\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Prompt/PromptGetterInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Prompt;\n\nuse Symfony\\AI\\McpSdk\\Exception\\PromptGetException;\nuse Symfony\\AI\\McpSdk\\Exception\\PromptNotFoundException;\n\ninterface PromptGetterInterface\n{\n /**\n * @throws PromptGetException if the prompt execution fails\n * @throws PromptNotFoundException if the prompt is not found\n */\n public function get(PromptGet $input): PromptGetResult;\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Prompt/MetadataInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Prompt;\n\ninterface MetadataInterface extends IdentifierInterface\n{\n public function getDescription(): ?string;\n\n /**\n * @return list\n */\n public function getArguments(): array;\n}\n"], ["/ai/src/platform/src/Message/Role.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message;\n\nuse OskarStark\\Enum\\Trait\\Comparable;\n\n/**\n * @author Christopher Hertel \n */\nenum Role: string\n{\n use Comparable;\n\n case System = 'system';\n case Assistant = 'assistant';\n case User = 'user';\n case ToolCall = 'tool';\n}\n"], ["/ai/src/platform/src/Message/Content/Image.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message\\Content;\n\n/**\n * @author Denis Zunke \n */\nfinal readonly class Image extends File\n{\n}\n"], ["/ai/src/platform/src/Message/Content/ContentInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message\\Content;\n\n/**\n * @author Denis Zunke \n */\ninterface ContentInterface\n{\n}\n"], ["/ai/src/platform/src/Message/MessageInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message;\n\nuse Symfony\\Component\\Uid\\AbstractUid;\nuse Symfony\\Component\\Uid\\TimeBasedUidInterface;\n\n/**\n * @author Denis Zunke \n */\ninterface MessageInterface\n{\n public function getRole(): Role;\n\n public function getId(): AbstractUid&TimeBasedUidInterface;\n}\n"], ["/ai/src/platform/src/Result/BaseResult.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\nuse Symfony\\AI\\Platform\\Result\\Metadata\\MetadataAwareTrait;\n\n/**\n * Base result of converted result classes.\n *\n * @author Denis Zunke \n */\nabstract class BaseResult implements ResultInterface\n{\n use MetadataAwareTrait;\n use RawResultAwareTrait;\n}\n"], ["/ai/src/agent/src/AgentAwareTrait.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent;\n\n/**\n * @author Christopher Hertel \n */\ntrait AgentAwareTrait\n{\n private AgentInterface $agent;\n\n public function setAgent(AgentInterface $agent): void\n {\n $this->agent = $agent;\n }\n}\n"], ["/ai/src/agent/src/Toolbox/ToolFactoryInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox;\n\nuse Symfony\\AI\\Agent\\Toolbox\\Exception\\ToolException;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\n\n/**\n * @author Christopher Hertel \n */\ninterface ToolFactoryInterface\n{\n /**\n * @return iterable\n *\n * @throws ToolException if the metadata for the given reference is not found\n */\n public function getTool(string $reference): iterable;\n}\n"], ["/ai/src/platform/src/PlatformInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform;\n\nuse Symfony\\AI\\Platform\\Result\\ResultPromise;\n\n/**\n * @author Christopher Hertel \n */\ninterface PlatformInterface\n{\n /**\n * @param array|string|object $input\n * @param array $options\n */\n public function invoke(Model $model, array|string|object $input, array $options = []): ResultPromise;\n}\n"], ["/ai/src/platform/src/ModelClientInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform;\n\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\n\n/**\n * @author Christopher Hertel \n */\ninterface ModelClientInterface\n{\n public function supports(Model $model): bool;\n\n /**\n * @param array $payload\n * @param array $options\n */\n public function request(Model $model, array|string $payload, array $options = []): RawResultInterface;\n}\n"], ["/ai/src/platform/src/Vector/VectorInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Vector;\n\n/**\n * @author Oskar Stark \n */\ninterface VectorInterface\n{\n /**\n * @return list\n */\n public function getData(): array;\n\n public function getDimensions(): int;\n}\n"], ["/ai/src/mcp-sdk/src/Server/NotificationHandler/InitializedHandler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\NotificationHandler;\n\nuse Symfony\\AI\\McpSdk\\Message\\Notification;\n\nfinal class InitializedHandler extends BaseNotificationHandler\n{\n protected function supportedNotification(): string\n {\n return 'initialized';\n }\n\n public function handle(Notification $notification): void\n {\n }\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Tool/MetadataInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Tool;\n\ninterface MetadataInterface extends IdentifierInterface\n{\n public function getDescription(): string;\n\n /**\n * @return array{\n * type?: string,\n * required?: list,\n * properties?: array,\n * }\n */\n public function getInputSchema(): array;\n}\n"], ["/ai/src/platform/src/Capability.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform;\n\n/**\n * @author Christopher Hertel \n */\nenum Capability: string\n{\n // INPUT\n case INPUT_AUDIO = 'input-audio';\n case INPUT_IMAGE = 'input-image';\n case INPUT_MESSAGES = 'input-messages';\n case INPUT_MULTIPLE = 'input-multiple';\n case INPUT_PDF = 'input-pdf';\n case INPUT_TEXT = 'input-text';\n\n // OUTPUT\n case OUTPUT_AUDIO = 'output-audio';\n case OUTPUT_IMAGE = 'output-image';\n case OUTPUT_STREAMING = 'output-streaming';\n case OUTPUT_STRUCTURED = 'output-structured';\n case OUTPUT_TEXT = 'output-text';\n\n // FUNCTIONALITY\n case TOOL_CALLING = 'tool-calling';\n}\n"], ["/ai/src/mcp-sdk/src/Server/Transport/Sse/StoreInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\Transport\\Sse;\n\nuse Symfony\\Component\\Uid\\Uuid;\n\ninterface StoreInterface\n{\n public function push(Uuid $id, string $message): void;\n\n public function pop(Uuid $id): ?string;\n\n public function remove(Uuid $id): void;\n}\n"], ["/ai/src/mcp-sdk/src/Server/RequestHandler/BaseRequestHandler.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server\\RequestHandler;\n\nuse Symfony\\AI\\McpSdk\\Message\\Request;\nuse Symfony\\AI\\McpSdk\\Server\\RequestHandlerInterface;\n\nabstract class BaseRequestHandler implements RequestHandlerInterface\n{\n public function supports(Request $message): bool\n {\n return $message->method === $this->supportedMethod();\n }\n\n abstract protected function supportedMethod(): string;\n}\n"], ["/ai/src/platform/src/Exception/ExceptionInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Exception;\n\n/**\n * @author Oskar Stark \n */\ninterface ExceptionInterface extends \\Throwable\n{\n}\n"], ["/ai/src/platform/src/Exception/RuntimeException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Exception;\n\n/**\n * @author Oskar Stark \n */\nclass RuntimeException extends \\RuntimeException implements ExceptionInterface\n{\n}\n"], ["/ai/src/agent/src/Exception/ExceptionInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Exception;\n\n/**\n * @author Oskar Stark \n */\ninterface ExceptionInterface extends \\Throwable\n{\n}\n"], ["/ai/src/store/src/Exception/ExceptionInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Exception;\n\n/**\n * @author Oskar Stark \n */\ninterface ExceptionInterface extends \\Throwable\n{\n}\n"], ["/ai/src/store/src/Exception/RuntimeException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Exception;\n\n/**\n * @author Oskar Stark \n */\nclass RuntimeException extends \\RuntimeException implements ExceptionInterface\n{\n}\n"], ["/ai/src/agent/src/Exception/RuntimeException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Exception;\n\n/**\n * @author Oskar Stark \n */\nclass RuntimeException extends \\RuntimeException implements ExceptionInterface\n{\n}\n"], ["/ai/src/agent/src/Exception/LogicException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Exception;\n\n/**\n * @author Oskar Stark \n */\nclass LogicException extends \\LogicException implements ExceptionInterface\n{\n}\n"], ["/ai/src/platform/src/ResultConverterInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform;\n\nuse Symfony\\AI\\Platform\\Result\\RawResultInterface;\nuse Symfony\\AI\\Platform\\Result\\ResultInterface;\n\n/**\n * @author Christopher Hertel \n */\ninterface ResultConverterInterface\n{\n public function supports(Model $model): bool;\n\n /**\n * @param array $options\n */\n public function convert(RawResultInterface $result, array $options = []): ResultInterface;\n}\n"], ["/ai/src/mcp-sdk/src/Server/RequestHandlerInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server;\n\nuse Symfony\\AI\\McpSdk\\Exception\\ExceptionInterface;\nuse Symfony\\AI\\McpSdk\\Message\\Error;\nuse Symfony\\AI\\McpSdk\\Message\\Request;\nuse Symfony\\AI\\McpSdk\\Message\\Response;\n\ninterface RequestHandlerInterface\n{\n public function supports(Request $message): bool;\n\n /**\n * @throws ExceptionInterface When the handler encounters an error processing the request\n */\n public function createResponse(Request $message): Response|Error;\n}\n"], ["/ai/src/agent/src/Toolbox/ToolCallArgumentResolverInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox;\n\nuse Symfony\\AI\\Platform\\Result\\ToolCall;\nuse Symfony\\AI\\Platform\\Tool\\Tool;\n\n/**\n * @author Valtteri R \n */\ninterface ToolCallArgumentResolverInterface\n{\n /**\n * @return array\n */\n public function resolveArguments(object $tool, Tool $metadata, ToolCall $toolCall): array;\n}\n"], ["/ai/src/mcp-sdk/src/Server/NotificationHandlerInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server;\n\nuse Symfony\\AI\\McpSdk\\Exception\\ExceptionInterface;\nuse Symfony\\AI\\McpSdk\\Message\\Notification;\n\ninterface NotificationHandlerInterface\n{\n public function supports(Notification $message): bool;\n\n /**\n * @throws ExceptionInterface When the handler encounters an error processing the notification\n */\n public function handle(Notification $notification): void;\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Provider.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace;\n\n/**\n * @author Christopher Hertel \n */\ninterface Provider\n{\n public const CEREBRAS = 'cerebras';\n public const COHERE = 'cohere';\n public const FAL_AI = 'fal-ai';\n public const FIREWORKS = 'fireworks-ai';\n public const HYPERBOLIC = 'hyperbolic';\n public const HF_INFERENCE = 'hf-inference';\n public const NEBIUS = 'nebius';\n public const NOVITA = 'novita';\n public const REPLICATE = 'replicate';\n public const SAMBA_NOVA = 'sambanova';\n public const TOGETHER = 'together';\n}\n"], ["/ai/src/platform/src/Bridge/HuggingFace/Task.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\HuggingFace;\n\n/**\n * @author Christopher Hertel \n */\ninterface Task\n{\n public const AUDIO_CLASSIFICATION = 'audio-classification';\n public const AUTOMATIC_SPEECH_RECOGNITION = 'automatic-speech-recognition';\n public const CHAT_COMPLETION = 'chat-completion';\n public const FEATURE_EXTRACTION = 'feature-extraction';\n public const FILL_MASK = 'fill-mask';\n public const IMAGE_CLASSIFICATION = 'image-classification';\n public const IMAGE_SEGMENTATION = 'image-segmentation';\n public const IMAGE_TO_TEXT = 'image-to-text';\n public const OBJECT_DETECTION = 'object-detection';\n public const QUESTION_ANSWERING = 'question-answering';\n public const SENTENCE_SIMILARITY = 'sentence-similarity';\n public const SUMMARIZATION = 'summarization';\n public const TABLE_QUESTION_ANSWERING = 'table-question-answering';\n public const TEXT_CLASSIFICATION = 'text-classification';\n public const TEXT_GENERATION = 'text-generation';\n public const TEXT_TO_IMAGE = 'text-to-image';\n public const TOKEN_CLASSIFICATION = 'token-classification';\n public const TRANSLATION = 'translation';\n public const ZERO_SHOT_CLASSIFICATION = 'zero-shot-classification';\n}\n"], ["/ai/src/platform/src/Bridge/OpenAI/Whisper/Task.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\OpenAI\\Whisper;\n\n/**\n * @author Christopher Hertel \n */\ninterface Task\n{\n public const TRANSCRIPTION = 'transcription';\n public const TRANSLATION = 'translation';\n}\n"], ["/ai/src/mcp-sdk/src/Server/TransportInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Server;\n\ninterface TransportInterface\n{\n public function initialize(): void;\n\n public function isConnected(): bool;\n\n public function receive(): \\Generator;\n\n public function send(string $data): void;\n\n public function close(): void;\n}\n"], ["/ai/src/agent/src/OutputProcessorInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent;\n\n/**\n * @author Christopher Hertel \n */\ninterface OutputProcessorInterface\n{\n public function processOutput(Output $output): void;\n}\n"], ["/ai/src/agent/src/InputProcessorInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent;\n\n/**\n * @author Christopher Hertel \n */\ninterface InputProcessorInterface\n{\n public function processInput(Input $input): void;\n}\n"], ["/ai/src/agent/src/AgentAwareInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent;\n\n/**\n * @author Christopher Hertel \n */\ninterface AgentAwareInterface\n{\n public function setAgent(AgentInterface $agent): void;\n}\n"], ["/ai/src/agent/src/Chat/MessageStoreInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Chat;\n\nuse Symfony\\AI\\Platform\\Message\\MessageBagInterface;\n\ninterface MessageStoreInterface\n{\n public function save(MessageBagInterface $messages): void;\n\n public function load(): MessageBagInterface;\n\n public function clear(): void;\n}\n"], ["/ai/src/platform/src/Result/RawResultInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Result;\n\n/**\n * Base class for raw model result.\n *\n * @author Christopher Hertel \n */\ninterface RawResultInterface\n{\n /**\n * Returns an array representation of the raw result data.\n *\n * @return array\n */\n public function getData(): array;\n\n public function getObject(): object;\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Tool/ToolCollectionInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Tool;\n\ninterface ToolCollectionInterface\n{\n /**\n * @return MetadataInterface[]\n */\n public function getMetadata(): array;\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Tool/IdentifierInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Tool;\n\ninterface IdentifierInterface\n{\n public function getName(): string;\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Resource/IdentifierInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Resource;\n\ninterface IdentifierInterface\n{\n public function getUri(): string;\n}\n"], ["/ai/src/mcp-sdk/src/Capability/Prompt/IdentifierInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Capability\\Prompt;\n\ninterface IdentifierInterface\n{\n public function getName(): string;\n}\n"], ["/ai/src/mcp-sdk/src/Exception/HandlerNotFoundException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Exception;\n\nclass HandlerNotFoundException extends \\InvalidArgumentException implements NotFoundExceptionInterface\n{\n}\n"], ["/ai/src/mcp-sdk/src/Exception/InvalidInputMessageException.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Exception;\n\nclass InvalidInputMessageException extends \\InvalidArgumentException implements ExceptionInterface\n{\n}\n"], ["/ai/src/platform/src/Message/Content/Document.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message\\Content;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class Document extends File\n{\n}\n"], ["/ai/src/platform/src/Message/Content/Audio.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Message\\Content;\n\n/**\n * @author Christopher Hertel \n */\nfinal readonly class Audio extends File\n{\n}\n"], ["/ai/src/store/src/StoreInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store;\n\nuse Symfony\\AI\\Store\\Document\\VectorDocument;\n\n/**\n * @author Christopher Hertel \n */\ninterface StoreInterface\n{\n public function add(VectorDocument ...$documents): void;\n}\n"], ["/ai/src/ai-bundle/src/Exception/ExceptionInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\AIBundle\\Exception;\n\n/**\n * @author Christopher Hertel \n */\ninterface ExceptionInterface extends \\Throwable\n{\n}\n"], ["/ai/src/store/src/Document/Metadata.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Store\\Document;\n\n/**\n * @template-extends \\ArrayObject\n *\n * @author Christopher Hertel \n */\nfinal class Metadata extends \\ArrayObject\n{\n}\n"], ["/ai/src/agent/src/Toolbox/Exception/ExceptionInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Agent\\Toolbox\\Exception;\n\nuse Symfony\\AI\\Agent\\Exception\\ExceptionInterface as BaseExceptionInterface;\n\n/**\n * @author Christopher Hertel \n */\ninterface ExceptionInterface extends BaseExceptionInterface\n{\n}\n"], ["/ai/src/platform/src/Bridge/LMStudio/Embeddings.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\Platform\\Bridge\\LMStudio;\n\nuse Symfony\\AI\\Platform\\Model;\n\n/**\n * @author André Lubian \n */\nclass Embeddings extends Model\n{\n}\n"], ["/ai/src/mcp-sdk/src/Exception/ExceptionInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Exception;\n\ninterface ExceptionInterface extends \\Throwable\n{\n}\n"], ["/ai/src/mcp-sdk/src/Exception/NotFoundExceptionInterface.php", "\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\AI\\McpSdk\\Exception;\n\ninterface NotFoundExceptionInterface extends ExceptionInterface\n{\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 21:25:08", "created_task_model": "DeepSeek-R1", "function_skeleton": "public function __construct (\n // can be used by many types\n public ?array $enum = null,\n public string|int|array|null $const = null,\n\n // string\n public ?string $pattern = null,\n public ?int $minLength = null,\n public ?int $maxLength = null,\n\n // integer\n public ?int $minimum = null,\n public ?int $maximum = null,\n public ?int $multipleOf = null,\n public ?int $exclusiveMinimum = null,\n public ?int $exclusiveMaximum = null,\n\n // array\n public ?int $minItems = null,\n public ?int $maxItems = null,\n public ?bool $uniqueItems = null,\n public ?int $minContains = null,\n public ?int $maxContains = null,\n\n // object\n public ?bool $required = null,\n public ?int $minProperties = null,\n public ?int $maxProperties = null,\n public ?bool $dependentRequired = null,\n ) {}", "code_description": "This code segment functions to: Define and enforce validation constraints on various data attributes by verifying parameter consistency, ensuring numerical boundaries adhere to logical ordering, and maintaining type-specific integrity checks for input values."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```php\n[TASK_BEGIN]\npublic function __construct(\n // can be used by many types\n public ?array $enum = null,\n public string|int|array|null $const = null,\n\n // string\n public ?string $pattern = null,\n public ?int $minLength = null,\n public ?int $maxLength = null,\n\n // integer\n public ?int $minimum = null,\n public ?int $maximum = null,\n public ?int $multipleOf = null,\n public ?int $exclusiveMinimum = null,\n public ?int $exclusiveMaximum = null,\n\n // array\n public ?int $minItems = null,\n public ?int $maxItems = null,\n public ?bool $uniqueItems = null,\n public ?int $minContains = null,\n public ?int $maxContains = null,\n\n // object\n public ?bool $required = null,\n public ?int $minProperties = null,\n public ?int $maxProperties = null,\n public ?bool $dependentRequired = null,\n) {}\n[TASK_END]\n```", "inference_time": "2025-08-20 21-25-22"}, "editdistance_info": {"edit_distance": 17.1828, "calculate_time": "2025-08-20 21:25:22", "true_code_clean": "public function __construct(\n public ?array $enum = null,\n public string|int|array|null $const = null,\n public ?string $pattern = null,\n public ?int $minLength = null,\n public ?int $maxLength = null,\n public ?int $minimum = null,\n public ?int $maximum = null,\n public ?int $multipleOf = null,\n public ?int $exclusiveMinimum = null,\n public ?int $exclusiveMaximum = null,\n public ?int $minItems = null,\n public ?int $maxItems = null,\n public ?bool $uniqueItems = null,\n public ?int $minContains = null,\n public ?int $maxContains = null,\n public ?bool $required = null,\n public ?int $minProperties = null,\n public ?int $maxProperties = null,\n public ?bool $dependentRequired = null,\n ) {\n if (\\is_array($enum)) {\n array_filter($enum, fn ($item) => \\is_string($item)) === $enum || throw new InvalidArgumentException('All enum values must be strings.');\n }\n if (\\is_string($const)) {\n '' !== trim($const) || throw new InvalidArgumentException('Const string must not be empty.');\n }\n if (\\is_string($pattern)) {\n '' !== trim($pattern) || throw new InvalidArgumentException('Pattern string must not be empty.');\n }\n if (\\is_int($minLength)) {\n $minLength >= 0 || throw new InvalidArgumentException('MinLength must be greater than or equal to 0.');\n if (\\is_int($maxLength)) {\n $maxLength >= $minLength || throw new InvalidArgumentException('MaxLength must be greater than or equal to minLength.');\n }\n }\n if (\\is_int($maxLength)) {\n $maxLength >= 0 || throw new InvalidArgumentException('MaxLength must be greater than or equal to 0.');\n }\n if (\\is_int($minimum)) {\n $minimum >= 0 || throw new InvalidArgumentException('Minimum must be greater than or equal to 0.');\n if (\\is_int($maximum)) {\n $maximum >= $minimum || throw new InvalidArgumentException('Maximum must be greater than or equal to minimum.');\n }\n }\n if (\\is_int($maximum)) {\n $maximum >= 0 || throw new InvalidArgumentException('Maximum must be greater than or equal to 0.');\n }\n if (\\is_int($multipleOf)) {\n $multipleOf >= 0 || throw new InvalidArgumentException('MultipleOf must be greater than or equal to 0.');\n }\n if (\\is_int($exclusiveMinimum)) {\n $exclusiveMinimum >= 0 || throw new InvalidArgumentException('ExclusiveMinimum must be greater than or equal to 0.');\n if (\\is_int($exclusiveMaximum)) {\n $exclusiveMaximum >= $exclusiveMinimum || throw new InvalidArgumentException('ExclusiveMaximum must be greater than or equal to exclusiveMinimum.');\n }\n }\n if (\\is_int($exclusiveMaximum)) {\n $exclusiveMaximum >= 0 || throw new InvalidArgumentException('ExclusiveMaximum must be greater than or equal to 0.');\n }\n if (\\is_int($minItems)) {\n $minItems >= 0 || throw new InvalidArgumentException('MinItems must be greater than or equal to 0.');\n if (\\is_int($maxItems)) {\n $maxItems >= $minItems || throw new InvalidArgumentException('MaxItems must be greater than or equal to minItems.');\n }\n }\n if (\\is_int($maxItems)) {\n $maxItems >= 0 || throw new InvalidArgumentException('MaxItems must be greater than or equal to 0.');\n }\n if (\\is_bool($uniqueItems)) {\n true === $uniqueItems || throw new InvalidArgumentException('UniqueItems must be true when specified.');\n }\n if (\\is_int($minContains)) {\n $minContains >= 0 || throw new InvalidArgumentException('MinContains must be greater than or equal to 0.');\n if (\\is_int($maxContains)) {\n $maxContains >= $minContains || throw new InvalidArgumentException('MaxContains must be greater than or equal to minContains.');\n }\n }\n if (\\is_int($maxContains)) {\n $maxContains >= 0 || throw new InvalidArgumentException('MaxContains must be greater than or equal to 0.');\n }\n if (\\is_int($minProperties)) {\n $minProperties >= 0 || throw new InvalidArgumentException('MinProperties must be greater than or equal to 0.');\n if (\\is_int($maxProperties)) {\n $maxProperties >= $minProperties || throw new InvalidArgumentException('MaxProperties must be greater than or equal to minProperties.');\n }\n }\n if (\\is_int($maxProperties)) {\n $maxProperties >= 0 || throw new InvalidArgumentException('MaxProperties must be greater than or equal to 0.');\n }\n }", "predict_code_clean": "public function __construct(\n public ?array $enum = null,\n public string|int|array|null $const = null,\n public ?string $pattern = null,\n public ?int $minLength = null,\n public ?int $maxLength = null,\n public ?int $minimum = null,\n public ?int $maximum = null,\n public ?int $multipleOf = null,\n public ?int $exclusiveMinimum = null,\n public ?int $exclusiveMaximum = null,\n public ?int $minItems = null,\n public ?int $maxItems = null,\n public ?bool $uniqueItems = null,\n public ?int $minContains = null,\n public ?int $maxContains = null,\n public ?bool $required = null,\n public ?int $minProperties = null,\n public ?int $maxProperties = null,\n public ?bool $dependentRequired = null,\n) {}"}}