tracetune 0.1.2__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,10 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ venv/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ out/
10
+ .env
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.5
2
+ Name: tracetune
3
+ Version: 0.1.2
4
+ Summary: Turn your AI agent's production traces into a clean, scored training dataset.
5
+ Project-URL: Homepage, https://github.com/mishraxharshit/applied-machine
6
+ Project-URL: Source, https://github.com/mishraxharshit/applied-machine
7
+ Project-URL: Issues, https://github.com/mishraxharshit/applied-machine/issues
8
+ Project-URL: Changelog, https://github.com/mishraxharshit/applied-machine/blob/main/CHANGELOG.md
9
+ Author: Harshit Mishra
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agents,dataset,fine-tuning,llm,observability,rlhf,traces
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Requires-Python: >=3.10
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest; extra == 'dev'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # tracetune
28
+
29
+ > Turn your agent's production traces into a better model, safely, with open-source tooling.
30
+
31
+ **The problem.** Teams running LLM agents in production collect real traces every day
32
+ (user requests, tool calls, outcomes). That data could improve their model, but turning
33
+ traces into clean training data, scoring them, retraining and deploying safely is manual
34
+ and scattered. Most small teams never do it.
35
+
36
+ **What tracetune does.** An open-source pipeline for the whole loop:
37
+
38
+ ```
39
+ traces (.jsonl) -> score + filter -> training dataset -> train (your tool) -> eval -> promote / reject
40
+ [v0.1: done] [v0.1: done] [v0.1: done] [planned] [planned] [planned]
41
+ ```
42
+
43
+ It does not replace trainers like TRL, Unsloth, verl or SkyRL. It feeds them.
44
+
45
+ ## Quickstart
46
+
47
+ ```bash
48
+ pip install tracetune
49
+ tracetune build --traces examples/sample_traces.jsonl --out out/dataset.jsonl
50
+ ```
51
+
52
+ (`examples/sample_traces.jsonl` is in the [GitHub repo](https://github.com/mishraxharshit/applied-machine/tree/main/packages/tracetune-py/examples). Use your own traces file, see the format below.)
53
+
54
+ Output:
55
+
56
+ ```
57
+ traces read : 8
58
+ kept : 4 -> out/dataset.jsonl
59
+ dropped : 4
60
+ - low_score: 1
61
+ - negative_feedback: 1
62
+ - step_error: 1
63
+ - trace_error: 1
64
+ ```
65
+
66
+ ## Trace format
67
+
68
+ One JSON object per line:
69
+
70
+ ```json
71
+ {"trace_id": "t1", "input": "How many customers are in Delhi?",
72
+ "steps": [{"name": "run_sql", "args": {"query": "..."}, "result": "42"}],
73
+ "output": "There are 42 customers in Delhi.", "feedback": 1}
74
+ ```
75
+
76
+ `feedback` is `1`, `-1` or omitted. `error` on a step or on the whole trace marks failures.
77
+
78
+ ## How scoring works
79
+
80
+ Each trace gets a score: thumbs up/down, minus penalties for failed tool calls, failed runs
81
+ and wandering (too many steps). Traces below `--min-score` (default `0.0`) are dropped.
82
+ All weights are in `RewardConfig` (`src/tracetune/filters.py`).
83
+
84
+ ## Roadmap
85
+
86
+ - [x] v0.1: JSONL traces -> scored, filtered chat-format dataset
87
+ - [ ] v0.2: importers for Langfuse and OpenTelemetry exports
88
+ - [ ] v0.3: LoRA training recipe on a small model + before/after eval report
89
+ - [ ] v0.4: promote / reject decision with regression checks
90
+
91
+ ## Development
92
+
93
+ ```bash
94
+ pip install -e ".[dev]"
95
+ pytest # or: python -m unittest
96
+ ```
97
+
98
+ ## License
99
+
100
+ Apache-2.0 (see `LICENSE`).
@@ -0,0 +1,74 @@
1
+ # tracetune
2
+
3
+ > Turn your agent's production traces into a better model, safely, with open-source tooling.
4
+
5
+ **The problem.** Teams running LLM agents in production collect real traces every day
6
+ (user requests, tool calls, outcomes). That data could improve their model, but turning
7
+ traces into clean training data, scoring them, retraining and deploying safely is manual
8
+ and scattered. Most small teams never do it.
9
+
10
+ **What tracetune does.** An open-source pipeline for the whole loop:
11
+
12
+ ```
13
+ traces (.jsonl) -> score + filter -> training dataset -> train (your tool) -> eval -> promote / reject
14
+ [v0.1: done] [v0.1: done] [v0.1: done] [planned] [planned] [planned]
15
+ ```
16
+
17
+ It does not replace trainers like TRL, Unsloth, verl or SkyRL. It feeds them.
18
+
19
+ ## Quickstart
20
+
21
+ ```bash
22
+ pip install tracetune
23
+ tracetune build --traces examples/sample_traces.jsonl --out out/dataset.jsonl
24
+ ```
25
+
26
+ (`examples/sample_traces.jsonl` is in the [GitHub repo](https://github.com/mishraxharshit/applied-machine/tree/main/packages/tracetune-py/examples). Use your own traces file, see the format below.)
27
+
28
+ Output:
29
+
30
+ ```
31
+ traces read : 8
32
+ kept : 4 -> out/dataset.jsonl
33
+ dropped : 4
34
+ - low_score: 1
35
+ - negative_feedback: 1
36
+ - step_error: 1
37
+ - trace_error: 1
38
+ ```
39
+
40
+ ## Trace format
41
+
42
+ One JSON object per line:
43
+
44
+ ```json
45
+ {"trace_id": "t1", "input": "How many customers are in Delhi?",
46
+ "steps": [{"name": "run_sql", "args": {"query": "..."}, "result": "42"}],
47
+ "output": "There are 42 customers in Delhi.", "feedback": 1}
48
+ ```
49
+
50
+ `feedback` is `1`, `-1` or omitted. `error` on a step or on the whole trace marks failures.
51
+
52
+ ## How scoring works
53
+
54
+ Each trace gets a score: thumbs up/down, minus penalties for failed tool calls, failed runs
55
+ and wandering (too many steps). Traces below `--min-score` (default `0.0`) are dropped.
56
+ All weights are in `RewardConfig` (`src/tracetune/filters.py`).
57
+
58
+ ## Roadmap
59
+
60
+ - [x] v0.1: JSONL traces -> scored, filtered chat-format dataset
61
+ - [ ] v0.2: importers for Langfuse and OpenTelemetry exports
62
+ - [ ] v0.3: LoRA training recipe on a small model + before/after eval report
63
+ - [ ] v0.4: promote / reject decision with regression checks
64
+
65
+ ## Development
66
+
67
+ ```bash
68
+ pip install -e ".[dev]"
69
+ pytest # or: python -m unittest
70
+ ```
71
+
72
+ ## License
73
+
74
+ Apache-2.0 (see `LICENSE`).
@@ -0,0 +1,8 @@
1
+ {"trace_id": "t1", "input": "How many customers are in Delhi?", "steps": [{"name": "run_sql", "args": {"query": "SELECT COUNT(*) FROM customers WHERE city='Delhi'"}, "result": "42"}], "output": "There are 42 customers in Delhi.", "feedback": 1}
2
+ {"trace_id": "t2", "input": "List all product categories.", "steps": [{"name": "run_sql", "args": {"query": "SELECT DISTINCT category FROM products"}, "result": "toys, books, tools"}], "output": "Categories: toys, books, tools."}
3
+ {"trace_id": "t3", "input": "Total revenue in 2025?", "steps": [{"name": "run_sql", "args": {"query": "SELECT SUM(amt) FROM orders WHERE yr=2025"}, "error": "no such column: yr"}, {"name": "run_sql", "args": {"query": "SELECT SUM(amount) FROM orders WHERE year=2025"}, "result": "1250000"}], "output": "Total revenue in 2025 was 1,250,000.", "feedback": 1}
4
+ {"trace_id": "t4", "input": "Which city has the most orders?", "steps": [{"name": "run_sql", "args": {"query": "SELECT city FROM orders LIMIT 1"}, "result": "Mumbai"}], "output": "Mumbai has the most orders.", "feedback": -1}
5
+ {"trace_id": "t5", "input": "Delete all test users.", "steps": [], "output": "", "error": "tool timeout"}
6
+ {"trace_id": "t6", "input": "Average order value?", "steps": [{"name": "run_sql", "args": {"query": "SELECT * FROM orders"}, "result": "..."}, {"name": "run_sql", "args": {"query": "SELECT * FROM products"}, "result": "..."}, {"name": "run_sql", "args": {"query": "SELECT * FROM customers"}, "result": "..."}, {"name": "run_sql", "args": {"query": "SELECT * FROM orders LIMIT 5"}, "result": "..."}, {"name": "run_sql", "args": {"query": "SELECT * FROM products LIMIT 5"}, "result": "..."}, {"name": "run_sql", "args": {"query": "SELECT AVG(amount) FROM orders"}, "result": "830"}, {"name": "run_sql", "args": {"query": "SELECT AVG(amount) FROM orders"}, "result": "830"}], "output": "Average order value is 830."}
7
+ {"trace_id": "t7", "input": "Top 3 customers by spend?", "steps": [{"name": "run_sql", "args": {"query": "SELECT customer_id, SUM(amount) s FROM orders GROUP BY 1 ORDER BY s DESC LIMIT 3"}, "result": "7, 12, 3"}, {"name": "run_sql", "args": {"query": "SELECT name FROM customers WHERE id IN (7,12,3)"}, "result": "Asha, Ravi, Meera"}], "output": "Top 3: Asha, Ravi, Meera.", "feedback": 1}
8
+ {"trace_id": "t8", "input": "How many orders were cancelled?", "steps": [{"name": "run_sql", "args": {"query": "SELECT COUNT(*) FROM orders WHERE status='cancelled'"}, "error": "table 'orders' locked"}], "output": "I could not find that."}
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "tracetune"
7
+ dynamic = ["version"] # single source of truth: src/tracetune/__init__.py
8
+ description = "Turn your AI agent's production traces into a clean, scored training dataset."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Harshit Mishra" }]
14
+ keywords = ["llm", "agents", "traces", "fine-tuning", "dataset", "rlhf", "observability"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Intended Audience :: Science/Research",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
24
+ "Topic :: Software Development :: Libraries",
25
+ ]
26
+ dependencies = [] # zero runtime deps on purpose
27
+
28
+ [project.optional-dependencies]
29
+ dev = ["pytest"]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/mishraxharshit/applied-machine"
33
+ Source = "https://github.com/mishraxharshit/applied-machine"
34
+ Issues = "https://github.com/mishraxharshit/applied-machine/issues"
35
+ Changelog = "https://github.com/mishraxharshit/applied-machine/blob/main/CHANGELOG.md"
36
+
37
+ [project.scripts]
38
+ tracetune = "tracetune.cli:main"
39
+
40
+ [tool.hatch.version]
41
+ path = "src/tracetune/__init__.py"
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ packages = ["src/tracetune"]
45
+
46
+ [tool.hatch.build.targets.sdist]
47
+ include = ["src", "tests", "examples", "README.md", "LICENSE", "pyproject.toml"]
@@ -0,0 +1,3 @@
1
+ """tracetune: turn agent production traces into training data."""
2
+
3
+ __version__ = "0.1.2"
@@ -0,0 +1,53 @@
1
+ """Command-line entry point: tracetune build --traces X.jsonl --out Y.jsonl"""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import sys
6
+
7
+ from . import __version__
8
+ from .export import write_dataset
9
+ from .filters import select_traces
10
+ from .loader import load_traces
11
+
12
+
13
+ def build_parser() -> argparse.ArgumentParser:
14
+ parser = argparse.ArgumentParser(
15
+ prog="tracetune",
16
+ description="Turn agent production traces into a filtered training dataset.",
17
+ )
18
+ parser.add_argument("--version", action="version", version=f"tracetune {__version__}")
19
+ sub = parser.add_subparsers(dest="command", required=True)
20
+
21
+ build = sub.add_parser("build", help="score, filter and export traces")
22
+ build.add_argument("--traces", required=True, help="input traces (.jsonl)")
23
+ build.add_argument("--out", required=True, help="output dataset (.jsonl)")
24
+ build.add_argument("--min-score", type=float, default=0.0, help="keep traces scoring >= this (default 0.0)")
25
+ build.add_argument(
26
+ "--dedup",
27
+ choices=["best", "none"],
28
+ default="best",
29
+ help="best: keep only the highest-scoring trace per identical input (default); none: keep all",
30
+ )
31
+ return parser
32
+
33
+
34
+ def main(argv: list[str] | None = None) -> int:
35
+ args = build_parser().parse_args(argv)
36
+
37
+ try:
38
+ result = select_traces(load_traces(args.traces), min_score=args.min_score, dedup=args.dedup)
39
+ written = write_dataset(result.kept, args.out)
40
+ except (OSError, ValueError) as e:
41
+ print(f"error: {e}", file=sys.stderr)
42
+ return 1
43
+
44
+ print(f"traces read : {result.total}")
45
+ print(f"kept : {written} -> {args.out}")
46
+ print(f"dropped : {result.dropped}")
47
+ for reason, count in sorted(result.dropped_by_reason.items()):
48
+ print(f" - {reason}: {count}")
49
+ return 0
50
+
51
+
52
+ if __name__ == "__main__":
53
+ sys.exit(main())
@@ -0,0 +1,54 @@
1
+ """Turn kept traces into a training dataset.
2
+
3
+ Output format: one JSON object per line with a "messages" list in the common
4
+ chat style (user / assistant / tool). Most fine-tuning tools (TRL, Unsloth,
5
+ Axolotl) can read this shape or something very close to it; small adapters
6
+ for specific trainers can be added later without changing the core.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+
13
+ from .schema import Trace
14
+
15
+
16
+ def trace_to_messages(trace: Trace) -> list[dict]:
17
+ messages: list[dict] = [{"role": "user", "content": trace.input}]
18
+ for i, step in enumerate(trace.steps):
19
+ call_id = f"call_{i}"
20
+ messages.append(
21
+ {
22
+ "role": "assistant",
23
+ "content": "",
24
+ "tool_calls": [
25
+ {
26
+ "id": call_id,
27
+ "type": "function",
28
+ "function": {"name": step.name, "arguments": json.dumps(step.args)},
29
+ }
30
+ ],
31
+ }
32
+ )
33
+ messages.append(
34
+ {
35
+ "role": "tool",
36
+ "tool_call_id": call_id,
37
+ "content": step.result if step.result is not None else (step.error or ""),
38
+ }
39
+ )
40
+ messages.append({"role": "assistant", "content": trace.output})
41
+ return messages
42
+
43
+
44
+ def write_dataset(kept: list[tuple[Trace, float]], out_path: str | Path) -> int:
45
+ out_path = Path(out_path)
46
+ out_path.parent.mkdir(parents=True, exist_ok=True)
47
+ with open(out_path, "w", encoding="utf-8") as f:
48
+ for trace, score in kept:
49
+ row = {
50
+ "messages": trace_to_messages(trace),
51
+ "metadata": {"trace_id": trace.trace_id, "score": score},
52
+ }
53
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
54
+ return len(kept)
@@ -0,0 +1,113 @@
1
+ """Reward scoring and filtering: the 'brain' of tracetune.
2
+
3
+ Idea: not every production trace is good training data. We give each trace a
4
+ numeric score (a simple reward function) and keep only the good ones.
5
+
6
+ Every number here is a *design choice*, not a law of nature. That is why they
7
+ live in RewardConfig: users can tune them without touching code.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+
13
+ from .schema import Trace
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class RewardConfig:
18
+ positive_feedback: float = 1.0
19
+ negative_feedback: float = -1.0
20
+ step_error_penalty: float = 1.0 # per failed tool call
21
+ trace_error_penalty: float = 2.0 # whole run failed
22
+ free_steps: int = 3 # steps allowed with no penalty
23
+ extra_step_penalty: float = 0.1 # per step beyond free_steps (prefers efficient agents)
24
+
25
+
26
+ DEFAULT_REWARD = RewardConfig()
27
+
28
+
29
+ def score_trace(trace: Trace, cfg: RewardConfig = DEFAULT_REWARD) -> float:
30
+ score = 0.0
31
+ if trace.feedback == 1:
32
+ score += cfg.positive_feedback
33
+ elif trace.feedback == -1:
34
+ score += cfg.negative_feedback
35
+
36
+ score -= cfg.step_error_penalty * sum(1 for s in trace.steps if s.error)
37
+
38
+ if trace.error:
39
+ score -= cfg.trace_error_penalty
40
+
41
+ extra_steps = max(0, len(trace.steps) - cfg.free_steps)
42
+ score -= cfg.extra_step_penalty * extra_steps
43
+ return round(score, 6)
44
+
45
+
46
+ def drop_reason(trace: Trace) -> str:
47
+ """Human-readable reason a trace was dropped. Order = most serious first."""
48
+ if trace.error:
49
+ return "trace_error"
50
+ if trace.feedback == -1:
51
+ return "negative_feedback"
52
+ if any(s.error for s in trace.steps):
53
+ return "step_error"
54
+ return "low_score"
55
+
56
+
57
+ def best_per_input(scored: list[tuple[Trace, float]]) -> list[tuple[Trace, float]]:
58
+ """Keep only the highest-scoring trace for each identical input.
59
+
60
+ Lesson learned: dedup must happen AFTER scoring. Removing duplicates first
61
+ can throw away the best run. On a tie the first trace seen wins, so the
62
+ result is deterministic. First-seen order of inputs is preserved.
63
+ """
64
+ best: dict[str, tuple[Trace, float]] = {}
65
+ for trace, score in scored:
66
+ current = best.get(trace.input)
67
+ if current is None or score > current[1]:
68
+ best[trace.input] = (trace, score)
69
+ return list(best.values())
70
+
71
+
72
+ @dataclass
73
+ class SelectionResult:
74
+ kept: list[tuple[Trace, float]] = field(default_factory=list)
75
+ dropped_by_reason: dict[str, int] = field(default_factory=dict)
76
+ total: int = 0
77
+
78
+ @property
79
+ def dropped(self) -> int:
80
+ return sum(self.dropped_by_reason.values())
81
+
82
+
83
+ def select_traces(
84
+ traces,
85
+ min_score: float = 0.0,
86
+ cfg: RewardConfig = DEFAULT_REWARD,
87
+ dedup: str = "best",
88
+ ) -> SelectionResult:
89
+ """Score every trace, optionally keep the best per input, then apply min_score.
90
+
91
+ dedup="best": one trace per identical input (default).
92
+ dedup="none": keep all duplicates.
93
+ """
94
+ if dedup not in ("best", "none"):
95
+ raise ValueError(f"dedup must be 'best' or 'none', got {dedup!r}")
96
+
97
+ scored = [(t, score_trace(t, cfg)) for t in traces]
98
+ result = SelectionResult(total=len(scored))
99
+
100
+ if dedup == "best":
101
+ unique = best_per_input(scored)
102
+ removed = len(scored) - len(unique)
103
+ if removed:
104
+ result.dropped_by_reason["duplicate"] = removed
105
+ scored = unique
106
+
107
+ for trace, score in scored:
108
+ if score >= min_score:
109
+ result.kept.append((trace, score))
110
+ else:
111
+ reason = drop_reason(trace)
112
+ result.dropped_by_reason[reason] = result.dropped_by_reason.get(reason, 0) + 1
113
+ return result
@@ -0,0 +1,32 @@
1
+ """Read traces from a JSONL file (one JSON object per line).
2
+
3
+ JSONL is used instead of one big JSON array because it can be streamed,
4
+ appended to, and read line by line without loading everything into memory.
5
+ Later, importers for Langfuse / OpenTelemetry exports will live next to this.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from pathlib import Path
11
+ from typing import Iterator
12
+
13
+ from .schema import Trace
14
+
15
+
16
+ def load_traces(path: str | Path) -> Iterator[Trace]:
17
+ with open(path, encoding="utf-8") as f:
18
+ for line_no, line in enumerate(f, start=1):
19
+ line = line.strip()
20
+ if not line:
21
+ continue
22
+ try:
23
+ raw = json.loads(line)
24
+ except json.JSONDecodeError as e:
25
+ # Always tell the user WHICH line is broken.
26
+ raise ValueError(f"{path}:{line_no}: invalid JSON ({e.msg})") from e
27
+ except RecursionError as e: # absurdly nested JSON
28
+ raise ValueError(f"{path}:{line_no}: JSON is nested too deeply") from e
29
+ try:
30
+ yield Trace.from_dict(raw)
31
+ except ValueError as e:
32
+ raise ValueError(f"{path}:{line_no}: {e}") from e
@@ -0,0 +1,91 @@
1
+ """The data model: what a 'trace' means in tracetune.
2
+
3
+ Everything else in the project (loading, scoring, exporting) depends on this
4
+ file, so keep it small and boring. If you change it, you change the contract
5
+ with every user's data.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Optional
11
+
12
+
13
+ @dataclass
14
+ class Step:
15
+ """One tool call made by the agent."""
16
+
17
+ name: str
18
+ args: dict[str, Any] = field(default_factory=dict)
19
+ result: Optional[str] = None
20
+ error: Optional[str] = None
21
+
22
+
23
+ @dataclass
24
+ class Trace:
25
+ """One full agent run: a user input, the steps taken, and the final answer."""
26
+
27
+ trace_id: str
28
+ input: str
29
+ output: str
30
+ steps: list[Step] = field(default_factory=list)
31
+ feedback: Optional[int] = None # +1 (thumbs up), -1 (thumbs down), None (unknown)
32
+ error: Optional[str] = None # set when the whole run failed
33
+
34
+ @classmethod
35
+ def from_dict(cls, d: Any) -> "Trace":
36
+ # Fail early with a clear message: bad data is the #1 source of bad models.
37
+ # Every check raises ValueError so the CLI can show a clean error, never a traceback.
38
+ if not isinstance(d, dict):
39
+ raise ValueError("trace must be a JSON object")
40
+ for key in ("trace_id", "input", "output"):
41
+ if key not in d:
42
+ raise ValueError(f"trace is missing required field '{key}'")
43
+
44
+ trace_id = d["trace_id"]
45
+ if isinstance(trace_id, bool) or not isinstance(trace_id, (str, int)):
46
+ raise ValueError("'trace_id' must be a string or integer")
47
+ for key in ("input", "output"):
48
+ if not isinstance(d[key], str):
49
+ raise ValueError(f"'{key}' must be a string (trace {trace_id!r})")
50
+
51
+ raw_steps = d.get("steps")
52
+ if raw_steps is None:
53
+ raw_steps = []
54
+ if not isinstance(raw_steps, list):
55
+ raise ValueError(f"'steps' must be a list (trace {trace_id!r})")
56
+
57
+ steps = []
58
+ for i, s in enumerate(raw_steps):
59
+ where = f"step {i} of trace {trace_id!r}"
60
+ if not isinstance(s, dict):
61
+ raise ValueError(f"{where} must be an object")
62
+ if not isinstance(s.get("name"), str) or not s["name"]:
63
+ raise ValueError(f"{where} has no 'name'")
64
+ args = s.get("args")
65
+ if args is None:
66
+ args = {}
67
+ if not isinstance(args, dict):
68
+ raise ValueError(f"{where}: 'args' must be an object")
69
+ for key in ("result", "error"):
70
+ if s.get(key) is not None and not isinstance(s[key], str):
71
+ raise ValueError(f"{where}: '{key}' must be a string")
72
+ steps.append(Step(name=s["name"], args=args, result=s.get("result"), error=s.get("error")))
73
+
74
+ feedback = d.get("feedback")
75
+ if feedback is not None and (isinstance(feedback, bool) or feedback not in (1, -1)):
76
+ raise ValueError(f"feedback must be 1, -1 or null, got {feedback!r}")
77
+ if feedback is not None:
78
+ feedback = int(feedback)
79
+
80
+ error = d.get("error")
81
+ if error is not None and not isinstance(error, str):
82
+ raise ValueError(f"'error' must be a string or null (trace {trace_id!r})")
83
+
84
+ return cls(
85
+ trace_id=str(trace_id),
86
+ input=d["input"],
87
+ output=d["output"],
88
+ steps=steps,
89
+ feedback=feedback,
90
+ error=error,
91
+ )
@@ -0,0 +1,96 @@
1
+ import json
2
+ import tempfile
3
+ import unittest
4
+ from pathlib import Path
5
+
6
+ from tracetune.cli import main
7
+ from tracetune.export import trace_to_messages
8
+ from tracetune.filters import best_per_input, score_trace, select_traces
9
+ from tracetune.loader import load_traces
10
+ from tracetune.schema import Step, Trace
11
+
12
+ SAMPLE = Path(__file__).parent.parent / "examples" / "sample_traces.jsonl"
13
+
14
+
15
+ class ScoringTests(unittest.TestCase):
16
+ def test_positive_clean_trace_scores_one(self):
17
+ t = Trace("x", "q", "a", steps=[Step("run_sql", result="ok")], feedback=1)
18
+ self.assertEqual(score_trace(t), 1.0)
19
+
20
+ def test_long_wandering_trace_is_penalised(self):
21
+ t = Trace("x", "q", "a", steps=[Step("run_sql", result="ok") for _ in range(7)])
22
+ self.assertAlmostEqual(score_trace(t), -0.4)
23
+
24
+ def test_failed_run_scores_negative(self):
25
+ t = Trace("x", "q", "", error="timeout")
26
+ self.assertLess(score_trace(t), 0)
27
+
28
+
29
+ class DedupTests(unittest.TestCase):
30
+ def test_keeps_best_scoring_trace_per_input(self):
31
+ good = Trace("good", "q1", "a", steps=[Step("run_sql", result="ok")], feedback=1)
32
+ bad = Trace("bad", "q1", "a", steps=[Step("run_sql", result="ok")], feedback=-1)
33
+ other = Trace("other", "q2", "a")
34
+ scored = [(bad, score_trace(bad)), (good, score_trace(good)), (other, score_trace(other))]
35
+ kept = best_per_input(scored)
36
+ self.assertEqual({t.trace_id for t, _ in kept}, {"good", "other"})
37
+
38
+ def test_tie_keeps_first_seen(self):
39
+ a = Trace("first", "q1", "a")
40
+ b = Trace("second", "q1", "a")
41
+ kept = best_per_input([(a, 0.0), (b, 0.0)])
42
+ self.assertEqual([t.trace_id for t, _ in kept], ["first"])
43
+
44
+ def test_best_run_survives_even_if_it_comes_second(self):
45
+ # The exact bug we found: dedup-first would keep the bad run and lose the good one.
46
+ bad = Trace("bad", "q1", "a", feedback=-1)
47
+ good = Trace("good", "q1", "a", feedback=1)
48
+ result = select_traces([bad, good])
49
+ self.assertEqual([t.trace_id for t, _ in result.kept], ["good"])
50
+ self.assertEqual(result.dropped_by_reason, {"duplicate": 1})
51
+
52
+ def test_dedup_none_keeps_all_duplicates(self):
53
+ a = Trace("a", "q1", "x")
54
+ b = Trace("b", "q1", "x")
55
+ result = select_traces([a, b], dedup="none")
56
+ self.assertEqual(len(result.kept), 2)
57
+
58
+ def test_invalid_dedup_value_is_rejected(self):
59
+ with self.assertRaises(ValueError):
60
+ select_traces([], dedup="maybe")
61
+
62
+
63
+ class PipelineTests(unittest.TestCase):
64
+ def test_sample_file_keeps_four_drops_four(self):
65
+ result = select_traces(load_traces(SAMPLE))
66
+ self.assertEqual(result.total, 8)
67
+ self.assertEqual([t.trace_id for t, _ in result.kept], ["t1", "t2", "t3", "t7"])
68
+ self.assertEqual(
69
+ result.dropped_by_reason,
70
+ {"negative_feedback": 1, "trace_error": 1, "low_score": 1, "step_error": 1},
71
+ )
72
+
73
+ def test_messages_shape(self):
74
+ t = Trace("x", "q", "final", steps=[Step("run_sql", {"query": "S"}, result="42")])
75
+ roles = [m["role"] for m in trace_to_messages(t)]
76
+ self.assertEqual(roles, ["user", "assistant", "tool", "assistant"])
77
+
78
+ def test_bad_json_reports_line_number(self):
79
+ with tempfile.TemporaryDirectory() as d:
80
+ p = Path(d) / "bad.jsonl"
81
+ p.write_text('{"trace_id": "a", "input": "q", "output": "o"}\nnot json\n')
82
+ with self.assertRaises(ValueError) as ctx:
83
+ list(load_traces(p))
84
+ self.assertIn(":2:", str(ctx.exception))
85
+
86
+ def test_cli_writes_dataset(self):
87
+ with tempfile.TemporaryDirectory() as d:
88
+ out = Path(d) / "out" / "dataset.jsonl"
89
+ code = main(["build", "--traces", str(SAMPLE), "--out", str(out)])
90
+ self.assertEqual(code, 0)
91
+ rows = [json.loads(line) for line in out.read_text().splitlines()]
92
+ self.assertEqual(len(rows), 4)
93
+
94
+
95
+ if __name__ == "__main__":
96
+ unittest.main()
@@ -0,0 +1,85 @@
1
+ import json
2
+ import tempfile
3
+ import unittest
4
+ from pathlib import Path
5
+
6
+ from tracetune.cli import main
7
+ from tracetune.schema import Trace
8
+
9
+
10
+ def ok(**over):
11
+ d = {"trace_id": "t", "input": "q", "output": "a"}
12
+ d.update(over)
13
+ return d
14
+
15
+
16
+ class SchemaValidationTests(unittest.TestCase):
17
+ def rejects(self, d, fragment):
18
+ with self.assertRaises(ValueError) as cm:
19
+ Trace.from_dict(d)
20
+ self.assertIn(fragment, str(cm.exception))
21
+
22
+ def test_minimal_trace_is_valid(self):
23
+ self.assertEqual(Trace.from_dict(ok()).trace_id, "t")
24
+
25
+ def test_not_an_object(self):
26
+ self.rejects([1, 2], "JSON object")
27
+
28
+ def test_input_must_be_string(self):
29
+ self.rejects(ok(input=5), "'input' must be a string")
30
+
31
+ def test_output_must_be_string(self):
32
+ self.rejects(ok(output=None), "'output' must be a string")
33
+
34
+ def test_trace_id_rejects_objects_and_bools(self):
35
+ self.rejects(ok(trace_id={"a": 1}), "trace_id")
36
+ self.rejects(ok(trace_id=True), "trace_id")
37
+
38
+ def test_steps_must_be_list(self):
39
+ self.rejects(ok(steps="run_sql"), "'steps' must be a list")
40
+
41
+ def test_step_must_be_object_with_name(self):
42
+ self.rejects(ok(steps=["x"]), "must be an object")
43
+ self.rejects(ok(steps=[{"args": {}}]), "no 'name'")
44
+
45
+ def test_step_args_must_be_object(self):
46
+ self.rejects(ok(steps=[{"name": "t", "args": "oops"}]), "'args' must be an object")
47
+
48
+ def test_step_result_must_be_string(self):
49
+ self.rejects(ok(steps=[{"name": "t", "result": 3}]), "'result' must be a string")
50
+
51
+ def test_feedback_rejects_bool_and_other_numbers(self):
52
+ self.rejects(ok(feedback=True), "feedback")
53
+ self.rejects(ok(feedback=2), "feedback")
54
+
55
+ def test_feedback_float_is_normalised(self):
56
+ self.assertEqual(Trace.from_dict(ok(feedback=1.0)).feedback, 1)
57
+
58
+ def test_error_must_be_string(self):
59
+ self.rejects(ok(error=["x"]), "'error' must be a string")
60
+
61
+
62
+ class CliErrorTests(unittest.TestCase):
63
+ def test_bad_trace_gives_clean_error_not_traceback(self):
64
+ with tempfile.TemporaryDirectory() as d:
65
+ src = Path(d) / "t.jsonl"
66
+ src.write_text(json.dumps(ok(steps="nope")) + "\n", encoding="utf-8")
67
+ self.assertEqual(main(["build", "--traces", str(src), "--out", str(Path(d) / "o.jsonl")]), 1)
68
+
69
+ def test_deeply_nested_json_is_a_clean_error(self):
70
+ with tempfile.TemporaryDirectory() as d:
71
+ src = Path(d) / "t.jsonl"
72
+ src.write_text("[" * 100000 + "]" * 100000 + "\n", encoding="utf-8")
73
+ self.assertEqual(main(["build", "--traces", str(src), "--out", str(Path(d) / "o.jsonl")]), 1)
74
+
75
+ def test_unwritable_output_is_a_clean_error(self):
76
+ with tempfile.TemporaryDirectory() as d:
77
+ src = Path(d) / "t.jsonl"
78
+ src.write_text(json.dumps(ok()) + "\n", encoding="utf-8")
79
+ blocker = Path(d) / "file"
80
+ blocker.write_text("x")
81
+ self.assertEqual(main(["build", "--traces", str(src), "--out", str(blocker / "o.jsonl")]), 1)
82
+
83
+
84
+ if __name__ == "__main__":
85
+ unittest.main()