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

Print total api costs #706

Merged
merged 3 commits into from
Sep 17, 2023
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
19 changes: 19 additions & 0 deletions gpt_engineer/ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import openai
import tiktoken

from langchain.callbacks.openai_info import MODEL_COST_PER_1K_TOKENS
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain.chat_models import AzureChatOpenAI, ChatOpenAI
from langchain.chat_models.base import BaseChatModel
Expand Down Expand Up @@ -271,6 +272,24 @@ def format_token_usage_log(self) -> str:
result += str(log.total_tokens) + "\n"
return result

def usage_cost(self) -> float:
"""
Return the total cost in USD of the api usage.

Returns
-------
float
Cost in USD.
"""
prompt_price = MODEL_COST_PER_1K_TOKENS[self.model_name]
completion_price = MODEL_COST_PER_1K_TOKENS[self.model_name + "-completion"]

result = 0
for log in self.token_usage_log:
result += log.total_prompt_tokens / 1000 * prompt_price
result += log.total_completion_tokens / 1000 * completion_price
return result

def num_tokens(self, txt: str) -> int:
"""
Get the number of tokens in a text.
Expand Down
2 changes: 2 additions & 0 deletions gpt_engineer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ def main(
messages = step(ai, dbs)
dbs.logs[step.__name__] = AI.serialize_messages(messages)

print("Total api cost: $ ", ai.usage_cost())

if collect_consent():
collect_learnings(model, temperature, steps, dbs)

Expand Down