Performance: Cost tracking across runs
This concept affects the responsiveness and resource usage during multiple executions of language model tasks, impacting user wait times and backend load.
total_cost = 0 for run in runs: run_cost = sum(call.price for call in run.api_calls) total_cost += run_cost print(f"Total cost across runs: {total_cost}")
for run in runs: cost = 0 for call in run.api_calls: cost += call.price print(f"Run cost: {cost}")
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Independent cost calculation per run | Minimal | 0 | 0 | [!] OK |
| Aggregated cost tracking across runs | Minimal | 0 | 0 | [OK] Good |
get_openai_callback() in LangChain?get_openai_callback()get_openai_callback() does not do.get_openai_callback() to track cost across multiple LangChain calls?get_openai_callback() must be used as a context manager with a with block to track usage across multiple calls.with block and accesses cb.total_cost after. The other options misuse the callback or access cost before running chains.with block for callback [OK]with to track cost across runs [OK]with block for callbackwith get_openai_callback() as cb:
chain.run("Hello")
chain.run("World")
print(cb.total_tokens)with block, all calls to chain.run() accumulate token usage tracked by cb.cb.total_tokens representswith block, so it sums tokens from both runs.with block [OK]total_tokens is invalidcb = get_openai_callback()
chain.run("Test")
print(cb.total_cost)with block to track usage properly. Here, it is created but not used as a context manager.with block, the callback does not track token or cost usage, so total_cost will not reflect actual usage.with for tracking [OK]with to activate callback tracking [OK]withwith blocks creates fresh callbacks per session, resetting counts automatically. Other options either reuse callbacks incorrectly or try manual resets which are unsupported.with get_openai_callback() as cb: blocks for each session -> Option Awith blocks reset tracking [OK]with block per session to reset cost [OK]with blocks for trackingPass the test and this pattern moves unknown