govagent 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.
@@ -0,0 +1,2 @@
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
govagent-0.1.0/.github ADDED
File without changes
@@ -0,0 +1,181 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # Ruff stuff:
171
+ .ruff_cache/
172
+
173
+ # PyPI configuration file
174
+ .pypirc
175
+
176
+ # Cursor
177
+ # Cursor is an AI-powered code editor.`.cursorignore` specifies files/directories to
178
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
179
+ # refer to https://docs.cursor.com/context/ignore-files
180
+ .cursorignore
181
+ .cursorindexingignore
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: govagent
3
+ Version: 0.1.0
4
+ Summary: The Governance-First Framework for Agentic AI
5
+ Project-URL: Homepage, https://github.com/thekakodkar/govagent
6
+ Author: Your Name
7
+ License: MIT
8
+ Keywords: agents,ai,enterprise,governance,roi
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: httpx>=0.25.0
11
+ Requires-Dist: pydantic>=2.0.0
12
+ Requires-Dist: pyyaml>=6.0.0
13
+ Description-Content-Type: text/markdown
14
+
15
+ # GovAgent: The Enterprise Protocol for Agentic AI
16
+
17
+ **The Governance-First Framework for Production-Grade Autonomous Systems.**
18
+
19
+ `GovAgent` is a high-abstraction, lightweight Python framework designed to bridge the gap between experimental AI and business-critical operations.
20
+
21
+ ## 🎯 Value Proposition
22
+ In high-stakes environments, the barrier to AI adoption is **reliability and control**. `GovAgent` ensures every action is transparent, budget-aware, and risk-managed.
23
+
24
+ * **Active Circuit Breakers:** Real-time enforcement of financial and operational limits.
25
+ * **Governance-as-Code:** Human-readable permission manifests (`policy.yaml`) that align technical execution with organizational policy.
26
+ * **Forensic Telemetry:** Standardized audit logs and ROI projections (USD saved vs. USD spent).
27
+ * **Zero-Trust Tooling:** Strict whitelisting for agent actions and domain access.
28
+
29
+ ---
30
+
31
+ ## 🏗️ Core Pillars
32
+
33
+ ### 1. The Governance Manifest (`policy.yaml`)
34
+ Define "Rules of Engagement" outside the codebase. This allows stakeholders to review and approve agent permissions.
35
+ * **Financial Guardrails:** Hard limits on USD spend per session.
36
+ * **Action Scopes:** Explicit whitelisting of approved tools.
37
+ * **Escalation Triggers:** Thresholds for Human-in-the-Loop (HITL) intervention.
38
+
39
+ ### 2. Forensic Telemetry (`telemetry.py`)
40
+ Every execution generates a **Business Value Summary**:
41
+ * **ROI Projection:** Estimated manual human-hours saved.
42
+ * **Audit Chain:** A verifiable history of every decision, tool call, and result.
43
+
44
+ ---
45
+
46
+ # GovAgent: Enterprise-Grade Agentic Governance
47
+
48
+ ## 🚧 Development Status (WIP)
49
+ **GovAgent is rapidly evolving.** We are currently moving from architectural design to core module implementation.
50
+
51
+ ### ✅ Completed Modules
52
+ * **Governance Manifest (`policy.py`):** Structured YAML-based policy enforcement.
53
+ * **Forensic Telemetry (`telemetry.py`):** Real-time ROI and audit trail generation.
54
+ * **Circuit Breakers (`guards.py`):** Financial and operational risk mitigation logic.
55
+ **Human-in-the-Loop (`hitl.py`)** - Managed intervention state.
56
+ * **The Executive Loop (`agent.py`):** A "Think-Guard-Act" orchestration engine.
57
+
58
+ ### 🛠️ In Active Development
59
+ * **Standardized Tool Registry:** A type-safe way to map business functions to agent capabilities.
60
+ * **Mock Model Client:** A testing utility to simulate LLM responses without incurring API costs.
61
+ * **HITL Connectors:** Initial hooks for manual approval via CLI.
62
+
63
+ ## 📖 Usage Example: Controlled Execution
64
+
65
+ GovAgent allows you to wrap any AI task in a protective governance layer. Here is how you enforce a $0.50 budget on a research task:
66
+
67
+ ```python
68
+ from govagent import ExecutiveAgent, Policy
69
+
70
+ # Load your enterprise SOP
71
+ policy = Policy.from_yaml("market_research_policy.yaml")
72
+
73
+ # Run the agent with real-time circuit breakers
74
+ agent = ExecutiveAgent(persona="Analyst", policy=policy, model_client=my_llm)
75
+ report = await agent.execute("Research competitor pricing")
76
+
77
+ print(f"Audit Trace: {report.audit_id}")
78
+ print(f"Budget Consumed: ${report.estimated_cost_usd}")
79
+
80
+ ### 💡 Call for Contributions & Ideas
81
+ We are looking for collaborators to help build:
82
+ 1. **Cloud Adapters:** Exporting `telemetry.py` logs to AWS CloudWatch or Azure Monitor.
83
+ 2. **Standard Policies:** Pre-built `policy.yaml` templates for common roles (e.g., "Safe Research", "Data Entry", "Code Review").
84
+ 3. **Reasoning Visualizers:** A tool to turn the Audit Trail JSON into a readable PDF report for non-technical stakeholders.
85
+
86
+ ---
87
+ **"Governance is not a constraint; it is the catalyst for enterprise AI adoption."**
88
+ ---
@@ -0,0 +1,74 @@
1
+ # GovAgent: The Enterprise Protocol for Agentic AI
2
+
3
+ **The Governance-First Framework for Production-Grade Autonomous Systems.**
4
+
5
+ `GovAgent` is a high-abstraction, lightweight Python framework designed to bridge the gap between experimental AI and business-critical operations.
6
+
7
+ ## 🎯 Value Proposition
8
+ In high-stakes environments, the barrier to AI adoption is **reliability and control**. `GovAgent` ensures every action is transparent, budget-aware, and risk-managed.
9
+
10
+ * **Active Circuit Breakers:** Real-time enforcement of financial and operational limits.
11
+ * **Governance-as-Code:** Human-readable permission manifests (`policy.yaml`) that align technical execution with organizational policy.
12
+ * **Forensic Telemetry:** Standardized audit logs and ROI projections (USD saved vs. USD spent).
13
+ * **Zero-Trust Tooling:** Strict whitelisting for agent actions and domain access.
14
+
15
+ ---
16
+
17
+ ## 🏗️ Core Pillars
18
+
19
+ ### 1. The Governance Manifest (`policy.yaml`)
20
+ Define "Rules of Engagement" outside the codebase. This allows stakeholders to review and approve agent permissions.
21
+ * **Financial Guardrails:** Hard limits on USD spend per session.
22
+ * **Action Scopes:** Explicit whitelisting of approved tools.
23
+ * **Escalation Triggers:** Thresholds for Human-in-the-Loop (HITL) intervention.
24
+
25
+ ### 2. Forensic Telemetry (`telemetry.py`)
26
+ Every execution generates a **Business Value Summary**:
27
+ * **ROI Projection:** Estimated manual human-hours saved.
28
+ * **Audit Chain:** A verifiable history of every decision, tool call, and result.
29
+
30
+ ---
31
+
32
+ # GovAgent: Enterprise-Grade Agentic Governance
33
+
34
+ ## 🚧 Development Status (WIP)
35
+ **GovAgent is rapidly evolving.** We are currently moving from architectural design to core module implementation.
36
+
37
+ ### ✅ Completed Modules
38
+ * **Governance Manifest (`policy.py`):** Structured YAML-based policy enforcement.
39
+ * **Forensic Telemetry (`telemetry.py`):** Real-time ROI and audit trail generation.
40
+ * **Circuit Breakers (`guards.py`):** Financial and operational risk mitigation logic.
41
+ **Human-in-the-Loop (`hitl.py`)** - Managed intervention state.
42
+ * **The Executive Loop (`agent.py`):** A "Think-Guard-Act" orchestration engine.
43
+
44
+ ### 🛠️ In Active Development
45
+ * **Standardized Tool Registry:** A type-safe way to map business functions to agent capabilities.
46
+ * **Mock Model Client:** A testing utility to simulate LLM responses without incurring API costs.
47
+ * **HITL Connectors:** Initial hooks for manual approval via CLI.
48
+
49
+ ## 📖 Usage Example: Controlled Execution
50
+
51
+ GovAgent allows you to wrap any AI task in a protective governance layer. Here is how you enforce a $0.50 budget on a research task:
52
+
53
+ ```python
54
+ from govagent import ExecutiveAgent, Policy
55
+
56
+ # Load your enterprise SOP
57
+ policy = Policy.from_yaml("market_research_policy.yaml")
58
+
59
+ # Run the agent with real-time circuit breakers
60
+ agent = ExecutiveAgent(persona="Analyst", policy=policy, model_client=my_llm)
61
+ report = await agent.execute("Research competitor pricing")
62
+
63
+ print(f"Audit Trace: {report.audit_id}")
64
+ print(f"Budget Consumed: ${report.estimated_cost_usd}")
65
+
66
+ ### 💡 Call for Contributions & Ideas
67
+ We are looking for collaborators to help build:
68
+ 1. **Cloud Adapters:** Exporting `telemetry.py` logs to AWS CloudWatch or Azure Monitor.
69
+ 2. **Standard Policies:** Pre-built `policy.yaml` templates for common roles (e.g., "Safe Research", "Data Entry", "Code Review").
70
+ 3. **Reasoning Visualizers:** A tool to turn the Audit Trail JSON into a readable PDF report for non-technical stakeholders.
71
+
72
+ ---
73
+ **"Governance is not a constraint; it is the catalyst for enterprise AI adoption."**
74
+ ---
@@ -0,0 +1,43 @@
1
+ import asyncio
2
+ from govagent.agent import ExecutiveAgent
3
+ from govagent.policy import Policy
4
+ from govagent.telemetry import TelemetryManager
5
+
6
+ # Mock Model Client for demonstration (No API key needed)
7
+ class MockModel:
8
+ async def generate_plan(self, task, persona):
9
+ # Simulating a thought process and an action
10
+ return (
11
+ "I need to search for Q4 trends but the cost is rising.",
12
+ "web_search",
13
+ {"query": "2026 tech trends", "source": "verified-news.com"}
14
+ )
15
+
16
+ async def main():
17
+ # 1. Load the Governance Policy
18
+ policy = Policy.from_yaml("examples/policy.yaml")
19
+
20
+ # 2. Initialize Telemetry and Agent
21
+ telemetry = TelemetryManager()
22
+ agent = ExecutiveAgent(
23
+ persona="Strategic Analyst",
24
+ policy=policy,
25
+ model_client=MockModel(),
26
+ telemetry=telemetry
27
+ )
28
+
29
+ print("--- Starting Governed Task ---")
30
+
31
+ # 3. Execute Task
32
+ # This will trigger the Think -> Guard -> Act cycle
33
+ result = await agent.execute("Analyze upcoming 2026 AI market shifts.")
34
+
35
+ # 4. Review the Executive Summary
36
+ print("\n--- Execution Summary ---")
37
+ print(f"Status: {result.status}")
38
+ print(f"Final Cost: ${result.estimated_cost_usd:.4f}")
39
+ print(f"Human Labor Saved: {result.human_minutes_saved} minutes")
40
+ print(f"Audit ID: {result.trace_id}")
41
+
42
+ if __name__ == "__main__":
43
+ asyncio.run(main())
@@ -0,0 +1,19 @@
1
+ version: "1.0"
2
+ agent_name: "MarketAnalyst"
3
+
4
+ # Financial Guardrails
5
+ max_spend_usd: 0.50 # Low limit to demonstrate the circuit breaker
6
+
7
+ # Action Scopes
8
+ allowed_tools:
9
+ - "web_search"
10
+ - "internal_db_query"
11
+ - "generate_summary"
12
+
13
+ restricted_domains:
14
+ - "competitor-alpha.com"
15
+ - "unverified-leak-site.org"
16
+
17
+ # Escalation
18
+ require_human_approval: true
19
+ confidence_threshold: 0.90
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "govagent"
7
+ version = "0.1.0"
8
+ description = "The Governance-First Framework for Agentic AI"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {text = "MIT"}
12
+ authors = [
13
+ {name = "Your Name", email = ""}
14
+ ]
15
+ keywords = ["ai", "agents", "governance", "roi", "enterprise"]
16
+ dependencies = [
17
+ "pydantic>=2.0.0",
18
+ "pyyaml>=6.0.0",
19
+ "httpx>=0.25.0", # Async-ready for modern LLM APIs
20
+ ]
21
+
22
+ [project.urls]
23
+ "Homepage" = "https://github.com/thekakodkar/govagent"
File without changes
@@ -0,0 +1,73 @@
1
+ from typing import List, Optional, Any
2
+ from govagent.policy import Policy
3
+ from govagent.guards import CircuitBreaker, GovernanceViolation
4
+ from govagent.telemetry import TelemetryManager
5
+
6
+ class ExecutiveAgent:
7
+ """
8
+ The core execution engine. Orchestrates reasoning while
9
+ enforcing governance constraints in real-time.
10
+ """
11
+ def __init__(
12
+ self,
13
+ persona: str,
14
+ policy: Policy,
15
+ model_client: Any,
16
+ telemetry: Optional[TelemetryManager] = None
17
+ ):
18
+ self.persona = persona
19
+ self.policy = policy
20
+ self.model = model_client
21
+ self.guard = CircuitBreaker(policy)
22
+ self.telemetry = telemetry or TelemetryManager()
23
+
24
+ async def execute(self, task: str):
25
+ """
26
+ The 'Governed Reasoning' Loop: Think -> Guard -> Act -> Record.
27
+ """
28
+ self.telemetry.start_trace(self.persona, task)
29
+ current_step = 0
30
+ max_steps = 10 # Safety ceiling
31
+
32
+ try:
33
+ while current_step < max_steps:
34
+ # 1. Financial Guard Check
35
+ self.guard.check_financial_risk(self.telemetry.current_session.estimated_cost_usd)
36
+
37
+ # 2. Reasoning Phase (LLM Call)
38
+ # Note: This is a conceptual representation of the LLM interaction
39
+ thought, action, params = await self.model.generate_plan(task, self.persona)
40
+
41
+ # 3. Action Validation Guard
42
+ # Intercept the intent before execution
43
+ self.guard.validate_action(action, params)
44
+
45
+ # 4. Human-in-the-Loop Check
46
+ if self.guard.assess_confidence(0.9) == "ESCALATE_TO_HUMAN":
47
+ # Placeholder for HITL protocol (Slack/Teams)
48
+ return "Pending Human Approval"
49
+
50
+ # 5. Execution & Logging
51
+ result = await self.perform_action(action, params)
52
+ self.telemetry.log_step(thought, action, result)
53
+
54
+ if self.is_task_complete(result):
55
+ break
56
+
57
+ current_step += 1
58
+
59
+ return self.telemetry.finalize(status="success", tokens=1200) # Mock token count
60
+
61
+ except GovernanceViolation as gv:
62
+ # Operationalize the error: Log the violation and stop
63
+ return self.telemetry.finalize(status=f"blocked: {str(gv)}", tokens=500)
64
+ except Exception as e:
65
+ return self.telemetry.finalize(status=f"error: {str(e)}", tokens=0)
66
+
67
+ async def perform_action(self, action: str, params: dict):
68
+ """Placeholder for actual tool execution logic."""
69
+ return f"Executed {action} with success."
70
+
71
+ def is_task_complete(self, result: str) -> bool:
72
+ """Logic to determine if the agent has reached its goal."""
73
+ return "complete" in result.lower()
@@ -0,0 +1,43 @@
1
+ from typing import Any, Dict
2
+ from govagent.policy import Policy
3
+ from govagent.telemetry import ExecutionSnapshot
4
+
5
+ class GovernanceViolation(Exception):
6
+ """Custom exception for audit-ready error handling."""
7
+ pass
8
+
9
+ class CircuitBreaker:
10
+ """
11
+ Real-time enforcement of the Governance Manifest.
12
+ """
13
+ def __init__(self, policy: Policy):
14
+ self.policy = policy
15
+
16
+ def check_financial_risk(self, current_spend: float):
17
+ """Prevents further execution if budget is exceeded."""
18
+ if current_spend >= self.policy.max_spend_usd:
19
+ raise GovernanceViolation(
20
+ f"Budget Exceeded: Current spend ${current_spend:.4f} "
21
+ f"exceeds limit of ${self.policy.max_spend_usd}"
22
+ )
23
+
24
+ def validate_action(self, tool_name: str, parameters: Dict[str, Any]):
25
+ """
26
+ Validates the intended action against the whitelist
27
+ and inspects for restricted domains.
28
+ """
29
+ # Whitelist check
30
+ if tool_name not in self.policy.allowed_tools:
31
+ raise GovernanceViolation(f"Unauthorized Tool: {tool_name} is not in the allowed manifest.")
32
+
33
+ # Restricted domain check (e.g., blocking specific URLs or IPs)
34
+ for domain in self.policy.restricted_domains:
35
+ if any(domain in str(val) for val in parameters.values()):
36
+ raise GovernanceViolation(f"Access Denied: Parameter contains restricted domain '{domain}'")
37
+
38
+ def assess_confidence(self, score: float):
39
+ """Forces Human-in-the-Loop if AI confidence is low."""
40
+ if score < self.policy.confidence_threshold:
41
+ # In a production loop, this would trigger the HITL protocol
42
+ return "ESCALATE_TO_HUMAN"
43
+ return "PROCEED"
File without changes
@@ -0,0 +1,26 @@
1
+ import yaml
2
+ from pydantic import BaseModel, Field
3
+ from typing import List, Optional
4
+
5
+ class Policy(BaseModel):
6
+ """The Governance Manifest schema for enterprise control."""
7
+ version: str = "1.0"
8
+ agent_name: str
9
+
10
+ # Financial Guardrails
11
+ max_spend_usd: float = Field(default=1.0, description="Hard limit for API costs")
12
+
13
+ # Action Scopes
14
+ allowed_tools: List[str] = Field(default_factory=list)
15
+ restricted_domains: List[str] = Field(default_factory=list)
16
+
17
+ # Escalation
18
+ require_human_approval: bool = True
19
+ confidence_threshold: float = 0.85
20
+
21
+ @classmethod
22
+ def from_yaml(cls, file_path: str):
23
+ """Standardizes the loading of governance policies from YAML files."""
24
+ with open(file_path, "r") as f:
25
+ data = yaml.safe_load(f)
26
+ return cls(**data)
@@ -0,0 +1,85 @@
1
+ import time
2
+ import uuid
3
+ from datetime import datetime
4
+ from typing import Dict, Any, Optional
5
+ from pydantic import BaseModel, Field
6
+
7
+ class ExecutionSnapshot(BaseModel):
8
+ """
9
+ A single point-in-time record of an agent's activity.
10
+ Designed for export to JSON/CSV for compliance reporting.
11
+ """
12
+ trace_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
13
+ timestamp: str = Field(default_factory=lambda: datetime.utcnow().isoformat())
14
+ agent_role: str
15
+ task_input: str
16
+
17
+ # Financial Metrics
18
+ estimated_cost_usd: float = 0.0
19
+ tokens_used: int = 0
20
+
21
+ # Performance Metrics
22
+ latency_seconds: float = 0.0
23
+ status: str = "initiated" # initiated, success, failed, human_intervention_required
24
+
25
+ # Business ROI Logic
26
+ human_minutes_saved: float = 0.0
27
+
28
+ # Audit Trail
29
+ reasoning_steps: list = []
30
+
31
+ class TelemetryManager:
32
+ """
33
+ Handles the collection and persistence of execution data.
34
+ Can be extended to push logs to CloudWatch, ELK, or a SQL DB.
35
+ """
36
+ def __init__(self, output_path: Optional[str] = "logs/audit_trail.json"):
37
+ self.output_path = output_path
38
+ self.current_session: Optional[ExecutionSnapshot] = None
39
+ self._start_time: float = 0.0
40
+
41
+ def start_trace(self, agent_role: str, task: str):
42
+ """Starts the 'stopwatch' for a specific agent task."""
43
+ self._start_time = time.perf_counter()
44
+ self.current_session = ExecutionSnapshot(
45
+ agent_role=agent_role,
46
+ task_input=task
47
+ )
48
+
49
+ def log_step(self, thought: str, action: str, result: str):
50
+ """Appends a reasoning step to the audit trail."""
51
+ if self.current_session:
52
+ step = {
53
+ "timestamp": datetime.utcnow().isoformat(),
54
+ "thought": thought,
55
+ "action": action,
56
+ "result": result
57
+ }
58
+ self.current_session.reasoning_steps.append(step)
59
+
60
+ def finalize(self, status: str, tokens: int, cost_per_1k: float = 0.02):
61
+ """
62
+ Calculates final ROI and latency.
63
+ In a real scenario, cost_per_1k would be dynamic based on the model used.
64
+ """
65
+ if not self.current_session:
66
+ return
67
+
68
+ self.current_session.latency_seconds = round(time.perf_counter() - self._start_time, 2)
69
+ self.current_session.status = status
70
+ self.current_session.tokens_used = tokens
71
+ self.current_session.estimated_cost_usd = (tokens / 1000) * cost_per_1k
72
+
73
+ # Simple heuristic for ROI: Assumes 1 min of human labor saved for every 5 tokens
74
+ # (This logic can be customized per use case)
75
+ self.current_session.human_minutes_saved = round(tokens / 50, 2)
76
+
77
+ self._persist_log()
78
+ return self.current_session
79
+
80
+ def _persist_log(self):
81
+ """Writes to a local file—first step toward a full database integration."""
82
+ if self.output_path and self.current_session:
83
+ # Here you would implement logic to append to a file or database
84
+ # For a 'Lite' version, logging to a standard JSONL file is often best.
85
+ pass