Skip to main content

LLM API call token usage-based expense tracker

Project description

TrackMyLLM(cost)

Usage

pip install llm-cost-tracker

1. Example usage for class method:

from tracker.cost_tracker import cost_tracker
from openai import OpenAI, AsyncOpenAI

class Agent:
    def __init__(self, model_name, api_key = None):
        self.model_name = model_name # nessary
        self.costs: dict[str, list[float]] = {} # nessary

        if api_key:
            self._initialize_client(api_key)
            
    def _initialize_client(self, api_key):
        self.client = OpenAI(api_key=api_key)
        self.aclient = AsyncOpenAI(api_key=api_key)
    
    # just for compatibility
    def total_cost(self):
        return float(round(sum(sum(lst) for lst in self.costs.values()), 6))
    
    @cost_tracker.track_cost() 
    def ask(self, prompt: str):
        resp = self.client.chat.completions.create(
            model=self.model_name,
            messages=[{"role":"user","content":prompt}],
        )
        return resp, {"model_response": resp.choices[0].message.content}
    
    @cost_tracker.track_cost() 
    async def aask(self, prompt: str):
        resp = await self.aclient.chat.completions.create(
            model=self.model_name,
            messages=[{"role":"user","content":prompt}],
        )
        return resp, {"model_response": resp.choices[0].message.content}

test_client = Agent(model_name="gpt-4o-mini")
a, b = test_client.ask("Hello, world!")
print("Individual costs: ", test_client.costs)
print("Total cost: ", format(test_client.total_cost(), "f"))

# Individual costs:  defaultdict(<class 'list'>, {'gpt-4o-mini': [8.400000000000001e-06]})
# Total cost:  0.000008

a, b = await test_client.aask("Hello, world!")
print("Individual costs: ", test_client.costs)
print("Total cost: ", format(test_client.total_cost(), "f"))

# Individual costs:  {'gpt-4o-mini': [7.65e-06, 7.65e-06]}
# Total cost:  0.000015

2. Example usage for single function:

from openai import OpenAI
from tracker.cost_tracker import cost_tracker

model_name = "gpt-4o-mini"
client = OpenAI()

@cost_tracker.track_cost()
def generate(model_name, prompt):
    completion = client.chat.completions.create(
        model = model_name,
        max_tokens=8192,
        messages=[
            {
                "role":"system",
                "content":"Your a Great AI"
            },
            {
                "role":"user",
                "content":prompt
            }
        ],
    )
    return completion

response = generate(model_name, "Hello, world!")
print("Individual costs: ", cost_tracker.costs)
print("Total cost: ", format(cost_tracker.total_cost(), "f"))

# Individual costs:  defaultdict(<class 'list'>, {'gpt-4o-mini': [8.400000000000001e-06]})
# Total cost:  0.000008

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

llm_cost_tracker-0.1.10.tar.gz (10.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

llm_cost_tracker-0.1.10-py3-none-any.whl (9.0 kB view details)

Uploaded Python 3

File details

Details for the file llm_cost_tracker-0.1.10.tar.gz.

File metadata

  • Download URL: llm_cost_tracker-0.1.10.tar.gz
  • Upload date:
  • Size: 10.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.3

File hashes

Hashes for llm_cost_tracker-0.1.10.tar.gz
Algorithm Hash digest
SHA256 6f5d9917e1427211e671b40edd3344b78898221a279e64b077f2c86b8d78f5a6
MD5 93a20185a6f9df533d500803731590c8
BLAKE2b-256 5f225ada6c518c6f9dd86be94abbc1b1e14ae118c1b0a00bcdb8021c5f2ea2a8

See more details on using hashes here.

File details

Details for the file llm_cost_tracker-0.1.10-py3-none-any.whl.

File metadata

File hashes

Hashes for llm_cost_tracker-0.1.10-py3-none-any.whl
Algorithm Hash digest
SHA256 45d2f9d85c371d62476663784fcb4b5db2d59dae68640e45a5d5c489bce8ab59
MD5 f7f55395b6a01b44459f8b1ed20d3e19
BLAKE2b-256 a0af7f210ffcb0b2681e9e7f35dc2d4dcdba7f2c421b48c80674104707532191

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page