diff --git a/README.md b/README.md index 400522e..1d40a7d 100644 --- a/README.md +++ b/README.md @@ -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) @@ -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( + << + + 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 diff --git a/src/ChatSession.php b/src/ChatSession.php index 0bcb17f..43e1dfe 100644 --- a/src/ChatSession.php +++ b/src/ChatSession.php @@ -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; @@ -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; + } }