@devries-cameron20 / composio-1 / commits / 26a1d56db
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

feat: add telemetry on the python SDK

angrybayblade committed Jun 17, 2025 at 16:55 UTC 26a1d56db23b44d26e3ab99ebd793f899413ceff
4 files changed +146 -8
python/composio/core/models/_telemetry.py new
+109
@@ -0,0 +1,109 @@
1 +import atexit
2 +import functools
3 +import queue as q
4 +import threading as tr
5 +import time
6 +import typing as t
7 +
8 +import httpx
9 +import typing_extensions as te
10 +
11 +TELEMETRY_URL = "https://telemetry.composio.dev/v1"
12 +METRIC_ENDPOINT = f"{TELEMETRY_URL}/metrics/invocations"
13 +ERROR_ENDPOINT = f"{TELEMETRY_URL}/errors"
14 +
15 +
16 +class ErrorData(te.TypedDict):
17 + name: str
18 + code: te.NotRequired[str]
19 + errorId: te.NotRequired[str]
20 + message: te.NotRequired[str]
21 + stack: te.NotRequired[str]
22 +
23 +
24 +class TelemetryData(te.TypedDict):
25 + functionName: str
26 + durationMs: te.NotRequired[float]
27 + timestamp: te.NotRequired[float]
28 + props: te.NotRequired[t.Dict]
29 + source: te.NotRequired[str]
30 + metadata: te.NotRequired[t.Dict]
31 + error: te.NotRequired[ErrorData]
32 +
33 +
34 +EventType: t.TypeAlias = t.Literal["metric", "error"]
35 +Event = t.Tuple[EventType, TelemetryData]
36 +EventQueue: t.TypeAlias = q.Queue[Event]
37 +
38 +_queue: t.Optional[EventQueue] = None
39 +_event: t.Optional[tr.Event] = None
40 +_thread: t.Optional[tr.Thread] = None
41 +
42 +
43 +def _setup():
44 + global _queue, _event, _thread
45 + if _queue is None:
46 + _queue = q.Queue[Event]()
47 +
48 + if _event is None:
49 + _event = tr.Event()
50 +
51 + if _thread is None:
52 + _thread = tr.Thread(
53 + target=_thread_loop,
54 + kwargs={
55 + "queue": _queue,
56 + "event": _event,
57 + },
58 + daemon=True,
59 + )
60 + _thread.start()
61 + atexit.register(
62 + functools.partial(
63 + _teardown,
64 + queue=_queue,
65 + event=_event,
66 + thread=_thread,
67 + )
68 + )
69 +
70 + return _queue, _event, _thread
71 +
72 +
73 +def _teardown(queue: EventQueue, event: tr.Event, thread: tr.Thread):
74 + while queue.qsize():
75 + time.sleep(0.1)
76 +
77 + event.set()
78 + thread.join()
79 +
80 +
81 +def _push(event: Event):
82 + _ = (
83 + httpx.post(
84 + url=METRIC_ENDPOINT,
85 + json=[event[1]],
86 + )
87 + if event[0] == "metric"
88 + else httpx.post(
89 + url=ERROR_ENDPOINT,
90 + json=event[1],
91 + )
92 + )
93 +
94 +
95 +def _thread_loop(queue: EventQueue, event: tr.Event):
96 + while not event.is_set():
97 + try:
98 + _push(queue.get(timeout=0.1))
99 + except q.Empty:
100 + continue
101 +
102 +
103 +def push_event(event: Event):
104 + q, _, _ = _setup()
105 + q.put(event)
106 +
107 +
108 +def create_event(type: EventType, **payload: te.Unpack[TelemetryData]) -> Event:
109 + return type, payload
python/composio/core/models/base.py
+34 -5
@@ -2,24 +2,53 @@
2 Base resource class for representing resources in the composio client.
3 """
4
5 +import contextvars
6 import functools
7 +import time
8 +import traceback
9 import typing as t
10
11 from composio.client import HttpClient
12 from composio.utils.logging import WithLogger
13
14 +from ._telemetry import Event, create_event, push_event
15 +
16 PayloadT = t.TypeVar("PayloadT", bound=dict)
17
18 +allow_tracking = contextvars.ContextVar[bool]("allow_tracking", default=True)
19 +
20
14 -# TODO: integrate the metric collection service @haxzie is working on
21 def trace_method(method: t.Callable, name: str, **attributes: t.Any) -> t.Callable:
22 """Wrap a method to log the call."""
23
24 @functools.wraps(method)
19 - def wrapper(self, *args, **kwargs):
20 - return method(self, *args, **kwargs)
25 + def trace_wrapper(self, *args, **kwargs):
26 + if not allow_tracking.get():
27 + return method(self, *args, **kwargs)
28 +
29 + event: t.Optional[Event] = None
30 + start_time = time.time()
31 + try:
32 + event = create_event(type="metric", functionName=name)
33 + return method(self, *args, **kwargs)
34 + except Exception as e:
35 + event = create_event(
36 + type="error",
37 + functionName=name,
38 + error={
39 + "name": e.__class__.__name__,
40 + "message": str(e),
41 + "stack": traceback.format_exc(),
42 + },
43 + )
44 + raise e
45 + finally:
46 + if event is not None:
47 + event[1]["durationMs"] = (time.time() - start_time) * 1000
48 + push_event(event=event)
49
22 - return wrapper
50 + trace_wrapper.__name__ = method.__name__
51 + return trace_wrapper
52
53
54 class ResourceMeta(type):
@@ -27,7 +56,7 @@ class ResourceMeta(type):
56
57 def __init__(cls, name, bases, attrs):
58 for attr in attrs:
30 - if "__" in attr:
59 + if "__" in attr or not callable(getattr(cls, attr)):
60 continue
61 setattr(cls, attr, trace_method(getattr(cls, attr), f"{name}.{attr}"))
62
python/composio/sdk.py
+3
@@ -14,6 +14,7 @@ from composio.core.models import (
14 Tools,
15 Triggers,
16 )
17 +from composio.core.models.base import allow_tracking
18 from composio.core.provider import TProvider
19 from composio.core.provider._openai import OpenAIProvider
20 from composio.utils.logging import WithLogger
@@ -27,6 +28,7 @@ class SDKConfig(te.TypedDict):
28 base_url: te.NotRequired[str]
29 timeout: te.NotRequired[int]
30 max_retries: te.NotRequired[int]
31 + allow_tracking: te.NotRequired[bool]
32
33
34 class Composio(t.Generic[TProvider], WithLogger):
@@ -57,6 +59,7 @@ class Composio(t.Generic[TProvider], WithLogger):
59 if not api_key:
60 raise exceptions.ApiKeyNotProvidedError()
61
62 + allow_tracking.set(kwargs.get("allow_tracking", True))
63 self._client = HttpClient(
64 environment=kwargs.get("environment", "production"),
65 provider=provider.name,
python/examples/tools.py
-3
@@ -2,9 +2,6 @@ from composio import Composio
2
3 composio = Composio()
4
5 -# Get all tools
6 -tools = composio.tools.get(user_id="default")
7 -
5 # Get all tools by toolkit
6 tools = composio.tools.get(user_id="default", toolkits=["GITHUB"])
7