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

feat: add token counting from API calls #1667

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
30 changes: 28 additions & 2 deletions camel/models/base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ def __init__(
self._api_key = api_key
self._url = url
self._token_counter = token_counter
self._last_response = None
self.check_model_config()

@property
Expand Down Expand Up @@ -188,7 +189,10 @@ def run(
# Empty -> use no tools
elif not tools:
tools = None
return self._run(messages, response_format, tools)

response = self._run(messages, response_format, tools)
self._last_response = response # type: ignore[assignment]
return response

async def arun(
self,
Expand Down Expand Up @@ -217,7 +221,10 @@ async def arun(
tools = self.model_config_dict.get("tools", None)
elif not tools:
tools = None
return await self._arun(messages, response_format, tools)

response = await self._arun(messages, response_format, tools)
self._last_response = response # type: ignore[assignment]
return response

@abstractmethod
def check_model_config(self):
Expand Down Expand Up @@ -294,3 +301,22 @@ def stream(self) -> bool:
bool: Whether the model is in stream mode.
"""
return False

def get_token_last_response(self) -> Optional[dict]:
r"""Get the number of tokens from the response.

Args:
response (ChatCompletion): The response from the model.
"""
if self._last_response is not None:
try:
d = {
"total_tokens": self._last_response.usage.total_tokens,
"prompt_tokens": self._last_response.usage.prompt_tokens,
"completion_tokens": self._last_response.usage.completion_tokens, # noqa: E501
}
return d
except AttributeError:
return None
else:
return None