|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +use Symfony\AI\Platform\Bridge\OpenAi\Embeddings; |
| 13 | +use Symfony\AI\Platform\Bridge\OpenAi\PlatformFactory; |
| 14 | +use Symfony\AI\Store\Bridge\Local\InMemoryStore; |
| 15 | +use Symfony\AI\Store\Document\Loader\InMemoryLoader; |
| 16 | +use Symfony\AI\Store\Document\Metadata; |
| 17 | +use Symfony\AI\Store\Document\TextDocument; |
| 18 | +use Symfony\AI\Store\Document\Transformer\TextSplitTransformer; |
| 19 | +use Symfony\AI\Store\Document\Vectorizer; |
| 20 | +use Symfony\AI\Store\Indexer; |
| 21 | +use Symfony\Component\Uid\Uuid; |
| 22 | + |
| 23 | +require_once dirname(__DIR__).'/bootstrap.php'; |
| 24 | + |
| 25 | +$platform = PlatformFactory::create(env('OPENAI_API_KEY'), http_client()); |
| 26 | +$store = new InMemoryStore(); |
| 27 | +$vectorizer = new Vectorizer($platform, new Embeddings('text-embedding-3-small')); |
| 28 | + |
| 29 | +$documents = [ |
| 30 | + new TextDocument( |
| 31 | + Uuid::v4(), |
| 32 | + 'Artificial Intelligence is transforming the way we work and live. Machine learning algorithms can now process vast amounts of data and make predictions with remarkable accuracy.', |
| 33 | + new Metadata(['title' => 'AI Revolution']) |
| 34 | + ), |
| 35 | + new TextDocument( |
| 36 | + Uuid::v4(), |
| 37 | + 'Climate change is one of the most pressing challenges of our time. Renewable energy sources like solar and wind power are becoming increasingly important for a sustainable future.', |
| 38 | + new Metadata(['title' => 'Climate Action']) |
| 39 | + ), |
| 40 | +]; |
| 41 | + |
| 42 | +$indexer = new Indexer( |
| 43 | + loader: new InMemoryLoader($documents), |
| 44 | + vectorizer: $vectorizer, |
| 45 | + store: $store, |
| 46 | + source: null, |
| 47 | + transformers: [ |
| 48 | + new TextSplitTransformer(chunkSize: 100, overlap: 20), |
| 49 | + ], |
| 50 | +); |
| 51 | + |
| 52 | +$indexer->index(); |
| 53 | + |
| 54 | +$vector = $vectorizer->vectorize('machine learning artificial intelligence'); |
| 55 | +$results = $store->query($vector); |
| 56 | +foreach ($results as $i => $document) { |
| 57 | + echo sprintf("%d. %s\n", $i + 1, substr($document->id, 0, 40).'...'); |
| 58 | +} |
0 commit comments