Skip to content

Enhance Token Counting to Include Chat History and System Instructions #64

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
16 changes: 16 additions & 0 deletions src/ChatSession.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use GeminiAPI\Enums\Role;
use GeminiAPI\Resources\Content;
use GeminiAPI\Resources\Parts\PartInterface;
use GeminiAPI\Responses\CountTokensResponse;
use GeminiAPI\Responses\GenerateContentResponse;
use GeminiAPI\Traits\ArrayTypeValidator;
use InvalidArgumentException;
Expand Down Expand Up @@ -98,4 +99,19 @@ public function withHistory(array $history): self

return $clone;
}

/**
* @throws ClientExceptionInterface
*/
public function countTokens(PartInterface ...$parts): CountTokensResponse
{
// Concatenate the parts of the history if it exists
if (!empty($this->history)) {
foreach ($this->history as $content) {
$parts = array_merge($content->parts, $parts);
}
}

return $this->model->countTokens(...$parts);
}
}
11 changes: 8 additions & 3 deletions src/GenerativeModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,17 @@ public function startChat(): ChatSession
*/
public function countTokens(PartInterface ...$parts): CountTokensResponse
{
$content = new Content($parts, Role::User);
$temporaryContent = new Content($parts, Role::User);

// Add system instruction if it exists
if ($this->systemInstruction !== null) {
$temporaryContent = $temporaryContent->addParts(...$this->systemInstruction->parts);
}

$request = new CountTokensRequest(
$this->modelName,
[$content],
[$temporaryContent]
);

return $this->client->countTokens($request);
}

Expand Down
11 changes: 11 additions & 0 deletions src/Resources/Content.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,17 @@ public function addFile(MimeType $mimeType, string $file): self
return $this;
}

public function addParts(PartInterface ...$parts): self
{
/** @var array<int, PartInterface> $typedParts */
$typedParts = $parts;

$this->ensureArrayOfType($typedParts, PartInterface::class);
$this->parts = array_merge($this->parts, $typedParts);

return $this;
}

public static function text(
string $text,
Role $role = Role::User,
Expand Down