|
| 1 | +from typing import List, Dict, Tuple |
| 2 | +from autogen import Agent |
| 3 | + |
| 4 | + |
| 5 | +def gather_usage_summary(agents: List[Agent]) -> Tuple[Dict[str, any], Dict[str, any]]: |
| 6 | + """Gather usage summary from all agents. |
| 7 | +
|
| 8 | + Args: |
| 9 | + agents: (list): List of agents. |
| 10 | +
|
| 11 | + Returns: |
| 12 | + tuple: (total_usage_summary, actual_usage_summary) |
| 13 | +
|
| 14 | + Example return: |
| 15 | + total_usage_summary = { |
| 16 | + 'total_cost': 0.0006090000000000001, |
| 17 | + 'gpt-35-turbo': |
| 18 | + { |
| 19 | + 'cost': 0.0006090000000000001, |
| 20 | + 'prompt_tokens': 242, |
| 21 | + 'completion_tokens': 123, |
| 22 | + 'total_tokens': 365 |
| 23 | + } |
| 24 | + } |
| 25 | + `actual_usage_summary` follows the same format. |
| 26 | + If none of the agents incurred any cost (not having a client), then the total_usage_summary and actual_usage_summary will be {'total_cost': 0}. |
| 27 | + """ |
| 28 | + |
| 29 | + def aggregate_summary(usage_summary: Dict[str, any], agent_summary: Dict[str, any]) -> None: |
| 30 | + if agent_summary is None: |
| 31 | + return |
| 32 | + usage_summary["total_cost"] += agent_summary.get("total_cost", 0) |
| 33 | + for model, data in agent_summary.items(): |
| 34 | + if model != "total_cost": |
| 35 | + if model not in usage_summary: |
| 36 | + usage_summary[model] = data.copy() |
| 37 | + else: |
| 38 | + usage_summary[model]["cost"] += data.get("cost", 0) |
| 39 | + usage_summary[model]["prompt_tokens"] += data.get("prompt_tokens", 0) |
| 40 | + usage_summary[model]["completion_tokens"] += data.get("completion_tokens", 0) |
| 41 | + usage_summary[model]["total_tokens"] += data.get("total_tokens", 0) |
| 42 | + |
| 43 | + total_usage_summary = {"total_cost": 0} |
| 44 | + actual_usage_summary = {"total_cost": 0} |
| 45 | + |
| 46 | + for agent in agents: |
| 47 | + if agent.client: |
| 48 | + aggregate_summary(total_usage_summary, agent.client.total_usage_summary) |
| 49 | + aggregate_summary(actual_usage_summary, agent.client.actual_usage_summary) |
| 50 | + |
| 51 | + return total_usage_summary, actual_usage_summary |
0 commit comments