-
-
Notifications
You must be signed in to change notification settings - Fork 29
[Store] Add SurrealDB #139
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+614
−1
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
use Symfony\AI\Agent\Agent; | ||
use Symfony\AI\Agent\Toolbox\AgentProcessor; | ||
use Symfony\AI\Agent\Toolbox\Tool\SimilaritySearch; | ||
use Symfony\AI\Agent\Toolbox\Toolbox; | ||
use Symfony\AI\Fixtures\Movies; | ||
use Symfony\AI\Platform\Bridge\OpenAI\Embeddings; | ||
use Symfony\AI\Platform\Bridge\OpenAI\GPT; | ||
use Symfony\AI\Platform\Bridge\OpenAI\PlatformFactory; | ||
use Symfony\AI\Platform\Message\Message; | ||
use Symfony\AI\Platform\Message\MessageBag; | ||
use Symfony\AI\Store\Bridge\SurrealDB\Store; | ||
use Symfony\AI\Store\Document\Metadata; | ||
use Symfony\AI\Store\Document\TextDocument; | ||
use Symfony\AI\Store\Document\Vectorizer; | ||
use Symfony\AI\Store\Indexer; | ||
use Symfony\Component\HttpClient\HttpClient; | ||
use Symfony\Component\Uid\Uuid; | ||
|
||
require_once dirname(__DIR__).'/bootstrap.php'; | ||
|
||
// initialize the store | ||
$store = new Store( | ||
httpClient: HttpClient::create(), | ||
endpointUrl: env('SURREALDB_HOST'), | ||
user: env('SURREALDB_USER'), | ||
password: env('SURREALDB_PASS'), | ||
namespace: 'default', | ||
database: 'movies', | ||
table: 'movies', | ||
); | ||
|
||
// initialize the table | ||
$store->initialize(); | ||
|
||
// create embeddings and documents | ||
$documents = []; | ||
foreach (Movies::all() as $i => $movie) { | ||
$documents[] = new TextDocument( | ||
id: Uuid::v4(), | ||
content: 'Title: '.$movie['title'].\PHP_EOL.'Director: '.$movie['director'].\PHP_EOL.'Description: '.$movie['description'], | ||
metadata: new Metadata($movie), | ||
); | ||
} | ||
|
||
// create embeddings for documents | ||
$platform = PlatformFactory::create($_SERVER['OPENAI_API_KEY']); | ||
$vectorizer = new Vectorizer($platform, $embeddings = new Embeddings()); | ||
$indexer = new Indexer($vectorizer, $store); | ||
$indexer->index($documents); | ||
|
||
$model = new GPT(GPT::GPT_4O_MINI); | ||
|
||
$similaritySearch = new SimilaritySearch($platform, $embeddings, $store); | ||
$toolbox = new Toolbox([$similaritySearch], logger: logger()); | ||
$processor = new AgentProcessor($toolbox); | ||
$agent = new Agent($platform, $model, [$processor], [$processor]); | ||
|
||
$messages = new MessageBag( | ||
Message::forSystem('Please answer all user questions only using SimilaritySearch function.'), | ||
Message::ofUser('Which movie fits the theme of technology?') | ||
); | ||
$response = $agent->call($messages); | ||
|
||
echo $response->getContent().\PHP_EOL; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,173 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\AI\Store\Bridge\SurrealDB; | ||
|
||
use Symfony\AI\Platform\Vector\NullVector; | ||
use Symfony\AI\Platform\Vector\Vector; | ||
use Symfony\AI\Store\Document\Metadata; | ||
use Symfony\AI\Store\Document\VectorDocument; | ||
use Symfony\AI\Store\Exception\InvalidArgumentException; | ||
use Symfony\AI\Store\Exception\RuntimeException; | ||
use Symfony\AI\Store\InitializableStoreInterface; | ||
use Symfony\AI\Store\VectorStoreInterface; | ||
use Symfony\Component\Uid\Uuid; | ||
use Symfony\Contracts\HttpClient\HttpClientInterface; | ||
|
||
/** | ||
* @author Guillaume Loulier <[email protected]> | ||
*/ | ||
final class Store implements InitializableStoreInterface, VectorStoreInterface | ||
{ | ||
private string $authenticationToken = ''; | ||
|
||
public function __construct( | ||
private readonly HttpClientInterface $httpClient, | ||
private readonly string $endpointUrl, | ||
#[\SensitiveParameter] private readonly string $user, | ||
#[\SensitiveParameter] private readonly string $password, | ||
#[\SensitiveParameter] private readonly string $namespace, | ||
#[\SensitiveParameter] private readonly string $database, | ||
private readonly string $table = 'vectors', | ||
private readonly string $vectorFieldName = '_vectors', | ||
private readonly string $strategy = 'cosine', | ||
private readonly int $embeddingsDimension = 1536, | ||
private readonly bool $isNamespacedUser = false, | ||
) { | ||
} | ||
|
||
public function add(VectorDocument ...$documents): void | ||
{ | ||
foreach ($documents as $document) { | ||
$this->request('POST', \sprintf('key/%s', $this->table), $this->convertToIndexableArray($document)); | ||
} | ||
} | ||
|
||
public function query(Vector $vector, array $options = [], ?float $minScore = null): array | ||
{ | ||
$vectors = json_encode($vector->getData()); | ||
|
||
$results = $this->request('POST', 'sql', \sprintf( | ||
'SELECT id, %s, _metadata, vector::similarity::%s(%s, %s) AS distance FROM %s WHERE %s <|2|> %s;', | ||
$this->vectorFieldName, $this->strategy, $this->vectorFieldName, $vectors, $this->table, $this->vectorFieldName, $vectors, | ||
)); | ||
|
||
return array_map($this->convertToVectorDocument(...), $results[0]['result']); | ||
} | ||
|
||
public function initialize(array $options = []): void | ||
{ | ||
$this->authenticate(); | ||
|
||
$this->request('POST', 'sql', \sprintf( | ||
'DEFINE INDEX %s_vectors ON %s FIELDS %s MTREE DIMENSION %d DIST %s TYPE F32', | ||
$this->table, $this->table, $this->vectorFieldName, $this->embeddingsDimension, $this->strategy | ||
)); | ||
} | ||
|
||
/** | ||
* @param array<string, mixed>|string $payload | ||
* | ||
* @return array<string|int, mixed> | ||
*/ | ||
private function request(string $method, string $endpoint, array|string $payload): array | ||
{ | ||
$url = \sprintf('%s/%s', $this->endpointUrl, $endpoint); | ||
|
||
$finalPayload = [ | ||
'json' => $payload, | ||
]; | ||
|
||
if (\is_string($payload)) { | ||
$finalPayload = [ | ||
'body' => $payload, | ||
]; | ||
} | ||
|
||
$response = $this->httpClient->request($method, $url, array_merge($finalPayload, [ | ||
'headers' => [ | ||
'Accept' => 'application/json', | ||
'Content-Type' => 'application/json', | ||
'Surreal-NS' => $this->namespace, | ||
'Surreal-DB' => $this->database, | ||
'Authorization' => \sprintf('Bearer %s', $this->authenticationToken), | ||
], | ||
])); | ||
|
||
return $response->toArray(); | ||
} | ||
|
||
/** | ||
* @return array<string, mixed> | ||
*/ | ||
private function convertToIndexableArray(VectorDocument $document): array | ||
{ | ||
return [ | ||
'id' => $document->id->toRfc4122(), | ||
$this->vectorFieldName => $document->vector->getData(), | ||
'_metadata' => array_merge($document->metadata->getArrayCopy(), [ | ||
'_id' => $document->id->toRfc4122(), | ||
]), | ||
]; | ||
} | ||
|
||
/** | ||
* @param array<string, mixed> $data | ||
*/ | ||
private function convertToVectorDocument(array $data): VectorDocument | ||
{ | ||
$id = $data['_metadata']['_id'] ?? throw new InvalidArgumentException('Missing "id" field in the document data'); | ||
|
||
$vector = !\array_key_exists($this->vectorFieldName, $data) || null === $data[$this->vectorFieldName] | ||
? new NullVector() | ||
: new Vector($data[$this->vectorFieldName]); | ||
|
||
unset($data['_metadata']['_id']); | ||
|
||
return new VectorDocument( | ||
id: Uuid::fromString($id), | ||
vector: $vector, | ||
metadata: new Metadata($data['_metadata']), | ||
); | ||
} | ||
|
||
private function authenticate(): void | ||
{ | ||
if ('' !== $this->authenticationToken) { | ||
return; | ||
} | ||
|
||
$authenticationPayload = [ | ||
'user' => $this->user, | ||
'pass' => $this->password, | ||
]; | ||
|
||
if ($this->isNamespacedUser) { | ||
$authenticationPayload['ns'] = $this->namespace; | ||
$authenticationPayload['db'] = $this->database; | ||
} | ||
|
||
$authenticationResponse = $this->httpClient->request('POST', \sprintf('%s/signin', $this->endpointUrl), [ | ||
'headers' => [ | ||
'Accept' => 'application/json', | ||
], | ||
'json' => $authenticationPayload, | ||
]); | ||
|
||
$payload = $authenticationResponse->toArray(); | ||
|
||
if (!\array_key_exists('token', $payload)) { | ||
throw new RuntimeException('The SurrealDB authentication response does not contain a token.'); | ||
} | ||
|
||
$this->authenticationToken = $payload['token']; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.