Skip to content

Commit

Permalink
Merge pull request #706 from lukaspetersson/print_cost
Browse files Browse the repository at this point in the history
Print total api costs
  • Loading branch information
ATheorell authored Sep 17, 2023
2 parents b60185a + 074b743 commit 29e891c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
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

0 comments on commit 29e891c

Please sign in to comment.