Skip to content

[Platform] Meilisearch message store #239

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions examples/misc/persistent-chat-meilisearch.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?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\Bridge\Meilisearch\MessageStore;
use Symfony\AI\Agent\Chat;
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;

require_once dirname(__DIR__).'/bootstrap.php';

$platform = PlatformFactory::create(env('OPENAI_API_KEY'), http_client());
$llm = new Gpt(Gpt::GPT_4O_MINI);

$agent = new Agent($platform, $llm, logger: logger());
$store = new MessageStore(
http_client(),
env('MEILISEARCH_HOST'),
env('MEILISEARCH_API_KEY'),
'chat',
);
$store->initialize();

$chat = new Chat($agent, $store);

$messages = new MessageBag(
Message::forSystem('You are a helpful assistant. You only answer with short sentences.'),
);

$chat->initiate($messages);
$chat->submit(Message::ofUser('My name is Christopher.'));
$message = $chat->submit(Message::ofUser('What is my name?'));

echo $message->content.\PHP_EOL;
177 changes: 177 additions & 0 deletions src/agent/src/Bridge/Meilisearch/MessageStore.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
<?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\Agent\Bridge\Meilisearch;

use Symfony\AI\Agent\Chat\InitializableMessageStoreInterface;
use Symfony\AI\Agent\Chat\MessageStoreInterface;
use Symfony\AI\Agent\Exception\InvalidArgumentException;
use Symfony\AI\Agent\Exception\LogicException;
use Symfony\AI\Platform\Message\AssistantMessage;
use Symfony\AI\Platform\Message\Content\Audio;
use Symfony\AI\Platform\Message\Content\ContentInterface;
use Symfony\AI\Platform\Message\Content\DocumentUrl;
use Symfony\AI\Platform\Message\Content\File;
use Symfony\AI\Platform\Message\Content\Image;
use Symfony\AI\Platform\Message\Content\ImageUrl;
use Symfony\AI\Platform\Message\Content\Text;
use Symfony\AI\Platform\Message\MessageBag;
use Symfony\AI\Platform\Message\MessageBagInterface;
use Symfony\AI\Platform\Message\MessageInterface;
use Symfony\AI\Platform\Message\SystemMessage;
use Symfony\AI\Platform\Message\ToolCallMessage;
use Symfony\AI\Platform\Message\UserMessage;
use Symfony\AI\Platform\Result\ToolCall;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
* @author Guillaume Loulier <[email protected]>
*/
final readonly class MessageStore implements InitializableMessageStoreInterface, MessageStoreInterface
{
public function __construct(
private HttpClientInterface $httpClient,
private string $endpointUrl,
#[\SensitiveParameter] private string $apiKey,
private string $indexName,
) {
}

public function save(MessageBagInterface $messages): void
{
$messages = $messages->getMessages();

$this->request('PUT', \sprintf('indexes/%s/documents', $this->indexName), array_map(
$this->convertToIndexableArray(...),
$messages,
));
}

public function load(): MessageBagInterface
{
$messages = $this->request('POST', \sprintf('indexes/%s/documents/fetch', $this->indexName));

return new MessageBag(...array_map($this->convertToMessage(...), $messages['results']));
}

public function clear(): void
{
$this->request('DELETE', \sprintf('indexes/%s/documents', $this->indexName));
}

public function initialize(array $options = []): void
{
if ([] !== $options) {
throw new InvalidArgumentException('No supported options.');
}

$this->request('POST', 'indexes', [
'uid' => $this->indexName,
'primaryKey' => 'id',
]);
}

/**
* @param array<string, mixed>|list<array<string, mixed>> $payload
*
* @return array<string, mixed>
*/
private function request(string $method, string $endpoint, array $payload = []): array
{
$url = \sprintf('%s/%s', $this->endpointUrl, $endpoint);
$result = $this->httpClient->request($method, $url, [
'headers' => [
'Authorization' => \sprintf('Bearer %s', $this->apiKey),
],
'json' => [] !== $payload ? $payload : new \stdClass(),
]);

return $result->toArray();
}

/**
* @return array<string, mixed>
*/
private function convertToIndexableArray(MessageInterface $message): array
{
$toolsCalls = [];

if ($message instanceof AssistantMessage && $message->hasToolCalls()) {
$toolsCalls = array_map(
static fn (ToolCall $toolCall): array => $toolCall->jsonSerialize(),
$message->toolCalls,
);
}

if ($message instanceof ToolCallMessage) {
$toolsCalls = $message->toolCall->jsonSerialize();
}

return [
'id' => $message->getId()->toRfc4122(),
'type' => $message::class,
'content' => ($message instanceof SystemMessage || $message instanceof AssistantMessage || $message instanceof ToolCallMessage) ? $message->content : '',
'contentAsBase64' => ($message instanceof UserMessage && [] !== $message->content) ? array_map(
static fn (ContentInterface $content) => [
'type' => $content::class,
'content' => match ($content::class) {
Text::class => $content->text,
File::class,
Image::class,
Audio::class => $content->asBase64(),
ImageUrl::class,
DocumentUrl::class => $content->url,
default => throw new LogicException(\sprintf('Unknown content type "%s".', $content::class)),
},
],
$message->content,
) : [],
'toolsCalls' => $toolsCalls,
];
}

/**
* @param array<string, mixed> $payload
*/
private function convertToMessage(array $payload): MessageInterface
{
$type = $payload['type'];
$content = $payload['content'] ?? '';
$contentAsBase64 = $payload['contentAsBase64'] ?? [];

return match ($type) {
SystemMessage::class => new SystemMessage($content),
AssistantMessage::class => new AssistantMessage($content, array_map(
static fn (array $toolsCall): ToolCall => new ToolCall(
$toolsCall['id'],
$toolsCall['function']['name'],
json_decode($toolsCall['function']['arguments'], true)
),
$payload['toolsCalls'],
)),
UserMessage::class => new UserMessage(...array_map(
static fn (array $contentAsBase64) => \in_array($contentAsBase64['type'], [File::class, Image::class, Audio::class], true)
? $contentAsBase64['type']::fromDataUrl($contentAsBase64['content'])
: new $contentAsBase64['type']($contentAsBase64['content']),
$contentAsBase64,
)),
ToolCallMessage::class => new ToolCallMessage(
new ToolCall(
$payload['toolsCalls']['id'],
$payload['toolsCalls']['function']['name'],
json_decode($payload['toolsCalls']['function']['arguments'], true)
),
$content
),
default => throw new LogicException(\sprintf('Unknown message type "%s".', $type)),
};
}
}
23 changes: 23 additions & 0 deletions src/agent/src/Chat/InitializableMessageStoreInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?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\Agent\Chat;

/**
* @author Guillaume Loulier <[email protected]>
*/
interface InitializableMessageStoreInterface
{
/**
* @param array<mixed> $options
*/
public function initialize(array $options = []): void;
}
Loading