From c8c8a4760b052512ed58f68abc7f0783bc4c68eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erdem=20K=C3=B6se?= Date: Wed, 27 Dec 2023 03:49:42 +0100 Subject: [PATCH] Add embedding content support --- README.md | 14 ++++++++++++++ composer.json | 2 +- src/Facades/Gemini.php | 1 + src/Gemini.php | 16 ++++++++++++++++ 4 files changed, 32 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c19e273..f307c35 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ _This library is not developed or endorsed by Google._ - [Text Generation using Image File](#text-generation-using-image-file) - [Text Generation using Image Data](#text-generation-using-image-data) - [Chat Session (Multi-Turn Conversations)](#chat-session-multi-turn-conversations) + - [Text Embeddings](#text-embeddings) - [Tokens counting](#tokens-counting) - [Listing models](#listing-models) - [Credits](#credits) @@ -150,6 +151,19 @@ print $chat->sendMessage('in Go'); // This code will print "Hello World!" to the standard output. ``` +### Text Embeddings + +```php +use GeminiAPI\Laravel\Facades\Gemini; + +print_r(Gemini::embedText('PHP in less than 100 chars')); +// [ +// [0] => 0.041395925 +// [1] => -0.017692696 +// ... +// ] +``` + ### Tokens counting ```php diff --git a/composer.json b/composer.json index 73b1aab..bb5c4b9 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ ], "require": { "php": "^8.1", - "gemini-api-php/client": "^1.2", + "gemini-api-php/client": "^1.3.1", "illuminate/support": "^9.0 || ^10.0 || ^11.0", "psr/container": "^1.0 || ^2.0", "psr/http-client": "^1.0" diff --git a/src/Facades/Gemini.php b/src/Facades/Gemini.php index 86615ee..8fcc599 100644 --- a/src/Facades/Gemini.php +++ b/src/Facades/Gemini.php @@ -10,6 +10,7 @@ /** * @method static int countTokens(string $prompt) + * @method static float[] embedText(string $prompt) * @method static string generateText(string $prompt) * @method static string generateTextUsingImage(string $imageType, string $image, string $prompt = '') * @method static string generateTextUsingImageFile(string $imageType, string $imagePath, string $prompt = '') diff --git a/src/Gemini.php b/src/Gemini.php index 524147b..e427948 100644 --- a/src/Gemini.php +++ b/src/Gemini.php @@ -34,6 +34,22 @@ public function __construct( ) { } + /** + * @return float[] + * + * @throws ClientExceptionInterface + */ + public function embedText(string $prompt, string $title = null): array + { + $model = $this->client->embeddingModel(ModelName::Embedding); + + $response = $title + ? $model->embedContentWithTitle($title, new TextPart($prompt)) + : $model->embedContent(new TextPart($prompt)); + + return $response->embedding->values; + } + /** * @throws ClientExceptionInterface */