hiveloop 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,448 @@
1
+ Metadata-Version: 2.4
2
+ Name: hiveloop
3
+ Version: 0.1.0
4
+ Summary: Lightweight observability SDK for AI agents
5
+ Project-URL: Homepage, https://hiveboard.io
6
+ Project-URL: Documentation, https://docs.hiveboard.io
7
+ Project-URL: Repository, https://github.com/hiveboard/hiveloop
8
+ Keywords: ai,agents,observability,monitoring,llm,telemetry
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Classifier: Topic :: System :: Monitoring
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ Requires-Dist: requests>=2.31.0
20
+
21
+ # HiveLoop
22
+
23
+ **Lightweight observability SDK for AI agents.**
24
+
25
+ HiveLoop instruments your AI agents with 3 lines of code and sends structured telemetry to [HiveBoard](https://hiveboard.io) -- giving you heartbeat monitoring, task timelines, LLM cost tracking, plan progress, queue visibility, and issue detection without changing how your agents work.
26
+
27
+ ```python
28
+ import hiveloop
29
+
30
+ hb = hiveloop.init(api_key="hb_live_...")
31
+ agent = hb.agent("lead-qualifier", type="sales")
32
+ ```
33
+
34
+ Your agent is now visible on the HiveBoard dashboard. Green dot = alive. Red dot = something's wrong. No logs to check.
35
+
36
+ ## Why HiveLoop?
37
+
38
+ AI agents fail silently. A credential expires, a queue backs up, a task hangs -- and nobody notices until a customer complains. HiveLoop makes these failures visible in seconds, not hours.
39
+
40
+ - **Heartbeat monitoring** -- know instantly when an agent stops responding
41
+ - **Task timelines** -- see every step an agent took, which tool failed, and why
42
+ - **LLM cost tracking** -- know exactly what each model call costs, per agent, per task
43
+ - **Plan progress** -- track multi-step plans and see where they diverge
44
+ - **Queue visibility** -- see what work is waiting and what's stuck
45
+ - **Issue detection** -- agents can self-report problems with recurrence tracking
46
+ - **Human-in-the-loop** -- track escalations and approval workflows
47
+
48
+ ## Installation
49
+
50
+ ```bash
51
+ pip install hiveloop
52
+ ```
53
+
54
+ Requires Python 3.11+. Only dependency: `requests`.
55
+
56
+ ## Quick Start
57
+
58
+ ### Layer 0: Presence (3 lines)
59
+
60
+ Register your agent. HiveBoard will show it as alive with heartbeat monitoring.
61
+
62
+ ```python
63
+ import hiveloop
64
+
65
+ hb = hiveloop.init(api_key="hb_live_...")
66
+ agent = hb.agent("my-agent", type="support", version="1.0.0")
67
+
68
+ # Your agent code runs here. Heartbeats are sent automatically.
69
+ # When you're done:
70
+ hiveloop.shutdown()
71
+ ```
72
+
73
+ **What you see on HiveBoard:** Agent card with name, type, status badge, heartbeat indicator.
74
+
75
+ ### Layer 1: Task Timelines (add context managers)
76
+
77
+ Track tasks to get success rates, durations, throughput, and failure diagnostics.
78
+
79
+ ```python
80
+ with agent.task("task-001", project="sales-pipeline", type="lead_qualification") as task:
81
+ lead = fetch_crm_data("lead-4821")
82
+ score = score_lead(lead)
83
+ route_lead(score)
84
+ ```
85
+
86
+ The task auto-completes on exit. If an exception is raised, it auto-fails with the exception details. Exceptions are never swallowed.
87
+
88
+ **What you see:** Task table, success rates, duration averages, throughput charts.
89
+
90
+ ### Layer 2: Full Story (add rich events)
91
+
92
+ Add LLM call tracking, plans, queue snapshots, and issue reporting for complete observability.
93
+
94
+ ```python
95
+ with agent.task("task-001", project="sales-pipeline") as task:
96
+ # Track LLM calls with cost data
97
+ task.llm_call(
98
+ "lead_scoring",
99
+ "claude-sonnet-4-20250514",
100
+ tokens_in=1800,
101
+ tokens_out=250,
102
+ cost=0.004,
103
+ duration_ms=1200,
104
+ prompt_preview="Score this lead based on...",
105
+ response_preview="Score: 72. Reasoning: ...",
106
+ )
107
+
108
+ # Track multi-step plans
109
+ task.plan("Process lead", ["Fetch CRM", "Score", "Enrich", "Route"])
110
+ task.plan_step(0, "completed", "CRM data retrieved", turns=1, tokens=800)
111
+ task.plan_step(1, "completed", "Lead scored 72", turns=2, tokens=3200)
112
+ task.plan_step(2, "failed", "Enrichment API timeout")
113
+
114
+ # Escalate when needed
115
+ task.escalate("Enrichment service down", reason="service_outage")
116
+
117
+ # Request human approval
118
+ task.request_approval("Credit $450 for customer BlueStar?", approver="sales-lead")
119
+ ```
120
+
121
+ **What you see:** Cost explorer, task timelines with LLM nodes, plan progress bars, escalation tracking.
122
+
123
+ ## Action Tracking
124
+
125
+ Track individual functions with the `@agent.track` decorator. Supports both sync and async functions, with automatic nesting.
126
+
127
+ ```python
128
+ @agent.track("fetch_crm_data")
129
+ def fetch_crm_data(lead_id):
130
+ return crm_client.get_lead(lead_id)
131
+
132
+ @agent.track("enrich_company")
133
+ async def enrich_company(company_name):
134
+ return await enrichment_api.lookup(company_name)
135
+
136
+ @agent.track("process_lead")
137
+ def process_lead(lead_id):
138
+ lead = fetch_crm_data(lead_id) # Nested action
139
+ company = enrich_company(lead.company) # Nested action
140
+ return score(lead, company)
141
+
142
+ with agent.task("task-001") as task:
143
+ result = process_lead("lead-4821")
144
+ ```
145
+
146
+ Each tracked function emits `action_started` and `action_completed` (or `action_failed`) events with duration. Nesting is tracked automatically -- `fetch_crm_data` and `enrich_company` show as children of `process_lead` in the timeline.
147
+
148
+ For inline tracking without decorators:
149
+
150
+ ```python
151
+ with agent.track_context("data_processing") as action:
152
+ items = process_batch(data)
153
+ action.set_payload({"items_processed": len(items)})
154
+ ```
155
+
156
+ ## Agent-Level Features
157
+
158
+ ### Queue Monitoring
159
+
160
+ Report your agent's work queue so HiveBoard can detect backed-up or abandoned work.
161
+
162
+ ```python
163
+ # Manual snapshot
164
+ agent.queue_snapshot(
165
+ depth=5,
166
+ oldest_age_seconds=120,
167
+ items=[
168
+ {"id": "lead-100", "priority": "high", "source": "inbound"},
169
+ {"id": "lead-101", "priority": "normal", "source": "referral"},
170
+ ],
171
+ )
172
+
173
+ # Or use automatic reporting via callback (emits with each heartbeat)
174
+ def get_queue():
175
+ return {"depth": len(my_queue), "oldest_age_seconds": my_queue.oldest_age()}
176
+
177
+ agent = hb.agent("my-agent", queue_provider=get_queue)
178
+ ```
179
+
180
+ ### Issue Reporting
181
+
182
+ Agents can self-report problems. HiveBoard tracks recurrence.
183
+
184
+ ```python
185
+ agent.report_issue(
186
+ "CRM API returning 403",
187
+ severity="high",
188
+ issue_id="crm-auth-failure",
189
+ category="permissions",
190
+ context={"endpoint": "/api/leads", "status_code": 403},
191
+ occurrence_count=8,
192
+ )
193
+
194
+ # Later, when resolved:
195
+ agent.resolve_issue("CRM credentials rotated", issue_id="crm-auth-failure")
196
+ ```
197
+
198
+ ### TODO Tracking
199
+
200
+ Track work items that agents create for themselves or for humans.
201
+
202
+ ```python
203
+ agent.todo(
204
+ "todo-001",
205
+ action="created",
206
+ summary="Follow up on failed enrichment for lead-4821",
207
+ priority="high",
208
+ source="failed_action",
209
+ due_by="2026-02-14T15:00:00Z",
210
+ )
211
+
212
+ # When completed:
213
+ agent.todo("todo-001", action="completed", summary="Enrichment retry succeeded")
214
+ ```
215
+
216
+ ### Scheduled Work
217
+
218
+ Report recurring jobs so HiveBoard can show what's coming next.
219
+
220
+ ```python
221
+ agent.scheduled([
222
+ {
223
+ "id": "daily-sync",
224
+ "name": "CRM Full Sync",
225
+ "next_run": "2026-02-14T06:00:00Z",
226
+ "interval": "24h",
227
+ "enabled": True,
228
+ },
229
+ {
230
+ "id": "hourly-check",
231
+ "name": "Lead Queue Check",
232
+ "next_run": "2026-02-13T15:00:00Z",
233
+ "interval": "1h",
234
+ "enabled": True,
235
+ },
236
+ ])
237
+ ```
238
+
239
+ ### Custom Heartbeat Data
240
+
241
+ Include operational metrics in heartbeats so HiveBoard can detect behavioral drift.
242
+
243
+ ```python
244
+ def heartbeat_data():
245
+ return {
246
+ "crm_sync": True,
247
+ "email_check": True,
248
+ "queue_depth": len(my_queue),
249
+ "last_success": last_success_time.isoformat(),
250
+ }
251
+
252
+ agent = hb.agent("my-agent", heartbeat_payload=heartbeat_data)
253
+ ```
254
+
255
+ ## Task Lifecycle
256
+
257
+ ### Context Manager (recommended)
258
+
259
+ ```python
260
+ with agent.task("task-001") as task:
261
+ do_work()
262
+ # Auto-completes on clean exit
263
+ # Auto-fails with exception details if exception is raised
264
+ ```
265
+
266
+ ### Manual Lifecycle
267
+
268
+ For long-running tasks or when you need explicit control:
269
+
270
+ ```python
271
+ task = agent.start_task("task-001", project="sales")
272
+
273
+ try:
274
+ result = do_work()
275
+ task.complete(status="success", payload={"result": result})
276
+ except Exception as e:
277
+ task.fail(exception=e)
278
+ ```
279
+
280
+ ### Setting Payload
281
+
282
+ Attach data to the completion event:
283
+
284
+ ```python
285
+ with agent.task("task-001") as task:
286
+ score = compute_score()
287
+ task.set_payload({"score": score, "threshold": 80, "decision": "nurture"})
288
+ ```
289
+
290
+ ## Approval Workflows
291
+
292
+ Track human-in-the-loop decisions:
293
+
294
+ ```python
295
+ with agent.task("refund-review") as task:
296
+ task.request_approval(
297
+ "Refund $450 for customer BlueStar",
298
+ approver="finance-team",
299
+ )
300
+
301
+ # ... wait for human decision ...
302
+
303
+ task.approval_received(
304
+ "Approved by @jsmith",
305
+ approved_by="jsmith",
306
+ decision="approved",
307
+ )
308
+ ```
309
+
310
+ ## Retry Tracking
311
+
312
+ Make retry behavior visible in task timelines:
313
+
314
+ ```python
315
+ with agent.task("task-001") as task:
316
+ for attempt in range(3):
317
+ try:
318
+ result = call_external_api()
319
+ break
320
+ except TimeoutError:
321
+ task.retry(
322
+ f"API timeout, attempt {attempt + 1}",
323
+ attempt=attempt + 1,
324
+ backoff_seconds=2 ** attempt,
325
+ )
326
+ time.sleep(2 ** attempt)
327
+ ```
328
+
329
+ ## Configuration
330
+
331
+ ### `hiveloop.init()` Parameters
332
+
333
+ | Parameter | Type | Default | Description |
334
+ |---|---|---|---|
335
+ | `api_key` | `str` | **required** | API key (must start with `hb_`) |
336
+ | `environment` | `str` | `"production"` | Environment identifier |
337
+ | `group` | `str` | `"default"` | Organizational group |
338
+ | `endpoint` | `str` | `"https://api.hiveboard.io"` | HiveBoard API endpoint |
339
+ | `flush_interval` | `float` | `5.0` | Seconds between automatic flushes |
340
+ | `batch_size` | `int` | `100` | Max events per batch (capped at 500) |
341
+ | `max_queue_size` | `int` | `10_000` | Max queued events before dropping oldest |
342
+ | `debug` | `bool` | `False` | Enable debug logging |
343
+
344
+ ### `hb.agent()` Parameters
345
+
346
+ | Parameter | Type | Default | Description |
347
+ |---|---|---|---|
348
+ | `agent_id` | `str` | **required** | Unique agent identifier |
349
+ | `type` | `str` | `"general"` | Agent type (e.g., `"sales"`, `"support"`) |
350
+ | `version` | `str \| None` | `None` | Agent version string |
351
+ | `framework` | `str` | `"custom"` | Framework (e.g., `"langchain"`, `"crewai"`) |
352
+ | `heartbeat_interval` | `float` | `30.0` | Seconds between heartbeats (0 to disable) |
353
+ | `stuck_threshold` | `int` | `300` | Seconds before agent is considered stuck |
354
+ | `heartbeat_payload` | `callable` | `None` | Callback returning dict of heartbeat data |
355
+ | `queue_provider` | `callable` | `None` | Callback returning queue state dict |
356
+
357
+ ## How It Works
358
+
359
+ HiveLoop runs a background daemon thread that batches events and sends them to HiveBoard via `POST /v1/ingest`. All SDK calls return immediately -- they never block your agent.
360
+
361
+ - **Non-blocking**: Events are queued in memory and flushed in the background
362
+ - **Thread-safe**: Safe to call from multiple threads. Task context is thread-local
363
+ - **Async-aware**: `@agent.track` works with both sync and async functions
364
+ - **Resilient**: Transport never raises exceptions to your code. Failed sends are retried with exponential backoff (1s, 2s, 4s, 8s, 16s) and silently dropped after 5 retries
365
+ - **Bounded**: Queue has a configurable max size (default 10,000). Oldest events are dropped when full
366
+ - **Graceful**: `hiveloop.shutdown()` flushes all remaining events before exiting. Also registered as an `atexit` handler
367
+
368
+ ## Framework Compatibility
369
+
370
+ HiveLoop is framework-agnostic. It works with:
371
+
372
+ - Plain Python scripts
373
+ - LangChain / LangGraph agents
374
+ - CrewAI crews
375
+ - AutoGen agents
376
+ - Any Python code that runs AI agents
377
+
378
+ No framework-specific adapters needed. Just `import hiveloop` and instrument.
379
+
380
+ ## Self-Hosted
381
+
382
+ Point HiveLoop at your own HiveBoard instance:
383
+
384
+ ```python
385
+ hb = hiveloop.init(
386
+ api_key="hb_live_...",
387
+ endpoint="https://hiveboard.your-company.com",
388
+ )
389
+ ```
390
+
391
+ ## API Reference
392
+
393
+ ### Module-Level Functions
394
+
395
+ ```python
396
+ hiveloop.init(api_key, ...) # Initialize SDK singleton
397
+ hiveloop.shutdown(timeout=5.0) # Shut down and flush
398
+ hiveloop.reset() # Clear singleton for re-initialization
399
+ hiveloop.flush() # Force immediate flush
400
+ ```
401
+
402
+ ### Task Methods
403
+
404
+ ```python
405
+ task.llm_call(name, model, ...) # Record LLM call
406
+ task.plan(goal, steps, revision=0) # Record plan
407
+ task.plan_step(index, action, summary) # Update plan step
408
+ task.escalate(summary, ...) # Escalate to human
409
+ task.request_approval(summary, ...) # Request approval
410
+ task.approval_received(summary, ...) # Record approval
411
+ task.retry(summary, ...) # Record retry
412
+ task.event(event_type, payload, ...) # Custom event
413
+ task.complete(status="success") # Manual complete
414
+ task.fail(exception=None) # Manual fail
415
+ task.set_payload(payload) # Set completion data
416
+ ```
417
+
418
+ ### Agent Methods
419
+
420
+ ```python
421
+ agent.task(task_id, ...) # Create task (context manager)
422
+ agent.start_task(task_id, ...) # Start task (manual lifecycle)
423
+ agent.track(action_name) # Decorator for action tracking
424
+ agent.track_context(action_name) # Context manager for actions
425
+ agent.llm_call(name, model, ...) # Agent-level LLM call
426
+ agent.queue_snapshot(depth, ...) # Report queue state
427
+ agent.todo(todo_id, action, summary, ...) # TODO lifecycle
428
+ agent.scheduled(items) # Scheduled work items
429
+ agent.report_issue(summary, severity, ...) # Report issue
430
+ agent.resolve_issue(summary, ...) # Resolve issue
431
+ agent.event(event_type, payload, ...) # Custom event
432
+ ```
433
+
434
+ ## Instrumentation Layers
435
+
436
+ You don't need to instrument everything on day one. Start small and add depth as needed.
437
+
438
+ | Layer | What You Add | What You See |
439
+ |---|---|---|
440
+ | **Layer 0: Presence** | `hiveloop.init()` + `hb.agent()` | Agent cards, heartbeats, stuck detection |
441
+ | **Layer 1: Timelines** | `agent.task()` + `@agent.track()` | Task table, success rates, durations, action trees |
442
+ | **Layer 2: Full Story** | `task.llm_call()`, `task.plan()`, `agent.report_issue()`, etc. | Cost explorer, plan progress, queue visibility, issue tracking |
443
+
444
+ ## Requirements
445
+
446
+ - Python >= 3.11
447
+ - `requests` >= 2.31.0
448
+ - A HiveBoard instance (cloud or self-hosted)