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

Conversation

AstritA
Copy link
Contributor

@AstritA AstritA commented Feb 5, 2025

Overview

This pull request introduces enhancements to the token counting functionalities within our chat models. The updates ensure that token counting reflects the entire context of a chat session, including chat history and system instructions, aligning our implementation with the official Gemini API guidelines.

Changes

  1. Chat Session Token Counting: Added a new function in the ChatSession class to calculate the total token count that includes the history of the chat session. This modification allows us to capture the multi-turn nature of conversations, as described in the Gemini API documentation:
    Multi-turn Tokens Documentation.

  2. System Instructions Integration: Updated the GenerativeModel class's token counting method to factor in system instructions. This ensures that our token counting is comprehensive and covers all elements that could potentially consume tokens as outlined here:
    System Instructions and Tools Documentation.

Motivation

The necessity for these updates was evident from the discussions in ticket #58, where it was highlighted that the current token counting mechanism did not account for the comprehensive context used by the Gemini API, leading to discrepancies in token usage calculations.

These enhancements ensure that our models are fully compliant with the guidelines and functionalities supported by the Gemini API, providing a more accurate and reliable count of token usage across different scenarios.

I look forward to your feedback on these enhancements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant