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: handle optional usage field in OpenAI API #47

Merged
merged 3 commits into from
Jun 26, 2024
Merged
Changes from 2 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: 9 additions & 7 deletions plugins/openai_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,14 +224,11 @@ def streaming_request_http(self, query: dict, user_id: int, test_end_time: float

# Last token comes with finish_reason set.
if message.get("choices", [])[0].get("finish_reason", None):
result.output_tokens = message["usage"]["completion_tokens"]
result.input_tokens = message["usage"]["prompt_tokens"]
result.stop_reason = message["choices"][0]["finish_reason"]
if message.get("usage"):
result.output_tokens = message["usage"]["completion_tokens"]
result.input_tokens = message["usage"]["prompt_tokens"]

# If test duration timeout didn't happen before the last token is received,
# total tokens before the timeout will be equal to the total tokens in the response.
if not result.output_tokens_before_timeout:
result.output_tokens_before_timeout = result.output_tokens
result.stop_reason = message["choices"][0]["finish_reason"]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You might wanna do the same (.get) for choices

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point!


except KeyError:
logging.exception("KeyError, unexpected response format in line: %s", line)
Expand All @@ -248,5 +245,10 @@ def streaming_request_http(self, query: dict, user_id: int, test_end_time: float
logger.warning("Output token count not found in response, length of token list")
result.output_tokens = len(tokens)

# If test duration timeout didn't happen before the last token is received,
# total tokens before the timeout will be equal to the total tokens in the response.
if not result.output_tokens_before_timeout:
result.output_tokens_before_timeout = result.output_tokens

result.calculate_results()
return result
Loading