glowtrace 0.3.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.

Potentially problematic release.


This version of glowtrace might be problematic. Click here for more details.

@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eman Khadim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,195 @@
1
+ Metadata-Version: 2.4
2
+ Name: glowtrace
3
+ Version: 0.3.0
4
+ Summary: Watch your AI agents think, live. A zero-config OpenTelemetry receiver that turns agent traces into a live, clickable graph.
5
+ Author: Eman Khadim
6
+ License-Expression: MIT
7
+ Keywords: agents,llm,opentelemetry,observability,tracing,multi-agent,visualization,genai
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Software Development :: Debuggers
10
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
11
+ Classifier: Framework :: AsyncIO
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: aiohttp>=3.9
16
+ Requires-Dist: opentelemetry-proto>=1.20
17
+ Requires-Dist: websockets>=13
18
+ Provides-Extra: live
19
+ Requires-Dist: opentelemetry-sdk>=1.20; extra == "live"
20
+ Dynamic: license-file
21
+
22
+ <div align="center">
23
+
24
+ # glowtrace
25
+
26
+ **Watch your AI agents work, live.**
27
+
28
+ A tiny OpenTelemetry receiver that turns agent traces into a live, glowing graph. You see which agent is running, what it's calling, and the exact prompt behind every step.
29
+
30
+ ![glowtrace demo](docs/demo.gif)
31
+
32
+ [Live demo](https://YOUR-USERNAME.github.io/glowtrace/) · [Quick start](#quick-start) · [Works with](#works-with) · [Compared to](#how-is-this-different) · [How it works](#how-it-works)
33
+
34
+ </div>
35
+
36
+ ---
37
+
38
+ Multi-agent systems get hard to follow once a few agents start handing work to each other. Something goes wrong and you end up scrolling a log. Dashboard tools are good for looking back at a run afterwards, but most of them don't show you the run *while it happens*.
39
+
40
+ glowtrace is for that moment. Start it and leave it open on a second screen while your agents run:
41
+
42
+ - **Agents, LLM calls and tool calls appear as they start.** The running ones glow, finished ones go quiet, and failures turn red.
43
+ - **Messages move along the edges**, so you can see who handed what to whom.
44
+ - **Click any node** to see its system prompt, the prompt messages, the completion, tool arguments and results, tokens, timing and the raw span attributes.
45
+ - **Framework plumbing is folded away.** `RunnableSequence`, prompt templates, routers and HTTP calls stay hidden, so the graph shows the parts you think about. Use `--all-spans` if you want everything.
46
+
47
+ ## How is this different?
48
+
49
+ | | glowtrace | LangGraph Studio | Arize Phoenix | agent-flow |
50
+ |---|---|---|---|---|
51
+ | Animated live graph while the run happens | ✅ | ✅ | trace views | ✅ |
52
+ | Works beyond one framework | ✅ any OpenTelemetry source | LangGraph only | ✅ | Claude Code only |
53
+ | Zero config for apps that already export OTel | ✅ port 4318 | — | ✅ (agent graph needs extra span attributes) | — |
54
+ | Folds framework plumbing into agent → LLM → tool | ✅ automatic | ✅ (graph nodes) | with span metadata | n/a |
55
+ | Setup | `pip install` + one command | LangGraph CLI / Agent Server | full platform | VS Code extension |
56
+
57
+ glowtrace is not a dashboard, an eval suite or an agent builder. It does one thing: lets you watch agents work, live, and click into any step. If you need stored history, evals and cost analytics, use Phoenix or Langfuse alongside it.
58
+
59
+ ## Quick start
60
+
61
+ ```bash
62
+ pip install glowtrace
63
+ glowtrace serve # → http://localhost:4318
64
+ ```
65
+
66
+ That's it. Port 4318 is OpenTelemetry's default OTLP/HTTP port, so **an app that already exports OTel traces shows up without code changes**. If your exporter points somewhere else, set:
67
+
68
+ ```bash
69
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
70
+ export OTEL_BSP_SCHEDULE_DELAY=200 # optional: send spans quickly instead of every 5s
71
+ ```
72
+
73
+ ### Make running steps glow, not just finished ones
74
+
75
+ Standard exporters only send a span after it ends. One extra line also streams span *starts*:
76
+
77
+ ```python
78
+ import glowtrace
79
+ glowtrace.instrument() # pip install "glowtrace[live]"
80
+ ```
81
+
82
+ ## Works with
83
+
84
+ glowtrace understands the three span conventions agent frameworks emit today:
85
+
86
+ | convention | emitted by |
87
+ |---|---|
88
+ | [OpenInference](https://github.com/Arize-ai/openinference) | instrumentors for LangChain / **LangGraph**, LlamaIndex, CrewAI, OpenAI Agents SDK, smolagents, DSPy, … |
89
+ | [OpenTelemetry GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/) (`gen_ai.*`) | frameworks with native OTel GenAI support, OpenLIT |
90
+ | [OpenLLMetry](https://github.com/traceloop/openllmetry) (`traceloop.*`) | Traceloop instrumentors |
91
+
92
+ Tested end to end with LangGraph ([`examples/langgraph_team.py`](examples/langgraph_team.py)) and with LangChain's official [langgraph-supervisor](https://github.com/langchain-ai/langgraph-supervisor-py) multi-agent quickstart, unmodified ([`examples/test_supervisor.py`](examples/test_supervisor.py)). The mapping for all three conventions is covered by unit tests. If your framework renders oddly, please open an issue with a trace attached, since that's the fastest way to fix it.
93
+
94
+ **LangGraph example:**
95
+
96
+ ```python
97
+ from openinference.instrumentation.langchain import LangChainInstrumentor
98
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
99
+ from opentelemetry.sdk.trace import TracerProvider
100
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
101
+ from opentelemetry import trace
102
+ import glowtrace
103
+
104
+ provider = TracerProvider()
105
+ provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
106
+ trace.set_tracer_provider(provider)
107
+ glowtrace.instrument() # optional, for live "running" state
108
+ LangChainInstrumentor().instrument(tracer_provider=provider)
109
+ # … build and run your graph as usual
110
+ ```
111
+
112
+ ### Try it without installing anything
113
+
114
+ The hosted demo plays a built-in, fictional agent run, and you can drop in any recorded `.jsonl` trace to replay it, slowly or step by step.
115
+
116
+ ### No LLM bill needed to try it
117
+
118
+ The examples run on any OpenAI-compatible endpoint, including a free local model:
119
+
120
+ ```bash
121
+ pip install "glowtrace[live]" openai langgraph langchain-openai langgraph-supervisor \
122
+ openinference-instrumentation-langchain opentelemetry-exporter-otlp-proto-http
123
+ ollama pull qwen2.5:7b
124
+ python examples/test_supervisor.py # LangChain's official multi-agent quickstart
125
+ python examples/langgraph_team.py # LangGraph team via OpenTelemetry
126
+ python examples/real_agents.py # plain-Python agents via glowtrace's own tracer
127
+ python examples/fake_run.py # scripted run, no LLM at all
128
+ ```
129
+
130
+ Groq, Gemini and OpenRouter also have free tiers. Set `LLM_BASE_URL`, `LLM_API_KEY` and `LLM_MODEL` to use one of them.
131
+
132
+ ## How it works
133
+
134
+ ```
135
+ your agents ──OTLP/HTTP (protobuf or JSON)──▶ glowtrace serve ──WebSocket──▶ browser
136
+ │
137
+ └─ span → graph mapper
138
+ ```
139
+
140
+ - **Out-of-order spans.** Exporters send children before parents. Unknown parents get a placeholder, shown as running, which is filled in when the real span arrives.
141
+ - **Folding.** Spans without AI semantics (HTTP, DB, framework internals) are folded into their parent. A generic LangGraph `agent` node is credited to the named sub-graph that owns it, so you see `researcher`, not `agent`.
142
+ - **Late joiners.** A tab opened mid-run receives the history and catches up.
143
+ - **Read-only sharing.** `glowtrace serve --token SECRET` means only requests carrying the token can send data. Everyone else can watch.
144
+
145
+ The UI is written in TypeScript with no framework, and builds to a single self-contained HTML file that ships inside the Python package. It also runs on its own: open it from GitHub Pages for the demo, or drop in a recorded `.jsonl` trace to replay a run.
146
+
147
+ ### Not using OpenTelemetry?
148
+
149
+ Use the small native tracer, or send JSON to `/ws` from any language:
150
+
151
+ ```python
152
+ from glowtrace import Tracer
153
+ tr = Tracer()
154
+ tr.session("orch", "Orchestrator", input=question)
155
+ with tr.agent("a1", "researcher", parent="orch", system=SYSTEM, input=task) as a:
156
+ with tr.tool("t1", "sql_query", parent="a1", args=sql) as t:
157
+ t.result = run(sql)
158
+ a.output, a.tokens = answer, usage
159
+ ```
160
+
161
+ | event | fields |
162
+ |---|---|
163
+ | `node` | `id, kind (session/step/agent/llm/tool), parent, title, status, model, system, input, args` |
164
+ | `update` | `id, status (waiting/running/done/error), note, output, result, tokens` |
165
+ | `message` | `from, to, content, label, tokens` |
166
+ | `remove` | `id`: the node's children move up to its parent |
167
+
168
+ ## Deploy a public live demo
169
+
170
+ The `Dockerfile` runs glowtrace plus a real agent run every few minutes. Deploy it on Hugging Face Spaces (Docker), Render or Railway, and set `LLM_BASE_URL`, `LLM_API_KEY`, `LLM_MODEL` and `GLOWTRACE_TOKEN`. Visitors can watch, but they can't send data or spend your quota.
171
+
172
+ ## Development
173
+
174
+ ```
175
+ glowtrace/ Python: server, OTLP → graph mapper, tracer
176
+ web/ TypeScript UI (Vite) → builds into glowtrace/static/index.html
177
+ src/store.ts graph state + event handling (no DOM, unit-tested)
178
+ src/layout.ts tree layout
179
+ src/graph.ts cards, edges, follow-scroll
180
+ src/particles.ts message pulses
181
+ src/panel.ts activity feed + details panel
182
+ src/sources.ts live WebSocket + trace-file parsing
183
+ examples/ demo agent teams (agent_loop.py = a tiny hand-written agent, not part of the package)
184
+ tests/ Python tests
185
+ ```
186
+
187
+ ```bash
188
+ pip install -e ".[live]" pytest && pytest # backend
189
+ cd web && npm install && npm test && npm run build # UI
190
+ npm run dev # UI with hot reload; pick "Live" and connect to a running `glowtrace serve`
191
+ ```
192
+
193
+ The built `glowtrace/static/index.html` is committed so `pip install` needs no Node. CI checks it is up to date.
194
+
195
+ MIT licensed.
@@ -0,0 +1,174 @@
1
+ <div align="center">
2
+
3
+ # glowtrace
4
+
5
+ **Watch your AI agents work, live.**
6
+
7
+ A tiny OpenTelemetry receiver that turns agent traces into a live, glowing graph. You see which agent is running, what it's calling, and the exact prompt behind every step.
8
+
9
+ ![glowtrace demo](docs/demo.gif)
10
+
11
+ [Live demo](https://YOUR-USERNAME.github.io/glowtrace/) · [Quick start](#quick-start) · [Works with](#works-with) · [Compared to](#how-is-this-different) · [How it works](#how-it-works)
12
+
13
+ </div>
14
+
15
+ ---
16
+
17
+ Multi-agent systems get hard to follow once a few agents start handing work to each other. Something goes wrong and you end up scrolling a log. Dashboard tools are good for looking back at a run afterwards, but most of them don't show you the run *while it happens*.
18
+
19
+ glowtrace is for that moment. Start it and leave it open on a second screen while your agents run:
20
+
21
+ - **Agents, LLM calls and tool calls appear as they start.** The running ones glow, finished ones go quiet, and failures turn red.
22
+ - **Messages move along the edges**, so you can see who handed what to whom.
23
+ - **Click any node** to see its system prompt, the prompt messages, the completion, tool arguments and results, tokens, timing and the raw span attributes.
24
+ - **Framework plumbing is folded away.** `RunnableSequence`, prompt templates, routers and HTTP calls stay hidden, so the graph shows the parts you think about. Use `--all-spans` if you want everything.
25
+
26
+ ## How is this different?
27
+
28
+ | | glowtrace | LangGraph Studio | Arize Phoenix | agent-flow |
29
+ |---|---|---|---|---|
30
+ | Animated live graph while the run happens | ✅ | ✅ | trace views | ✅ |
31
+ | Works beyond one framework | ✅ any OpenTelemetry source | LangGraph only | ✅ | Claude Code only |
32
+ | Zero config for apps that already export OTel | ✅ port 4318 | — | ✅ (agent graph needs extra span attributes) | — |
33
+ | Folds framework plumbing into agent → LLM → tool | ✅ automatic | ✅ (graph nodes) | with span metadata | n/a |
34
+ | Setup | `pip install` + one command | LangGraph CLI / Agent Server | full platform | VS Code extension |
35
+
36
+ glowtrace is not a dashboard, an eval suite or an agent builder. It does one thing: lets you watch agents work, live, and click into any step. If you need stored history, evals and cost analytics, use Phoenix or Langfuse alongside it.
37
+
38
+ ## Quick start
39
+
40
+ ```bash
41
+ pip install glowtrace
42
+ glowtrace serve # → http://localhost:4318
43
+ ```
44
+
45
+ That's it. Port 4318 is OpenTelemetry's default OTLP/HTTP port, so **an app that already exports OTel traces shows up without code changes**. If your exporter points somewhere else, set:
46
+
47
+ ```bash
48
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
49
+ export OTEL_BSP_SCHEDULE_DELAY=200 # optional: send spans quickly instead of every 5s
50
+ ```
51
+
52
+ ### Make running steps glow, not just finished ones
53
+
54
+ Standard exporters only send a span after it ends. One extra line also streams span *starts*:
55
+
56
+ ```python
57
+ import glowtrace
58
+ glowtrace.instrument() # pip install "glowtrace[live]"
59
+ ```
60
+
61
+ ## Works with
62
+
63
+ glowtrace understands the three span conventions agent frameworks emit today:
64
+
65
+ | convention | emitted by |
66
+ |---|---|
67
+ | [OpenInference](https://github.com/Arize-ai/openinference) | instrumentors for LangChain / **LangGraph**, LlamaIndex, CrewAI, OpenAI Agents SDK, smolagents, DSPy, … |
68
+ | [OpenTelemetry GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/) (`gen_ai.*`) | frameworks with native OTel GenAI support, OpenLIT |
69
+ | [OpenLLMetry](https://github.com/traceloop/openllmetry) (`traceloop.*`) | Traceloop instrumentors |
70
+
71
+ Tested end to end with LangGraph ([`examples/langgraph_team.py`](examples/langgraph_team.py)) and with LangChain's official [langgraph-supervisor](https://github.com/langchain-ai/langgraph-supervisor-py) multi-agent quickstart, unmodified ([`examples/test_supervisor.py`](examples/test_supervisor.py)). The mapping for all three conventions is covered by unit tests. If your framework renders oddly, please open an issue with a trace attached, since that's the fastest way to fix it.
72
+
73
+ **LangGraph example:**
74
+
75
+ ```python
76
+ from openinference.instrumentation.langchain import LangChainInstrumentor
77
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
78
+ from opentelemetry.sdk.trace import TracerProvider
79
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
80
+ from opentelemetry import trace
81
+ import glowtrace
82
+
83
+ provider = TracerProvider()
84
+ provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
85
+ trace.set_tracer_provider(provider)
86
+ glowtrace.instrument() # optional, for live "running" state
87
+ LangChainInstrumentor().instrument(tracer_provider=provider)
88
+ # … build and run your graph as usual
89
+ ```
90
+
91
+ ### Try it without installing anything
92
+
93
+ The hosted demo plays a built-in, fictional agent run, and you can drop in any recorded `.jsonl` trace to replay it, slowly or step by step.
94
+
95
+ ### No LLM bill needed to try it
96
+
97
+ The examples run on any OpenAI-compatible endpoint, including a free local model:
98
+
99
+ ```bash
100
+ pip install "glowtrace[live]" openai langgraph langchain-openai langgraph-supervisor \
101
+ openinference-instrumentation-langchain opentelemetry-exporter-otlp-proto-http
102
+ ollama pull qwen2.5:7b
103
+ python examples/test_supervisor.py # LangChain's official multi-agent quickstart
104
+ python examples/langgraph_team.py # LangGraph team via OpenTelemetry
105
+ python examples/real_agents.py # plain-Python agents via glowtrace's own tracer
106
+ python examples/fake_run.py # scripted run, no LLM at all
107
+ ```
108
+
109
+ Groq, Gemini and OpenRouter also have free tiers. Set `LLM_BASE_URL`, `LLM_API_KEY` and `LLM_MODEL` to use one of them.
110
+
111
+ ## How it works
112
+
113
+ ```
114
+ your agents ──OTLP/HTTP (protobuf or JSON)──▶ glowtrace serve ──WebSocket──▶ browser
115
+ │
116
+ └─ span → graph mapper
117
+ ```
118
+
119
+ - **Out-of-order spans.** Exporters send children before parents. Unknown parents get a placeholder, shown as running, which is filled in when the real span arrives.
120
+ - **Folding.** Spans without AI semantics (HTTP, DB, framework internals) are folded into their parent. A generic LangGraph `agent` node is credited to the named sub-graph that owns it, so you see `researcher`, not `agent`.
121
+ - **Late joiners.** A tab opened mid-run receives the history and catches up.
122
+ - **Read-only sharing.** `glowtrace serve --token SECRET` means only requests carrying the token can send data. Everyone else can watch.
123
+
124
+ The UI is written in TypeScript with no framework, and builds to a single self-contained HTML file that ships inside the Python package. It also runs on its own: open it from GitHub Pages for the demo, or drop in a recorded `.jsonl` trace to replay a run.
125
+
126
+ ### Not using OpenTelemetry?
127
+
128
+ Use the small native tracer, or send JSON to `/ws` from any language:
129
+
130
+ ```python
131
+ from glowtrace import Tracer
132
+ tr = Tracer()
133
+ tr.session("orch", "Orchestrator", input=question)
134
+ with tr.agent("a1", "researcher", parent="orch", system=SYSTEM, input=task) as a:
135
+ with tr.tool("t1", "sql_query", parent="a1", args=sql) as t:
136
+ t.result = run(sql)
137
+ a.output, a.tokens = answer, usage
138
+ ```
139
+
140
+ | event | fields |
141
+ |---|---|
142
+ | `node` | `id, kind (session/step/agent/llm/tool), parent, title, status, model, system, input, args` |
143
+ | `update` | `id, status (waiting/running/done/error), note, output, result, tokens` |
144
+ | `message` | `from, to, content, label, tokens` |
145
+ | `remove` | `id`: the node's children move up to its parent |
146
+
147
+ ## Deploy a public live demo
148
+
149
+ The `Dockerfile` runs glowtrace plus a real agent run every few minutes. Deploy it on Hugging Face Spaces (Docker), Render or Railway, and set `LLM_BASE_URL`, `LLM_API_KEY`, `LLM_MODEL` and `GLOWTRACE_TOKEN`. Visitors can watch, but they can't send data or spend your quota.
150
+
151
+ ## Development
152
+
153
+ ```
154
+ glowtrace/ Python: server, OTLP → graph mapper, tracer
155
+ web/ TypeScript UI (Vite) → builds into glowtrace/static/index.html
156
+ src/store.ts graph state + event handling (no DOM, unit-tested)
157
+ src/layout.ts tree layout
158
+ src/graph.ts cards, edges, follow-scroll
159
+ src/particles.ts message pulses
160
+ src/panel.ts activity feed + details panel
161
+ src/sources.ts live WebSocket + trace-file parsing
162
+ examples/ demo agent teams (agent_loop.py = a tiny hand-written agent, not part of the package)
163
+ tests/ Python tests
164
+ ```
165
+
166
+ ```bash
167
+ pip install -e ".[live]" pytest && pytest # backend
168
+ cd web && npm install && npm test && npm run build # UI
169
+ npm run dev # UI with hot reload; pick "Live" and connect to a running `glowtrace serve`
170
+ ```
171
+
172
+ The built `glowtrace/static/index.html` is committed so `pip install` needs no Node. CI checks it is up to date.
173
+
174
+ MIT licensed.
@@ -0,0 +1,13 @@
1
+ """glowtrace — watch your agents think, live."""
2
+ from __future__ import annotations
3
+
4
+ from .tracer import Tracer
5
+
6
+ __all__ = ["Tracer", "instrument"]
7
+ __version__ = "0.3.0"
8
+
9
+
10
+ def instrument(endpoint: str | None = None, service_name: str | None = None, token: str | None = None):
11
+ """Stream OpenTelemetry spans to glowtrace live (span starts too). Needs glowtrace[live]."""
12
+ from .live import instrument as _instrument
13
+ return _instrument(endpoint, service_name, token)
@@ -0,0 +1,27 @@
1
+ import argparse
2
+ import os
3
+
4
+
5
+ def main():
6
+ ap = argparse.ArgumentParser(prog="glowtrace", description="Live visualizer for multi-agent systems")
7
+ sub = ap.add_subparsers(dest="cmd", required=True)
8
+ s = sub.add_parser("serve", help="serve the UI, the event stream and an OTLP/HTTP trace receiver")
9
+ s.add_argument("--host", default=os.environ.get("GLOWTRACE_HOST", "localhost"))
10
+ s.add_argument("--port", type=int, default=int(os.environ.get("PORT", 4318)),
11
+ help="default 4318 = OpenTelemetry's standard OTLP/HTTP port")
12
+ s.add_argument("--token", default=os.environ.get("GLOWTRACE_TOKEN"),
13
+ help="only clients with this token may send data (use when hosting publicly)")
14
+ s.add_argument("--all-spans", action="store_true",
15
+ help="also show non-AI spans (HTTP, DB…); hidden by default")
16
+ args = ap.parse_args()
17
+
18
+ if args.cmd == "serve":
19
+ from .server import run
20
+ try:
21
+ run(args.host, args.port, args.token, args.all_spans)
22
+ except KeyboardInterrupt:
23
+ pass
24
+
25
+
26
+ if __name__ == "__main__":
27
+ main()
@@ -0,0 +1,120 @@
1
+ """Optional: make running spans glow *while* they run.
2
+
3
+ Standard OTel exporters only send a span after it ends, so glowtrace sees
4
+ finished work. `glowtrace.instrument()` adds a span processor that also
5
+ reports span *starts* immediately and ships ends without batching delay.
6
+
7
+ import glowtrace
8
+ glowtrace.instrument() # before your framework instrumentor
9
+ OpenAIInstrumentor().instrument() # or LangChainInstrumentor, CrewAIInstrumentor, …
10
+
11
+ Needs `pip install glowtrace[live]` (opentelemetry-sdk).
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import queue
18
+ import threading
19
+ import urllib.request
20
+
21
+ try:
22
+ from opentelemetry import trace
23
+ from opentelemetry.sdk.resources import Resource
24
+ from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
25
+ except ImportError as e: # pragma: no cover
26
+ raise ImportError("glowtrace live mode needs the OpenTelemetry SDK: pip install 'glowtrace[live]'") from e
27
+
28
+
29
+ def _any(v):
30
+ if isinstance(v, bool):
31
+ return {"boolValue": v}
32
+ if isinstance(v, int):
33
+ return {"intValue": str(v)}
34
+ if isinstance(v, float):
35
+ return {"doubleValue": v}
36
+ if isinstance(v, (list, tuple)):
37
+ return {"arrayValue": {"values": [_any(x) for x in v]}}
38
+ return {"stringValue": str(v)}
39
+
40
+
41
+ def _attrs(d) -> list:
42
+ return [{"key": k, "value": _any(v)} for k, v in (d or {}).items()]
43
+
44
+
45
+ def _span_json(span, ended: bool) -> dict:
46
+ ctx = span.get_span_context()
47
+ out = {
48
+ "traceId": format(ctx.trace_id, "032x"),
49
+ "spanId": format(ctx.span_id, "016x"),
50
+ "parentSpanId": format(span.parent.span_id, "016x") if span.parent else "",
51
+ "name": span.name,
52
+ "startTimeUnixNano": str(span.start_time or 0),
53
+ "endTimeUnixNano": str(span.end_time or 0) if ended else "0",
54
+ "attributes": _attrs(span.attributes),
55
+ }
56
+ if ended:
57
+ out["status"] = {"code": span.status.status_code.value, "message": span.status.description or ""}
58
+ out["events"] = [{"name": e.name, "attributes": _attrs(e.attributes)} for e in span.events]
59
+ return out
60
+
61
+
62
+ class LiveSpanProcessor(SpanProcessor):
63
+ """Posts span starts and ends to glowtrace as OTLP/JSON from a background thread."""
64
+
65
+ def __init__(self, endpoint: str | None = None, token: str | None = None):
66
+ base = endpoint or os.environ.get("GLOWTRACE_OTLP", "http://localhost:4318")
67
+ self.url = base.rstrip("/") + ("" if base.rstrip("/").endswith("/v1/traces") else "/v1/traces")
68
+ self.headers = {"Content-Type": "application/json"}
69
+ token = token or os.environ.get("GLOWTRACE_TOKEN")
70
+ if token:
71
+ self.headers["Authorization"] = f"Bearer {token}"
72
+ self.q: queue.Queue = queue.Queue(maxsize=10_000)
73
+ self._warned = False
74
+ threading.Thread(target=self._loop, daemon=True).start()
75
+
76
+ def on_start(self, span, parent_context=None):
77
+ self._put(span, ended=False)
78
+
79
+ def on_end(self, span):
80
+ self._put(span, ended=True)
81
+
82
+ def _put(self, span, ended):
83
+ try:
84
+ self.q.put_nowait((span.resource, _span_json(span, ended)))
85
+ except queue.Full:
86
+ pass
87
+
88
+ def _loop(self):
89
+ while True:
90
+ items = [self.q.get()]
91
+ while not self.q.empty() and len(items) < 200:
92
+ items.append(self.q.get_nowait())
93
+ by_res: dict = {}
94
+ for res, sj in items:
95
+ by_res.setdefault(id(res), (res, []))[1].append(sj)
96
+ body = {"resourceSpans": [{"resource": {"attributes": _attrs(res.attributes)},
97
+ "scopeSpans": [{"spans": spans}]} for res, spans in by_res.values()]}
98
+ try:
99
+ req = urllib.request.Request(self.url, json.dumps(body).encode(), self.headers, method="POST")
100
+ urllib.request.urlopen(req, timeout=3).read()
101
+ except Exception as e:
102
+ if not self._warned:
103
+ print(f"[glowtrace] could not reach {self.url} ({e}); is `glowtrace serve` running?")
104
+ self._warned = True
105
+
106
+ def shutdown(self):
107
+ pass
108
+
109
+ def force_flush(self, timeout_millis: int = 30000):
110
+ return True
111
+
112
+
113
+ def instrument(endpoint: str | None = None, service_name: str | None = None, token: str | None = None):
114
+ """Attach glowtrace to the global TracerProvider (creating one if needed)."""
115
+ provider = trace.get_tracer_provider()
116
+ if not isinstance(provider, TracerProvider):
117
+ provider = TracerProvider(resource=Resource.create({"service.name": service_name or "glowtrace-app"}))
118
+ trace.set_tracer_provider(provider)
119
+ provider.add_span_processor(LiveSpanProcessor(endpoint, token))
120
+ return provider