agentpnl 0.1.0__tar.gz

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.
Files changed (40) hide show
  1. agentpnl-0.1.0/.claude/agents/code-reviewer.md +22 -0
  2. agentpnl-0.1.0/.claude/agents/docs-writer.md +24 -0
  3. agentpnl-0.1.0/.claude/agents/test-runner.md +24 -0
  4. agentpnl-0.1.0/.gitignore +19 -0
  5. agentpnl-0.1.0/CLAUDE.md +44 -0
  6. agentpnl-0.1.0/LICENSE +21 -0
  7. agentpnl-0.1.0/PKG-INFO +156 -0
  8. agentpnl-0.1.0/README.md +122 -0
  9. agentpnl-0.1.0/agentpnl/__init__.py +3 -0
  10. agentpnl-0.1.0/agentpnl/adapters/__init__.py +1 -0
  11. agentpnl-0.1.0/agentpnl/adapters/base.py +75 -0
  12. agentpnl-0.1.0/agentpnl/adapters/csv_import.py +121 -0
  13. agentpnl-0.1.0/agentpnl/adapters/helicone.py +224 -0
  14. agentpnl-0.1.0/agentpnl/adapters/langfuse.py +136 -0
  15. agentpnl-0.1.0/agentpnl/cli.py +366 -0
  16. agentpnl-0.1.0/agentpnl/config.py +131 -0
  17. agentpnl-0.1.0/agentpnl/data/model_pricing.yaml +64 -0
  18. agentpnl-0.1.0/agentpnl/data/sample_config.yaml +52 -0
  19. agentpnl-0.1.0/agentpnl/engine/__init__.py +1 -0
  20. agentpnl-0.1.0/agentpnl/engine/contribution.py +151 -0
  21. agentpnl-0.1.0/agentpnl/engine/cost_calculator.py +117 -0
  22. agentpnl-0.1.0/agentpnl/engine/outcome_engine.py +152 -0
  23. agentpnl-0.1.0/agentpnl/models/__init__.py +1 -0
  24. agentpnl-0.1.0/agentpnl/models/database.py +164 -0
  25. agentpnl-0.1.0/agentpnl/models/pricing.py +56 -0
  26. agentpnl-0.1.0/agentpnl/reports/__init__.py +1 -0
  27. agentpnl-0.1.0/agentpnl/reports/generator.py +49 -0
  28. agentpnl-0.1.0/agentpnl/reports/templates/report.html +282 -0
  29. agentpnl-0.1.0/docs/CNAME +1 -0
  30. agentpnl-0.1.0/docs/financial-framework.md +158 -0
  31. agentpnl-0.1.0/docs/financial-reporting-standard.md +377 -0
  32. agentpnl-0.1.0/docs/quickstart.md +97 -0
  33. agentpnl-0.1.0/examples/demo_config.yaml +37 -0
  34. agentpnl-0.1.0/examples/demo_data.csv +51 -0
  35. agentpnl-0.1.0/examples/sample_report.html +371 -0
  36. agentpnl-0.1.0/pyproject.toml +55 -0
  37. agentpnl-0.1.0/tests/__init__.py +0 -0
  38. agentpnl-0.1.0/tests/test_adapters.py +101 -0
  39. agentpnl-0.1.0/tests/test_cli.py +66 -0
  40. agentpnl-0.1.0/tests/test_engine.py +165 -0
@@ -0,0 +1,22 @@
1
+ ---
2
+ description: Reviews code changes for quality, correctness, and adherence to project conventions.
3
+ tools:
4
+ - Read
5
+ - Bash
6
+ - Agent
7
+ ---
8
+
9
+ # Code Reviewer
10
+
11
+ You review code changes in the AgentPnL repository.
12
+
13
+ ## What to check
14
+ 1. **Correctness** — Will this code work? Are edge cases handled?
15
+ 2. **Financial accuracy** — Cost calculations, attribution logic, and rounding must be precise. This is accounting software.
16
+ 3. **Style** — Ruff rules (line-length 100, select E/F/I/N/W). Run `ruff check` on changed files.
17
+ 4. **Tests** — Are new features covered? Do existing tests still pass? Run `pytest` to verify.
18
+ 5. **Dependencies** — New deps must be justified. The project targets 5 core dependencies.
19
+ 6. **Config compatibility** — Changes to YAML config format must be backward-compatible or clearly documented.
20
+
21
+ ## Output
22
+ Provide a concise summary: what's good, what needs fixing, and a pass/fail recommendation. Be direct — no filler.
@@ -0,0 +1,24 @@
1
+ ---
2
+ description: Keeps documentation accurate and up to date with the codebase.
3
+ tools:
4
+ - Read
5
+ - Write
6
+ - Edit
7
+ - Bash
8
+ ---
9
+
10
+ # Docs Writer
11
+
12
+ You maintain documentation for AgentPnL.
13
+
14
+ ## Responsibilities
15
+ 1. **README.md** — Keep install instructions, feature list, and examples current.
16
+ 2. **docs/** — Update quickstart.md and financial-framework.md when the codebase changes.
17
+ 3. **Docstrings** — Ensure public functions have clear docstrings.
18
+ 4. **CHANGELOG** — Log notable changes with version numbers.
19
+ 5. **Config docs** — Document all YAML config options with examples.
20
+
21
+ ## Style
22
+ - Write for two audiences: developers (quickstart, API) and finance people (framework, config).
23
+ - Be concise. Code examples over paragraphs.
24
+ - Use the same tone as the README — direct, no fluff.
@@ -0,0 +1,24 @@
1
+ ---
2
+ description: Runs tests and writes new test cases for untested code paths.
3
+ tools:
4
+ - Read
5
+ - Write
6
+ - Edit
7
+ - Bash
8
+ ---
9
+
10
+ # Test Runner
11
+
12
+ You maintain and expand the test suite for AgentPnL.
13
+
14
+ ## Responsibilities
15
+ 1. **Run tests** — Execute `pip install -e ".[dev]" && pytest -v` and report results.
16
+ 2. **Coverage gaps** — Identify untested functions, especially in `engine/` and `adapters/`.
17
+ 3. **Write tests** — Add pytest tests for uncovered code. Tests go in `tests/`.
18
+ 4. **Financial edge cases** — Zero-cost agents, negative margins, division by zero, missing data, currency rounding.
19
+
20
+ ## Conventions
21
+ - Use pytest (not unittest)
22
+ - Test files: `test_<module>.py`
23
+ - Use fixtures for sample data
24
+ - Keep tests fast — mock external API calls (Langfuse, etc.)
@@ -0,0 +1,19 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .eggs/
8
+ *.db
9
+ *.sqlite
10
+ *.egg
11
+ .venv/
12
+ venv/
13
+ .env
14
+ .ruff_cache/
15
+ .pytest_cache/
16
+ *.html
17
+ !agentpnl/reports/templates/*.html
18
+ !examples/sample_report.html
19
+ *.db
@@ -0,0 +1,44 @@
1
+ # AgentPnL — Project Context
2
+
3
+ ## What This Is
4
+ AgentPnL is a Python CLI tool that treats AI agents like business units. It ingests run data from observability platforms (Langfuse, CSV), applies configurable financial rules (cost replacement, time saving, per-unit, revenue attribution), and generates P&L reports per agent.
5
+
6
+ ## Owner
7
+ Gian Gieri (@giangieri) — Financial Controller and fractional CFO. This project lives in the Business Idea Simulator project on Claude.ai.
8
+
9
+ ## Architecture
10
+ - `agentpnl/` — Core package
11
+ - `adapters/` — Data source connectors (Langfuse, CSV; Helicone and OTel planned)
12
+ - `engine/` — Cost calculator, outcome engine, contribution analysis
13
+ - `models/` — Data models, pricing lookups, SQLite database
14
+ - `reports/` — HTML report generator (Jinja2 templates)
15
+ - `data/` — Model pricing YAML, sample configs
16
+ - `cli.py` — Click-based CLI entry point
17
+ - `config.py` — YAML config loader
18
+ - `docs/` — Financial framework docs, quickstart guide
19
+ - `examples/` — Demo configs and sample data
20
+ - `tests/` — Pytest suite
21
+
22
+ ## Tech Stack
23
+ - Python 3.10+, hatchling build
24
+ - Dependencies: httpx, pandas, pyyaml, jinja2, click
25
+ - Optional: weasyprint (PDF export)
26
+ - Dev: pytest, ruff
27
+
28
+ ## Key Design Decisions
29
+ - Runs locally — no cloud account needed
30
+ - YAML config is readable by non-engineers (CFOs, controllers)
31
+ - Reports are standalone HTML files that travel via email
32
+ - 5 core dependencies, minimal footprint
33
+ - Honest attribution — configurable rules, not magic
34
+
35
+ ## Conventions
36
+ - Ruff for linting (line-length 100)
37
+ - Tests in `tests/` — run with `pytest`
38
+ - Commits should be descriptive, one logical change per commit
39
+
40
+ ## Roadmap (from README)
41
+ - v0.1: Langfuse + CSV adapters ✅
42
+ - v0.2: Helicone adapter
43
+ - v0.3: OpenTelemetry adapter
44
+ - Future: Dashboard mode, multi-period comparisons, budget vs actual
agentpnl-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AgentPnL
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,156 @@
1
+ Metadata-Version: 2.5
2
+ Name: agentpnl
3
+ Version: 0.1.0
4
+ Summary: Management accounting for autonomous AI agents — P&L reporting, cost allocation, and unit economics.
5
+ Project-URL: Homepage, https://agentpnl.ai
6
+ Project-URL: Repository, https://github.com/agentpnl/agentpnl
7
+ Project-URL: Documentation, https://github.com/agentpnl/agentpnl/tree/main/docs
8
+ Author-email: AgentPnL <hello@agentpnl.ai>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: accounting,agents,ai,cost-allocation,observability,pnl,unit-economics
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Financial and Insurance Industry
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Office/Business :: Financial :: Accounting
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: click>=8.1
23
+ Requires-Dist: httpx>=0.27
24
+ Requires-Dist: jinja2>=3.1
25
+ Requires-Dist: pandas>=2.1
26
+ Requires-Dist: pyyaml>=6.0
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
29
+ Requires-Dist: pytest>=8.0; extra == 'dev'
30
+ Requires-Dist: ruff>=0.5; extra == 'dev'
31
+ Provides-Extra: pdf
32
+ Requires-Dist: weasyprint>=62; extra == 'pdf'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # AgentPnL
36
+
37
+ **Management accounting for autonomous AI agents.**
38
+
39
+ Know which agents make money and which ones burn it. AgentPnL connects to your agent observability platform, applies a financial framework, and generates P&L reports per agent that a CFO can read.
40
+
41
+ ```
42
+ pip install agentpnl
43
+ agentpnl configure
44
+ agentpnl ingest --source langfuse
45
+ agentpnl report
46
+ ```
47
+
48
+ ## The Problem
49
+
50
+ You're running 15 AI agents. Your monthly inference bill is $4,200. Some agents save your team 40 hours a week. Others run 500 times and produce nothing measurable.
51
+
52
+ Your observability tool shows tokens and latency. Your CFO asks: *"What's the ROI on our AI spend?"*
53
+
54
+ You don't have an answer.
55
+
56
+ ## What AgentPnL Does
57
+
58
+ AgentPnL treats every AI agent like a business unit:
59
+
60
+ | Metric | What It Tells You |
61
+ |---|---|
62
+ | **Gross Value** | Dollar value each agent produces (configurable per agent type) |
63
+ | **Direct Costs** | Inference + API + tool costs per agent |
64
+ | **Allocated Overhead** | Share of platform/infra costs |
65
+ | **Error Costs** | Cost of failed runs and human escalations |
66
+ | **Net Contribution** | Value minus all costs — the bottom line per agent |
67
+ | **ROI** | Return on investment per agent |
68
+
69
+ The output is a single HTML report you can email to your CFO, print, or open in a browser.
70
+
71
+ ## Quick Start
72
+
73
+ ### 1. Install
74
+
75
+ ```bash
76
+ pip install agentpnl
77
+ ```
78
+
79
+ ### 2. Configure
80
+
81
+ ```bash
82
+ agentpnl configure # generates agentpnl.yaml
83
+ ```
84
+
85
+ Edit `agentpnl.yaml` to define how each agent type creates value:
86
+
87
+ ```yaml
88
+ company: "Acme Corp"
89
+ currency: "USD"
90
+
91
+ outcome_rules:
92
+ - agent_type: "customer-support"
93
+ method: "cost_replacement"
94
+ benchmark: 4200 # monthly cost of human doing same job
95
+
96
+ - agent_type: "code-review"
97
+ method: "time_saving"
98
+ hourly_rate: 150
99
+ avg_time_saved_minutes: 30
100
+ ```
101
+
102
+ ### 3. Ingest Data
103
+
104
+ From Langfuse:
105
+ ```bash
106
+ export LANGFUSE_PUBLIC_KEY=pk-...
107
+ export LANGFUSE_SECRET_KEY=sk-...
108
+ agentpnl ingest --source langfuse
109
+ ```
110
+
111
+ From CSV:
112
+ ```bash
113
+ agentpnl ingest --source csv --file runs.csv
114
+ ```
115
+
116
+ ### 4. Generate Report
117
+
118
+ ```bash
119
+ agentpnl report -o report.html
120
+ ```
121
+
122
+ ## Supported Data Sources
123
+
124
+ | Source | Status |
125
+ |---|---|
126
+ | **Langfuse** | ✅ v0.1 |
127
+ | **CSV / JSON** | ✅ v0.1 |
128
+ | Helicone | 🔜 v0.2 |
129
+ | OpenTelemetry | 🔜 v0.3 |
130
+
131
+ ## Value Attribution Methods
132
+
133
+ AgentPnL doesn't pretend to magically know what an agent is worth. You define the rules:
134
+
135
+ - **Cost Replacement** — "This agent replaces a $4,200/mo employee"
136
+ - **Time Saving** — "Each run saves a developer 30 minutes at $150/hr"
137
+ - **Per Unit** — "Each processed invoice is worth $3.50"
138
+ - **Revenue Attribution** — "5% of downstream deal value"
139
+ - **Cost Only** — Track spend without revenue attribution
140
+
141
+ ## Design Principles
142
+
143
+ 1. **Runs locally.** `pip install`, point at your API key, get a report. No cloud account needed.
144
+ 2. **YAML config speaks accounting.** Non-engineers can read and validate the financial rules.
145
+ 3. **Reports travel.** A CFO reads an HTML file in email. Dashboards require logins.
146
+ 4. **Honest attribution.** Configurable, not magic. Audit-friendly methodology notes in every report.
147
+ 5. **5 dependencies.** httpx, pandas, pyyaml, jinja2, click.
148
+
149
+ ## License
150
+
151
+ MIT — use it however you want.
152
+
153
+ ## Links
154
+
155
+ - **Website:** [agentpnl.ai](https://agentpnl.ai)
156
+ - **Docs:** [docs/](docs/)
@@ -0,0 +1,122 @@
1
+ # AgentPnL
2
+
3
+ **Management accounting for autonomous AI agents.**
4
+
5
+ Know which agents make money and which ones burn it. AgentPnL connects to your agent observability platform, applies a financial framework, and generates P&L reports per agent that a CFO can read.
6
+
7
+ ```
8
+ pip install agentpnl
9
+ agentpnl configure
10
+ agentpnl ingest --source langfuse
11
+ agentpnl report
12
+ ```
13
+
14
+ ## The Problem
15
+
16
+ You're running 15 AI agents. Your monthly inference bill is $4,200. Some agents save your team 40 hours a week. Others run 500 times and produce nothing measurable.
17
+
18
+ Your observability tool shows tokens and latency. Your CFO asks: *"What's the ROI on our AI spend?"*
19
+
20
+ You don't have an answer.
21
+
22
+ ## What AgentPnL Does
23
+
24
+ AgentPnL treats every AI agent like a business unit:
25
+
26
+ | Metric | What It Tells You |
27
+ |---|---|
28
+ | **Gross Value** | Dollar value each agent produces (configurable per agent type) |
29
+ | **Direct Costs** | Inference + API + tool costs per agent |
30
+ | **Allocated Overhead** | Share of platform/infra costs |
31
+ | **Error Costs** | Cost of failed runs and human escalations |
32
+ | **Net Contribution** | Value minus all costs — the bottom line per agent |
33
+ | **ROI** | Return on investment per agent |
34
+
35
+ The output is a single HTML report you can email to your CFO, print, or open in a browser.
36
+
37
+ ## Quick Start
38
+
39
+ ### 1. Install
40
+
41
+ ```bash
42
+ pip install agentpnl
43
+ ```
44
+
45
+ ### 2. Configure
46
+
47
+ ```bash
48
+ agentpnl configure # generates agentpnl.yaml
49
+ ```
50
+
51
+ Edit `agentpnl.yaml` to define how each agent type creates value:
52
+
53
+ ```yaml
54
+ company: "Acme Corp"
55
+ currency: "USD"
56
+
57
+ outcome_rules:
58
+ - agent_type: "customer-support"
59
+ method: "cost_replacement"
60
+ benchmark: 4200 # monthly cost of human doing same job
61
+
62
+ - agent_type: "code-review"
63
+ method: "time_saving"
64
+ hourly_rate: 150
65
+ avg_time_saved_minutes: 30
66
+ ```
67
+
68
+ ### 3. Ingest Data
69
+
70
+ From Langfuse:
71
+ ```bash
72
+ export LANGFUSE_PUBLIC_KEY=pk-...
73
+ export LANGFUSE_SECRET_KEY=sk-...
74
+ agentpnl ingest --source langfuse
75
+ ```
76
+
77
+ From CSV:
78
+ ```bash
79
+ agentpnl ingest --source csv --file runs.csv
80
+ ```
81
+
82
+ ### 4. Generate Report
83
+
84
+ ```bash
85
+ agentpnl report -o report.html
86
+ ```
87
+
88
+ ## Supported Data Sources
89
+
90
+ | Source | Status |
91
+ |---|---|
92
+ | **Langfuse** | ✅ v0.1 |
93
+ | **CSV / JSON** | ✅ v0.1 |
94
+ | Helicone | 🔜 v0.2 |
95
+ | OpenTelemetry | 🔜 v0.3 |
96
+
97
+ ## Value Attribution Methods
98
+
99
+ AgentPnL doesn't pretend to magically know what an agent is worth. You define the rules:
100
+
101
+ - **Cost Replacement** — "This agent replaces a $4,200/mo employee"
102
+ - **Time Saving** — "Each run saves a developer 30 minutes at $150/hr"
103
+ - **Per Unit** — "Each processed invoice is worth $3.50"
104
+ - **Revenue Attribution** — "5% of downstream deal value"
105
+ - **Cost Only** — Track spend without revenue attribution
106
+
107
+ ## Design Principles
108
+
109
+ 1. **Runs locally.** `pip install`, point at your API key, get a report. No cloud account needed.
110
+ 2. **YAML config speaks accounting.** Non-engineers can read and validate the financial rules.
111
+ 3. **Reports travel.** A CFO reads an HTML file in email. Dashboards require logins.
112
+ 4. **Honest attribution.** Configurable, not magic. Audit-friendly methodology notes in every report.
113
+ 5. **5 dependencies.** httpx, pandas, pyyaml, jinja2, click.
114
+
115
+ ## License
116
+
117
+ MIT — use it however you want.
118
+
119
+ ## Links
120
+
121
+ - **Website:** [agentpnl.ai](https://agentpnl.ai)
122
+ - **Docs:** [docs/](docs/)
@@ -0,0 +1,3 @@
1
+ """AgentPnL — Management accounting for autonomous AI agents."""
2
+
3
+ __version__ = "0.1.0"
@@ -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