agentpnl 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentpnl/__init__.py +3 -0
- agentpnl/adapters/__init__.py +1 -0
- agentpnl/adapters/base.py +75 -0
- agentpnl/adapters/csv_import.py +121 -0
- agentpnl/adapters/helicone.py +224 -0
- agentpnl/adapters/langfuse.py +136 -0
- agentpnl/cli.py +366 -0
- agentpnl/config.py +131 -0
- agentpnl/data/model_pricing.yaml +64 -0
- agentpnl/data/sample_config.yaml +52 -0
- agentpnl/engine/__init__.py +1 -0
- agentpnl/engine/contribution.py +151 -0
- agentpnl/engine/cost_calculator.py +117 -0
- agentpnl/engine/outcome_engine.py +152 -0
- agentpnl/models/__init__.py +1 -0
- agentpnl/models/database.py +164 -0
- agentpnl/models/pricing.py +56 -0
- agentpnl/reports/__init__.py +1 -0
- agentpnl/reports/generator.py +49 -0
- agentpnl/reports/templates/report.html +282 -0
- agentpnl-0.1.0.dist-info/METADATA +156 -0
- agentpnl-0.1.0.dist-info/RECORD +25 -0
- agentpnl-0.1.0.dist-info/WHEEL +4 -0
- agentpnl-0.1.0.dist-info/entry_points.txt +2 -0
- agentpnl-0.1.0.dist-info/licenses/LICENSE +21 -0
agentpnl/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Data source adapters for ingesting agent telemetry."""
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Abstract base adapter interface for data source integrations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class NormalizedAgent:
|
|
12
|
+
"""Standardized agent record from any source."""
|
|
13
|
+
|
|
14
|
+
agent_id: str
|
|
15
|
+
agent_name: str
|
|
16
|
+
agent_type: str = "default"
|
|
17
|
+
cost_center: str = "general"
|
|
18
|
+
source_platform: str = ""
|
|
19
|
+
first_seen: str = ""
|
|
20
|
+
last_seen: str = ""
|
|
21
|
+
metadata: dict = None
|
|
22
|
+
|
|
23
|
+
def __post_init__(self):
|
|
24
|
+
if self.metadata is None:
|
|
25
|
+
self.metadata = {}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class NormalizedRun:
|
|
30
|
+
"""Standardized run record from any source."""
|
|
31
|
+
|
|
32
|
+
run_id: str
|
|
33
|
+
agent_id: str
|
|
34
|
+
started_at: str
|
|
35
|
+
ended_at: str | None = None
|
|
36
|
+
status: str = "success"
|
|
37
|
+
prompt_tokens: int = 0
|
|
38
|
+
completion_tokens: int = 0
|
|
39
|
+
total_tokens: int = 0
|
|
40
|
+
model: str = ""
|
|
41
|
+
latency_ms: int = 0
|
|
42
|
+
error_type: str | None = None
|
|
43
|
+
source_trace_id: str = ""
|
|
44
|
+
metadata: dict = None
|
|
45
|
+
|
|
46
|
+
def __post_init__(self):
|
|
47
|
+
if self.metadata is None:
|
|
48
|
+
self.metadata = {}
|
|
49
|
+
if self.total_tokens == 0 and (self.prompt_tokens or self.completion_tokens):
|
|
50
|
+
self.total_tokens = self.prompt_tokens + self.completion_tokens
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class BaseAdapter(ABC):
|
|
54
|
+
"""Abstract adapter that all data source integrations must implement."""
|
|
55
|
+
|
|
56
|
+
source_platform: str = "unknown"
|
|
57
|
+
|
|
58
|
+
@abstractmethod
|
|
59
|
+
def test_connection(self) -> bool:
|
|
60
|
+
"""Verify that the data source is reachable and credentials are valid."""
|
|
61
|
+
...
|
|
62
|
+
|
|
63
|
+
@abstractmethod
|
|
64
|
+
def fetch_agents(self) -> list[NormalizedAgent]:
|
|
65
|
+
"""Retrieve all known agents from the source."""
|
|
66
|
+
...
|
|
67
|
+
|
|
68
|
+
@abstractmethod
|
|
69
|
+
def fetch_runs(
|
|
70
|
+
self,
|
|
71
|
+
since: datetime | None = None,
|
|
72
|
+
until: datetime | None = None,
|
|
73
|
+
) -> list[NormalizedRun]:
|
|
74
|
+
"""Retrieve agent runs within the given time range."""
|
|
75
|
+
...
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""CSV/JSON import adapter — universal fallback for any data source."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import json
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .base import BaseAdapter, NormalizedAgent, NormalizedRun
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CSVAdapter(BaseAdapter):
|
|
14
|
+
"""Import agent run data from CSV or JSON files.
|
|
15
|
+
|
|
16
|
+
Expected CSV columns (minimum):
|
|
17
|
+
run_id, agent_name, started_at, model, prompt_tokens, completion_tokens, status
|
|
18
|
+
|
|
19
|
+
Optional columns:
|
|
20
|
+
agent_type, ended_at, latency_ms, error_type, total_tokens
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
source_platform = "csv"
|
|
24
|
+
|
|
25
|
+
def __init__(self, file_path: str | Path):
|
|
26
|
+
self.file_path = Path(file_path)
|
|
27
|
+
self._data: list[dict] | None = None
|
|
28
|
+
|
|
29
|
+
def _load(self) -> list[dict]:
|
|
30
|
+
"""Load and parse the file."""
|
|
31
|
+
if self._data is not None:
|
|
32
|
+
return self._data
|
|
33
|
+
|
|
34
|
+
if not self.file_path.exists():
|
|
35
|
+
raise FileNotFoundError(f"Import file not found: {self.file_path}")
|
|
36
|
+
|
|
37
|
+
suffix = self.file_path.suffix.lower()
|
|
38
|
+
|
|
39
|
+
if suffix == ".json":
|
|
40
|
+
with open(self.file_path) as f:
|
|
41
|
+
raw = json.load(f)
|
|
42
|
+
self._data = raw if isinstance(raw, list) else raw.get("data", raw.get("runs", []))
|
|
43
|
+
elif suffix in (".csv", ".tsv"):
|
|
44
|
+
delimiter = "\t" if suffix == ".tsv" else ","
|
|
45
|
+
with open(self.file_path, newline="") as f:
|
|
46
|
+
reader = csv.DictReader(f, delimiter=delimiter)
|
|
47
|
+
self._data = list(reader)
|
|
48
|
+
else:
|
|
49
|
+
raise ValueError(f"Unsupported file format: {suffix}. Use .csv, .tsv, or .json")
|
|
50
|
+
|
|
51
|
+
return self._data
|
|
52
|
+
|
|
53
|
+
def test_connection(self) -> bool:
|
|
54
|
+
try:
|
|
55
|
+
self._load()
|
|
56
|
+
return True
|
|
57
|
+
except Exception:
|
|
58
|
+
return False
|
|
59
|
+
|
|
60
|
+
def fetch_agents(self) -> list[NormalizedAgent]:
|
|
61
|
+
data = self._load()
|
|
62
|
+
agents: dict[str, NormalizedAgent] = {}
|
|
63
|
+
|
|
64
|
+
for row in data:
|
|
65
|
+
name = row.get("agent_name", row.get("agent", "unnamed"))
|
|
66
|
+
agent_id = f"csv:{name}"
|
|
67
|
+
|
|
68
|
+
if agent_id not in agents:
|
|
69
|
+
agents[agent_id] = NormalizedAgent(
|
|
70
|
+
agent_id=agent_id,
|
|
71
|
+
agent_name=name,
|
|
72
|
+
agent_type=row.get("agent_type", "default"),
|
|
73
|
+
source_platform="csv",
|
|
74
|
+
first_seen=row.get("started_at", ""),
|
|
75
|
+
last_seen=row.get("started_at", ""),
|
|
76
|
+
)
|
|
77
|
+
else:
|
|
78
|
+
ts = row.get("started_at", "")
|
|
79
|
+
if ts > agents[agent_id].last_seen:
|
|
80
|
+
agents[agent_id].last_seen = ts
|
|
81
|
+
|
|
82
|
+
return list(agents.values())
|
|
83
|
+
|
|
84
|
+
def fetch_runs(
|
|
85
|
+
self,
|
|
86
|
+
since: datetime | None = None,
|
|
87
|
+
until: datetime | None = None,
|
|
88
|
+
) -> list[NormalizedRun]:
|
|
89
|
+
data = self._load()
|
|
90
|
+
runs = []
|
|
91
|
+
|
|
92
|
+
for i, row in enumerate(data):
|
|
93
|
+
started = row.get("started_at", "")
|
|
94
|
+
|
|
95
|
+
# Basic date filtering
|
|
96
|
+
if since and started and started < since.isoformat():
|
|
97
|
+
continue
|
|
98
|
+
if until and started and started > until.isoformat():
|
|
99
|
+
continue
|
|
100
|
+
|
|
101
|
+
prompt_tokens = int(row.get("prompt_tokens", 0) or 0)
|
|
102
|
+
completion_tokens = int(row.get("completion_tokens", 0) or 0)
|
|
103
|
+
total = int(row.get("total_tokens", 0) or 0)
|
|
104
|
+
|
|
105
|
+
run = NormalizedRun(
|
|
106
|
+
run_id=row.get("run_id", f"csv-{i}"),
|
|
107
|
+
agent_id=f"csv:{row.get('agent_name', row.get('agent', 'unnamed'))}",
|
|
108
|
+
started_at=started,
|
|
109
|
+
ended_at=row.get("ended_at"),
|
|
110
|
+
status=row.get("status", "success"),
|
|
111
|
+
prompt_tokens=prompt_tokens,
|
|
112
|
+
completion_tokens=completion_tokens,
|
|
113
|
+
total_tokens=total if total else prompt_tokens + completion_tokens,
|
|
114
|
+
model=row.get("model", ""),
|
|
115
|
+
latency_ms=int(row.get("latency_ms", 0) or 0),
|
|
116
|
+
error_type=row.get("error_type"),
|
|
117
|
+
source_trace_id=row.get("trace_id", ""),
|
|
118
|
+
)
|
|
119
|
+
runs.append(run)
|
|
120
|
+
|
|
121
|
+
return runs
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Helicone adapter — ingests agent run data via the Helicone API.
|
|
2
|
+
|
|
3
|
+
Helicone is a proxy-based observability tool that logs LLM requests.
|
|
4
|
+
It doesn't have a native "agent" concept, so we infer agents from
|
|
5
|
+
Helicone properties (custom headers) or session groupings.
|
|
6
|
+
|
|
7
|
+
Setup:
|
|
8
|
+
1. Get your Helicone API key from helicone.ai/dashboard
|
|
9
|
+
2. Run: agentpnl ingest --source helicone --helicone-api-key YOUR_KEY
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
|
|
19
|
+
from agentpnl.adapters.base import AgentData, BaseAdapter, RunData
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class HeliconeAdapter(BaseAdapter):
|
|
23
|
+
"""Fetch agent run data from the Helicone API.
|
|
24
|
+
|
|
25
|
+
Helicone identifies agents via custom properties set as request headers:
|
|
26
|
+
Helicone-Property-Agent: "my-support-agent"
|
|
27
|
+
Helicone-Property-AgentType: "customer-support"
|
|
28
|
+
|
|
29
|
+
If no agent property is set, runs are grouped by model as a fallback.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
BASE_URL = "https://api.helicone.ai/v1"
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
api_key: str,
|
|
37
|
+
base_url: str | None = None,
|
|
38
|
+
agent_property: str = "Agent",
|
|
39
|
+
agent_type_property: str = "AgentType",
|
|
40
|
+
):
|
|
41
|
+
self.api_key = api_key
|
|
42
|
+
self.base_url = base_url or self.BASE_URL
|
|
43
|
+
self.agent_property = agent_property
|
|
44
|
+
self.agent_type_property = agent_type_property
|
|
45
|
+
self.client = httpx.Client(
|
|
46
|
+
base_url=self.base_url,
|
|
47
|
+
headers={
|
|
48
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
49
|
+
"Content-Type": "application/json",
|
|
50
|
+
},
|
|
51
|
+
timeout=30.0,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
def test_connection(self) -> bool:
|
|
55
|
+
"""Verify API key works by fetching a single request."""
|
|
56
|
+
try:
|
|
57
|
+
resp = self.client.post(
|
|
58
|
+
"/request/query",
|
|
59
|
+
json={
|
|
60
|
+
"limit": 1,
|
|
61
|
+
"offset": 0,
|
|
62
|
+
"filter": {},
|
|
63
|
+
},
|
|
64
|
+
)
|
|
65
|
+
return resp.status_code == 200
|
|
66
|
+
except Exception:
|
|
67
|
+
return False
|
|
68
|
+
|
|
69
|
+
def _fetch_requests(
|
|
70
|
+
self,
|
|
71
|
+
limit: int = 1000,
|
|
72
|
+
offset: int = 0,
|
|
73
|
+
start_date: str | None = None,
|
|
74
|
+
end_date: str | None = None,
|
|
75
|
+
) -> list[dict[str, Any]]:
|
|
76
|
+
"""Fetch request logs from Helicone with pagination."""
|
|
77
|
+
filter_obj: dict[str, Any] = {}
|
|
78
|
+
if start_date:
|
|
79
|
+
filter_obj["request_created_at"] = {
|
|
80
|
+
"gte": start_date,
|
|
81
|
+
}
|
|
82
|
+
if end_date:
|
|
83
|
+
if "request_created_at" not in filter_obj:
|
|
84
|
+
filter_obj["request_created_at"] = {}
|
|
85
|
+
filter_obj["request_created_at"]["lte"] = end_date
|
|
86
|
+
|
|
87
|
+
all_requests: list[dict[str, Any]] = []
|
|
88
|
+
current_offset = offset
|
|
89
|
+
|
|
90
|
+
while True:
|
|
91
|
+
resp = self.client.post(
|
|
92
|
+
"/request/query",
|
|
93
|
+
json={
|
|
94
|
+
"limit": min(limit, 100),
|
|
95
|
+
"offset": current_offset,
|
|
96
|
+
"filter": filter_obj,
|
|
97
|
+
"sort": {"request_created_at": "desc"},
|
|
98
|
+
},
|
|
99
|
+
)
|
|
100
|
+
resp.raise_for_status()
|
|
101
|
+
data = resp.json()
|
|
102
|
+
|
|
103
|
+
requests = data.get("data", [])
|
|
104
|
+
if not requests:
|
|
105
|
+
break
|
|
106
|
+
|
|
107
|
+
all_requests.extend(requests)
|
|
108
|
+
current_offset += len(requests)
|
|
109
|
+
|
|
110
|
+
if len(all_requests) >= limit or len(requests) < 100:
|
|
111
|
+
break
|
|
112
|
+
|
|
113
|
+
return all_requests[:limit]
|
|
114
|
+
|
|
115
|
+
def _extract_agent_id(self, request: dict[str, Any]) -> str:
|
|
116
|
+
"""Extract agent identifier from Helicone properties or fall back to model."""
|
|
117
|
+
properties = request.get("properties", {}) or {}
|
|
118
|
+
|
|
119
|
+
# Check for explicit agent property
|
|
120
|
+
agent = properties.get(self.agent_property)
|
|
121
|
+
if agent:
|
|
122
|
+
return str(agent)
|
|
123
|
+
|
|
124
|
+
# Check for session-based grouping
|
|
125
|
+
session_id = properties.get("Helicone-Session-Id")
|
|
126
|
+
if session_id:
|
|
127
|
+
return f"session-{session_id}"
|
|
128
|
+
|
|
129
|
+
# Fall back to model name as agent grouping
|
|
130
|
+
model = request.get("model", "unknown")
|
|
131
|
+
return f"model-{model}"
|
|
132
|
+
|
|
133
|
+
def _extract_agent_type(self, request: dict[str, Any]) -> str:
|
|
134
|
+
"""Extract agent type from properties or default."""
|
|
135
|
+
properties = request.get("properties", {}) or {}
|
|
136
|
+
return str(properties.get(self.agent_type_property, "default"))
|
|
137
|
+
|
|
138
|
+
def fetch_agents(self) -> list[AgentData]:
|
|
139
|
+
"""Discover unique agents from request properties."""
|
|
140
|
+
requests = self._fetch_requests(limit=5000)
|
|
141
|
+
|
|
142
|
+
agents_map: dict[str, dict[str, Any]] = {}
|
|
143
|
+
|
|
144
|
+
for req in requests:
|
|
145
|
+
agent_id = self._extract_agent_id(req)
|
|
146
|
+
if agent_id not in agents_map:
|
|
147
|
+
agents_map[agent_id] = {
|
|
148
|
+
"agent_id": agent_id,
|
|
149
|
+
"agent_name": agent_id,
|
|
150
|
+
"agent_type": self._extract_agent_type(req),
|
|
151
|
+
"first_seen": req.get("request_created_at", ""),
|
|
152
|
+
"last_seen": req.get("request_created_at", ""),
|
|
153
|
+
}
|
|
154
|
+
else:
|
|
155
|
+
# Update last_seen
|
|
156
|
+
created = req.get("request_created_at", "")
|
|
157
|
+
if created > agents_map[agent_id]["last_seen"]:
|
|
158
|
+
agents_map[agent_id]["last_seen"] = created
|
|
159
|
+
if created < agents_map[agent_id]["first_seen"]:
|
|
160
|
+
agents_map[agent_id]["first_seen"] = created
|
|
161
|
+
|
|
162
|
+
return [
|
|
163
|
+
AgentData(
|
|
164
|
+
agent_id=a["agent_id"],
|
|
165
|
+
agent_name=a["agent_name"],
|
|
166
|
+
agent_type=a["agent_type"],
|
|
167
|
+
cost_center="general",
|
|
168
|
+
source_platform="helicone",
|
|
169
|
+
first_seen=a["first_seen"],
|
|
170
|
+
last_seen=a["last_seen"],
|
|
171
|
+
)
|
|
172
|
+
for a in agents_map.values()
|
|
173
|
+
]
|
|
174
|
+
|
|
175
|
+
def fetch_runs(self) -> list[RunData]:
|
|
176
|
+
"""Convert Helicone request logs into AgentPnL runs."""
|
|
177
|
+
requests = self._fetch_requests(limit=10000)
|
|
178
|
+
|
|
179
|
+
runs: list[RunData] = []
|
|
180
|
+
|
|
181
|
+
for req in requests:
|
|
182
|
+
request_id = req.get("request_id", "")
|
|
183
|
+
agent_id = self._extract_agent_id(req)
|
|
184
|
+
|
|
185
|
+
# Extract token usage
|
|
186
|
+
usage = req.get("usage", {}) or {}
|
|
187
|
+
prompt_tokens = usage.get("prompt_tokens", 0) or 0
|
|
188
|
+
completion_tokens = usage.get("completion_tokens", 0) or 0
|
|
189
|
+
total_tokens = usage.get("total_tokens", prompt_tokens + completion_tokens)
|
|
190
|
+
|
|
191
|
+
# Determine status
|
|
192
|
+
status_code = req.get("response_status", 200)
|
|
193
|
+
status = "success" if 200 <= status_code < 400 else "error"
|
|
194
|
+
error_type = None
|
|
195
|
+
if status == "error":
|
|
196
|
+
error_type = f"http_{status_code}"
|
|
197
|
+
|
|
198
|
+
# Timestamps
|
|
199
|
+
started_at = req.get("request_created_at", "")
|
|
200
|
+
ended_at = req.get("response_created_at", started_at)
|
|
201
|
+
|
|
202
|
+
# Latency
|
|
203
|
+
latency_ms = req.get("latency_ms", 0) or req.get("delay_ms", 0) or 0
|
|
204
|
+
|
|
205
|
+
runs.append(RunData(
|
|
206
|
+
run_id=request_id,
|
|
207
|
+
agent_id=agent_id,
|
|
208
|
+
started_at=started_at,
|
|
209
|
+
ended_at=ended_at,
|
|
210
|
+
status=status,
|
|
211
|
+
prompt_tokens=prompt_tokens,
|
|
212
|
+
completion_tokens=completion_tokens,
|
|
213
|
+
total_tokens=total_tokens,
|
|
214
|
+
model=req.get("model", "unknown"),
|
|
215
|
+
latency_ms=int(latency_ms),
|
|
216
|
+
error_type=error_type,
|
|
217
|
+
source_trace_id=request_id,
|
|
218
|
+
))
|
|
219
|
+
|
|
220
|
+
return runs
|
|
221
|
+
|
|
222
|
+
def close(self) -> None:
|
|
223
|
+
"""Close the HTTP client."""
|
|
224
|
+
self.client.close()
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Langfuse adapter — ingests traces and generations from the Langfuse API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from .base import BaseAdapter, NormalizedAgent, NormalizedRun
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LangfuseAdapter(BaseAdapter):
|
|
13
|
+
"""Fetches agent run data from the Langfuse observability platform.
|
|
14
|
+
|
|
15
|
+
Requires a Langfuse public key and secret key, plus the host URL
|
|
16
|
+
(defaults to Langfuse Cloud).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
source_platform = "langfuse"
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
public_key: str,
|
|
24
|
+
secret_key: str,
|
|
25
|
+
host: str = "https://cloud.langfuse.com",
|
|
26
|
+
):
|
|
27
|
+
self.public_key = public_key
|
|
28
|
+
self.secret_key = secret_key
|
|
29
|
+
self.host = host.rstrip("/")
|
|
30
|
+
self.client = httpx.Client(
|
|
31
|
+
base_url=f"{self.host}/api/public",
|
|
32
|
+
auth=(public_key, secret_key),
|
|
33
|
+
timeout=30.0,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def test_connection(self) -> bool:
|
|
37
|
+
"""Verify Langfuse credentials by hitting the health endpoint."""
|
|
38
|
+
try:
|
|
39
|
+
resp = self.client.get("/health")
|
|
40
|
+
return resp.status_code == 200
|
|
41
|
+
except httpx.HTTPError:
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
def fetch_agents(self) -> list[NormalizedAgent]:
|
|
45
|
+
"""Derive agents from unique trace names in Langfuse."""
|
|
46
|
+
agents: dict[str, NormalizedAgent] = {}
|
|
47
|
+
page = 1
|
|
48
|
+
|
|
49
|
+
while True:
|
|
50
|
+
resp = self.client.get("/traces", params={"page": page, "limit": 100})
|
|
51
|
+
resp.raise_for_status()
|
|
52
|
+
data = resp.json()
|
|
53
|
+
traces = data.get("data", [])
|
|
54
|
+
|
|
55
|
+
if not traces:
|
|
56
|
+
break
|
|
57
|
+
|
|
58
|
+
for trace in traces:
|
|
59
|
+
name = trace.get("name", "unnamed-agent")
|
|
60
|
+
agent_id = f"langfuse:{name}"
|
|
61
|
+
|
|
62
|
+
if agent_id not in agents:
|
|
63
|
+
agents[agent_id] = NormalizedAgent(
|
|
64
|
+
agent_id=agent_id,
|
|
65
|
+
agent_name=name,
|
|
66
|
+
agent_type=trace.get("tags", ["default"])[0] if trace.get("tags") else "default",
|
|
67
|
+
source_platform="langfuse",
|
|
68
|
+
first_seen=trace.get("timestamp", ""),
|
|
69
|
+
last_seen=trace.get("timestamp", ""),
|
|
70
|
+
metadata=trace.get("metadata", {}),
|
|
71
|
+
)
|
|
72
|
+
else:
|
|
73
|
+
# Update last_seen
|
|
74
|
+
ts = trace.get("timestamp", "")
|
|
75
|
+
if ts > agents[agent_id].last_seen:
|
|
76
|
+
agents[agent_id].last_seen = ts
|
|
77
|
+
|
|
78
|
+
page += 1
|
|
79
|
+
if page > data.get("meta", {}).get("totalPages", 1):
|
|
80
|
+
break
|
|
81
|
+
|
|
82
|
+
return list(agents.values())
|
|
83
|
+
|
|
84
|
+
def fetch_runs(
|
|
85
|
+
self,
|
|
86
|
+
since: datetime | None = None,
|
|
87
|
+
until: datetime | None = None,
|
|
88
|
+
) -> list[NormalizedRun]:
|
|
89
|
+
"""Fetch generations (LLM calls) from Langfuse as normalized runs."""
|
|
90
|
+
runs: list[NormalizedRun] = []
|
|
91
|
+
page = 1
|
|
92
|
+
|
|
93
|
+
while True:
|
|
94
|
+
params: dict = {"page": page, "limit": 100}
|
|
95
|
+
if since:
|
|
96
|
+
params["fromTimestamp"] = since.isoformat()
|
|
97
|
+
if until:
|
|
98
|
+
params["toTimestamp"] = until.isoformat()
|
|
99
|
+
|
|
100
|
+
resp = self.client.get("/generations", params=params)
|
|
101
|
+
resp.raise_for_status()
|
|
102
|
+
data = resp.json()
|
|
103
|
+
generations = data.get("data", [])
|
|
104
|
+
|
|
105
|
+
if not generations:
|
|
106
|
+
break
|
|
107
|
+
|
|
108
|
+
for gen in generations:
|
|
109
|
+
trace_name = gen.get("traceName", "unnamed-agent")
|
|
110
|
+
usage = gen.get("usage", {}) or {}
|
|
111
|
+
|
|
112
|
+
run = NormalizedRun(
|
|
113
|
+
run_id=gen.get("id", ""),
|
|
114
|
+
agent_id=f"langfuse:{trace_name}",
|
|
115
|
+
started_at=gen.get("startTime", ""),
|
|
116
|
+
ended_at=gen.get("endTime"),
|
|
117
|
+
status="error" if gen.get("statusMessage") else "success",
|
|
118
|
+
prompt_tokens=usage.get("promptTokens", 0) or 0,
|
|
119
|
+
completion_tokens=usage.get("completionTokens", 0) or 0,
|
|
120
|
+
total_tokens=usage.get("totalTokens", 0) or 0,
|
|
121
|
+
model=gen.get("model", ""),
|
|
122
|
+
latency_ms=int(gen.get("latency", 0) * 1000) if gen.get("latency") else 0,
|
|
123
|
+
error_type=gen.get("statusMessage") if gen.get("statusMessage") else None,
|
|
124
|
+
source_trace_id=gen.get("traceId", ""),
|
|
125
|
+
metadata=gen.get("metadata", {}),
|
|
126
|
+
)
|
|
127
|
+
runs.append(run)
|
|
128
|
+
|
|
129
|
+
page += 1
|
|
130
|
+
if page > data.get("meta", {}).get("totalPages", 1):
|
|
131
|
+
break
|
|
132
|
+
|
|
133
|
+
return runs
|
|
134
|
+
|
|
135
|
+
def close(self):
|
|
136
|
+
self.client.close()
|