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

fix: Fix missing usage metadata in GoogleAIGeminiChatGenerator #1195

Merged
merged 2 commits into from
Nov 19, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -313,9 +313,24 @@ def _get_response(self, response_body: GenerateContentResponse) -> List[ChatMess
"""
replies: List[ChatMessage] = []
metadata = response_body.to_dict()

# currently Google only supports one candidate and usage metadata reflects this
# this should be refactored when multiple candidates are supported
usage_metadata_openai_format = {}

usage_metadata = metadata.get("usage_metadata")
if usage_metadata:
usage_metadata_openai_format = {
"prompt_tokens": usage_metadata["prompt_token_count"],
"completion_tokens": usage_metadata["candidates_token_count"],
"total_tokens": usage_metadata["total_token_count"],
}

for idx, candidate in enumerate(response_body.candidates):
candidate_metadata = metadata["candidates"][idx]
candidate_metadata.pop("content", None) # we remove content from the metadata
if usage_metadata_openai_format:
candidate_metadata["usage"] = usage_metadata_openai_format

for part in candidate.content.parts:
if part.text != "":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,5 +295,11 @@ def test_past_conversation():
]
response = gemini_chat.run(messages=messages)
assert "replies" in response
assert len(response["replies"]) > 0
assert all(reply.role == ChatRole.ASSISTANT for reply in response["replies"])
replies = response["replies"]
assert len(replies) > 0
assert all(reply.role == ChatRole.ASSISTANT for reply in replies)

assert all("usage" in reply.meta for reply in replies)
assert all("prompt_tokens" in reply.meta["usage"] for reply in replies)
assert all("completion_tokens" in reply.meta["usage"] for reply in replies)
assert all("total_tokens" in reply.meta["usage"] for reply in replies)