swaptrace 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Holden Anderson
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,221 @@
1
+ Metadata-Version: 2.4
2
+ Name: swaptrace
3
+ Version: 0.1.0
4
+ Summary: Trace and compare LLM swap attempts.
5
+ Author: Holden Anderson
6
+ License-Expression: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.11
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Requires-Python: >=3.11
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest; extra == "dev"
15
+ Provides-Extra: swapllm
16
+ Requires-Dist: swapllm>=0.1.0; extra == "swapllm"
17
+ Dynamic: license-file
18
+
19
+ # swaptrace
20
+
21
+ **Fallback-cascade observability for multi-provider LLM routers — see every attempt, not just the final answer.**
22
+
23
+ ## The problem
24
+
25
+ When a router falls back across providers — Groq rate-limits, so it tries OpenAI,
26
+ which times out, so it tries Anthropic, which answers — the only thing you get
27
+ back is that final answer. The retry history is thrown away the moment a provider
28
+ succeeds. But that history is exactly what answers *"why did this request cost 3×
29
+ the usual"* and *"which provider is actually carrying the traffic."* `swaptrace`
30
+ records every attempt in a cascade — provider, model, outcome, latency, token
31
+ cost — and keeps them whether the trace ends in success or in exhaustion.
32
+
33
+ ## Install
34
+
35
+ ```
36
+ pip install swaptrace
37
+ ```
38
+
39
+ For the [swapLLM](https://github.com/HWalker13/swapllm) integration:
40
+
41
+ ```
42
+ pip install "swaptrace[swapllm]"
43
+ ```
44
+
45
+ `swaptrace`'s core is standard-library only — no runtime dependencies. The
46
+ `swapllm` extra is opt-in.
47
+
48
+ ## Quickstart
49
+
50
+ ### Standalone
51
+
52
+ Wrap your own retry loop. `swaptrace` defines no exception types and makes no HTTP
53
+ calls — you classify each failure, it does the bookkeeping.
54
+
55
+ ```python
56
+ from swaptrace import Trace
57
+
58
+
59
+ class RateLimited(Exception):
60
+ """Your own exception type — swaptrace defines none of its own."""
61
+
62
+
63
+ def call_provider(name):
64
+ if name == "groq":
65
+ raise RateLimited("429 Too Many Requests")
66
+ return {"text": "...", "prompt_tokens": 41, "completion_tokens": 12}
67
+
68
+
69
+ with Trace() as trace:
70
+ for provider in ["groq", "openai"]:
71
+ with trace.attempt(provider=provider, model="llama-3.1-8b-instant") as attempt:
72
+ try:
73
+ resp = call_provider(provider)
74
+ except RateLimited as err:
75
+ attempt.record_failure(err, retryable=True)
76
+ continue
77
+ attempt.record_success(
78
+ resp,
79
+ prompt_tokens=resp["prompt_tokens"],
80
+ completion_tokens=resp["completion_tokens"],
81
+ )
82
+ break
83
+
84
+ print(trace.final_status) # success
85
+ print(trace.winning_provider) # openai
86
+ print(trace.retry_count) # 1
87
+ for a in trace.attempts:
88
+ print(a.attempt_index, a.provider, a.outcome, a.error_type, a.cost_usd)
89
+ # 0 groq retryable_error RateLimited None
90
+ # 1 openai success None 3.0100000000000004e-06
91
+ ```
92
+
93
+ `cost_usd` is estimated from a small built-in per-token price table
94
+ (`swaptrace.pricing.DEFAULT_PRICING`). For models it doesn't know, pass
95
+ `pricing_overrides={"model-name": (input_rate, output_rate)}` to
96
+ `record_success` — rates are USD per million tokens.
97
+
98
+ ### swapLLM integration
99
+
100
+ `traced()` wraps a `swapllm.Router` and records a `Trace` for every `.complete()`
101
+ call — without changing what `.complete()` returns or which exceptions it raises,
102
+ so existing call sites are untouched.
103
+
104
+ ```python
105
+ from swapllm import Router, GroqProvider, OpenAIProvider
106
+ from swaptrace import storage
107
+ from swaptrace.integrations.swapllm import traced
108
+
109
+ router = Router(
110
+ providers=[
111
+ GroqProvider(api_key=..., model="llama-3.1-8b-instant"),
112
+ OpenAIProvider(api_key=..., model="gpt-4o-mini"),
113
+ ],
114
+ fallback_order=["groq", "openai"],
115
+ )
116
+
117
+ # record every trace to a JSONL file as it completes
118
+ router = traced(
119
+ router,
120
+ on_trace=lambda t: storage.append_trace(t, ".swaptrace/traces.jsonl"),
121
+ )
122
+
123
+ answer = router.complete(messages=[{"role": "user", "content": "..."}])
124
+
125
+ router.last_trace.winning_provider
126
+ # "openai"
127
+ [(a.provider, a.outcome) for a in router.last_trace.attempts]
128
+ # [('groq', 'retryable_error'), ('openai', 'success')]
129
+ ```
130
+
131
+ `traced()` re-implements swapLLM's fallback loop instead of wrapping
132
+ `Router.complete()`: swapLLM discards per-attempt information once a provider
133
+ succeeds, so the only way to observe it is to drive the loop. `AllProvidersFailedError`,
134
+ `ProviderRequestError`, and schema-validation behaviour are preserved exactly.
135
+ swapLLM's provider adapters return only text, so `cost_usd` stays `None` for
136
+ swapLLM-traced attempts.
137
+
138
+ ## CLI
139
+
140
+ `swaptrace` never writes trace files on its own — wire `storage.append_trace`
141
+ into `on_trace` as shown above. It reads `.swaptrace/traces.jsonl` (relative to
142
+ the working directory — traces are per-project, like `.git/`) by default;
143
+ override with `--path`.
144
+
145
+ ### `swaptrace query`
146
+
147
+ List traces, optionally filtered. `--provider` and `--status` match a trace if
148
+ *any* of its attempts matches; `--min-cost` is checked against the trace total.
149
+ Active filters combine with AND.
150
+
151
+ ```
152
+ $ swaptrace query
153
+ 2026-09-03T19:35:13.726568+00:00 a60d166a success groq 1 attempt(s) $0.000025 25.0ms
154
+ 2026-09-03T19:35:13.752308+00:00 a34ff498 success openai 2 attempt(s) $0.000221 45.1ms
155
+ 2026-09-03T19:35:13.798053+00:00 4847ffd3 success anthropic 3 attempt(s) $0.001980 70.5ms
156
+ 2026-09-03T19:35:13.869284+00:00 c627f556 exhausted - 3 attempt(s) $0.000000 68.6ms
157
+ 2026-09-03T19:35:13.939634+00:00 9647ec87 exhausted - 1 attempt(s) $0.000000 22.1ms
158
+ 5 of 5 trace(s).
159
+
160
+ $ swaptrace query --min-cost 0.001
161
+ 2026-09-03T19:35:13.798053+00:00 4847ffd3 success anthropic 3 attempt(s) $0.001980 70.5ms
162
+ 1 of 5 trace(s).
163
+ ```
164
+
165
+ ### `swaptrace report --compare-providers`
166
+
167
+ Flatten every attempt across every trace, grouped by provider — reliability,
168
+ latency, and cost side by side, most reliable first.
169
+
170
+ ```
171
+ $ swaptrace report --compare-providers
172
+ PROVIDER ATTEMPTS SUCCESSES SUCCESS% AVG LATENCY TOTAL COST $/SUCCESS
173
+ anthropic 2 1 50.0% 22.3ms $0.001980 $0.001980
174
+ groq 4 1 25.0% 23.6ms $0.000025 $0.000025
175
+ openai 4 1 25.0% 23.1ms $0.000221 $0.000221
176
+ ```
177
+
178
+ `SUCCESS%` is per-attempt reliability (successes ÷ attempts, across all traces);
179
+ `AVG LATENCY` is over every attempt, successful or not; `$/SUCCESS` is `-` for a
180
+ provider that has never succeeded.
181
+
182
+ ## Instrumentation overhead
183
+
184
+ Wrapping a provider call in swaptrace's `Trace`/`Attempt` bookkeeping adds a
185
+ measured **7.75 µs per call at the median and 7.96 µs at p95** (CPython 3.12.8,
186
+ macOS arm64; 5 trials × 1000 iterations, warm-up, GC disabled, `time.perf_counter`).
187
+ That overhead is a fixed cost of swaptrace's own work — a couple of `uuid4()` and
188
+ `datetime.now()` calls, the trace rollup, a pricing-table lookup — and does not
189
+ scale with the wrapped call, so against a typical 200 ms–2 s LLM API call it is
190
+ **well under 0.01%** (≈0.008% at 100 ms, ≈0.0004% at 2 s). Reproduce with
191
+ `python benchmarks/benchmark_overhead.py`; the full raw dataset is in
192
+ `benchmarks/results/`.
193
+
194
+ ## What this isn't
195
+
196
+ - No hosted dashboard or web UI — `swaptrace query` / `report` are the interface.
197
+ - No OpenTelemetry / OTLP exporter yet.
198
+ - No streaming-response support.
199
+ - No multi-agent span tracing (agentrace-ai / spyllm cover that space) — a
200
+ `swaptrace` trace is scoped to a single provider cascade.
201
+
202
+ ## Development
203
+
204
+ ```
205
+ pip install -e ".[dev]"
206
+ pytest
207
+ ```
208
+
209
+ runs the core suite — **61 passed, 1 skipped** (the swapLLM integration tests
210
+ skip when the extra isn't installed). For the full **73**:
211
+
212
+ ```
213
+ pip install -e ".[dev,swapllm]"
214
+ pytest
215
+ ```
216
+
217
+ Requires Python 3.11+.
218
+
219
+ ## License
220
+
221
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,203 @@
1
+ # swaptrace
2
+
3
+ **Fallback-cascade observability for multi-provider LLM routers — see every attempt, not just the final answer.**
4
+
5
+ ## The problem
6
+
7
+ When a router falls back across providers — Groq rate-limits, so it tries OpenAI,
8
+ which times out, so it tries Anthropic, which answers — the only thing you get
9
+ back is that final answer. The retry history is thrown away the moment a provider
10
+ succeeds. But that history is exactly what answers *"why did this request cost 3×
11
+ the usual"* and *"which provider is actually carrying the traffic."* `swaptrace`
12
+ records every attempt in a cascade — provider, model, outcome, latency, token
13
+ cost — and keeps them whether the trace ends in success or in exhaustion.
14
+
15
+ ## Install
16
+
17
+ ```
18
+ pip install swaptrace
19
+ ```
20
+
21
+ For the [swapLLM](https://github.com/HWalker13/swapllm) integration:
22
+
23
+ ```
24
+ pip install "swaptrace[swapllm]"
25
+ ```
26
+
27
+ `swaptrace`'s core is standard-library only — no runtime dependencies. The
28
+ `swapllm` extra is opt-in.
29
+
30
+ ## Quickstart
31
+
32
+ ### Standalone
33
+
34
+ Wrap your own retry loop. `swaptrace` defines no exception types and makes no HTTP
35
+ calls — you classify each failure, it does the bookkeeping.
36
+
37
+ ```python
38
+ from swaptrace import Trace
39
+
40
+
41
+ class RateLimited(Exception):
42
+ """Your own exception type — swaptrace defines none of its own."""
43
+
44
+
45
+ def call_provider(name):
46
+ if name == "groq":
47
+ raise RateLimited("429 Too Many Requests")
48
+ return {"text": "...", "prompt_tokens": 41, "completion_tokens": 12}
49
+
50
+
51
+ with Trace() as trace:
52
+ for provider in ["groq", "openai"]:
53
+ with trace.attempt(provider=provider, model="llama-3.1-8b-instant") as attempt:
54
+ try:
55
+ resp = call_provider(provider)
56
+ except RateLimited as err:
57
+ attempt.record_failure(err, retryable=True)
58
+ continue
59
+ attempt.record_success(
60
+ resp,
61
+ prompt_tokens=resp["prompt_tokens"],
62
+ completion_tokens=resp["completion_tokens"],
63
+ )
64
+ break
65
+
66
+ print(trace.final_status) # success
67
+ print(trace.winning_provider) # openai
68
+ print(trace.retry_count) # 1
69
+ for a in trace.attempts:
70
+ print(a.attempt_index, a.provider, a.outcome, a.error_type, a.cost_usd)
71
+ # 0 groq retryable_error RateLimited None
72
+ # 1 openai success None 3.0100000000000004e-06
73
+ ```
74
+
75
+ `cost_usd` is estimated from a small built-in per-token price table
76
+ (`swaptrace.pricing.DEFAULT_PRICING`). For models it doesn't know, pass
77
+ `pricing_overrides={"model-name": (input_rate, output_rate)}` to
78
+ `record_success` — rates are USD per million tokens.
79
+
80
+ ### swapLLM integration
81
+
82
+ `traced()` wraps a `swapllm.Router` and records a `Trace` for every `.complete()`
83
+ call — without changing what `.complete()` returns or which exceptions it raises,
84
+ so existing call sites are untouched.
85
+
86
+ ```python
87
+ from swapllm import Router, GroqProvider, OpenAIProvider
88
+ from swaptrace import storage
89
+ from swaptrace.integrations.swapllm import traced
90
+
91
+ router = Router(
92
+ providers=[
93
+ GroqProvider(api_key=..., model="llama-3.1-8b-instant"),
94
+ OpenAIProvider(api_key=..., model="gpt-4o-mini"),
95
+ ],
96
+ fallback_order=["groq", "openai"],
97
+ )
98
+
99
+ # record every trace to a JSONL file as it completes
100
+ router = traced(
101
+ router,
102
+ on_trace=lambda t: storage.append_trace(t, ".swaptrace/traces.jsonl"),
103
+ )
104
+
105
+ answer = router.complete(messages=[{"role": "user", "content": "..."}])
106
+
107
+ router.last_trace.winning_provider
108
+ # "openai"
109
+ [(a.provider, a.outcome) for a in router.last_trace.attempts]
110
+ # [('groq', 'retryable_error'), ('openai', 'success')]
111
+ ```
112
+
113
+ `traced()` re-implements swapLLM's fallback loop instead of wrapping
114
+ `Router.complete()`: swapLLM discards per-attempt information once a provider
115
+ succeeds, so the only way to observe it is to drive the loop. `AllProvidersFailedError`,
116
+ `ProviderRequestError`, and schema-validation behaviour are preserved exactly.
117
+ swapLLM's provider adapters return only text, so `cost_usd` stays `None` for
118
+ swapLLM-traced attempts.
119
+
120
+ ## CLI
121
+
122
+ `swaptrace` never writes trace files on its own — wire `storage.append_trace`
123
+ into `on_trace` as shown above. It reads `.swaptrace/traces.jsonl` (relative to
124
+ the working directory — traces are per-project, like `.git/`) by default;
125
+ override with `--path`.
126
+
127
+ ### `swaptrace query`
128
+
129
+ List traces, optionally filtered. `--provider` and `--status` match a trace if
130
+ *any* of its attempts matches; `--min-cost` is checked against the trace total.
131
+ Active filters combine with AND.
132
+
133
+ ```
134
+ $ swaptrace query
135
+ 2026-09-03T19:35:13.726568+00:00 a60d166a success groq 1 attempt(s) $0.000025 25.0ms
136
+ 2026-09-03T19:35:13.752308+00:00 a34ff498 success openai 2 attempt(s) $0.000221 45.1ms
137
+ 2026-09-03T19:35:13.798053+00:00 4847ffd3 success anthropic 3 attempt(s) $0.001980 70.5ms
138
+ 2026-09-03T19:35:13.869284+00:00 c627f556 exhausted - 3 attempt(s) $0.000000 68.6ms
139
+ 2026-09-03T19:35:13.939634+00:00 9647ec87 exhausted - 1 attempt(s) $0.000000 22.1ms
140
+ 5 of 5 trace(s).
141
+
142
+ $ swaptrace query --min-cost 0.001
143
+ 2026-09-03T19:35:13.798053+00:00 4847ffd3 success anthropic 3 attempt(s) $0.001980 70.5ms
144
+ 1 of 5 trace(s).
145
+ ```
146
+
147
+ ### `swaptrace report --compare-providers`
148
+
149
+ Flatten every attempt across every trace, grouped by provider — reliability,
150
+ latency, and cost side by side, most reliable first.
151
+
152
+ ```
153
+ $ swaptrace report --compare-providers
154
+ PROVIDER ATTEMPTS SUCCESSES SUCCESS% AVG LATENCY TOTAL COST $/SUCCESS
155
+ anthropic 2 1 50.0% 22.3ms $0.001980 $0.001980
156
+ groq 4 1 25.0% 23.6ms $0.000025 $0.000025
157
+ openai 4 1 25.0% 23.1ms $0.000221 $0.000221
158
+ ```
159
+
160
+ `SUCCESS%` is per-attempt reliability (successes ÷ attempts, across all traces);
161
+ `AVG LATENCY` is over every attempt, successful or not; `$/SUCCESS` is `-` for a
162
+ provider that has never succeeded.
163
+
164
+ ## Instrumentation overhead
165
+
166
+ Wrapping a provider call in swaptrace's `Trace`/`Attempt` bookkeeping adds a
167
+ measured **7.75 µs per call at the median and 7.96 µs at p95** (CPython 3.12.8,
168
+ macOS arm64; 5 trials × 1000 iterations, warm-up, GC disabled, `time.perf_counter`).
169
+ That overhead is a fixed cost of swaptrace's own work — a couple of `uuid4()` and
170
+ `datetime.now()` calls, the trace rollup, a pricing-table lookup — and does not
171
+ scale with the wrapped call, so against a typical 200 ms–2 s LLM API call it is
172
+ **well under 0.01%** (≈0.008% at 100 ms, ≈0.0004% at 2 s). Reproduce with
173
+ `python benchmarks/benchmark_overhead.py`; the full raw dataset is in
174
+ `benchmarks/results/`.
175
+
176
+ ## What this isn't
177
+
178
+ - No hosted dashboard or web UI — `swaptrace query` / `report` are the interface.
179
+ - No OpenTelemetry / OTLP exporter yet.
180
+ - No streaming-response support.
181
+ - No multi-agent span tracing (agentrace-ai / spyllm cover that space) — a
182
+ `swaptrace` trace is scoped to a single provider cascade.
183
+
184
+ ## Development
185
+
186
+ ```
187
+ pip install -e ".[dev]"
188
+ pytest
189
+ ```
190
+
191
+ runs the core suite — **61 passed, 1 skipped** (the swapLLM integration tests
192
+ skip when the extra isn't installed). For the full **73**:
193
+
194
+ ```
195
+ pip install -e ".[dev,swapllm]"
196
+ pytest
197
+ ```
198
+
199
+ Requires Python 3.11+.
200
+
201
+ ## License
202
+
203
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "swaptrace"
7
+ version = "0.1.0"
8
+ description = "Trace and compare LLM swap attempts."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Holden Anderson" }]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Programming Language :: Python :: 3.12",
18
+ ]
19
+
20
+ [project.optional-dependencies]
21
+ dev = ["pytest"]
22
+ swapllm = ["swapllm>=0.1.0"]
23
+
24
+ [project.scripts]
25
+ swaptrace = "swaptrace.cli:main"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
29
+
30
+ [tool.pytest.ini_options]
31
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ """swaptrace -- trace and compare LLM swap attempts."""
2
+
3
+ from swaptrace.core import Attempt, AttemptOutcome, Trace, TraceStatus
4
+
5
+ __all__ = ["Trace", "Attempt", "AttemptOutcome", "TraceStatus"]