trodo-python 1.0.0__py3-none-any.whl → 1.2.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,134 +1,177 @@
1
- """
2
- trodo-python — Trodo Analytics SDK for Python
3
-
4
- Usage (module-level singleton):
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})
15
- """
16
-
17
- from __future__ import annotations
18
-
19
- from typing import Any, Dict, List, Optional, Union
20
-
21
- from .client import TrodoClient
22
- from .user_context import UserContext
23
- from .managers.group_manager import GroupProfile
24
- from .types import ApiResult, IdentifyResult, ResetResult, WalletAddressResult
25
-
26
- __all__ = [
27
- "TrodoClient",
28
- "UserContext",
29
- "GroupProfile",
30
- "init",
31
- "for_user",
32
- "track",
33
- "identify",
34
- "wallet_address",
35
- "reset",
36
- "enable_auto_events",
37
- "disable_auto_events",
38
- "flush",
39
- "shutdown",
40
- ]
41
-
42
- # ============================================================================
43
- # Singleton convenience API
44
- # ============================================================================
45
-
46
- _client: Optional[TrodoClient] = None
47
-
48
-
49
- def _get_client() -> TrodoClient:
50
- if _client is None:
51
- raise RuntimeError(
52
- "trodo-python: Call trodo.init(site_id=...) before using the SDK."
53
- )
54
- return _client
55
-
56
-
57
- def init(
58
- site_id: str,
59
- api_base: str = "https://sdkapi.trodo.ai",
60
- timeout: int = 10,
61
- retries: int = 2,
62
- batch_enabled: bool = False,
63
- batch_size: int = 50,
64
- batch_flush_interval: float = 5.0,
65
- auto_events: bool = False,
66
- on_error: Optional[Any] = None,
67
- debug: bool = False,
68
- ) -> TrodoClient:
69
- """Initialise the singleton SDK instance."""
70
- global _client
71
- _client = TrodoClient(
72
- site_id=site_id,
73
- api_base=api_base,
74
- timeout=timeout,
75
- retries=retries,
76
- batch_enabled=batch_enabled,
77
- batch_size=batch_size,
78
- batch_flush_interval=batch_flush_interval,
79
- auto_events=auto_events,
80
- on_error=on_error,
81
- debug=debug,
82
- )
83
- return _client
84
-
85
-
86
- def for_user(
87
- distinct_id: str,
88
- session_id: Optional[str] = None,
89
- ) -> UserContext:
90
- """Return a UserContext bound to the given distinctId."""
91
- return _get_client().for_user(distinct_id, session_id)
92
-
93
-
94
- def track(
95
- distinct_id: str,
96
- event_name: str,
97
- properties: Optional[Dict[str, Any]] = None,
98
- category: str = "custom",
99
- ) -> None:
100
- """Track an event for a user (direct-call pattern)."""
101
- _get_client().track(distinct_id, event_name, properties, category)
102
-
103
-
104
- def identify(distinct_id: str, identify_id: str) -> IdentifyResult:
105
- """Alias a user's distinctId to an external identifier."""
106
- return _get_client().identify(distinct_id, identify_id)
107
-
108
-
109
- def wallet_address(distinct_id: str, wallet_addr: str) -> WalletAddressResult:
110
- """Associate a wallet address with a user."""
111
- return _get_client().wallet_address(distinct_id, wallet_addr)
112
-
113
-
114
- def reset(distinct_id: str) -> ResetResult:
115
- """Reset a user's session."""
116
- return _get_client().reset(distinct_id)
117
-
118
-
119
- def enable_auto_events() -> None:
120
- _get_client().enable_auto_events()
121
-
122
-
123
- def disable_auto_events() -> None:
124
- _get_client().disable_auto_events()
125
-
126
-
127
- def flush() -> None:
128
- """Flush any queued batch events."""
129
- _get_client().flush()
130
-
131
-
132
- def shutdown() -> None:
133
- """Flush, stop timers, and disable auto events."""
134
- _get_client().shutdown()
1
+ """
2
+ trodo-python — Trodo Analytics SDK for Python
3
+
4
+ Usage (module-level singleton):
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})
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any, Dict, List, Optional, Union
20
+
21
+ from .client import TrodoClient
22
+ from .user_context import UserContext
23
+ from .managers.group_manager import GroupProfile
24
+ from .types import (
25
+ ApiResult, ResetResult, WalletAddressResult,
26
+ AgentCallProps, ToolUseProps, AgentResponseProps, AgentErrorProps, FeedbackProps,
27
+ )
28
+
29
+ __all__ = [
30
+ "TrodoClient",
31
+ "UserContext",
32
+ "GroupProfile",
33
+ "init",
34
+ "for_user",
35
+ "track",
36
+ "identify",
37
+ "wallet_address",
38
+ "reset",
39
+ "enable_auto_events",
40
+ "disable_auto_events",
41
+ "flush",
42
+ "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",
54
+ ]
55
+
56
+ # ============================================================================
57
+ # Singleton convenience API
58
+ # ============================================================================
59
+
60
+ _client: Optional[TrodoClient] = None
61
+
62
+
63
+ def _get_client() -> TrodoClient:
64
+ if _client is None:
65
+ raise RuntimeError(
66
+ "trodo-python: Call trodo.init(site_id=...) before using the SDK."
67
+ )
68
+ return _client
69
+
70
+
71
+ def init(
72
+ site_id: str,
73
+ api_base: str = "https://sdkapi.trodo.ai",
74
+ timeout: int = 10,
75
+ retries: int = 2,
76
+ batch_enabled: bool = False,
77
+ batch_size: int = 50,
78
+ batch_flush_interval: float = 5.0,
79
+ auto_events: bool = False,
80
+ on_error: Optional[Any] = None,
81
+ debug: bool = False,
82
+ ) -> TrodoClient:
83
+ """Initialise the singleton SDK instance."""
84
+ global _client
85
+ _client = TrodoClient(
86
+ site_id=site_id,
87
+ api_base=api_base,
88
+ timeout=timeout,
89
+ retries=retries,
90
+ batch_enabled=batch_enabled,
91
+ batch_size=batch_size,
92
+ batch_flush_interval=batch_flush_interval,
93
+ auto_events=auto_events,
94
+ on_error=on_error,
95
+ debug=debug,
96
+ )
97
+ return _client
98
+
99
+
100
+ def for_user(
101
+ distinct_id: str,
102
+ session_id: Optional[str] = None,
103
+ ) -> UserContext:
104
+ """Return a UserContext bound to the given distinctId."""
105
+ return _get_client().for_user(distinct_id, session_id)
106
+
107
+
108
+ def track(
109
+ distinct_id: str,
110
+ event_name: str,
111
+ properties: Optional[Dict[str, Any]] = None,
112
+ category: str = "custom",
113
+ ) -> None:
114
+ """Track an event for a user (direct-call pattern)."""
115
+ _get_client().track(distinct_id, event_name, properties, category)
116
+
117
+
118
+ 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
+ return _get_client().identify(identify_id, session_id)
121
+
122
+
123
+ def wallet_address(distinct_id: str, wallet_addr: str) -> WalletAddressResult:
124
+ """Associate a wallet address with a user."""
125
+ return _get_client().wallet_address(distinct_id, wallet_addr)
126
+
127
+
128
+ def reset(distinct_id: str) -> ResetResult:
129
+ """Reset a user's session."""
130
+ return _get_client().reset(distinct_id)
131
+
132
+
133
+ def enable_auto_events() -> None:
134
+ _get_client().enable_auto_events()
135
+
136
+
137
+ def disable_auto_events() -> None:
138
+ _get_client().disable_auto_events()
139
+
140
+
141
+ def flush() -> None:
142
+ """Flush any queued batch events."""
143
+ _get_client().flush()
144
+
145
+
146
+ def shutdown() -> None:
147
+ """Flush, stop timers, and disable auto events."""
148
+ _get_client().shutdown()
149
+
150
+
151
+ # ----------------------------------------------------------------------------
152
+ # Agent Analytics — singleton wrappers
153
+ # ----------------------------------------------------------------------------
154
+
155
+ def track_agent_call(props: AgentCallProps) -> None:
156
+ """Track an LLM invocation / inbound message."""
157
+ _get_client().track_agent_call(props)
158
+
159
+
160
+ def track_tool_use(props: ToolUseProps) -> None:
161
+ """Track a tool invocation within an agent turn."""
162
+ _get_client().track_tool_use(props)
163
+
164
+
165
+ def track_agent_response(props: AgentResponseProps) -> None:
166
+ """Track an LLM response / completion."""
167
+ _get_client().track_agent_response(props)
168
+
169
+
170
+ def track_agent_error(props: AgentErrorProps) -> None:
171
+ """Track an error during an agent turn."""
172
+ _get_client().track_agent_error(props)
173
+
174
+
175
+ def track_feedback(props: FeedbackProps) -> None:
176
+ """Track a user feedback reaction on an agent response."""
177
+ _get_client().track_feedback(props)
trodo/api/async_client.py CHANGED
@@ -1,96 +1,96 @@
1
- """Async HTTP client using httpx (optional dependency)."""
2
-
3
- from __future__ import annotations
4
-
5
- import sys
6
- import asyncio
7
- from typing import Any, Callable, Dict, Optional
8
-
9
- from ..types import ApiResult, EventPayload
10
-
11
-
12
- class AsyncHttpClient:
13
- def __init__(
14
- self,
15
- api_base: str,
16
- site_id: str,
17
- timeout: int = 10,
18
- retries: int = 2,
19
- on_error: Optional[Callable[[Exception], None]] = None,
20
- debug: bool = False,
21
- ) -> None:
22
- try:
23
- import httpx # noqa: F401
24
- except ImportError:
25
- raise ImportError(
26
- "trodo-python async support requires httpx: pip install trodo-python[async]"
27
- )
28
-
29
- self.api_base = api_base.rstrip("/")
30
- self.site_id = site_id
31
- self.timeout = timeout
32
- self.retries = retries
33
- self.on_error = on_error
34
- self.debug = debug
35
-
36
- def _log(self, *args: Any) -> None:
37
- if self.debug:
38
- sys.stderr.write(f"[trodo-python-async] {' '.join(str(a) for a in args)}\n")
39
-
40
- async def _request(
41
- self, path: str, body: Dict[str, Any], attempt: int = 0
42
- ) -> ApiResult:
43
- import httpx
44
-
45
- url = f"{self.api_base}{path}"
46
- self._log(f"POST {url}")
47
- headers = {
48
- "Content-Type": "application/json",
49
- "X-Trodo-Site-Id": self.site_id,
50
- }
51
- try:
52
- async with httpx.AsyncClient(timeout=self.timeout) as client:
53
- resp = await client.post(url, json=body, headers=headers)
54
- if resp.status_code >= 500 and attempt < self.retries:
55
- delay = 2 ** attempt
56
- self._log(f"Retry {attempt + 1} after {delay}s")
57
- await asyncio.sleep(delay)
58
- return await self._request(path, body, attempt + 1)
59
- try:
60
- return resp.json()
61
- except Exception:
62
- return {}
63
- except Exception as exc:
64
- if attempt < self.retries:
65
- await asyncio.sleep(2 ** attempt)
66
- return await self._request(path, body, attempt + 1)
67
- self._log(f"Error: {exc}")
68
- if self.on_error:
69
- self.on_error(exc)
70
- return {}
71
-
72
- async def post_track(self, session_data: Dict[str, Any]) -> ApiResult:
73
- return await self._request("/api/sdk/track", {"sessionData": session_data})
74
-
75
- async def post_event(self, event: EventPayload) -> ApiResult:
76
- return await self._request("/api/events", event.to_dict())
77
-
78
- async def post_bulk_events(self, events: list) -> ApiResult:
79
- return await self._request(
80
- "/api/events/bulk", {"events": [e.to_dict() for e in events]}
81
- )
82
-
83
- async def post_identify(self, payload: Dict[str, Any]) -> ApiResult:
84
- return await self._request("/api/sdk/identify", payload)
85
-
86
- async def post_wallet_address(self, payload: Dict[str, Any]) -> ApiResult:
87
- return await self._request("/api/sdk/wallet-address", payload)
88
-
89
- async def post_reset(self, payload: Dict[str, Any]) -> ApiResult:
90
- return await self._request("/api/sdk/reset", payload)
91
-
92
- async def post_people(self, path: str, payload: Dict[str, Any]) -> ApiResult:
93
- return await self._request(path, payload)
94
-
95
- async def post_group(self, path: str, payload: Dict[str, Any]) -> ApiResult:
96
- return await self._request(path, payload)
1
+ """Async HTTP client using httpx (optional dependency)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import asyncio
7
+ from typing import Any, Callable, Dict, Optional
8
+
9
+ from ..types import ApiResult, EventPayload
10
+
11
+
12
+ class AsyncHttpClient:
13
+ def __init__(
14
+ self,
15
+ api_base: str,
16
+ site_id: str,
17
+ timeout: int = 10,
18
+ retries: int = 2,
19
+ on_error: Optional[Callable[[Exception], None]] = None,
20
+ debug: bool = False,
21
+ ) -> None:
22
+ try:
23
+ import httpx # noqa: F401
24
+ except ImportError:
25
+ raise ImportError(
26
+ "trodo-python async support requires httpx: pip install trodo-python[async]"
27
+ )
28
+
29
+ self.api_base = api_base.rstrip("/")
30
+ self.site_id = site_id
31
+ self.timeout = timeout
32
+ self.retries = retries
33
+ self.on_error = on_error
34
+ self.debug = debug
35
+
36
+ def _log(self, *args: Any) -> None:
37
+ if self.debug:
38
+ sys.stderr.write(f"[trodo-python-async] {' '.join(str(a) for a in args)}\n")
39
+
40
+ async def _request(
41
+ self, path: str, body: Dict[str, Any], attempt: int = 0
42
+ ) -> ApiResult:
43
+ import httpx
44
+
45
+ url = f"{self.api_base}{path}"
46
+ self._log(f"POST {url}")
47
+ headers = {
48
+ "Content-Type": "application/json",
49
+ "X-Trodo-Site-Id": self.site_id,
50
+ }
51
+ try:
52
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
53
+ resp = await client.post(url, json=body, headers=headers)
54
+ if resp.status_code >= 500 and attempt < self.retries:
55
+ delay = 2 ** attempt
56
+ self._log(f"Retry {attempt + 1} after {delay}s")
57
+ await asyncio.sleep(delay)
58
+ return await self._request(path, body, attempt + 1)
59
+ try:
60
+ return resp.json()
61
+ except Exception:
62
+ return {}
63
+ except Exception as exc:
64
+ if attempt < self.retries:
65
+ await asyncio.sleep(2 ** attempt)
66
+ return await self._request(path, body, attempt + 1)
67
+ self._log(f"Error: {exc}")
68
+ if self.on_error:
69
+ self.on_error(exc)
70
+ return {}
71
+
72
+ async def post_track(self, session_data: Dict[str, Any]) -> ApiResult:
73
+ return await self._request("/api/sdk/track", {"sessionData": session_data})
74
+
75
+ async def post_event(self, event: EventPayload) -> ApiResult:
76
+ return await self._request("/api/events", event.to_dict())
77
+
78
+ async def post_bulk_events(self, events: list) -> ApiResult:
79
+ return await self._request(
80
+ "/api/events/bulk", {"events": [e.to_dict() for e in events]}
81
+ )
82
+
83
+ async def post_identify(self, payload: Dict[str, Any]) -> ApiResult:
84
+ return await self._request("/api/sdk/identify", payload)
85
+
86
+ async def post_wallet_address(self, payload: Dict[str, Any]) -> ApiResult:
87
+ return await self._request("/api/sdk/wallet-address", payload)
88
+
89
+ async def post_reset(self, payload: Dict[str, Any]) -> ApiResult:
90
+ return await self._request("/api/sdk/reset", payload)
91
+
92
+ async def post_people(self, path: str, payload: Dict[str, Any]) -> ApiResult:
93
+ return await self._request(path, payload)
94
+
95
+ async def post_group(self, path: str, payload: Dict[str, Any]) -> ApiResult:
96
+ return await self._request(path, payload)
trodo/api/endpoints.py CHANGED
@@ -1,20 +1,21 @@
1
- TRACK = "/api/sdk/track"
2
- EVENTS = "/api/events"
3
- EVENTS_BULK = "/api/events/bulk"
4
- IDENTIFY = "/api/sdk/identify"
5
- WALLET_ADDRESS = "/api/sdk/wallet-address"
6
- RESET = "/api/sdk/reset"
7
- PEOPLE_SET = "/api/sdk/people/set"
8
- PEOPLE_SET_ONCE = "/api/sdk/people/set_once"
9
- PEOPLE_UNSET = "/api/sdk/people/unset"
10
- PEOPLE_INCREMENT = "/api/sdk/people/increment"
11
- PEOPLE_APPEND = "/api/sdk/people/append"
12
- PEOPLE_UNION = "/api/sdk/people/union"
13
- PEOPLE_REMOVE = "/api/sdk/people/remove"
14
- PEOPLE_TRACK_CHARGE = "/api/sdk/people/track_charge"
15
- PEOPLE_CLEAR_CHARGES = "/api/sdk/people/clear_charges"
16
- PEOPLE_DELETE_USER = "/api/sdk/people/delete_user"
17
- GROUPS_SET = "/api/sdk/groups/set_group"
18
- GROUPS_ADD = "/api/sdk/groups/add_group"
19
- GROUPS_REMOVE = "/api/sdk/groups/remove_group"
20
- GROUPS_PROFILE = "/api/sdk/groups/profile"
1
+ TRACK = "/api/sdk/track"
2
+ TRACK_AGENT = "/api/sdk/track-agent"
3
+ EVENTS = "/api/events"
4
+ EVENTS_BULK = "/api/events/bulk"
5
+ IDENTIFY = "/api/sdk/identify"
6
+ WALLET_ADDRESS = "/api/sdk/wallet-address"
7
+ RESET = "/api/sdk/reset"
8
+ PEOPLE_SET = "/api/sdk/people/set"
9
+ PEOPLE_SET_ONCE = "/api/sdk/people/set_once"
10
+ PEOPLE_UNSET = "/api/sdk/people/unset"
11
+ PEOPLE_INCREMENT = "/api/sdk/people/increment"
12
+ PEOPLE_APPEND = "/api/sdk/people/append"
13
+ PEOPLE_UNION = "/api/sdk/people/union"
14
+ PEOPLE_REMOVE = "/api/sdk/people/remove"
15
+ PEOPLE_TRACK_CHARGE = "/api/sdk/people/track_charge"
16
+ PEOPLE_CLEAR_CHARGES = "/api/sdk/people/clear_charges"
17
+ PEOPLE_DELETE_USER = "/api/sdk/people/delete_user"
18
+ GROUPS_SET = "/api/sdk/groups/set_group"
19
+ GROUPS_ADD = "/api/sdk/groups/add_group"
20
+ GROUPS_REMOVE = "/api/sdk/groups/remove_group"
21
+ GROUPS_PROFILE = "/api/sdk/groups/profile"