File size: 10,143 Bytes
f9d84be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""
Observability — Callback hooks, cost tracking, and span tracing.

Provides production-grade visibility into agent runs:
  - Token & cost tracking per step, per task, per agent
  - Callback hooks for custom integrations (LangSmith, Arize, custom dashboards)
  - Structured event logging
  - Performance profiling

Lightweight — no external dependencies. Integrates with OpenTelemetry-compatible
systems via the callback interface.
"""

from __future__ import annotations

import json
import logging
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable, Protocol

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# Cost Tracking
# ---------------------------------------------------------------------------

# Approximate cost per 1M tokens (input) for common models
MODEL_COSTS_PER_1M_INPUT = {
    # Cloud LLMs
    "gpt-4o": 2.50,
    "gpt-4o-mini": 0.15,
    "claude-3-5-sonnet": 3.00,
    "claude-3-5-haiku": 0.80,
    # Cloud SLMs via inference providers
    "qwen/qwen3-32b": 0.20,
    "qwen/qwen3-8b": 0.05,
    "meta-llama/llama-3.1-8b-instruct": 0.05,
    # Local models (electricity cost estimate per 1M tokens)
    "local-gpu": 0.01,    # ~$0.01/1M tokens on consumer GPU
    "local-cpu": 0.005,   # ~$0.005/1M tokens on CPU
    "ollama": 0.005,      # Estimate for local Ollama
}


@dataclass
class TokenUsage:
    """Token usage for a single LLM call."""
    prompt_tokens: int = 0
    completion_tokens: int = 0
    total_tokens: int = 0
    model: str = ""
    estimated_cost_usd: float = 0.0
    timestamp: float = field(default_factory=time.time)


@dataclass
class CostTracker:
    """
    Tracks token usage and estimated costs across all LLM calls.
    
    Usage:
        tracker = CostTracker(model_name="qwen3:1.7b", cost_per_1m=0.005)
        tracker.record(prompt_tokens=500, completion_tokens=200)
        print(tracker.summary())
    """
    model_name: str = "unknown"
    cost_per_1m_input: float = 0.01
    cost_per_1m_output: float = 0.02
    calls: list[TokenUsage] = field(default_factory=list)

    def record(
        self,
        prompt_tokens: int = 0,
        completion_tokens: int = 0,
        model: str | None = None,
    ) -> TokenUsage:
        """Record a single LLM call."""
        total = prompt_tokens + completion_tokens
        cost = (
            prompt_tokens * self.cost_per_1m_input / 1_000_000
            + completion_tokens * self.cost_per_1m_output / 1_000_000
        )

        usage = TokenUsage(
            prompt_tokens=prompt_tokens,
            completion_tokens=completion_tokens,
            total_tokens=total,
            model=model or self.model_name,
            estimated_cost_usd=cost,
        )
        self.calls.append(usage)
        return usage

    @property
    def total_tokens(self) -> int:
        return sum(c.total_tokens for c in self.calls)

    @property
    def total_cost_usd(self) -> float:
        return sum(c.estimated_cost_usd for c in self.calls)

    @property
    def total_calls(self) -> int:
        return len(self.calls)

    def summary(self) -> dict[str, Any]:
        return {
            "model": self.model_name,
            "total_calls": self.total_calls,
            "total_tokens": self.total_tokens,
            "prompt_tokens": sum(c.prompt_tokens for c in self.calls),
            "completion_tokens": sum(c.completion_tokens for c in self.calls),
            "estimated_cost_usd": round(self.total_cost_usd, 6),
        }

    def reset(self):
        self.calls.clear()


# ---------------------------------------------------------------------------
# Callback System
# ---------------------------------------------------------------------------

class EventType(Enum):
    """Events emitted during agent execution."""
    TASK_START = "task_start"
    TASK_END = "task_end"
    STEP_START = "step_start"
    STEP_END = "step_end"
    ACTION_DECIDED = "action_decided"
    TOOL_CALLED = "tool_called"
    TOOL_RESULT = "tool_result"
    STATE_EVALUATED = "state_evaluated"
    LLM_CALL_START = "llm_call_start"
    LLM_CALL_END = "llm_call_end"
    HEURISTIC_LEARNED = "heuristic_learned"
    MEMORY_UPDATED = "memory_updated"
    OPTIMIZATION_START = "optimization_start"
    OPTIMIZATION_END = "optimization_end"
    ERROR = "error"
    CHECKPOINT = "checkpoint"
    HUMAN_INPUT_REQUESTED = "human_input_requested"
    HUMAN_INPUT_RECEIVED = "human_input_received"


@dataclass
class AgentEvent:
    """A structured event emitted during agent execution."""
    event_type: EventType
    data: dict[str, Any] = field(default_factory=dict)
    step: int = 0
    task_id: str = ""
    agent_id: str = ""
    timestamp: float = field(default_factory=time.time)
    duration_s: float = 0.0

    def to_dict(self) -> dict[str, Any]:
        return {
            "event": self.event_type.value,
            "data": self.data,
            "step": self.step,
            "task_id": self.task_id,
            "agent_id": self.agent_id,
            "timestamp": self.timestamp,
            "duration_s": self.duration_s,
        }

    def to_json(self) -> str:
        return json.dumps(self.to_dict(), default=str)


class AgentCallback(Protocol):
    """Protocol for agent callbacks. Implement this to integrate with external systems."""

    def on_event(self, event: AgentEvent) -> None:
        """Called when an event occurs during agent execution."""
        ...


class LoggingCallback:
    """Simple callback that logs all events."""

    def __init__(self, level: int = logging.INFO):
        self.level = level
        self.events: list[AgentEvent] = []

    def on_event(self, event: AgentEvent) -> None:
        self.events.append(event)
        logger.log(
            self.level,
            f"[{event.event_type.value}] step={event.step} "
            f"task={event.task_id} {json.dumps(event.data, default=str)[:200]}",
        )


class JSONFileCallback:
    """Callback that writes events to a JSON Lines file."""

    def __init__(self, path: str):
        self.path = path

    def on_event(self, event: AgentEvent) -> None:
        with open(self.path, "a") as f:
            f.write(event.to_json() + "\n")


class MetricsCollector:
    """
    Callback that collects aggregate metrics for analysis.
    
    Usage:
        collector = MetricsCollector()
        # ... run tasks with collector as callback ...
        print(collector.summary())
    """

    def __init__(self):
        self.tasks: list[dict] = []
        self.steps: list[dict] = []
        self.llm_calls: list[dict] = []
        self.errors: list[dict] = []
        self._current_task: dict = {}
        self._step_start: float = 0

    def on_event(self, event: AgentEvent) -> None:
        if event.event_type == EventType.TASK_START:
            self._current_task = {"task_id": event.task_id, "start": event.timestamp, "steps": 0}
        elif event.event_type == EventType.TASK_END:
            self._current_task["end"] = event.timestamp
            self._current_task["duration_s"] = event.timestamp - self._current_task.get("start", event.timestamp)
            self._current_task.update(event.data)
            self.tasks.append(self._current_task)
        elif event.event_type == EventType.STEP_START:
            self._step_start = event.timestamp
            if self._current_task:
                self._current_task["steps"] = self._current_task.get("steps", 0) + 1
        elif event.event_type == EventType.STATE_EVALUATED:
            self.steps.append({
                "step": event.step,
                "task_id": event.task_id,
                "duration_s": event.timestamp - self._step_start if self._step_start else 0,
                **event.data,
            })
        elif event.event_type == EventType.LLM_CALL_END:
            self.llm_calls.append(event.data)
        elif event.event_type == EventType.ERROR:
            self.errors.append({"step": event.step, **event.data})

    def summary(self) -> dict[str, Any]:
        if not self.tasks:
            return {"tasks": 0}

        success_count = sum(1 for t in self.tasks if t.get("success_rate", 0) > 0.5)
        total_steps = sum(t.get("steps", 0) for t in self.tasks)
        total_duration = sum(t.get("duration_s", 0) for t in self.tasks)
        avg_phi_deltas = [s.get("delta", 0) for s in self.steps if "delta" in s]

        return {
            "total_tasks": len(self.tasks),
            "successful_tasks": success_count,
            "success_rate": success_count / len(self.tasks) if self.tasks else 0,
            "total_steps": total_steps,
            "avg_steps_per_task": total_steps / len(self.tasks),
            "total_duration_s": round(total_duration, 2),
            "avg_duration_per_task_s": round(total_duration / len(self.tasks), 2),
            "total_llm_calls": len(self.llm_calls),
            "total_errors": len(self.errors),
            "avg_phi_delta": round(sum(avg_phi_deltas) / len(avg_phi_deltas), 3) if avg_phi_deltas else 0,
        }


# ---------------------------------------------------------------------------
# Callback Manager — dispatches events to multiple callbacks
# ---------------------------------------------------------------------------

class CallbackManager:
    """
    Manages multiple callbacks and dispatches events to all of them.
    
    Usage:
        mgr = CallbackManager()
        mgr.add(LoggingCallback())
        mgr.add(MetricsCollector())
        mgr.add(JSONFileCallback("events.jsonl"))
        
        mgr.emit(AgentEvent(EventType.TASK_START, data={"purpose": "..."}))
    """

    def __init__(self, callbacks: list | None = None):
        self.callbacks: list = callbacks or []

    def add(self, callback) -> "CallbackManager":
        self.callbacks.append(callback)
        return self

    def emit(self, event: AgentEvent) -> None:
        for cb in self.callbacks:
            try:
                cb.on_event(event)
            except Exception as e:
                logger.warning(f"Callback {type(cb).__name__} failed: {e}")