A programming framework for agentic AI
add structured logging for llm calls (#33)
Jack Gerrits15268a86dd92
diff --git a/pyproject.toml b/pyproject.tomlindex b9a20b913..0ae9b954c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -16,7 +16,7 @@ classifiers = [dependencies = ["openai>=1.3", "pillow", "aiohttp", "typing-extensions"][project.optional-dependencies]-dev = ["ruff", "pyright", "mypy", "pytest", "pytest-asyncio", "types-Pillow"]+dev = ["ruff==0.4.6", "pyright", "mypy", "pytest", "pytest-asyncio", "types-Pillow"]docs = [ "sphinx", "furo", "sphinxcontrib-apidoc"][tool.setuptools.package-data]diff --git a/src/agnext/agent_components/model_client/_openai_client.py b/src/agnext/agent_components/model_client/_openai_client.pyindex 1c1f024ec..c12ad1ec7 100644--- a/src/agnext/agent_components/model_client/_openai_client.py+++ b/src/agnext/agent_components/model_client/_openai_client.py@@ -1,4 +1,5 @@import inspect+import loggingimport warningsfrom typing import (Any,@@ -31,6 +32,8 @@ from openai.types.chat import ()from typing_extensions import Required, TypedDict, Unpack+from ...application_components.logging import EVENT_LOGGER_NAME, LLMCallEvent+# from ..._pydantic import type2schemafrom ..image import Imagefrom ..types import (@@ -47,6 +50,8 @@ from ..types import (from . import _model_infofrom ._model_client import ModelCapabilities, ModelClient+logger = logging.getLogger(EVENT_LOGGER_NAME)+openai_init_kwargs = set(inspect.getfullargspec(AsyncOpenAI.__init__).kwonlyargs)aopenai_init_kwargs = set(inspect.getfullargspec(AsyncAzureOpenAI.__init__).kwonlyargs)@@ -346,6 +351,11 @@ class BaseOpenAI(ModelClient):else:result = await self._client.chat.completions.create(messages=oai_messages, stream=False, **create_args)+ if result.usage is not None:+ logger.info(+ LLMCallEvent(prompt_tokens=result.usage.prompt_tokens, completion_tokens=result.usage.completion_tokens)+ )+usage = RequestUsage(# TODO backup token countingprompt_tokens=result.usage.prompt_tokens if result.usage is not None else 0,@@ -441,7 +451,6 @@ class BaseOpenAI(ModelClient):choice = chunk.choices[0]stop_reason = choice.finish_reasonmaybe_model = chunk.model-# First try get contentif choice.delta.content is not None:content_deltas.append(choice.delta.content)diff --git a/src/agnext/application_components/logging/__init__.py b/src/agnext/application_components/logging/__init__.pynew file mode 100644index 000000000..e9940925e--- /dev/null+++ b/src/agnext/application_components/logging/__init__.py@@ -0,0 +1,6 @@+from ._events import LLMCallEvent+from ._llm_usage import LLMUsageTracker++EVENT_LOGGER_NAME = "agnext.events"++__all__ = ["LLMCallEvent", "EVENT_LOGGER_NAME", "LLMUsageTracker"]diff --git a/src/agnext/application_components/logging/_events.py b/src/agnext/application_components/logging/_events.pynew file mode 100644index 000000000..2d860cf0f--- /dev/null+++ b/src/agnext/application_components/logging/_events.py@@ -0,0 +1,37 @@+import json+from typing import Any, cast+++class LLMCallEvent:+ def __init__(self, *, prompt_tokens: int, completion_tokens: int, **kwargs: Any) -> None:+ """To be used by model clients to log the call to the LLM.++ Args:+ prompt_tokens (int): Number of tokens used in the prompt.+ completion_tokens (int): Number of tokens used in the completion.++ Example:++ .. code-block:: python++ from agnext.application_components.logging import LLMCallEvent, EVENT_LOGGER_NAME++ logger = logging.getLogger(EVENT_LOGGER_NAME)+ logger.info(LLMCallEvent(prompt_tokens=10, completion_tokens=20))++ """+ self.kwargs = kwargs+ self.kwargs["prompt_tokens"] = prompt_tokens+ self.kwargs["completion_tokens"] = completion_tokens++ @property+ def prompt_tokens(self) -> int:+ return cast(int, self.kwargs["prompt_tokens"])++ @property+ def completion_tokens(self) -> int:+ return cast(int, self.kwargs["completion_tokens"])++ # This must output the event in a json serializable format+ def __str__(self) -> str:+ return json.dumps(self.kwargs)diff --git a/src/agnext/application_components/logging/_llm_usage.py b/src/agnext/application_components/logging/_llm_usage.pynew file mode 100644index 000000000..3deb2591b--- /dev/null+++ b/src/agnext/application_components/logging/_llm_usage.py@@ -0,0 +1,57 @@+import logging++from ._events import LLMCallEvent+++class LLMUsageTracker(logging.Handler):+ def __init__(self) -> None:+ """Logging handler that tracks the number of tokens used in the prompt and completion.++ Example:++ .. code-block:: python++ from agnext.application_components.logging import LLMUsageTracker, EVENT_LOGGER_NAME++ # Set up the logging configuration to use the custom handler+ logger = logging.getLogger(EVENT_LOGGER_NAME)+ logger.setLevel(logging.INFO)+ llm_usage = LLMUsageTracker()+ logger.handlers = [llm_usage]++ # ...++ print(llm_usage.prompt_tokens)+ print(llm_usage.completion_tokens)++ """+ super().__init__()+ self._prompt_tokens = 0+ self._completion_tokens = 0++ @property+ def tokens(self) -> int:+ return self._prompt_tokens + self._completion_tokens++ @property+ def prompt_tokens(self) -> int:+ return self._prompt_tokens++ @property+ def completion_tokens(self) -> int:+ return self._completion_tokens++ def reset(self) -> None:+ self._prompt_tokens = 0+ self._completion_tokens = 0++ def emit(self, record: logging.LogRecord) -> None:+ """Emit the log record. To be used by the logging module."""+ try:+ # Use the StructuredMessage if the message is an instance of it+ if isinstance(record.msg, LLMCallEvent):+ event = record.msg+ self._prompt_tokens += event.prompt_tokens+ self._completion_tokens += event.completion_tokens+ except Exception:+ self.handleError(record)diff --git a/src/agnext/core/_agent.py b/src/agnext/core/_agent.pyindex f3f130e54..8869669f7 100644--- a/src/agnext/core/_agent.py+++ b/src/agnext/core/_agent.py@@ -34,6 +34,15 @@ class Agent(Protocol):"""...- def save_state(self) -> Mapping[str, Any]: ...+ def save_state(self) -> Mapping[str, Any]:+ """Save the state of the agent. The result must be JSON serializable."""+ ...++ def load_state(self, state: Mapping[str, Any]) -> None:+ """Load in the state of the agent obtained from `save_state`.++ Args:+ state (Mapping[str, Any]): State of the agent. Must be JSON serializable.+ """- def load_state(self, state: Mapping[str, Any]) -> None: ...+ ...diff --git a/test.py b/test.pynew file mode 100644index 000000000..0bdd5399a--- /dev/null+++ b/test.py@@ -0,0 +1,35 @@+import json+import logging++class StructuredMessage:+ def __init__(self, message, /, **kwargs):+ self.message = message+ self.kwargs = kwargs++ def __str__(self):+ return '%s >>> %s' % (self.message, json.dumps(self.kwargs))++_ = StructuredMessage # optional, to improve readability++class StructuredLoggingHandler(logging.Handler):+ def emit(self, record):+ try:+ # Use the StructuredMessage if the message is an instance of it+ if isinstance(record.msg, StructuredMessage):+ print("got it")+ message = str(record.msg)+ else:+ message = self.format(record)+ print(message) # You can replace this with any other output method (e.g., writing to a file)+ except Exception:+ self.handleError(record)++# Set up the logging configuration to use the custom handler+logging.basicConfig(level=logging.INFO, format='%(message)s')+logger = logging.getLogger()+logger.handlers = [] # Remove default handlers+structured_handler = StructuredLoggingHandler()+logger.addHandler(structured_handler)++# Example usage+logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))\ No newline at end of filediff --git a/tests/test_llm_usage.py b/tests/test_llm_usage.pynew file mode 100644index 000000000..2f3142663--- /dev/null+++ b/tests/test_llm_usage.py@@ -0,0 +1,31 @@+from agnext.application_components.logging import LLMUsageTracker, EVENT_LOGGER_NAME, LLMCallEvent++import logging++def test_llm_usage() -> None:++ # Set up the logging configuration to use the custom handler+ logger = logging.getLogger(EVENT_LOGGER_NAME)+ logger.setLevel(logging.INFO)+ llm_usage = LLMUsageTracker()+ logger.handlers = [llm_usage]++ logger.info(LLMCallEvent(prompt_tokens=10, completion_tokens=20))++ assert llm_usage.prompt_tokens == 10+ assert llm_usage.completion_tokens == 20++ logger.info(LLMCallEvent(prompt_tokens=1, completion_tokens=1))++ assert llm_usage.prompt_tokens == 11+ assert llm_usage.completion_tokens == 21++ llm_usage.reset()++ assert llm_usage.prompt_tokens == 0+ assert llm_usage.completion_tokens == 0++ logger.info(LLMCallEvent(prompt_tokens=1, completion_tokens=1))++ assert llm_usage.prompt_tokens == 1+ assert llm_usage.completion_tokens == 1