|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[email protected]> |
| 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\Fixtures\Movies; |
| 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\Vectorizer; |
| 19 | +use Symfony\AI\Store\Indexer; |
| 20 | +use Symfony\AI\Store\Retriever; |
| 21 | +use Symfony\Component\Uid\Uuid; |
| 22 | + |
| 23 | +require_once dirname(__DIR__).'/bootstrap.php'; |
| 24 | + |
| 25 | +$store = new InMemoryStore(); |
| 26 | + |
| 27 | +$documents = []; |
| 28 | +foreach (Movies::all() as $movie) { |
| 29 | + $documents[] = new TextDocument( |
| 30 | + id: Uuid::v4(), |
| 31 | + content: 'Title: '.$movie['title'].\PHP_EOL.'Director: '.$movie['director'].\PHP_EOL.'Description: '.$movie['description'], |
| 32 | + metadata: new Metadata($movie), |
| 33 | + ); |
| 34 | +} |
| 35 | + |
| 36 | +$platform = PlatformFactory::create(env('OPENAI_API_KEY'), http_client()); |
| 37 | +$vectorizer = new Vectorizer($platform, 'text-embedding-3-small', logger()); |
| 38 | + |
| 39 | +$indexer = new Indexer(new InMemoryLoader($documents), $vectorizer, $store, logger: logger()); |
| 40 | +$indexer->index(); |
| 41 | + |
| 42 | +$retriever = new Retriever($vectorizer, $store, logger()); |
| 43 | + |
| 44 | +echo "Searching for movies about 'crime family mafia'\n"; |
| 45 | +echo "================================================\n\n"; |
| 46 | + |
| 47 | +$results = $retriever->retrieve('crime family mafia'); |
| 48 | + |
| 49 | +foreach ($results as $i => $document) { |
| 50 | + $title = $document->metadata['title']; |
| 51 | + $director = $document->metadata['director']; |
| 52 | + $score = $document->score; |
| 53 | + |
| 54 | + echo sprintf("%d. %s (Director: %s)\n", $i + 1, $title, $director); |
| 55 | + echo sprintf(" Score: %.4f\n\n", $score ?? 0); |
| 56 | +} |
0 commit comments