trodo-python 1.2.0__py3-none-any.whl → 2.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.
trodo/__init__.py CHANGED
@@ -1,35 +1,71 @@
1
1
  """
2
2
  trodo-python — Trodo Analytics SDK for Python
3
3
 
4
- Usage (module-level singleton):
4
+ Quick start (any stack):
5
5
  import trodo
6
- trodo.init(site_id='your-site-id')
7
- user = trodo.for_user('user-123')
8
- user.track('purchase_completed', {'amount': 99.99})
9
-
10
- Usage (class):
11
- from trodo import TrodoClient
12
- client = TrodoClient(site_id='your-site-id')
13
- user = client.for_user('user-123')
14
- user.track('purchase_completed', {'amount': 99.99})
6
+ trodo.init(site_id='your-site-id') # auto-instrument on by default
7
+
8
+ # Anthropic / OpenAI / LangChain / LlamaIndex — nothing else to do.
9
+ with trodo.wrap_agent('customer-support',
10
+ distinct_id=uid, conversation_id=conv) as run:
11
+ result = agent.run(query)
12
+ run.set_output(result)
13
+
14
+ trodo.feedback(run.run_id, satisfaction='positive', rating=5)
15
+
16
+ Raw-HTTP LLM caller (no OTel integration for your client):
17
+ resp = httpx.post(..., json=body).json()
18
+ trodo.track_llm_call(
19
+ model='gemini-2.5-flash', provider='google',
20
+ input_tokens=resp['usageMetadata']['promptTokenCount'],
21
+ output_tokens=resp['usageMetadata']['candidatesTokenCount'],
22
+ prompt=body, completion=resp,
23
+ )
24
+
25
+ Custom tool:
26
+ @trodo.tool()
27
+ def run_funnel_query(team_id, preset): ...
28
+
29
+ Downstream microservice (join the caller's run instead of making a new one):
30
+ # In FastAPI:
31
+ app.middleware('http')(trodo.fastapi_middleware())
32
+
33
+ # Or manually:
34
+ with trodo.join_run(
35
+ run_id=headers['X-Trodo-Run-Id'],
36
+ parent_span_id=headers['X-Trodo-Parent-Span-Id'],
37
+ ):
38
+ ...
15
39
  """
16
40
 
17
41
  from __future__ import annotations
18
42
 
19
- from typing import Any, Dict, List, Optional, Union
43
+ __version__ = "2.1.0"
44
+
45
+ from typing import Any, Callable, Dict, List, Optional, Union
20
46
 
21
47
  from .client import TrodoClient
22
48
  from .user_context import UserContext
23
49
  from .managers.group_manager import GroupProfile
50
+ from .otel.wrap_agent import (
51
+ wrap_agent as _wrap_agent_ctx,
52
+ span as _span_ctx,
53
+ join_run as _join_run_ctx,
54
+ RunHandle,
55
+ SpanHandle,
56
+ )
24
57
  from .types import (
25
58
  ApiResult, ResetResult, WalletAddressResult,
26
- AgentCallProps, ToolUseProps, AgentResponseProps, AgentErrorProps, FeedbackProps,
59
+ FeedbackProps,
27
60
  )
28
61
 
29
62
  __all__ = [
30
63
  "TrodoClient",
31
64
  "UserContext",
32
65
  "GroupProfile",
66
+ "RunHandle",
67
+ "SpanHandle",
68
+ "FeedbackProps",
33
69
  "init",
34
70
  "for_user",
35
71
  "track",
@@ -40,17 +76,23 @@ __all__ = [
40
76
  "disable_auto_events",
41
77
  "flush",
42
78
  "shutdown",
43
- # Agent analytics
44
- "AgentCallProps",
45
- "ToolUseProps",
46
- "AgentResponseProps",
47
- "AgentErrorProps",
48
- "FeedbackProps",
49
- "track_agent_call",
50
- "track_tool_use",
51
- "track_agent_response",
52
- "track_agent_error",
53
- "track_feedback",
79
+ # Agent runs
80
+ "wrap_agent",
81
+ "agent",
82
+ "span",
83
+ "tool",
84
+ "trace",
85
+ "llm",
86
+ "retrieval",
87
+ "join_run",
88
+ "track_llm_call",
89
+ "feedback",
90
+ "get_tracer",
91
+ # Cross-service propagation
92
+ "fastapi_middleware",
93
+ "propagation_headers",
94
+ "current_run_id",
95
+ "current_span_id",
54
96
  ]
55
97
 
56
98
  # ============================================================================
@@ -68,6 +110,10 @@ def _get_client() -> TrodoClient:
68
110
  return _client
69
111
 
70
112
 
113
+ def _maybe_client() -> Optional[TrodoClient]:
114
+ return _client
115
+
116
+
71
117
  def init(
72
118
  site_id: str,
73
119
  api_base: str = "https://sdkapi.trodo.ai",
@@ -79,8 +125,15 @@ def init(
79
125
  auto_events: bool = False,
80
126
  on_error: Optional[Any] = None,
81
127
  debug: bool = False,
128
+ auto_instrument: bool = True,
82
129
  ) -> TrodoClient:
83
- """Initialise the singleton SDK instance."""
130
+ """Initialise the singleton SDK instance.
131
+
132
+ ``auto_instrument=True`` (default) registers OTel adapters for
133
+ Anthropic, OpenAI, LangChain, LlamaIndex, Google Generative AI and
134
+ any other installed opentelemetry-instrumentation-* package, so
135
+ LLM calls emit token/cost spans with no further code.
136
+ """
84
137
  global _client
85
138
  _client = TrodoClient(
86
139
  site_id=site_id,
@@ -93,6 +146,7 @@ def init(
93
146
  auto_events=auto_events,
94
147
  on_error=on_error,
95
148
  debug=debug,
149
+ auto_instrument=auto_instrument,
96
150
  )
97
151
  return _client
98
152
 
@@ -101,7 +155,6 @@ def for_user(
101
155
  distinct_id: str,
102
156
  session_id: Optional[str] = None,
103
157
  ) -> UserContext:
104
- """Return a UserContext bound to the given distinctId."""
105
158
  return _get_client().for_user(distinct_id, session_id)
106
159
 
107
160
 
@@ -111,22 +164,18 @@ def track(
111
164
  properties: Optional[Dict[str, Any]] = None,
112
165
  category: str = "custom",
113
166
  ) -> None:
114
- """Track an event for a user (direct-call pattern)."""
115
167
  _get_client().track(distinct_id, event_name, properties, category)
116
168
 
117
169
 
118
170
  def identify(identify_id: str, session_id: Optional[str] = None) -> UserContext:
119
- """Create or retrieve a UserContext for an identified user. Fires identify API on first call."""
120
171
  return _get_client().identify(identify_id, session_id)
121
172
 
122
173
 
123
174
  def wallet_address(distinct_id: str, wallet_addr: str) -> WalletAddressResult:
124
- """Associate a wallet address with a user."""
125
175
  return _get_client().wallet_address(distinct_id, wallet_addr)
126
176
 
127
177
 
128
178
  def reset(distinct_id: str) -> ResetResult:
129
- """Reset a user's session."""
130
179
  return _get_client().reset(distinct_id)
131
180
 
132
181
 
@@ -139,39 +188,243 @@ def disable_auto_events() -> None:
139
188
 
140
189
 
141
190
  def flush() -> None:
142
- """Flush any queued batch events."""
143
191
  _get_client().flush()
144
192
 
145
193
 
146
194
  def shutdown() -> None:
147
- """Flush, stop timers, and disable auto events."""
148
195
  _get_client().shutdown()
149
196
 
150
197
 
151
198
  # ----------------------------------------------------------------------------
152
- # Agent Analytics — singleton wrappers
199
+ # Agent Runs
153
200
  # ----------------------------------------------------------------------------
154
201
 
155
- def track_agent_call(props: AgentCallProps) -> None:
156
- """Track an LLM invocation / inbound message."""
157
- _get_client().track_agent_call(props)
202
+ def wrap_agent(
203
+ agent_name: str,
204
+ *,
205
+ distinct_id: Optional[str] = None,
206
+ conversation_id: Optional[str] = None,
207
+ parent_run_id: Optional[str] = None,
208
+ metadata: Optional[Dict[str, Any]] = None,
209
+ ) -> _wrap_agent_ctx:
210
+ """Wrap a block as an agent run — returns a context manager yielding RunHandle."""
211
+ return _get_client().wrap_agent(
212
+ agent_name,
213
+ distinct_id=distinct_id,
214
+ conversation_id=conversation_id,
215
+ parent_run_id=parent_run_id,
216
+ metadata=metadata,
217
+ )
218
+
219
+
220
+ def agent(
221
+ agent_name: str,
222
+ *,
223
+ distinct_id: Optional[str] = None,
224
+ conversation_id: Optional[str] = None,
225
+ metadata: Optional[Dict[str, Any]] = None,
226
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
227
+ """Decorator form of wrap_agent."""
228
+ return _get_client().agent(
229
+ agent_name,
230
+ distinct_id=distinct_id,
231
+ conversation_id=conversation_id,
232
+ metadata=metadata,
233
+ )
234
+
235
+
236
+ def span(
237
+ name: str,
238
+ *,
239
+ kind: str = "generic",
240
+ input: Any = None,
241
+ attributes: Optional[Dict[str, Any]] = None,
242
+ ) -> _span_ctx:
243
+ """Nested span inside the current run."""
244
+ return _get_client().span(name, kind=kind, input=input, attributes=attributes)
245
+
246
+
247
+ def join_run(
248
+ run_id: str,
249
+ parent_span_id: Optional[str] = None,
250
+ *,
251
+ name: str = "remote.handler",
252
+ kind: str = "agent",
253
+ input: Any = None,
254
+ attributes: Optional[Dict[str, Any]] = None,
255
+ ) -> _join_run_ctx:
256
+ """Open a span on an existing run owned by a remote service."""
257
+ return _get_client().join_run(
258
+ run_id,
259
+ parent_span_id,
260
+ name=name,
261
+ kind=kind,
262
+ input=input,
263
+ attributes=attributes,
264
+ )
265
+
266
+
267
+ def tool(
268
+ name: Any = None,
269
+ fn: Optional[Callable[..., Any]] = None,
270
+ *,
271
+ kind: str = "tool",
272
+ ) -> Any:
273
+ """Wrap a function as a tool span — dual-form helper and decorator.
274
+
275
+ Helper form::
276
+
277
+ run_funnel_query = trodo.tool('run_funnel_query', run_funnel_query)
278
+
279
+ Decorator form (backward-compatible)::
280
+
281
+ @trodo.tool()
282
+ def run_funnel_query(team_id, preset): ...
283
+
284
+ @trodo.tool(name='custom-name')
285
+ async def fetch(...): ...
286
+ """
287
+ # Deferred import: allow @trodo.tool() at import-time before init().
288
+ from .otel.helpers import tool as _tool_helper
289
+ return _tool_helper(name, fn, kind=kind)
290
+
291
+
292
+ def trace(
293
+ name: Any = None,
294
+ fn: Optional[Callable[..., Any]] = None,
295
+ ) -> Any:
296
+ """Wrap a function as a generic span — dual-form helper and decorator."""
297
+ from .otel.helpers import trace as _trace_helper
298
+ return _trace_helper(name, fn)
299
+
300
+
301
+ def llm(
302
+ name: Any = None,
303
+ fn: Optional[Callable[..., Any]] = None,
304
+ *,
305
+ model: Optional[str] = None,
306
+ provider: Optional[str] = None,
307
+ temperature: Optional[float] = None,
308
+ extract_usage: Optional[Callable[[Any], Any]] = None,
309
+ ) -> Any:
310
+ """Wrap an LLM call — auto-captures tokens from OpenAI/Anthropic/Gemini
311
+ response shapes. Dual-form helper and decorator."""
312
+ from .otel.helpers import llm as _llm_helper
313
+ return _llm_helper(
314
+ name,
315
+ fn,
316
+ model=model,
317
+ provider=provider,
318
+ temperature=temperature,
319
+ extract_usage=extract_usage,
320
+ )
321
+
322
+
323
+ def retrieval(
324
+ name: Any = None,
325
+ fn: Optional[Callable[..., Any]] = None,
326
+ ) -> Any:
327
+ """Wrap a retriever / vector search as a kind='retrieval' span."""
328
+ from .otel.helpers import retrieval as _retrieval_helper
329
+ return _retrieval_helper(name, fn)
330
+
331
+
332
+ def get_tracer(name: str = "trodo") -> Any:
333
+ """Return a raw OTel tracer — the Trodo processor is already subscribed.
334
+
335
+ Use for advanced cases where you want to emit spans with the raw OTel
336
+ API; they'll be captured and forwarded to Trodo like any other span.
337
+
338
+ tracer = trodo.get_tracer('my.module')
339
+ with tracer.start_as_current_span('custom') as sp:
340
+ sp.set_attribute('foo', 'bar')
341
+ """
342
+ try:
343
+ from opentelemetry import trace as _otel_trace # type: ignore
344
+ except Exception as e: # pragma: no cover
345
+ raise RuntimeError(
346
+ "trodo.get_tracer requires the opentelemetry-api package"
347
+ ) from e
348
+ return _otel_trace.get_tracer(name)
349
+
350
+
351
+ def track_llm_call(
352
+ *,
353
+ model: Optional[str] = None,
354
+ provider: Optional[str] = None,
355
+ input_tokens: Optional[int] = None,
356
+ output_tokens: Optional[int] = None,
357
+ prompt: Any = None,
358
+ completion: Any = None,
359
+ temperature: Optional[float] = None,
360
+ cost: Optional[float] = None,
361
+ name: Optional[str] = None,
362
+ metadata: Optional[Dict[str, Any]] = None,
363
+ ) -> None:
364
+ """Record a one-shot LLM span for a raw-HTTP caller."""
365
+ from .otel.helpers import track_llm_call as _fn
366
+ _fn(
367
+ model=model,
368
+ provider=provider,
369
+ input_tokens=input_tokens,
370
+ output_tokens=output_tokens,
371
+ prompt=prompt,
372
+ completion=completion,
373
+ temperature=temperature,
374
+ cost=cost,
375
+ name=name,
376
+ metadata=metadata,
377
+ )
378
+
379
+
380
+ def feedback(
381
+ run_id: str,
382
+ *,
383
+ satisfaction: Optional[str] = None,
384
+ rating: Optional[float] = None,
385
+ comment: Optional[str] = None,
386
+ feedback: Optional[str] = None,
387
+ distinct_id: Optional[str] = None,
388
+ metadata: Optional[Dict[str, Any]] = None,
389
+ ) -> ApiResult:
390
+ """Attach feedback to a completed run."""
391
+ return _get_client().feedback(
392
+ run_id,
393
+ satisfaction=satisfaction,
394
+ rating=rating,
395
+ comment=comment,
396
+ feedback=feedback,
397
+ distinct_id=distinct_id,
398
+ metadata=metadata,
399
+ )
400
+
401
+
402
+ # ----------------------------------------------------------------------------
403
+ # Cross-service propagation
404
+ # ----------------------------------------------------------------------------
158
405
 
406
+ def fastapi_middleware() -> Callable:
407
+ """Return a FastAPI/Starlette middleware that auto-joins inbound runs.
159
408
 
160
- def track_tool_use(props: ToolUseProps) -> None:
161
- """Track a tool invocation within an agent turn."""
162
- _get_client().track_tool_use(props)
409
+ Usage:
410
+ app = FastAPI()
411
+ trodo.init(site_id='...')
412
+ app.middleware('http')(trodo.fastapi_middleware())
413
+ """
414
+ return _get_client().fastapi_middleware()
163
415
 
164
416
 
165
- def track_agent_response(props: AgentResponseProps) -> None:
166
- """Track an LLM response / completion."""
167
- _get_client().track_agent_response(props)
417
+ def propagation_headers() -> Dict[str, str]:
418
+ """Return outbound HTTP headers carrying the current run/span id."""
419
+ from .otel.helpers import propagation_headers as _fn
420
+ return _fn()
168
421
 
169
422
 
170
- def track_agent_error(props: AgentErrorProps) -> None:
171
- """Track an error during an agent turn."""
172
- _get_client().track_agent_error(props)
423
+ def current_run_id() -> Optional[str]:
424
+ from .otel.wrap_agent import current_run_id as _fn
425
+ return _fn()
173
426
 
174
427
 
175
- def track_feedback(props: FeedbackProps) -> None:
176
- """Track a user feedback reaction on an agent response."""
177
- _get_client().track_feedback(props)
428
+ def current_span_id() -> Optional[str]:
429
+ from .otel.wrap_agent import current_span_id as _fn
430
+ return _fn()
trodo/api/endpoints.py CHANGED
@@ -1,5 +1,4 @@
1
1
  TRACK = "/api/sdk/track"
2
- TRACK_AGENT = "/api/sdk/track-agent"
3
2
  EVENTS = "/api/events"
4
3
  EVENTS_BULK = "/api/events/bulk"
5
4
  IDENTIFY = "/api/sdk/identify"
@@ -19,3 +18,8 @@ GROUPS_SET = "/api/sdk/groups/set_group"
19
18
  GROUPS_ADD = "/api/sdk/groups/add_group"
20
19
  GROUPS_REMOVE = "/api/sdk/groups/remove_group"
21
20
  GROUPS_PROFILE = "/api/sdk/groups/profile"
21
+ # Agent run tracking (Lemma-style, run-centric)
22
+ RUNS_INGEST = "/api/sdk/runs/ingest"
23
+ RUNS_START = "/api/sdk/runs/start"
24
+ RUNS_BASE = "/api/sdk/runs" # /runs/{run_id}/end, /spans, /feedback
25
+ OTLP_TRACES = "/api/sdk/otel/v1/traces"
trodo/api/http_client.py CHANGED
@@ -86,5 +86,33 @@ class HttpClient:
86
86
  def post_group(self, path: str, payload: Dict[str, Any]) -> ApiResult:
87
87
  return self._request(path, payload)
88
88
 
89
- def post_agent_event(self, payload: Dict[str, Any]) -> ApiResult:
90
- return self._request("/api/sdk/track-agent", payload)
89
+ # ------------------------------------------------------------------
90
+ # Agent Runs (Lemma-style)
91
+ # ------------------------------------------------------------------
92
+
93
+ def post_run_ingest(self, payload: Dict[str, Any]) -> ApiResult:
94
+ return self._request("/api/sdk/runs/ingest", payload)
95
+
96
+ def post_run_start(self, payload: Dict[str, Any]) -> ApiResult:
97
+ return self._request("/api/sdk/runs/start", payload)
98
+
99
+ def post_run_end(self, run_id: str, payload: Dict[str, Any]) -> ApiResult:
100
+ from urllib.parse import quote
101
+ return self._request(f"/api/sdk/runs/{quote(run_id, safe='')}/end", payload)
102
+
103
+ def post_spans_append(self, run_id: str, spans: list) -> ApiResult:
104
+ from urllib.parse import quote
105
+ return self._request(
106
+ f"/api/sdk/runs/{quote(run_id, safe='')}/spans",
107
+ {"spans": spans},
108
+ )
109
+
110
+ def post_run_feedback(self, run_id: str, payload: Dict[str, Any]) -> ApiResult:
111
+ from urllib.parse import quote
112
+ return self._request(
113
+ f"/api/sdk/runs/{quote(run_id, safe='')}/feedback",
114
+ payload,
115
+ )
116
+
117
+ def post_otlp_traces(self, payload: Dict[str, Any]) -> ApiResult:
118
+ return self._request("/api/sdk/otel/v1/traces", payload)