A programming framework for agentic AI
Add cost summary to client.py (#812)
Yiran Wu7a4ba1a732ae
diff --git a/autogen/oai/client.py b/autogen/oai/client.pyindex b4a139401..70a28e15e 100644--- a/autogen/oai/client.py+++ b/autogen/oai/client.py@@ -36,6 +36,8 @@ class OpenAIWrapper:cache_path_root: str = ".cache"extra_kwargs = {"cache_seed", "filter_func", "allow_format_str_template", "context", "api_version"}openai_kwargs = set(inspect.getfullargspec(OpenAI.__init__).kwonlyargs)+ total_usage_summary: Dict = None+ actual_usage_summary: Dict = Nonedef __init__(self, *, config_list: List[Dict] = None, **base_config):"""@@ -233,6 +235,8 @@ class OpenAIWrapper:# Try to get the response from cachekey = get_key(params)response = cache.get(key, None)+ if response is not None:+ self._update_usage_summary(response, use_cache=True)if response is not None:# check the filterpass_filter = filter_func is None or filter_func(context=context, response=response)@@ -240,7 +244,6 @@ class OpenAIWrapper:# Return the response if it passes the filter or it is the last clientresponse.config_id = iresponse.pass_filter = pass_filter- response.cost = self.cost(response)return responsecontinue # filter is not passed; try the next configtry:@@ -250,6 +253,9 @@ class OpenAIWrapper:if i == last:raiseelse:+ # add cost calculation before caching not matter filter is passed or not+ response.cost = self.cost(response)+ self._update_usage_summary(response, use_cache=False)if cache_seed is not None:# Cache the responsewith diskcache.Cache(f"{self.cache_path_root}/{cache_seed}") as cache:@@ -261,25 +267,9 @@ class OpenAIWrapper:# Return the response if it passes the filter or it is the last clientresponse.config_id = iresponse.pass_filter = pass_filter- response.cost = self.cost(response)return responsecontinue # filter is not passed; try the next config- def cost(self, response: Union[ChatCompletion, Completion]) -> float:- """Calculate the cost of the response."""- model = response.model- if model not in oai_price1k:- # TODO: add logging to warn that the model is not found- return 0-- n_input_tokens = response.usage.prompt_tokens- n_output_tokens = response.usage.completion_tokens- tmp_price1K = oai_price1k[model]- # First value is input token rate, second value is output token rate- if isinstance(tmp_price1K, tuple):- return (tmp_price1K[0] * n_input_tokens + tmp_price1K[1] * n_output_tokens) / 1000- return tmp_price1K * (n_input_tokens + n_output_tokens) / 1000-def _completions_create(self, client, params):completions = client.chat.completions if "messages" in params else client.completions# If streaming is enabled, has messages, and does not have functions, then@@ -342,6 +332,105 @@ class OpenAIWrapper:response = completions.create(**params)return response+ def _update_usage_summary(self, response: ChatCompletion | Completion, use_cache: bool) -> None:+ """Update the usage summary.++ Usage is calculated no mattter filter is passed or not.+ """++ def update_usage(usage_summary):+ if usage_summary is None:+ usage_summary = {"total_cost": response.cost}+ else:+ usage_summary["total_cost"] += response.cost++ usage_summary[response.model] = {+ "cost": usage_summary.get(response.model, {}).get("cost", 0) + response.cost,+ "prompt_tokens": usage_summary.get(response.model, {}).get("prompt_tokens", 0)+ + response.usage.prompt_tokens,+ "completion_tokens": usage_summary.get(response.model, {}).get("completion_tokens", 0)+ + response.usage.completion_tokens,+ "total_tokens": usage_summary.get(response.model, {}).get("total_tokens", 0)+ + response.usage.total_tokens,+ }+ return usage_summary++ self.total_usage_summary = update_usage(self.total_usage_summary)+ if not use_cache:+ self.actual_usage_summary = update_usage(self.actual_usage_summary)++ def print_usage_summary(self, mode: Union[str, List[str]] = ["actual", "total"]) -> None:+ """Print the usage summary."""++ def print_usage(usage_summary, usage_type="total"):+ word_from_type = "including" if usage_type == "total" else "excluding"+ if usage_summary is None:+ print("No actual cost incurred (all completions are using cache).", flush=True)+ return++ print(f"Usage summary {word_from_type} cached usage: ", flush=True)+ print(f"Total cost: {round(usage_summary['total_cost'], 5)}", flush=True)+ for model, counts in usage_summary.items():+ if model == "total_cost":+ continue #+ print(+ f"* Model '{model}': cost: {round(counts['cost'], 5)}, prompt_tokens: {counts['prompt_tokens']}, completion_tokens: {counts['completion_tokens']}, total_tokens: {counts['total_tokens']}",+ flush=True,+ )++ if self.total_usage_summary is None:+ print('No usage summary. Please call "create" first.', flush=True)+ return++ if isinstance(mode, list):+ if len(mode) == 0 or len(mode) > 2:+ raise ValueError(f'Invalid mode: {mode}, choose from "actual", "total", ["actual", "total"]')+ if "actual" in mode and "total" in mode:+ mode = "both"+ elif "actual" in mode:+ mode = "actual"+ elif "total" in mode:+ mode = "total"++ print("-" * 100, flush=True)+ if mode == "both":+ print_usage(self.actual_usage_summary, "actual")+ print()+ if self.total_usage_summary != self.actual_usage_summary:+ print_usage(self.total_usage_summary, "total")+ else:+ print(+ "All completions are non-cached: the total cost with cached completions is the same as actual cost.",+ flush=True,+ )+ elif mode == "total":+ print_usage(self.total_usage_summary, "total")+ elif mode == "actual":+ print_usage(self.actual_usage_summary, "actual")+ else:+ raise ValueError(f'Invalid mode: {mode}, choose from "actual", "total", ["actual", "total"]')+ print("-" * 100, flush=True)++ def clear_usage_summary(self) -> None:+ """Clear the usage summary."""+ self.total_usage_summary = None+ self.actual_usage_summary = None++ def cost(self, response: Union[ChatCompletion, Completion]) -> float:+ """Calculate the cost of the response."""+ model = response.model+ if model not in oai_price1k:+ # TODO: add logging to warn that the model is not found+ return 0++ n_input_tokens = response.usage.prompt_tokens+ n_output_tokens = response.usage.completion_tokens+ tmp_price1K = oai_price1k[model]+ # First value is input token rate, second value is output token rate+ if isinstance(tmp_price1K, tuple):+ return (tmp_price1K[0] * n_input_tokens + tmp_price1K[1] * n_output_tokens) / 1000+ return tmp_price1K * (n_input_tokens + n_output_tokens) / 1000+@classmethoddef extract_text_or_function_call(cls, response: ChatCompletion | Completion) -> List[str]:"""Extract the text or function calls from a completion or chat response.diff --git a/notebook/oai_client_cost.ipynb b/notebook/oai_client_cost.ipynbnew file mode 100644index 000000000..50d3dfdc6--- /dev/null+++ b/notebook/oai_client_cost.ipynb@@ -0,0 +1,308 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "<a href=\"https://colab.research.google.com/github/microsoft/autogen/blob/main/notebook/oai_client_cost.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "Copyright (c) Microsoft Corporation. All rights reserved. \n",+ "\n",+ "Licensed under the MIT License.\n",+ "\n",+ "# Use AutoGen's OpenAIWrapper for cost estimation\n",+ "The `OpenAIWrapper` from `autogen` tracks token counts and costs of your API calls. Use the `create()` method to initiate requests and `print_usage_summary()` to retrieve a detailed usage report, including total cost and token usage for both cached and actual requests.\n",+ "\n",+ "- `mode=[\"actual\", \"total\"]` (default): print usage summary for non-caching completions and all completions (including cache).\n",+ "- `mode='actual'`: only print non-cached usage.\n",+ "- `mode='total'`: only print all usage (including cache).\n",+ "\n",+ "Reset your session's usage data with `clear_usage_summary()` when needed.\n",+ "\n",+ "## Requirements\n",+ "\n",+ "AutoGen requires `Python>=3.8`:\n",+ "```bash\n",+ "pip install \"pyautogen\"\n",+ "```"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Set your API Endpoint\n",+ "\n",+ "The [`config_list_from_json`](https://microsoft.github.io/autogen/docs/reference/oai/openai_utils#config_list_from_json) function loads a list of configurations from an environment variable or a json file.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 1,+ "metadata": {},+ "outputs": [],+ "source": [+ "import autogen\n",+ "\n",+ "# config_list = autogen.config_list_from_json(\n",+ "# \"OAI_CONFIG_LIST\",\n",+ "# filter_dict={\n",+ "# \"model\": [\"gpt-3.5-turbo\", \"gpt-4-1106-preview\"],\n",+ "# },\n",+ "# )\n",+ "\n",+ "config_list = autogen.config_list_from_json(\n",+ " \"OAI_CONFIG_LIST\",\n",+ " filter_dict={\n",+ " \"model\": [\"gpt-3.5-turbo\"],\n",+ " },\n",+ ")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "It first looks for environment variable \"OAI_CONFIG_LIST\" which needs to be a valid json string. If that variable is not found, it then looks for a json file named \"OAI_CONFIG_LIST\". It filters the configs by models (you can filter by other keys as well).\n",+ "\n",+ "The config list looks like the following:\n",+ "```python\n",+ "config_list = [\n",+ " {\n",+ " \"model\": \"gpt-4\",\n",+ " \"api_key\": \"<your OpenAI API key>\",\n",+ " }, # OpenAI API endpoint for gpt-4\n",+ " {\n",+ " \"model\": \"gpt-35-turbo-0631\", # 0631 or newer is needed to use functions\n",+ " \"base_url\": \"<your Azure OpenAI API base>\", \n",+ " \"api_type\": \"azure\", \n",+ " \"api_version\": \"2023-08-01-preview\", # 2023-07-01-preview or newer is needed to use functions\n",+ " \"api_key\": \"<your Azure OpenAI API key>\"\n",+ " }\n",+ "]\n",+ "```\n",+ "\n",+ "You can set the value of config_list in any way you prefer. Please refer to this [notebook](https://github.com/microsoft/autogen/blob/main/notebook/oai_openai_utils.ipynb) for full code examples of the different methods."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## OpenAIWrapper with cost estimation"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "In update_usage_summary\n",+ "0.0001555\n"+ ]+ }+ ],+ "source": [+ "from autogen import OpenAIWrapper\n",+ "\n",+ "client = OpenAIWrapper(config_list=config_list)\n",+ "messages = [{'role': 'user', 'content': 'Can you give me 3 useful tips on learning Python? Keep it simple and short.'},]\n",+ "response = client.create(messages=messages, model=\"gpt-35-turbo-1106\", cache_seed=None)\n",+ "print(response.cost)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Usage Summary\n",+ "\n",+ "When creating a instance of OpenAIWrapper, cost of all completions from the same instance is recorded. You can call `print_usage_summary()` to checkout your usage summary. To clear up, use `clear_usage_summary()`.\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 14,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "No usage summary. Please call \"create\" first.\n"+ ]+ }+ ],+ "source": [+ "from autogen import OpenAIWrapper\n",+ "\n",+ "client = OpenAIWrapper(config_list=config_list)\n",+ "messages = [{'role': 'user', 'content': 'Can you give me 3 useful tips on learning Python? Keep it simple and short.'},]\n",+ "client.print_usage_summary() # print usage summary"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 15,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "In update_usage_summary\n",+ "----------------------------------------------------------------------------------------------------\n",+ "Usage summary excluding cached usage: \n",+ "Total cost: 0.00026\n",+ "* Model 'gpt-35-turbo': cost: 0.00026, prompt_tokens: 25, completion_tokens: 110, total_tokens: 135\n",+ "\n",+ "All completions are non-cached: the total cost with cached completions is the same as actual cost.\n",+ "----------------------------------------------------------------------------------------------------\n",+ "----------------------------------------------------------------------------------------------------\n",+ "Usage summary excluding cached usage: \n",+ "Total cost: 0.00026\n",+ "* Model 'gpt-35-turbo': cost: 0.00026, prompt_tokens: 25, completion_tokens: 110, total_tokens: 135\n",+ "----------------------------------------------------------------------------------------------------\n",+ "----------------------------------------------------------------------------------------------------\n",+ "Usage summary including cached usage: \n",+ "Total cost: 0.00026\n",+ "* Model 'gpt-35-turbo': cost: 0.00026, prompt_tokens: 25, completion_tokens: 110, total_tokens: 135\n",+ "----------------------------------------------------------------------------------------------------\n"+ ]+ }+ ],+ "source": [+ "# The first creation\n",+ "# By default, cache_seed is set to 41 and enabled. If you don't want to use cache, set cache_seed to None.\n",+ "response = client.create(messages=messages, model=\"gpt-35-turbo-1106\", cache_seed=41)\n",+ "client.print_usage_summary() # default to [\"actual\", \"total\"]\n",+ "client.print_usage_summary(mode='actual') # print actual usage summary\n",+ "client.print_usage_summary(mode='total') # print total usage summary"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 16,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "{'total_cost': 0.0002575, 'gpt-35-turbo': {'cost': 0.0002575, 'prompt_tokens': 25, 'completion_tokens': 110, 'total_tokens': 135}}\n",+ "{'total_cost': 0.0002575, 'gpt-35-turbo': {'cost': 0.0002575, 'prompt_tokens': 25, 'completion_tokens': 110, 'total_tokens': 135}}\n"+ ]+ }+ ],+ "source": [+ "# take out cost\n",+ "print(client.actual_usage_summary)\n",+ "print(client.total_usage_summary)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 17,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "In update_usage_summary\n",+ "----------------------------------------------------------------------------------------------------\n",+ "Usage summary excluding cached usage: \n",+ "Total cost: 0.00026\n",+ "* Model 'gpt-35-turbo': cost: 0.00026, prompt_tokens: 25, completion_tokens: 110, total_tokens: 135\n",+ "\n",+ "Usage summary including cached usage: \n",+ "Total cost: 0.00052\n",+ "* Model 'gpt-35-turbo': cost: 0.00052, prompt_tokens: 50, completion_tokens: 220, total_tokens: 270\n",+ "----------------------------------------------------------------------------------------------------\n"+ ]+ }+ ],+ "source": [+ "# Since cache is enabled, the same completion will be returned from cache, which will not incur any actual cost. \n",+ "# So acutal cost doesn't change but total cost doubles.\n",+ "response = client.create(messages=messages, model=\"gpt-35-turbo-1106\", cache_seed=41)\n",+ "client.print_usage_summary()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 18,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "No usage summary. Please call \"create\" first.\n"+ ]+ }+ ],+ "source": [+ "# clear usage summary\n",+ "client.clear_usage_summary() \n",+ "client.print_usage_summary()"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 19,+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "In update_usage_summary\n",+ "----------------------------------------------------------------------------------------------------\n",+ "No actual cost incurred (all completions are using cache).\n",+ "\n",+ "Usage summary including cached usage: \n",+ "Total cost: 0.00026\n",+ "* Model 'gpt-35-turbo': cost: 0.00026, prompt_tokens: 25, completion_tokens: 110, total_tokens: 135\n",+ "----------------------------------------------------------------------------------------------------\n"+ ]+ }+ ],+ "source": [+ "# all completions are returned from cache, so no actual cost incurred.\n",+ "response = client.create(messages=messages, model=\"gpt-35-turbo-1106\", cache_seed=41)\n",+ "client.print_usage_summary()"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "msft",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.9.18"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2+}diff --git a/test/oai/test_client.py b/test/oai/test_client.pyindex 3f881fce3..de96857ad 100644--- a/test/oai/test_client.py+++ b/test/oai/test_client.py@@ -64,8 +64,39 @@ def test_cost(cache_seed, model):print(response.cost)[email protected](skip, reason="openai>=1 not installed")+def test_usage_summary():+ config_list = config_list_openai_aoai(KEY_LOC)+ client = OpenAIWrapper(config_list=config_list)+ response = client.create(prompt="1+3=", model="gpt-3.5-turbo-instruct", cache_seed=42)++ # usage should be recorded+ assert client.actual_usage_summary["total_cost"] > 0, "total_cost should be greater than 0"+ assert client.total_usage_summary["total_cost"] > 0, "total_cost should be greater than 0"++ # check print+ client.print_usage_summary()++ # check update+ client._update_usage_summary(response, use_cache=True)+ assert (+ client.actual_usage_summary["total_cost"] == response.cost * 2+ ), "total_cost should be equal to response.cost * 2"++ # check clear+ client.clear_usage_summary()+ assert client.actual_usage_summary is None, "actual_usage_summary should be None"+ assert client.total_usage_summary is None, "total_usage_summary should be None"++ # actual usage and all usage should be different+ response = client.create(prompt="1+3=", model="gpt-3.5-turbo-instruct", cache_seed=42)+ assert client.total_usage_summary["total_cost"] > 0, "total_cost should be greater than 0"+ assert client.actual_usage_summary is None, "No actual cost should be recorded"++if __name__ == "__main__":test_aoai_chat_completion()test_chat_completion()test_completion()test_cost()+ test_usage_summary()diff --git a/test/test_notebook.py b/test/test_notebook.pyindex 9838f2eee..68f0d9bb1 100644--- a/test/test_notebook.py+++ b/test/test_notebook.py@@ -100,6 +100,14 @@ def test_graph_modelling_language_using_select_speaker(save=False):run_notebook("agentchat_graph_modelling_language_using_select_speaker.ipynb", save=save)+ skip or not sys.version.startswith("3.10"),+ reason="do not run if openai is not installed or py!=3.10",+)+def test_oai_client_cost(save=False):+ run_notebook("oai_client_cost.ipynb", save=save)++if __name__ == "__main__":# test_agentchat_auto_feedback_from_code(save=True)# test_oai_chatgpt_gpt4(save=True)diff --git a/website/docs/Examples.md b/website/docs/Examples.mdindex b5596afc6..049be78a6 100644--- a/website/docs/Examples.md+++ b/website/docs/Examples.md@@ -65,3 +65,4 @@ Please find documentation about this feature [here](/docs/Use-Cases/enhanced_infLinks to notebook examples:* [Optimize for Code Generation](https://github.com/microsoft/autogen/blob/main/notebook/oai_completion.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/autogen/blob/main/notebook/oai_completion.ipynb)* [Optimize for Math](https://github.com/microsoft/autogen/blob/main/notebook/oai_chatgpt_gpt4.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/autogen/blob/main/notebook/oai_chatgpt_gpt4.ipynb)+* [Usage Estimation](https://github.com/microsoft/autogen/blob/main/notebook/oai_client_cost.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/autogen/blob/main/notebook/oai_client_cost.ipynb)diff --git a/website/docs/Use-Cases/enhanced_inference.md b/website/docs/Use-Cases/enhanced_inference.mdindex 27dffb7d7..f96599b13 100644--- a/website/docs/Use-Cases/enhanced_inference.md+++ b/website/docs/Use-Cases/enhanced_inference.md@@ -135,6 +135,37 @@ For local LLMs, one can spin up an endpoint using a package like [FastChat](http<!-- When only working with the chat-based models, `autogen.ChatCompletion` can be used. It also does automatic conversion from prompt to messages, if prompt is provided instead of messages. -->+## Usage Summary++The `OpenAIWrapper` from `autogen` tracks token counts and costs of your API calls. Use the `create()` method to initiate requests and `print_usage_summary()` to retrieve a detailed usage report, including total cost and token usage for both cached and actual requests.++- `mode=["actual", "total"]` (default): print usage summary for all completions and non-caching completions.+- `mode='actual'`: only print non-cached usage.+- `mode='total'`: only print all usage (including cache).++Reset your session's usage data with `clear_usage_summary()` when needed. [View Notebook](https://github.com/microsoft/autogen/blob/main/notebook/oai_client_cost.ipynb)++Example usage:+```python+from autogen import OpenAIWrapper++client = OpenAIWrapper()+client.create(messages=[{"role": "user", "content": "Python learning tips."}], model="gpt-3.5-turbo")+client.print_usage_summary() # Display usage+client.clear_usage_summary() # Reset usage data+```++Sample output:+```+Usage summary excluding cached usage:+Total cost: 0.00015+* Model 'gpt-3.5-turbo': cost: 0.00015, prompt_tokens: 25, completion_tokens: 58, total_tokens: 83++Usage summary including cached usage:+Total cost: 0.00027+* Model 'gpt-3.5-turbo': cost: 0.00027, prompt_tokens: 50, completion_tokens: 100, total_tokens: 150+```+## CachingAPI call results are cached locally and reused when the same request is issued. This is useful when repeating or continuing experiments for reproducibility and cost saving. It still allows controlled randomness by setting the "cache_seed" specified in `OpenAIWrapper.create()` or the constructor of `OpenAIWrapper`.