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.count_tokens #382

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Changes from 1 commit
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
51 changes: 47 additions & 4 deletions google/generativeai/generative_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,9 @@

from collections.abc import Iterable
import textwrap
from typing import Any, Union, overload
from typing import overload
import reprlib

# pylint: disable=bad-continuation, line-too-long


import google.api_core.exceptions
from google.generativeai import protos
from google.generativeai import client
Expand Down Expand Up @@ -504,6 +501,52 @@ def __init__(
self._last_received: generation_types.BaseGenerateContentResponse | None = None
self.enable_automatic_function_calling = enable_automatic_function_calling

def count_tokens(
self,
content: content_types.ContentType | None = None,
*,
tools: content_types.FunctionLibraryType | None = None,
tool_config: content_types.ToolConfigType | None = None,
request_options: helper_types.RequestOptionsType | None = None,
):
history = self.history[:]

if content is not None:
content = content_types.to_content(content)
if not content.role:
content.role = self._USER_ROLE
history.append(content)

return self.model.count_tokens(
contents=history,
tools=tools,
tool_config=tool_config,
request_options=request_options,
)

def count_tokens_async(
self,
content: content_types.ContentType | None = None,
*,
tools: content_types.FunctionLibraryType | None = None,
tool_config: content_types.ToolConfigType | None = None,
request_options: helper_types.RequestOptionsType | None = None,
):
history = self.history[:]

if content is not None:
content = content_types.to_content(content)
if not content.role:
content.role = self._USER_ROLE
history.append(content)

return await self.model.count_tokens(
contents=history,
tools=tools,
tool_config=tool_config,
request_options=request_options,
)

def send_message(
self,
content: content_types.ContentType,
Expand Down
Loading