Metadata-Version: 2.4
Name: traceforge-llm
Version: 0.2.0
Summary: Agent runtime tracing and deterministic replay for LLM applications
Author-email: Daniel Blanco <hello@danblanco.dev>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for describing the origin of the Work and
              reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may accept and charge a
              fee for acceptance of support, warranty, indemnity, or other liability
              obligations and/or rights consistent with this License. However, in
              accepting such obligations, You may act only on Your own behalf
              and on Your sole responsibility, not on behalf of any other Contributor,
              and only if You agree to indemnify, defend, and hold each Contributor
              harmless for any liability incurred by, or claims asserted against,
              such Contributor by reason of your accepting any such warranty or
              additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2026 Daniel Blanco
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/Danultimate/traceforge
Project-URL: Repository, https://github.com/Danultimate/traceforge
Project-URL: Documentation, https://github.com/Danultimate/traceforge#readme
Project-URL: Issues, https://github.com/Danultimate/traceforge/issues
Project-URL: Changelog, https://github.com/Danultimate/traceforge/releases
Keywords: llm,agent,tracing,observability,replay,langchain,langgraph,anthropic,openai,debugging
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Debuggers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: Apache Software License
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.0.0
Requires-Dist: rich>=13.0.0
Requires-Dist: python-ulid>=2.0.0
Requires-Dist: click>=8.0.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: jinja2>=3.0.0
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.25.0; extra == "anthropic"
Provides-Extra: openai
Requires-Dist: openai>=1.0.0; extra == "openai"
Provides-Extra: langchain
Requires-Dist: langchain>=0.2.0; extra == "langchain"
Provides-Extra: langgraph
Requires-Dist: langgraph>=0.1.0; extra == "langgraph"
Provides-Extra: all
Requires-Dist: anthropic>=0.25.0; extra == "all"
Requires-Dist: openai>=1.0.0; extra == "all"
Requires-Dist: langchain>=0.2.0; extra == "all"
Requires-Dist: langgraph>=0.1.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: ruff>=0.1; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Dynamic: license-file

# TraceForge

**Agent runtime tracing + LLM-mock replay for Python. Pip install. Async-first. Self-contained reports.**

[![PyPI version](https://img.shields.io/pypi/v/traceforge-llm?label=pypi&color=blue)](https://pypi.org/project/traceforge-llm/)
[![Python versions](https://img.shields.io/pypi/pyversions/traceforge-llm?label=python)](https://pypi.org/project/traceforge-llm/)
[![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](LICENSE)
[![CI](https://github.com/Danultimate/traceforge/actions/workflows/ci.yml/badge.svg)](https://github.com/Danultimate/traceforge/actions/workflows/ci.yml)
[![Replay](https://img.shields.io/badge/replay-llm--mock%20%2B%20dry--run-success)](#replay)

![TraceForge HTML report](docs/report-screenshot.png)

> ⚠️ **Pre-release (v0.2).** Tracer, replay, instrumentors, cost tracking, and the pytest plugin are implemented end-to-end and tested. APIs are stabilising — don't depend on this in production yet.

TraceForge records every LLM call, tool invocation, error, and state transition your agent makes into a typed span. The output is a replayable `run.jsonl` artifact plus a self-contained HTML report you can open in any browser — no server, no SaaS, no SDK lock-in. Replay mode re-executes the agent with cached LLM responses (or cached tool outputs) so you can verify the execution path without burning API calls.

```bash
pip install "traceforge-llm[anthropic]"   # or [openai], [all]
traceforge init && python agent.py
```

---

## Why TraceForge

| | TraceForge | [LangSmith](https://smith.langchain.com/) | [Langfuse](https://langfuse.com/) | [OpenLLMetry](https://github.com/traceloop/openllmetry) | `print()` |
|---|:---:|:---:|:---:|:---:|:---:|
| Pip install, no account, no server                 | ✅ | — | partial (self-host) | ✅ | ✅ |
| Records LLM I/O + tool I/O + state per span        | ✅ | ✅ | ✅ | partial | — |
| **Replay with cached LLM responses (`llm-mock`)**  | ✅ | — | — | — | — |
| **Dry-run replay with cached tool outputs**        | ✅ | — | — | — | — |
| Self-contained HTML report (no CDN, no server)     | ✅ | — | — | — | — |
| Auto-cost tracking per-span + per-run              | ✅ | ✅ | ✅ | partial | — |
| First-class pytest plugin with snapshot testing    | ✅ | — | — | — | — |
| Auto-patches your SDK clients                      | opt-in | ✅ | ✅ | ✅ | n/a |
| Cloud storage / hosted dashboard                   | — | ✅ | ✅ | via vendor | — |

**Where TraceForge fits:** when you need a *local, file-based, replayable* record of what your agent did — for debugging, CI regression tests, or post-hoc analysis — without sending your traces to anyone else's database. Auto-patching frameworks like LangSmith give you a UI; OpenLLMetry gives you OTel pipes. TraceForge gives you a JSONL you can `git diff`, an HTML you can email, and a `tracer.replay()` you can run offline.

---

## 60-second quickstart

**1. Install and scaffold.**

```bash
pip install "traceforge-llm[anthropic]"
traceforge init
```

`traceforge init` writes `traceforge.yaml`, a working `agent.py` example, and a `.gitignore` entry.

**2. Wrap your agent.**

```python
import asyncio
from anthropic import AsyncAnthropic
from traceforge import Tracer
from traceforge.integrations.anthropic import AnthropicInstrumentor

tracer = Tracer()

async def main():
    async with tracer.run() as run:
        client = AnthropicInstrumentor(run).instrument(AsyncAnthropic())
        response = await client.messages.create(
            model="claude-haiku-4-5-20251001",
            max_tokens=256,
            messages=[{"role": "user", "content": "What is 2 + 2?"}],
        )
        print(response.content[0].text)
    run.trace.print_summary()

asyncio.run(main())
```

**3. Run.**

```bash
export ANTHROPIC_API_KEY=sk-ant-...
python agent.py
```

You get a Rich-formatted summary on stdout, plus a directory at `.traceforge/runs/<ulid>-<run-name>/` containing `manifest.json`, `run.jsonl`, and a self-contained `report.html`.

<details>
<summary><b>Library-only API (no instrumentor)</b></summary>

```python
async with tracer.run() as run:
    run.record_llm_call(
        provider="anthropic",
        model="claude-haiku-4-5",
        messages=[...],
        response="...",
        input_tokens=12, output_tokens=4, latency_ms=180,
    )
    run.record_tool_call("search", tool_input={"q": "..."}, tool_output={"hits": 3})
    run.custom("phase.done", metadata={"step": 1})

run.trace.print_summary()
```

Manual recording is the lower-level API the instrumentors are built on. Useful when you don't want TraceForge anywhere near the SDK call.
</details>

<details>
<summary><b>Decorator sugar</b></summary>

```python
@tracer.trace
async def my_agent(query, _run=None):
    _run.record_tool_call("search", {"q": query}, {"hits": 3})
    return "done"

await my_agent("hello")        # auto-saves trace to .traceforge/runs/
trace = tracer.last()
```
</details>

---

## Reports

`tracer.run()` writes three files per run to `.traceforge/runs/<ulid>-<run-name>/`:

```
.traceforge/runs/01KS8E...-true-elk/
├── report.html      ← open this
├── run.jsonl        ← replayable artifact (one span per line + manifest)
└── manifest.json    ← aggregate counts + cost + token totals
```

**Terminal:** `run.trace.print_summary()` prints a Rich panel + span tree:

![Terminal report](docs/terminal-report.svg)

**HTML:** self-contained, dark theme, no CDN. Open `report.html` in any browser (or via `traceforge open <run-name>`):

- **Stat strip** at the top: duration, span count, LLM calls, tool calls, token totals, **cost**, errors
- **Span cards** with type-coded left border (indigo LLM, cyan tool, slate custom, **red errors**)
- **Collapsible payloads** for system prompts, message arrays, and tool I/O — kept folded by default so the page stays scannable
- **Per-span cost** rendered inline for every LLM call

A live example sits at [`docs/example-report.html`](docs/example-report.html) — open it directly to see the layout.

---

## Replay

```python
# llm-mock: LLM responses served from cache, tools execute live
result = await tracer.replay(trace, agent_fn, mode="llm-mock")

# dry-run: both LLM responses AND tool outputs served from cache, no network
result = await tracer.replay(trace, agent_fn, mode="dry-run")

result.print()
# Similarity: 100%  ·  Status: ALIGNED
```

The replay engine builds two interceptors keyed by SHA-256 of the original messages / tool inputs, and hands them to your agent function. Your agent consults the interceptor before calling out:

```python
async def my_agent(query, _run=None, _mock_llm=None, _mock_tool=None):
    cached = _mock_llm.get(messages) if _mock_llm else None
    if cached is not None:
        return cached
    return await client.messages.create(...)
```

The shipped instrumentors handle this for you — just pass `mock_interceptor=_mock_llm` when instrumenting:

```python
client = AnthropicInstrumentor(_run, mock_interceptor=_mock_llm).instrument(AsyncAnthropic())
```

**Similarity scoring.** `ReplayResult.similarity_score` is the ratio of matching span types between original and replayed traces. Below 0.4 the replay is marked `DIVERGED`. See [`docs/replay-faq.md`](docs/replay-faq.md) for why replays diverge and how to fix it.

---

## Cost tracking

Every LLM span gets a USD cost estimate attached automatically, looked up from a built-in pricing table for the major Anthropic and OpenAI models (with longest-prefix matching, so versioned IDs like `claude-haiku-4-5-20251001` resolve correctly). Aggregates flow into `manifest.total_cost_usd`.

```python
async with tracer.run() as run:
    await client.messages.create(...)  # instrumentor records cost

print(run.trace.manifest.total_cost_usd)  # → 0.0042
```

Override the table for negotiated contract pricing or private models:

```python
from traceforge import Tracer
from traceforge.pricing import ModelPrice

tracer = Tracer(pricing={
    "my-internal-model": ModelPrice(input_per_million=0.5, output_per_million=1.5),
    "claude-opus-4-7":   ModelPrice(input_per_million=12.0, output_per_million=60.0),
})
```

Unknown models cost 0 and emit a one-shot warning so the trace still saves.

---

## Pytest plugin

`pip install traceforge-llm` auto-registers a pytest plugin (via `pytest11` entry point). Three fixtures appear in any test suite:

```python
import pytest

@pytest.mark.asyncio
async def test_agent_runs_under_budget(tracer, tf_assert, tf_snapshot):
    async with tracer.run() as run:
        await my_agent("hello", _run=run)

    tf_assert(
        run.trace,
        has_span="search",
        llm_calls=1,
        max_cost_usd=0.01,
        max_tokens=2000,
    )

    # Golden-trace snapshot — fails if the span-type sequence drifts.
    tf_snapshot.assert_match(run.trace, "agent_v1")
```

| Fixture | What it gives you |
|---|---|
| `tracer` | A non-auto-saving `Tracer` per test (no `.traceforge/` cruft) |
| `tf_assert(trace, ...)` | One-line common assertions: `has_span`, `has_span_type`, `no_errors`, `llm_calls`, `tool_calls`, `max_cost_usd`, `max_tokens`, `min_spans` |
| `tf_snapshot.assert_match(trace, name)` | Records the trace on first run, then asserts span-type-sequence similarity ≥ 0.8 on every subsequent run |

Snapshots live in `tests/__tf_snapshots__/<name>.jsonl` by default — override with `--tf-snapshot-dir`. Commit them like you commit any other golden file. Refresh after intentional changes with:

```bash
pytest --tf-update-snapshots
```

---

## Instrumentors

| Provider | Class | Wraps |
|---|---|---|
| Anthropic | `traceforge.integrations.anthropic.AnthropicInstrumentor` | `client.messages.create` |
| OpenAI    | `traceforge.integrations.openai.OpenAIInstrumentor`       | `client.chat.completions.create` |
| LangChain | `traceforge.integrations.langchain.LangChainInstrumentor` | manual `record_chain_step` / `record_llm_step` |

LangChain is intentionally manual — auto-patching is fragile across versions, so TraceForge ships a bridge helper you call from your callback handler.

---

## CLI

| Command | Purpose |
|---|---|
| `traceforge init` | Scaffold `traceforge.yaml`, `agent.py` example, `.gitignore` entry |
| `traceforge list` | Table of local runs (newest first) |
| `traceforge open <id>` | Open a run's HTML report in your browser |
| `traceforge show <id>` | Print a run summary to the terminal |

`<id>` accepts a ULID prefix *or* the human-readable run name (`brave-salmon`).

---

## Non-goals

- **No auto-patching by default.** Instrumentors are opt-in. Your code stays explicit about what's being traced.
- **No time-travel debugging.** TraceForge records and replays; it does not pause your agent mid-flight.
- **No cloud storage.** Traces live in `.traceforge/runs/`. Bring your own object store if you want central retention.
- **No built-in eval scoring.** TraceForge captures the run; pair it with `evalkit` (or your own scorer) for grading.

---

## Status

| Feature | Status |
|---|---|
| Async + sync context manager, `@tracer.trace` decorator | ✅ shipped |
| Anthropic / OpenAI instrumentors | ✅ shipped |
| LangChain bridge (manual) | ✅ shipped |
| File store: `manifest.json` + `run.jsonl` + `report.html` | ✅ shipped |
| Self-contained HTML report (no CDN) | ✅ shipped |
| LLM-mock replay | ✅ shipped |
| Dry-run replay (tool cache) | ✅ shipped |
| Cost tracking (per-span + manifest total) | ✅ shipped (v0.2) |
| Custom pricing tables | ✅ shipped (v0.2) |
| Pytest plugin (`tracer`, `tf_assert`) | ✅ shipped (v0.2) |
| Trace snapshot testing (`tf_snapshot`) | ✅ shipped (v0.2) |
| Streaming + tool-use in instrumentors | deferred |
| `traceforge diff` (span-level diff) | deferred |
| Slim mode (`--slim`) | deferred |
| LangGraph auto-instrumentation | manual only |
| Cloud storage backends | non-goal |

Track progress and propose features via [GitHub Issues](https://github.com/Danultimate/traceforge/issues).

---

## Docs

- [Replay FAQ](docs/replay-faq.md) — why replays diverge, and how to fix it
- [Example HTML report](docs/example-report.html) — live, self-contained

## License

[Apache 2.0](LICENSE).
