Skip to content

Commit

Permalink
Add chat history support
Browse files Browse the repository at this point in the history
  • Loading branch information
erdemkose committed Dec 25, 2023
1 parent d64cd79 commit 32e1c47
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ _This library is not developed or endorsed by Google._
- [Basic text generation](#basic-text-generation)
- [Multimodal input](#multimodal-input)
- [Chat Session (Multi-Turn Conversations)](#chat-session-multi-turn-conversations)
- [Chat Session with history](#chat-session-with-history)
- [Tokens counting](#tokens-counting)
- [Listing models](#listing-models)

Expand Down Expand Up @@ -111,6 +112,44 @@ func main() {
This code will print "Hello World!" to the standard output.
```

### Chat Session with history

```php
$client = new GeminiAPI\Client('GEMINI_API_KEY');

$history = [
Content::text('Hello World in PHP', Role::User),
Content::text(
<<<TEXT
<?php
echo "Hello World!";
?>

This code will print "Hello World!" to the standard output.
TEXT,
Role::Model,
),
];
$chat = $client->geminiPro()
->startChat()
->withHistory($history);

$response = $chat->sendMessage(new TextPart('in Go'));
print $response->text();
```

```text
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
}
This code will print "Hello World!" to the standard output.
```

### Tokens counting

```php
Expand Down
27 changes: 27 additions & 0 deletions src/ChatSession.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@
use GeminiAPI\Resources\Content;
use GeminiAPI\Resources\Parts\PartInterface;
use GeminiAPI\Responses\GenerateContentResponse;
use GeminiAPI\Traits\ArrayTypeValidator;
use InvalidArgumentException;
use Psr\Http\Client\ClientExceptionInterface;

class ChatSession
{
use ArrayTypeValidator;

/** @var Content[] */
private array $history;

Expand Down Expand Up @@ -40,4 +44,27 @@ public function sendMessage(PartInterface ...$parts): GenerateContentResponse

return $response;
}

/**
* @return Content[]
*/
public function history(): array
{
return $this->history;
}

/**
* @param Content[] $history
* @return $this
* @throws InvalidArgumentException
*/
public function withHistory(array $history): self
{
$this->ensureArrayOfType($history, Content::class);

$clone = clone $this;
$clone->history = $history;

return $clone;
}
}

0 comments on commit 32e1c47

Please sign in to comment.