{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Tracking LLM usage with a logger\n", "\n", "The model clients included in AutoGen emit structured events that can be used to track the usage of the model. This notebook demonstrates how to use the logger to track the usage of the model.\n", "\n", "These events are logged to the logger with the name: :py:attr:`autogen_core.EVENT_LOGGER_NAME`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import logging\n", "\n", "from autogen_core.logging import LLMCallEvent\n", "\n", "\n", "class LLMUsageTracker(logging.Handler):\n", " def __init__(self) -> None:\n", " \"\"\"Logging handler that tracks the number of tokens used in the prompt and completion.\"\"\"\n", " super().__init__()\n", " self._prompt_tokens = 0\n", " self._completion_tokens = 0\n", "\n", " @property\n", " def tokens(self) -> int:\n", " return self._prompt_tokens + self._completion_tokens\n", "\n", " @property\n", " def prompt_tokens(self) -> int:\n", " return self._prompt_tokens\n", "\n", " @property\n", " def completion_tokens(self) -> int:\n", " return self._completion_tokens\n", "\n", " def reset(self) -> None:\n", " self._prompt_tokens = 0\n", " self._completion_tokens = 0\n", "\n", " def emit(self, record: logging.LogRecord) -> None:\n", " \"\"\"Emit the log record. To be used by the logging module.\"\"\"\n", " try:\n", " # Use the StructuredMessage if the message is an instance of it\n", " if isinstance(record.msg, LLMCallEvent):\n", " event = record.msg\n", " self._prompt_tokens += event.prompt_tokens\n", " self._completion_tokens += event.completion_tokens\n", " except Exception:\n", " self.handleError(record)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then, this logger can be attached like any other Python logger and the values read after the model is run." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from autogen_core import EVENT_LOGGER_NAME\n", "\n", "# Set up the logging configuration to use the custom handler\n", "logger = logging.getLogger(EVENT_LOGGER_NAME)\n", "logger.setLevel(logging.INFO)\n", "llm_usage = LLMUsageTracker()\n", "logger.handlers = [llm_usage]\n", "\n", "# client.create(...)\n", "\n", "print(llm_usage.prompt_tokens)\n", "print(llm_usage.completion_tokens)" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "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.11.5" } }, "nbformat": 4, "nbformat_minor": 2 }