maos-agent 0.1.1__py3-none-any.whl → 0.1.2__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.
maos_agent/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .core import MaosAgent
2
+ from .lifecycle import SpotInterruptionError
3
+
4
+ __all__ = ["MaosAgent", "SpotInterruptionError"]
maos_agent/core.py ADDED
@@ -0,0 +1,30 @@
1
+ from .metrics import MetricsManager
2
+ from .lifecycle import LifecycleManager
3
+ from .decorators import TaskContext, instrument_tool
4
+
5
+ class MaosAgent:
6
+ def __init__(self, service_name: str, version: str = "v1.0", metrics_port: int = 8000):
7
+ self.service_name = service_name
8
+ self.metrics = MetricsManager(service_name, version, metrics_port)
9
+ self.lifecycle = LifecycleManager()
10
+
11
+ def check_health(self):
12
+ """
13
+ Proxy to lifecycle check.
14
+ Raises SpotInterruptionError if the node is dying.
15
+ """
16
+ self.lifecycle.check_health()
17
+
18
+ def tool(self, name: str = None):
19
+ """
20
+ Decorator to track tool usage automatically.
21
+ Usage: @agent.tool(name="search")
22
+ """
23
+ return instrument_tool(self.metrics, name)
24
+
25
+ def task(self, name: str):
26
+ """
27
+ Context manager for the main job loop.
28
+ Usage: with agent.task("analyze") as task: ...
29
+ """
30
+ return TaskContext(self.metrics, name)
@@ -0,0 +1,63 @@
1
+ import functools
2
+ import time
3
+ import logging
4
+
5
+ # We import metrics inside the methods to avoid circular imports
6
+ # or we pass the metrics manager object into these classes.
7
+
8
+ class TaskContext:
9
+ """
10
+ Context manager for a unit of work (Task).
11
+ Tracks duration, step count, and final success/failure status.
12
+ """
13
+ def __init__(self, metrics, name: str):
14
+ self.metrics = metrics
15
+ self.name = name
16
+ self.start_time = time.time()
17
+ self.steps = 0
18
+ self.logger = logging.getLogger("maos.agent")
19
+
20
+ def __enter__(self):
21
+ self.logger.info(f"Starting task: {self.name}")
22
+ return self
23
+
24
+ def step(self):
25
+ """
26
+ Record a 'cognitive step' (e.g., one LLM thought loop).
27
+ """
28
+ self.steps += 1
29
+
30
+ def __exit__(self, exc_type, exc_val, exc_tb):
31
+ duration = time.time() - self.start_time
32
+ status = "error" if exc_type else "success"
33
+
34
+ self.metrics.record_task_success(self.name, status)
35
+ self.metrics.record_steps(self.name, self.steps)
36
+ self.metrics.record_duration(self.name, duration)
37
+
38
+ if exc_type:
39
+ self.logger.error(f"Task '{self.name}' failed: {exc_val}")
40
+
41
+
42
+ def instrument_tool(metrics, name: str = None):
43
+ """
44
+ Factory that returns the actual decorator.
45
+ We pass 'metrics' (the manager instance) in so the decorator knows where to record.
46
+ """
47
+ def decorator(func):
48
+ # Use the provided name or default to the function name
49
+ tool_name = name or func.__name__
50
+
51
+ @functools.wraps(func)
52
+ def wrapper(*args, **kwargs):
53
+ try:
54
+ result = func(*args, **kwargs)
55
+ # Record Success
56
+ metrics.record_tool(tool_name, status="success")
57
+ return result
58
+ except Exception as e:
59
+ # Record Failure & Re-raise
60
+ metrics.record_tool(tool_name, status="error")
61
+ raise e
62
+ return wrapper
63
+ return decorator
@@ -0,0 +1,28 @@
1
+ import signal
2
+ import sys
3
+ import logging
4
+
5
+ class SpotInterruptionError(Exception):
6
+ """Raised when the environment signals a shutdown."""
7
+ pass
8
+
9
+ class LifecycleManager:
10
+ def __init__(self):
11
+ self.should_exit = False
12
+ self.logger = logging.getLogger("maos.lifecycle")
13
+
14
+ # Register the signal handlers
15
+ signal.signal(signal.SIGTERM, self._handle_sigterm)
16
+ signal.signal(signal.SIGINT, self._handle_sigterm) # Handle Ctrl+C locally too
17
+
18
+ def _handle_sigterm(self, signum, frame):
19
+ self.logger.warning("⚠️ SIGTERM received from Kubernetes! Node is draining.")
20
+ self.should_exit = True
21
+
22
+ def check_health(self):
23
+ """
24
+ Call this inside your agent loop.
25
+ If a kill signal was received, it raises an exception to break the loop safely.
26
+ """
27
+ if self.should_exit:
28
+ raise SpotInterruptionError("Spot Instance Reclaim Imminent")
maos_agent/metrics.py ADDED
@@ -0,0 +1,65 @@
1
+ from prometheus_client import Counter, Histogram, start_http_server
2
+ import time
3
+
4
+ # --- Metric Definitions (Must match Grafana Queries) ---
5
+
6
+ # Histogram: maos_agent_task_duration_seconds
7
+ TASK_DURATION = Histogram(
8
+ 'maos_agent_task_duration_seconds',
9
+ 'Time spent executing the agent task',
10
+ ['task_type', 'service_name', 'version']
11
+ )
12
+
13
+ # Counter: maos_agent_tool_calls_total
14
+ TOOL_CALLS = Counter(
15
+ 'maos_agent_tool_calls_total',
16
+ 'Total number of tool invocations',
17
+ ['tool_name', 'status', 'service_name', 'version']
18
+ )
19
+
20
+ # Counter: maos_agent_token_usage_total
21
+ TOKEN_USAGE = Counter(
22
+ 'maos_agent_token_usage_total',
23
+ 'Total LLM tokens consumed',
24
+ ['model', 'type', 'service_name', 'version']
25
+ )
26
+
27
+ # Histogram: maos_agent_steps_per_goal
28
+ STEPS_PER_GOAL = Histogram(
29
+ 'maos_agent_steps_per_goal',
30
+ 'Number of cognitive steps taken to solve a goal',
31
+ ['task_type', 'service_name', 'version'],
32
+ buckets=[1, 3, 5, 10, 20, 50] # Optimized for "Loop of Death" detection
33
+ )
34
+
35
+ # Counter: maos_agent_task_success_total
36
+ TASK_SUCCESS = Counter(
37
+ 'maos_agent_task_success_total',
38
+ 'Total task completions',
39
+ ['task_type', 'status', 'service_name', 'version']
40
+ )
41
+
42
+ class MetricsManager:
43
+ def __init__(self, service_name: str, version: str = "v1", port: int = 8000):
44
+ self.labels = {"service_name": service_name, "version": version}
45
+ # Start the Prometheus exporter server automatically
46
+ try:
47
+ start_http_server(port)
48
+ print(f"[Maosproject] Metrics server started on port {port}")
49
+ except Exception as e:
50
+ print(f"[Maosproject] Warning: Could not start metrics server: {e}")
51
+
52
+ def record_tool(self, tool_name: str, status: str = "success"):
53
+ TOOL_CALLS.labels(tool_name=tool_name, status=status, **self.labels).inc()
54
+
55
+ def record_tokens(self, count: int, model: str = "unknown", type: str = "total"):
56
+ TOKEN_USAGE.labels(model=model, type=type, **self.labels).inc(count)
57
+
58
+ def record_task_success(self, task_type: str, status: str):
59
+ TASK_SUCCESS.labels(task_type=task_type, status=status, **self.labels).inc()
60
+
61
+ def record_duration(self, task_type: str, seconds: float):
62
+ TASK_DURATION.labels(task_type=task_type, **self.labels).observe(seconds)
63
+
64
+ def record_steps(self, task_type: str, count: int):
65
+ STEPS_PER_GOAL.labels(task_type=task_type, **self.labels).observe(count)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: maos-agent
3
- Version: 0.1.1
3
+ Version: 0.1.2
4
4
  Summary: The Observability & Resilience SDK for Maos AI Agents
5
5
  Project-URL: Homepage, https://github.com/maosproject-dev/maos-agent
6
6
  Project-URL: Bug Tracker, https://github.com/maosproject-dev/maos-agent/issues
@@ -14,16 +14,6 @@ Requires-Python: >=3.9
14
14
  Requires-Dist: prometheus-client>=0.17.0
15
15
  Description-Content-Type: text/markdown
16
16
 
17
- **CTO here.**
18
-
19
- Here is the `README.md`.
20
-
21
- It is written to be "Marketing-Engineering" aligned. It doesn't just say *how* to use it; it explains *why* a developer needs it (to stop their agents from dying silently on Spot instances).
22
-
23
- I’ve added badges, a clear "Quick Start," and a section linking the metrics directly to the Grafana dashboard we just built.
24
-
25
- ---
26
-
27
17
  # Maos Agent SDK
28
18
 
29
19
  The official Python SDK for building resilient, observable AI Agents on the **Maos Platform**.
@@ -0,0 +1,9 @@
1
+ maos_agent/__init__.py,sha256=VS0Tmmk8fzdrtu0XISOgjVqJpkOACzgoE9JPPkWtcL0,122
2
+ maos_agent/core.py,sha256=KIgPkCFHJAKvX140GzpRQZMgKA9UrofIeF8lv6gTYD0,997
3
+ maos_agent/decorators.py,sha256=7OFy8BPTZJqP3dH-Pq7ZMHvEK3BFQcP25Y5osO8Bnxk,2012
4
+ maos_agent/lifecycle.py,sha256=RIJzRUyfxX9tMc_A-IQtgFFhJF2GyC0xUE5RVtgQ_Ko,937
5
+ maos_agent/metrics.py,sha256=9KSTHx87-3G0EqBExirDUTq4oYYxhXoLnLkmyQaFPh4,2414
6
+ maos_agent-0.1.2.dist-info/METADATA,sha256=ZXE2uXmokk3Y51WoTHZSSGQnFUpSjmSCSWtZ1NdzFIo,4713
7
+ maos_agent-0.1.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
8
+ maos_agent-0.1.2.dist-info/licenses/LICENSE,sha256=pSwPJCJHLTj7MzXnoRrLL1a9wblFZoynxjBdlHvkv3E,1071
9
+ maos_agent-0.1.2.dist-info/RECORD,,
@@ -1,4 +0,0 @@
1
- maos_agent-0.1.1.dist-info/METADATA,sha256=3twBguo0DN6Q18gcBemuegbbesOq3WTwtXPA-YXUbCQ,5079
2
- maos_agent-0.1.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
3
- maos_agent-0.1.1.dist-info/licenses/LICENSE,sha256=pSwPJCJHLTj7MzXnoRrLL1a9wblFZoynxjBdlHvkv3E,1071
4
- maos_agent-0.1.1.dist-info/RECORD,,