trainhiro-sdk 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.

Potentially problematic release.


This version of trainhiro-sdk might be problematic. Click here for more details.

Files changed (36) hide show
  1. trainhiro_sdk-0.1.0/.gitignore +3 -0
  2. trainhiro_sdk-0.1.0/LICENSE +23 -0
  3. trainhiro_sdk-0.1.0/PKG-INFO +257 -0
  4. trainhiro_sdk-0.1.0/README.md +223 -0
  5. trainhiro_sdk-0.1.0/hatch_build.py +24 -0
  6. trainhiro_sdk-0.1.0/pyproject.toml +75 -0
  7. trainhiro_sdk-0.1.0/src/trainhiro/__init__.py +50 -0
  8. trainhiro_sdk-0.1.0/src/trainhiro/__main__.py +7 -0
  9. trainhiro_sdk-0.1.0/src/trainhiro/_record.py +633 -0
  10. trainhiro_sdk-0.1.0/src/trainhiro/_util.py +103 -0
  11. trainhiro_sdk-0.1.0/src/trainhiro/cli.py +915 -0
  12. trainhiro_sdk-0.1.0/src/trainhiro/context.py +267 -0
  13. trainhiro_sdk-0.1.0/src/trainhiro/export.py +38 -0
  14. trainhiro_sdk-0.1.0/src/trainhiro/exporters.py +810 -0
  15. trainhiro_sdk-0.1.0/src/trainhiro/integrations/__init__.py +188 -0
  16. trainhiro_sdk-0.1.0/src/trainhiro/integrations/_common.py +275 -0
  17. trainhiro_sdk-0.1.0/src/trainhiro/integrations/anthropic.py +186 -0
  18. trainhiro_sdk-0.1.0/src/trainhiro/integrations/langchain.py +608 -0
  19. trainhiro_sdk-0.1.0/src/trainhiro/integrations/openai.py +408 -0
  20. trainhiro_sdk-0.1.0/src/trainhiro/pricing.json +394 -0
  21. trainhiro_sdk-0.1.0/src/trainhiro/pricing.py +285 -0
  22. trainhiro_sdk-0.1.0/src/trainhiro/py.typed +0 -0
  23. trainhiro_sdk-0.1.0/src/trainhiro/redaction.json +174 -0
  24. trainhiro_sdk-0.1.0/src/trainhiro/routing/__init__.py +54 -0
  25. trainhiro_sdk-0.1.0/src/trainhiro/routing/config.py +500 -0
  26. trainhiro_sdk-0.1.0/src/trainhiro/routing/gate.py +877 -0
  27. trainhiro_sdk-0.1.0/src/trainhiro/routing/jsonschema_subset.py +383 -0
  28. trainhiro_sdk-0.1.0/src/trainhiro/routing/router.py +1464 -0
  29. trainhiro_sdk-0.1.0/src/trainhiro/routing/safe_regex.py +565 -0
  30. trainhiro_sdk-0.1.0/src/trainhiro/routing/translate.py +864 -0
  31. trainhiro_sdk-0.1.0/src/trainhiro/schema/__init__.py +76 -0
  32. trainhiro_sdk-0.1.0/src/trainhiro/schema/routing.v1.json +165 -0
  33. trainhiro_sdk-0.1.0/src/trainhiro/schema/span.v1.json +249 -0
  34. trainhiro_sdk-0.1.0/src/trainhiro/scrub.py +633 -0
  35. trainhiro_sdk-0.1.0/src/trainhiro/span.py +305 -0
  36. trainhiro_sdk-0.1.0/src/trainhiro/step_key.py +135 -0
@@ -0,0 +1,3 @@
1
+ __pycache__/
2
+ *.pyc
3
+ dist/
@@ -0,0 +1,23 @@
1
+ PLACEHOLDER NOTICE - NOT REVIEWED BY A LAWYER
2
+ =============================================
3
+
4
+ This file is a placeholder written by engineering. It has not been reviewed by
5
+ counsel and is not the final licence text. A lawyer must review and replace it
6
+ (including the name of the legal entity below) before this package is given to
7
+ any customer.
8
+
9
+ ---------------------------------------------------------------------------
10
+
11
+ Copyright (c) 2026 Hiro. All rights reserved.
12
+
13
+ This software and its documentation (the "Software") are proprietary and
14
+ confidential to Hiro.
15
+
16
+ The Software may be used only under, and in accordance with, a written
17
+ agreement with Hiro. Without such an agreement no licence or other right is
18
+ granted, whether by implication, estoppel or otherwise, and you may not use,
19
+ copy, modify, merge, publish, distribute, sublicense or sell the Software or
20
+ any part of it.
21
+
22
+ Except as that written agreement expressly states, the Software is provided
23
+ "as is", without warranty of any kind.
@@ -0,0 +1,257 @@
1
+ Metadata-Version: 2.5
2
+ Name: trainhiro-sdk
3
+ Version: 0.1.0
4
+ Summary: Trace your app's LLM calls to Hiro, which builds small models for the steps that do not need a frontier model
5
+ Project-URL: Homepage, https://trainhiro.com
6
+ Project-URL: Documentation, https://docs.trainhiro.com
7
+ Author: Hiro
8
+ License-Expression: LicenseRef-Proprietary
9
+ License-File: LICENSE
10
+ Keywords: anthropic,langchain,llm,observability,openai,tracing
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Classifier: Topic :: System :: Monitoring
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Provides-Extra: all
24
+ Requires-Dist: anthropic>=0.40; extra == 'all'
25
+ Requires-Dist: langchain-core>=0.3.30; extra == 'all'
26
+ Requires-Dist: openai>=1.0; extra == 'all'
27
+ Provides-Extra: anthropic
28
+ Requires-Dist: anthropic>=0.40; extra == 'anthropic'
29
+ Provides-Extra: langchain
30
+ Requires-Dist: langchain-core>=0.3.30; extra == 'langchain'
31
+ Provides-Extra: openai
32
+ Requires-Dist: openai>=1.0; extra == 'openai'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # trainhiro-sdk
36
+
37
+ The Python SDK for [Hiro](https://trainhiro.com). It records every LLM call your app makes, scrubs personal
38
+ data out of each record inside your process, and sends the records to Hiro. Hiro finds the steps of your app
39
+ that a small open-weight model can do as well as the frontier model you call today, builds that model, and
40
+ proves it on held-out data before anything changes in your app.
41
+
42
+ Python 3.12 or newer. No runtime dependencies. Recording never blocks or breaks your LLM calls: everything
43
+ after the call (scrubbing, batching, sending) happens on a background thread, and every failure there is
44
+ logged and dropped, never raised.
45
+
46
+ ## Install
47
+
48
+ ```sh
49
+ pip install trainhiro-sdk
50
+ ```
51
+
52
+ It traces the `openai` and `anthropic` clients you already have installed. Extras pin known-good versions if
53
+ you want them: `trainhiro-sdk[openai]`, `[anthropic]`, `[langchain]` (for the LangChain callback handler) or
54
+ `[all]`.
55
+
56
+ ## Set up
57
+
58
+ **1. Look at your project.** From your project's root folder:
59
+
60
+ ```sh
61
+ trainhiro init
62
+ ```
63
+
64
+ It checks your Python version, finds the LLM libraries you use (and says plainly if one is not supported),
65
+ lists where LLM clients are created and which calls build their prompt per call, and shows the lines to add.
66
+ It changes no file; `trainhiro init --write-env-example` also adds an empty `HIRO_API_KEY=` line to
67
+ `.env.example`.
68
+
69
+ **2. Add two lines** where your app starts, before it makes any LLM call:
70
+
71
+ ```python
72
+ import trainhiro
73
+ trainhiro.instrument()
74
+ ```
75
+
76
+ Every OpenAI and Anthropic client in the process is now recorded, including clients created later.
77
+
78
+ **3. Name the steps whose prompt changes per call.** Hiro groups calls into steps by their system prompt and
79
+ tools. A system prompt that contains per-call data (a user's name, today's date, a retrieved document) would
80
+ make every call look like a new step, so give those calls a stable name:
81
+
82
+ ```python
83
+ with trainhiro.step("draft_reply"):
84
+ client.messages.create(model="claude-sonnet-5-5", max_tokens=1024, system=system_prompt, messages=messages)
85
+ ```
86
+
87
+ `trainhiro init` lists the calls that need one. `trainhiro.step` also works as a decorator on sync and async
88
+ functions.
89
+
90
+ **4. Set your key and check.** Create a key in the Hiro dashboard (use a staging key first), then:
91
+
92
+ ```sh
93
+ export HIRO_API_KEY=hiro_test_...
94
+ trainhiro check
95
+ ```
96
+
97
+ `trainhiro check` sends one scrubbed test span and waits until Hiro confirms it arrived. On any problem it
98
+ exits non-zero with a one-line fix. Then set `HIRO_API_KEY` on your server and deploy. Unset it to turn
99
+ sending off.
100
+
101
+ ## What leaves your process
102
+
103
+ For each LLM call, one record ("span"): the provider and model, the request (system prompt, messages, tools,
104
+ parameters), the response (content, tool calls, stop reason), token usage, latency, an estimated cost, the
105
+ step name and key, and success or error. The API keys your OpenAI and Anthropic clients use are not part of
106
+ it, and your Hiro key is sent only in the `Authorization` header, never inside a span.
107
+
108
+ **Scrubbing.** Before a span is sent, the SDK replaces personal data and secrets in every text field with
109
+ placeholders: emails, phone numbers, card numbers, US social security numbers, IBANs, IP addresses, street
110
+ addresses and postcodes, API keys and tokens (OpenAI, Anthropic, AWS, GitHub, JWT, bearer tokens, private
111
+ keys, Hiro keys). The same value gets the same placeholder within a span (`[EMAIL_1]` twice), a different
112
+ value the next number (`[EMAIL_2]`), and numbering starts again for every span. Fields that are not free text
113
+ (ids, model, token counts, timings, tool names, message roles) are kept as they are, and so are JSON numbers:
114
+ a number field, such as a card number passed as an integer in a tool call's input, is not scrubbed in your
115
+ process. Hiro scrubs again when the span arrives, and that pass also checks numbers.
116
+
117
+ Each scrubbed span says so (`hiro.scrubbed: true`) and how many values were replaced
118
+ (`hiro.scrub.matches`), never what they were. A span with more than 500,000 characters of text, more than
119
+ 10,000 values to replace, or one that takes longer than half a second to scan, is sent without its text:
120
+ metadata only, marked `hiro.scrub.dropped: "size"`, `"matches"` or `"time"`. If scrubbing cannot run at all,
121
+ the text is dropped too; unscrubbed text is never sent. Long text is scanned in pieces of about 32,000
122
+ characters, so your app's own threads never wait more than a few milliseconds for the scrubber.
123
+
124
+ Scrubbing finds patterns, not meaning: it does not remove names or business details written in plain words.
125
+ See exactly what would be sent, without sending anything:
126
+
127
+ ```sh
128
+ HIRO_EXPORT=off HIRO_TRACE_FILE=spans.jsonl python app.py # record locally only, even with a key in .env
129
+ trainhiro preview spans.jsonl # print the spans as Hiro would receive them
130
+ trainhiro preview --run python app.py # or both in one go
131
+ ```
132
+
133
+ `HIRO_EXPORT=off` turns sending off whatever else is set, including a `HIRO_API_KEY` your app loads from a
134
+ `.env` file. `trainhiro preview --run` sets it for the command it runs, so neither form sends anything.
135
+
136
+ How long Hiro keeps what it receives, and how to delete it: [docs.trainhiro.com](https://docs.trainhiro.com).
137
+
138
+ ## Reliability
139
+
140
+ - The instrumented call only appends the span to a bounded in-memory queue. Scrubbing, batching, gzip and
141
+ HTTPS happen on one background thread.
142
+ - If Hiro is slow or unreachable, batches are retried a few times with backoff, then dropped. When the queue
143
+ is full (1,000 spans), new spans are dropped. Your app is never slowed down to deliver a span.
144
+ - If Hiro rejects the key (401) or the organisation is paused (403), sending pauses: one warning is logged,
145
+ spans are dropped, and one batch is retried every five minutes, so sending resumes by itself once the
146
+ key or the organisation is fixed. A 429 waits for its `Retry-After`.
147
+ - At exit, the SDK waits up to 2 seconds to send what is queued. Short scripts can call `trainhiro.flush()`.
148
+ - Problems are logged to the `trainhiro` logger (rate-limited), never raised.
149
+
150
+ ## Configuration
151
+
152
+ | Environment variable | Meaning | Default |
153
+ |---|---|---|
154
+ | `HIRO_API_KEY` | send spans to Hiro with this key (`hiro_live_...` or `hiro_test_...`) | unset: nothing is sent |
155
+ | `HIRO_COLLECTOR_URL` | where to send them (must be `https://`) | `https://ingest.trainhiro.com` |
156
+ | `HIRO_EXPORT` | `off`: send nothing, whatever else is set (`HIRO_TRACE_FILE` still works) | on |
157
+ | `HIRO_TRACE_FILE` | also append every span, unscrubbed, to this local JSON-lines file | off |
158
+ | `HIRO_EXPORT_QUEUE_SIZE` | spans held in memory while waiting to be sent | 1000 |
159
+ | `HIRO_EXPORT_BATCH_SIZE` / `HIRO_EXPORT_INTERVAL_MS` | spans per request / longest wait before a partial batch is sent | 100 / 2000 |
160
+ | `HIRO_EXPORT_TIMEOUT_MS` / `HIRO_EXPORT_MAX_RETRIES` | per-request timeout / retries for network errors, 5xx and 429 | 10000 / 3 |
161
+ | `HIRO_EXIT_FLUSH_TIMEOUT_MS` | how long the exit hook waits to send queued spans | 2000 |
162
+ | `HIRO_PRICING_FILE` | your own prices for cost estimates (see below) | built-in table |
163
+ | `HIRO_ROUTING_CONFIG` / `HIRO_ROUTING` | the routing file Hiro gives you / `off` to turn routing off | off |
164
+
165
+ In code, `trainhiro.configure([...])` replaces the exporters (`trainhiro.HttpExporter`,
166
+ `trainhiro.JsonlExporter`, `trainhiro.InMemoryExporter`; `[]` turns export off). An `HttpExporter` given an
167
+ `api_key` follows the same rules as one built from `HIRO_API_KEY`: https only, every span scrubbed, bodies
168
+ gzipped.
169
+
170
+ ## Traces, steps and attributes
171
+
172
+ ```python
173
+ with trainhiro.trace("ticket-4711"): # one trace = one run of your agent or request
174
+ with trainhiro.step("classify"):
175
+ client.chat.completions.create(...)
176
+ with trainhiro.step("draft_reply"):
177
+ trainhiro.set_attributes({"customer_tier": "gold"})
178
+ client.messages.create(...)
179
+ ```
180
+
181
+ - Calls outside `trainhiro.trace` each get their own trace. A nested `trainhiro.trace` stays in the outer
182
+ trace; its name is recorded in `hiro.trace.path`.
183
+ - `trainhiro.step(name)` sets the step name of the calls inside it (the innermost wins). Both work as
184
+ decorators.
185
+ - `trainhiro.set_attributes({...})` adds attributes to the calls in the innermost open block. Keys starting
186
+ with `hiro.` are reserved. Mark calls that are not part of your product (an evaluation judge, a test
187
+ harness) with `{"hiro.role": "harness"}` and Hiro will leave them out of its analysis.
188
+ - Context follows `contextvars`: asyncio tasks inherit it; new threads do not. Carry it into a thread pool
189
+ with `executor.submit(contextvars.copy_context().run, fn, *args)`.
190
+
191
+ ## What is recorded
192
+
193
+ - OpenAI (`OpenAI`, `AsyncOpenAI`, `AzureOpenAI`): `chat.completions.create` and `.parse`, `responses.create`
194
+ and `.parse`, the `beta` forms, and the `.stream()` helpers.
195
+ - Anthropic (`Anthropic`, `AsyncAnthropic`, and the Bedrock and Vertex clients): `messages.create`,
196
+ `.stream()` and `.parse`, and the same on `beta.messages`.
197
+ - Streaming calls, sync and async, and the `with_raw_response` / `with_streaming_response` forms. Streams are
198
+ handed back to you unchanged and recorded when they end; a stream you stop early is recorded with what
199
+ arrived (`hiro.stream.incomplete`). Streamed spans carry the time to the first token (`hiro.ttft_ms`).
200
+ - Errors are recorded and re-raised unchanged.
201
+ - `trainhiro.wrap(client)` instruments a single client instead of every client.
202
+
203
+ Not recorded: other LLM libraries (LiteLLM, Google, Cohere, Mistral, Bedrock through `boto3`, ...;
204
+ `trainhiro init` lists them), and a `with_raw_response` accessor first read before `trainhiro.instrument()`.
205
+
206
+ ## LangChain and LangGraph
207
+
208
+ `ChatOpenAI` and `ChatAnthropic` call the `openai` and `anthropic` clients underneath, so
209
+ `trainhiro.instrument()` records them. For one span per model run, with the LangGraph node as its step name,
210
+ also pass the callback handler at the top-level call (needs `trainhiro-sdk[langchain]`):
211
+
212
+ ```python
213
+ from trainhiro.integrations.langchain import HiroCallbackHandler
214
+
215
+ app.invoke({"question": "Where is order A1?"}, config={"callbacks": [HiroCallbackHandler()]})
216
+ ```
217
+
218
+ Each chat-model or LLM run becomes one span (sync, async, streaming, batch), and the client call underneath is
219
+ not recorded a second time. A `trainhiro.step(...)` around the call wins over the node name.
220
+
221
+ ## Cost estimates
222
+
223
+ `cost_usd` is estimated from the model and token counts with a built-in price table (USD per million
224
+ tokens), including cache reads and writes. A model without a price, an error, or a call without token counts
225
+ gets `null`: the SDK never guesses. To use your own rates, point `HIRO_PRICING_FILE` at a JSON file:
226
+
227
+ ```json
228
+ {"models": {"gpt-5": {"provider": "openai", "input": 1.0, "output": 8.0, "cache_read": 0.1}, "my-finetune": null}}
229
+ ```
230
+
231
+ An entry replaces the built-in one with the same id, `null` removes a model, and `"replace": true` at the top
232
+ level drops the built-in table. `trainhiro.pricing.set_prices({...})` does the same in code.
233
+
234
+ ## Routing
235
+
236
+ Once Hiro has built and proven a small model for one of your steps, it gives you a routing file. With
237
+ `HIRO_ROUTING_CONFIG` pointing at it, calls of that step go to the small model, and a confidence gate sends any
238
+ answer it is not sure of back to your frontier model, so your code still gets an answer in the shape it
239
+ expects. Without a routing file nothing is routed. `HIRO_ROUTING=off` turns routing off at once; an invalid
240
+ file logs one warning and routes nothing. A rewritten file is picked up within 5 seconds, without a restart.
241
+ Every routed call's span says what happened (`hiro.route`: `small`, `frontier_fallback` or `frontier`, and
242
+ why).
243
+
244
+ ## Command line
245
+
246
+ | Command | What it does |
247
+ |---|---|
248
+ | `trainhiro init [PATH]` | checks Python, finds LLM libraries, client constructors and per-call prompts, and shows the lines to add; changes no file (`--write-env-example` adds `HIRO_API_KEY=` to `.env.example`) |
249
+ | `trainhiro check` | sends one scrubbed test span with `HIRO_API_KEY` and waits up to 30 s for Hiro's receipt (`--wait`) |
250
+ | `trainhiro preview FILE...` | prints the spans in a JSON-lines file as Hiro would receive them; sends nothing (`--jsonl` for one per line) |
251
+ | `trainhiro preview --run CMD...` | runs `CMD` with `HIRO_EXPORT=off` and spans written to a local file, then prints them scrubbed |
252
+
253
+ `python -m trainhiro` is the same command.
254
+
255
+ ## Licence
256
+
257
+ Use of this package is subject to the terms in its `LICENSE` file.
@@ -0,0 +1,223 @@
1
+ # trainhiro-sdk
2
+
3
+ The Python SDK for [Hiro](https://trainhiro.com). It records every LLM call your app makes, scrubs personal
4
+ data out of each record inside your process, and sends the records to Hiro. Hiro finds the steps of your app
5
+ that a small open-weight model can do as well as the frontier model you call today, builds that model, and
6
+ proves it on held-out data before anything changes in your app.
7
+
8
+ Python 3.12 or newer. No runtime dependencies. Recording never blocks or breaks your LLM calls: everything
9
+ after the call (scrubbing, batching, sending) happens on a background thread, and every failure there is
10
+ logged and dropped, never raised.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pip install trainhiro-sdk
16
+ ```
17
+
18
+ It traces the `openai` and `anthropic` clients you already have installed. Extras pin known-good versions if
19
+ you want them: `trainhiro-sdk[openai]`, `[anthropic]`, `[langchain]` (for the LangChain callback handler) or
20
+ `[all]`.
21
+
22
+ ## Set up
23
+
24
+ **1. Look at your project.** From your project's root folder:
25
+
26
+ ```sh
27
+ trainhiro init
28
+ ```
29
+
30
+ It checks your Python version, finds the LLM libraries you use (and says plainly if one is not supported),
31
+ lists where LLM clients are created and which calls build their prompt per call, and shows the lines to add.
32
+ It changes no file; `trainhiro init --write-env-example` also adds an empty `HIRO_API_KEY=` line to
33
+ `.env.example`.
34
+
35
+ **2. Add two lines** where your app starts, before it makes any LLM call:
36
+
37
+ ```python
38
+ import trainhiro
39
+ trainhiro.instrument()
40
+ ```
41
+
42
+ Every OpenAI and Anthropic client in the process is now recorded, including clients created later.
43
+
44
+ **3. Name the steps whose prompt changes per call.** Hiro groups calls into steps by their system prompt and
45
+ tools. A system prompt that contains per-call data (a user's name, today's date, a retrieved document) would
46
+ make every call look like a new step, so give those calls a stable name:
47
+
48
+ ```python
49
+ with trainhiro.step("draft_reply"):
50
+ client.messages.create(model="claude-sonnet-5-5", max_tokens=1024, system=system_prompt, messages=messages)
51
+ ```
52
+
53
+ `trainhiro init` lists the calls that need one. `trainhiro.step` also works as a decorator on sync and async
54
+ functions.
55
+
56
+ **4. Set your key and check.** Create a key in the Hiro dashboard (use a staging key first), then:
57
+
58
+ ```sh
59
+ export HIRO_API_KEY=hiro_test_...
60
+ trainhiro check
61
+ ```
62
+
63
+ `trainhiro check` sends one scrubbed test span and waits until Hiro confirms it arrived. On any problem it
64
+ exits non-zero with a one-line fix. Then set `HIRO_API_KEY` on your server and deploy. Unset it to turn
65
+ sending off.
66
+
67
+ ## What leaves your process
68
+
69
+ For each LLM call, one record ("span"): the provider and model, the request (system prompt, messages, tools,
70
+ parameters), the response (content, tool calls, stop reason), token usage, latency, an estimated cost, the
71
+ step name and key, and success or error. The API keys your OpenAI and Anthropic clients use are not part of
72
+ it, and your Hiro key is sent only in the `Authorization` header, never inside a span.
73
+
74
+ **Scrubbing.** Before a span is sent, the SDK replaces personal data and secrets in every text field with
75
+ placeholders: emails, phone numbers, card numbers, US social security numbers, IBANs, IP addresses, street
76
+ addresses and postcodes, API keys and tokens (OpenAI, Anthropic, AWS, GitHub, JWT, bearer tokens, private
77
+ keys, Hiro keys). The same value gets the same placeholder within a span (`[EMAIL_1]` twice), a different
78
+ value the next number (`[EMAIL_2]`), and numbering starts again for every span. Fields that are not free text
79
+ (ids, model, token counts, timings, tool names, message roles) are kept as they are, and so are JSON numbers:
80
+ a number field, such as a card number passed as an integer in a tool call's input, is not scrubbed in your
81
+ process. Hiro scrubs again when the span arrives, and that pass also checks numbers.
82
+
83
+ Each scrubbed span says so (`hiro.scrubbed: true`) and how many values were replaced
84
+ (`hiro.scrub.matches`), never what they were. A span with more than 500,000 characters of text, more than
85
+ 10,000 values to replace, or one that takes longer than half a second to scan, is sent without its text:
86
+ metadata only, marked `hiro.scrub.dropped: "size"`, `"matches"` or `"time"`. If scrubbing cannot run at all,
87
+ the text is dropped too; unscrubbed text is never sent. Long text is scanned in pieces of about 32,000
88
+ characters, so your app's own threads never wait more than a few milliseconds for the scrubber.
89
+
90
+ Scrubbing finds patterns, not meaning: it does not remove names or business details written in plain words.
91
+ See exactly what would be sent, without sending anything:
92
+
93
+ ```sh
94
+ HIRO_EXPORT=off HIRO_TRACE_FILE=spans.jsonl python app.py # record locally only, even with a key in .env
95
+ trainhiro preview spans.jsonl # print the spans as Hiro would receive them
96
+ trainhiro preview --run python app.py # or both in one go
97
+ ```
98
+
99
+ `HIRO_EXPORT=off` turns sending off whatever else is set, including a `HIRO_API_KEY` your app loads from a
100
+ `.env` file. `trainhiro preview --run` sets it for the command it runs, so neither form sends anything.
101
+
102
+ How long Hiro keeps what it receives, and how to delete it: [docs.trainhiro.com](https://docs.trainhiro.com).
103
+
104
+ ## Reliability
105
+
106
+ - The instrumented call only appends the span to a bounded in-memory queue. Scrubbing, batching, gzip and
107
+ HTTPS happen on one background thread.
108
+ - If Hiro is slow or unreachable, batches are retried a few times with backoff, then dropped. When the queue
109
+ is full (1,000 spans), new spans are dropped. Your app is never slowed down to deliver a span.
110
+ - If Hiro rejects the key (401) or the organisation is paused (403), sending pauses: one warning is logged,
111
+ spans are dropped, and one batch is retried every five minutes, so sending resumes by itself once the
112
+ key or the organisation is fixed. A 429 waits for its `Retry-After`.
113
+ - At exit, the SDK waits up to 2 seconds to send what is queued. Short scripts can call `trainhiro.flush()`.
114
+ - Problems are logged to the `trainhiro` logger (rate-limited), never raised.
115
+
116
+ ## Configuration
117
+
118
+ | Environment variable | Meaning | Default |
119
+ |---|---|---|
120
+ | `HIRO_API_KEY` | send spans to Hiro with this key (`hiro_live_...` or `hiro_test_...`) | unset: nothing is sent |
121
+ | `HIRO_COLLECTOR_URL` | where to send them (must be `https://`) | `https://ingest.trainhiro.com` |
122
+ | `HIRO_EXPORT` | `off`: send nothing, whatever else is set (`HIRO_TRACE_FILE` still works) | on |
123
+ | `HIRO_TRACE_FILE` | also append every span, unscrubbed, to this local JSON-lines file | off |
124
+ | `HIRO_EXPORT_QUEUE_SIZE` | spans held in memory while waiting to be sent | 1000 |
125
+ | `HIRO_EXPORT_BATCH_SIZE` / `HIRO_EXPORT_INTERVAL_MS` | spans per request / longest wait before a partial batch is sent | 100 / 2000 |
126
+ | `HIRO_EXPORT_TIMEOUT_MS` / `HIRO_EXPORT_MAX_RETRIES` | per-request timeout / retries for network errors, 5xx and 429 | 10000 / 3 |
127
+ | `HIRO_EXIT_FLUSH_TIMEOUT_MS` | how long the exit hook waits to send queued spans | 2000 |
128
+ | `HIRO_PRICING_FILE` | your own prices for cost estimates (see below) | built-in table |
129
+ | `HIRO_ROUTING_CONFIG` / `HIRO_ROUTING` | the routing file Hiro gives you / `off` to turn routing off | off |
130
+
131
+ In code, `trainhiro.configure([...])` replaces the exporters (`trainhiro.HttpExporter`,
132
+ `trainhiro.JsonlExporter`, `trainhiro.InMemoryExporter`; `[]` turns export off). An `HttpExporter` given an
133
+ `api_key` follows the same rules as one built from `HIRO_API_KEY`: https only, every span scrubbed, bodies
134
+ gzipped.
135
+
136
+ ## Traces, steps and attributes
137
+
138
+ ```python
139
+ with trainhiro.trace("ticket-4711"): # one trace = one run of your agent or request
140
+ with trainhiro.step("classify"):
141
+ client.chat.completions.create(...)
142
+ with trainhiro.step("draft_reply"):
143
+ trainhiro.set_attributes({"customer_tier": "gold"})
144
+ client.messages.create(...)
145
+ ```
146
+
147
+ - Calls outside `trainhiro.trace` each get their own trace. A nested `trainhiro.trace` stays in the outer
148
+ trace; its name is recorded in `hiro.trace.path`.
149
+ - `trainhiro.step(name)` sets the step name of the calls inside it (the innermost wins). Both work as
150
+ decorators.
151
+ - `trainhiro.set_attributes({...})` adds attributes to the calls in the innermost open block. Keys starting
152
+ with `hiro.` are reserved. Mark calls that are not part of your product (an evaluation judge, a test
153
+ harness) with `{"hiro.role": "harness"}` and Hiro will leave them out of its analysis.
154
+ - Context follows `contextvars`: asyncio tasks inherit it; new threads do not. Carry it into a thread pool
155
+ with `executor.submit(contextvars.copy_context().run, fn, *args)`.
156
+
157
+ ## What is recorded
158
+
159
+ - OpenAI (`OpenAI`, `AsyncOpenAI`, `AzureOpenAI`): `chat.completions.create` and `.parse`, `responses.create`
160
+ and `.parse`, the `beta` forms, and the `.stream()` helpers.
161
+ - Anthropic (`Anthropic`, `AsyncAnthropic`, and the Bedrock and Vertex clients): `messages.create`,
162
+ `.stream()` and `.parse`, and the same on `beta.messages`.
163
+ - Streaming calls, sync and async, and the `with_raw_response` / `with_streaming_response` forms. Streams are
164
+ handed back to you unchanged and recorded when they end; a stream you stop early is recorded with what
165
+ arrived (`hiro.stream.incomplete`). Streamed spans carry the time to the first token (`hiro.ttft_ms`).
166
+ - Errors are recorded and re-raised unchanged.
167
+ - `trainhiro.wrap(client)` instruments a single client instead of every client.
168
+
169
+ Not recorded: other LLM libraries (LiteLLM, Google, Cohere, Mistral, Bedrock through `boto3`, ...;
170
+ `trainhiro init` lists them), and a `with_raw_response` accessor first read before `trainhiro.instrument()`.
171
+
172
+ ## LangChain and LangGraph
173
+
174
+ `ChatOpenAI` and `ChatAnthropic` call the `openai` and `anthropic` clients underneath, so
175
+ `trainhiro.instrument()` records them. For one span per model run, with the LangGraph node as its step name,
176
+ also pass the callback handler at the top-level call (needs `trainhiro-sdk[langchain]`):
177
+
178
+ ```python
179
+ from trainhiro.integrations.langchain import HiroCallbackHandler
180
+
181
+ app.invoke({"question": "Where is order A1?"}, config={"callbacks": [HiroCallbackHandler()]})
182
+ ```
183
+
184
+ Each chat-model or LLM run becomes one span (sync, async, streaming, batch), and the client call underneath is
185
+ not recorded a second time. A `trainhiro.step(...)` around the call wins over the node name.
186
+
187
+ ## Cost estimates
188
+
189
+ `cost_usd` is estimated from the model and token counts with a built-in price table (USD per million
190
+ tokens), including cache reads and writes. A model without a price, an error, or a call without token counts
191
+ gets `null`: the SDK never guesses. To use your own rates, point `HIRO_PRICING_FILE` at a JSON file:
192
+
193
+ ```json
194
+ {"models": {"gpt-5": {"provider": "openai", "input": 1.0, "output": 8.0, "cache_read": 0.1}, "my-finetune": null}}
195
+ ```
196
+
197
+ An entry replaces the built-in one with the same id, `null` removes a model, and `"replace": true` at the top
198
+ level drops the built-in table. `trainhiro.pricing.set_prices({...})` does the same in code.
199
+
200
+ ## Routing
201
+
202
+ Once Hiro has built and proven a small model for one of your steps, it gives you a routing file. With
203
+ `HIRO_ROUTING_CONFIG` pointing at it, calls of that step go to the small model, and a confidence gate sends any
204
+ answer it is not sure of back to your frontier model, so your code still gets an answer in the shape it
205
+ expects. Without a routing file nothing is routed. `HIRO_ROUTING=off` turns routing off at once; an invalid
206
+ file logs one warning and routes nothing. A rewritten file is picked up within 5 seconds, without a restart.
207
+ Every routed call's span says what happened (`hiro.route`: `small`, `frontier_fallback` or `frontier`, and
208
+ why).
209
+
210
+ ## Command line
211
+
212
+ | Command | What it does |
213
+ |---|---|
214
+ | `trainhiro init [PATH]` | checks Python, finds LLM libraries, client constructors and per-call prompts, and shows the lines to add; changes no file (`--write-env-example` adds `HIRO_API_KEY=` to `.env.example`) |
215
+ | `trainhiro check` | sends one scrubbed test span with `HIRO_API_KEY` and waits up to 30 s for Hiro's receipt (`--wait`) |
216
+ | `trainhiro preview FILE...` | prints the spans in a JSON-lines file as Hiro would receive them; sends nothing (`--jsonl` for one per line) |
217
+ | `trainhiro preview --run CMD...` | runs `CMD` with `HIRO_EXPORT=off` and spans written to a local file, then prints them scrubbed |
218
+
219
+ `python -m trainhiro` is the same command.
220
+
221
+ ## Licence
222
+
223
+ Use of this package is subject to the terms in its `LICENSE` file.
@@ -0,0 +1,24 @@
1
+ """Build hook: ship the repo's ``configs/pricing.json`` and ``configs/redaction.json`` inside the package.
2
+
3
+ They land at ``trainhiro/pricing.json`` (cost estimates) and ``trainhiro/redaction.json`` (the scrubbing rules,
4
+ the same file Hiro's servers apply). From a repo checkout they are copied from ``../configs``; when building a
5
+ wheel from the sdist they are already under ``src/trainhiro/``.
6
+ """
7
+
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from hatchling.builders.hooks.plugin.interface import BuildHookInterface
12
+
13
+ CONFIG_FILES = ("pricing.json", "redaction.json")
14
+
15
+
16
+ class CustomBuildHook(BuildHookInterface): # type: ignore[type-arg]
17
+ def initialize(self, version: str, build_data: dict[str, Any]) -> None:
18
+ if self.target_name not in ("wheel", "sdist") or version == "editable":
19
+ return # editable installs read configs/ from the checkout
20
+ for name in CONFIG_FILES:
21
+ src = Path(self.root).parent / "configs" / name
22
+ if src.is_file():
23
+ dest = f"trainhiro/{name}" if self.target_name == "wheel" else f"src/trainhiro/{name}"
24
+ build_data["force_include"][str(src)] = dest
@@ -0,0 +1,75 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"] # 1.27: the PEP 639 license / license-files fields below
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ # The distribution name. The import name is `trainhiro` (PyPI already has an unrelated `hiro`).
7
+ name = "trainhiro-sdk"
8
+ version = "0.1.0"
9
+ description = "Trace your app's LLM calls to Hiro, which builds small models for the steps that do not need a frontier model"
10
+ readme = "README.md"
11
+ requires-python = ">=3.12"
12
+ # Proprietary: the terms are in LICENSE (a placeholder until a lawyer has reviewed it), shipped in the wheel.
13
+ # Published on public PyPI (D11); a human uploads it. 0.1.0 ships with the placeholder LICENSE (decision of
14
+ # 2026-11-28); the lawyer-reviewed text goes out in the next version.
15
+ license = "LicenseRef-Proprietary"
16
+ license-files = ["LICENSE"]
17
+ authors = [{ name = "Hiro" }]
18
+ keywords = ["llm", "tracing", "observability", "openai", "anthropic", "langchain"]
19
+ # No License :: classifier: PEP 639 replaces it with the license expression above.
20
+ classifiers = [
21
+ "Development Status :: 3 - Alpha",
22
+ "Intended Audience :: Developers",
23
+ "Operating System :: OS Independent",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3 :: Only",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Programming Language :: Python :: 3.14",
29
+ "Topic :: Software Development :: Libraries",
30
+ "Topic :: System :: Monitoring",
31
+ "Typing :: Typed",
32
+ ]
33
+ # Zero runtime dependencies on purpose: the SDK is installed into customer agents.
34
+ dependencies = []
35
+
36
+ [project.scripts]
37
+ trainhiro = "trainhiro.cli:main"
38
+
39
+ [project.optional-dependencies]
40
+ # The client libraries trainhiro.wrap()/trainhiro.instrument() trace, and langchain-core for
41
+ # trainhiro.integrations.langchain.HiroCallbackHandler. Install the ones you use.
42
+ openai = ["openai>=1.0"]
43
+ anthropic = ["anthropic>=0.40"]
44
+ langchain = ["langchain-core>=0.3.30"]
45
+ all = ["openai>=1.0", "anthropic>=0.40", "langchain-core>=0.3.30"]
46
+
47
+ # No repository URL on purpose: the source repo is private.
48
+ [project.urls]
49
+ Homepage = "https://trainhiro.com"
50
+ Documentation = "https://docs.trainhiro.com"
51
+
52
+ # What a customer gets: the trainhiro package, minus the cross-language test vectors. Nothing reads the
53
+ # vectors at run time (only the test suites and the generators in scripts/ do); the two JSON
54
+ # Schemas next to them stay, because trainhiro.routing.config and Hiro's ingest load them.
55
+ # tests/test_packaging.py builds the wheel and pins its file list.
56
+ [tool.hatch.build.targets.wheel]
57
+ packages = ["src/trainhiro"]
58
+ exclude = ["src/trainhiro/schema/*_vectors.json"]
59
+
60
+ # The wheel is what ships. An sdist, if someone builds one, carries only what a wheel build needs:
61
+ # no tests/, no scripts/, no vectors (pyproject.toml and PKG-INFO are always added).
62
+ # hatchling always copies the nearest .gitignore into an sdist. The .gitignore next to this file exists so that this is
63
+ # a three-line file and not the repo root's, which lists internal paths.
64
+ [tool.hatch.build.targets.sdist]
65
+ include = ["/src/trainhiro", "/LICENSE", "/README.md", "/hatch_build.py"]
66
+ exclude = ["src/trainhiro/schema/*_vectors.json"]
67
+
68
+ # hatch_build.py copies ../configs/pricing.json into the package (trainhiro/pricing.json).
69
+ [tool.hatch.build.hooks.custom]
70
+
71
+ # Lint/format settings live in ../ruff.toml. `src` scopes isort's first-party detection to this
72
+ # package (its src/ modules and tests/ helpers); the other Hiro package sorts as third-party.
73
+ [tool.ruff]
74
+ extend = "../ruff.toml"
75
+ src = ["src", "tests"]
@@ -0,0 +1,50 @@
1
+ """Hiro SDK: trace every LLM call your app makes, and route proven steps to a small model.
2
+
3
+ Quick start::
4
+
5
+ import trainhiro, anthropic
6
+ client = trainhiro.wrap(anthropic.Anthropic()) # or trainhiro.instrument() for every client
7
+ with trainhiro.trace("my-agent-run"):
8
+ with trainhiro.step("plan"):
9
+ client.messages.create(...)
10
+ trainhiro.flush()
11
+
12
+ Export is configured from env vars (``HIRO_API_KEY``, ``HIRO_COLLECTOR_URL``, ``HIRO_TRACE_FILE``;
13
+ see :mod:`trainhiro.exporters`) or with :func:`trainhiro.configure`. The routing config
14
+ comes from ``HIRO_ROUTING_CONFIG`` or ``trainhiro.configure(routing=...)``, and
15
+ ``HIRO_ROUTING=off`` turns it off (see :mod:`trainhiro.routing.config`).
16
+ """
17
+
18
+ __version__ = "0.1.0"
19
+
20
+ from trainhiro.context import TraceHandle, current_trace_id, set_attributes, step, trace
21
+ from trainhiro.exporters import (
22
+ HttpExporter,
23
+ InMemoryExporter,
24
+ JsonlExporter,
25
+ configure,
26
+ flush,
27
+ shutdown,
28
+ )
29
+ from trainhiro.integrations import instrument, uninstrument, wrap
30
+ from trainhiro.routing.config import get_routing, reload_routing
31
+
32
+ __all__ = [
33
+ "HttpExporter",
34
+ "InMemoryExporter",
35
+ "JsonlExporter",
36
+ "TraceHandle",
37
+ "__version__",
38
+ "configure",
39
+ "current_trace_id",
40
+ "flush",
41
+ "get_routing",
42
+ "instrument",
43
+ "reload_routing",
44
+ "set_attributes",
45
+ "shutdown",
46
+ "step",
47
+ "trace",
48
+ "uninstrument",
49
+ "wrap",
50
+ ]
@@ -0,0 +1,7 @@
1
+ """``python -m trainhiro``: the ``trainhiro`` command."""
2
+
3
+ import sys
4
+
5
+ from trainhiro.cli import main
6
+
7
+ sys.exit(main())