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 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
18 changes: 10 additions & 8 deletions plugins/openai_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,15 +223,12 @@ def streaming_request_http(self, query: dict, user_id: int, test_end_time: float
tokens.append(token)

# 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("choices", [{}])[0].get("finish_reason", None):
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.get("choices", [{}])[0].get("finish_reason", None)

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