Skip to content
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

Add chat history support #3

Merged
merged 1 commit into from
Dec 25, 2023
Merged
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
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,32 @@ print $chat->sendMessage('in Go');
// This code will print "Hello World!" to the standard output.
```

### Chat Session with History

```php
use GeminiAPI\Laravel\Facades\Gemini;

$history = [
[
'message' => 'Hello World in PHP',
'role' => 'user',
],
[
'message' => <<<MESSAGE
echo "Hello World!";

This code will print "Hello World!" to the standard output.
MESSAGE,
'role' => 'model',
],
];
$chat = Gemini::startChat($history);

print $chat->sendMessage('in Go');
// fmt.Println("Hello World!")
// This code will print "Hello World!" to the standard output.
```

### Tokens counting

```php
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
],
"require": {
"php": "^8.1",
"gemini-api-php/client": "^1.1",
"gemini-api-php/client": "^1.2",
"illuminate/support": "^9.0 || ^10.0 || ^11.0",
"psr/container": "^1.0 || ^2.0",
"psr/http-client": "^1.0"
Expand Down
18 changes: 18 additions & 0 deletions src/ChatSession.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace GeminiAPI\Laravel;

use GeminiAPI\ChatSession as ApiChatSession;
use GeminiAPI\Resources\Content;
use GeminiAPI\Resources\Parts\TextPart;
use Psr\Http\Client\ClientExceptionInterface;

Expand All @@ -24,4 +25,21 @@ public function sendMessage(string $text): string
->sendMessage(new TextPart($text))
->text();
}

/**
* @return array<int, array{
* message: string,
* role: string,
* }>
*/
public function history(): array
{
return array_map(
static fn (Content $content): array => [
'message' => $content->parts[0] instanceof TextPart ? $content->parts[0]->text : '',
'role' => $content->role->value,
],
$this->chatSession->history(),
);
}
}
40 changes: 39 additions & 1 deletion src/Gemini.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,26 @@
use GeminiAPI\ClientInterface;
use GeminiAPI\Enums\MimeType;
use GeminiAPI\Enums\ModelName;
use GeminiAPI\Enums\Role;
use GeminiAPI\Laravel\Contracts\GeminiContract;
use GeminiAPI\Laravel\Exceptions\InvalidArgumentException;
use GeminiAPI\Laravel\Exceptions\InvalidMimeType;
use GeminiAPI\Resources\Content;
use GeminiAPI\Resources\Model;
use GeminiAPI\Resources\Parts\ImagePart;
use GeminiAPI\Resources\Parts\TextPart;
use Psr\Http\Client\ClientExceptionInterface;

use function array_map;
use function base64_encode;
use function file_get_contents;
use function in_array;
use function is_file;
use function is_null;
use function is_readable;
use function is_string;
use function sprintf;

class Gemini implements GeminiContract
{
public function __construct(
Expand Down Expand Up @@ -114,12 +126,38 @@ public function generateTextUsingImage(
return $response->text();
}

public function startChat(): ChatSession
/**
* @param array<int, array{
* message: string,
* role: string,
* }> $history
*
* @throws InvalidArgumentException
*/
public function startChat(array $history = []): ChatSession
{
$chatSession = $this->client
->generativeModel(ModelName::GeminiPro)
->startChat();

if (! empty($history)) {
$contents = array_map(
static function (array $message): Content {
if (empty($message['message']) || empty($message['role'])) {
throw new InvalidArgumentException('Invalid message in the chat history');
}

if (! is_string($message['message']) || ! in_array($message['role'], ['user', 'model'], true)) {
throw new InvalidArgumentException('Invalid message in the chat history');
}

return Content::text($message['message'], Role::from($message['role']));
},
$history,
);
$chatSession = $chatSession->withHistory($contents);
}

return new ChatSession($chatSession);
}

Expand Down
Loading