Skip to content
vmore2Public

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

1 Commit

Folders and files

Repository files navigation

RuntimeX

A tiny, model-agnostic AI agent harness.
Every run is a replayable event log. Agents learn from every failure.

CI Python License: MIT Code style: ruff Typed


"Debugging an AI agent shouldn't feel like forensics."

Most agent frameworks ship you a black box. You send a task, hope for an answer, and when something goes wrong β€” good luck. RuntimeX is built on the opposite premise: total visibility, zero magic, and a loop you can read in one sitting.

from runtimex import Agent, LiteLLMModel

agent = Agent(model=LiteLLMModel("openai/gpt-4o-mini"))
result = agent.run_sync("Summarise the breaking changes in CHANGELOG.md")
print(result.answer)

No config files. No mandatory cloud services. No framework lock-in. Just Python.


What makes RuntimeX different

There are a lot of agent frameworks. Here is what sets RuntimeX apart and why each decision was made deliberately.

πŸ” Deterministic Replay β€” the flagship feature

Every run produces an append-only event log stored in SQLite. That log captures the exact messages sent to the model, every tool call, every result, and every model response.

# Replay any run, offline, with zero API calls
runtimex replay abc123 -v
# Or do it programmatically
from runtimex import replay, TraceStore
import asyncio

store = TraceStore(".runtimex/traces.db")
events = asyncio.run(replay("abc123", store))

You get the exact same output as the original run, deterministically, every time. This is not approximation or re-running with the same prompt β€” it feeds the recorded model responses back through the same loop.

Why this matters: When an agent misbehaves at step 7 of a 20-step run, you don't want to burn $0.40 re-running the whole thing to reproduce it. You replay, isolate, and fix.


βͺ Time-Travel Fork β€” edit any step and go live from there

Fork a trace at any step. RuntimeX replays your recorded responses up to step N, then hands off to a live model. Change the system prompt, swap the model, inject a different tool β€” all without replaying the expensive early steps.

from runtimex import fork, LiteLLMModel

# Replay steps 1-4 (free, no API calls), then go live with a different model
events = asyncio.run(fork(
    run_id="abc123",
    store=store,
    from_step=5,
    live_model=LiteLLMModel("anthropic/claude-3-5-sonnet-20241022"),
    new_system_prompt="Be more concise. Prefer code over prose.",
))

Why this matters: This is how you iterate on agent behaviour without burning tokens. It's the equivalent of a debugger's "jump to line" β€” except for AI.


🧠 Failure Memory β€” agents that don't repeat mistakes

When a run fails, RuntimeX extracts a structured failure card β€” what task was attempted, what error occurred, which tools were used, and what the lesson is. On future runs with similar tasks, those cards are injected into the system prompt automatically.

from runtimex import FailureMemory

memory = FailureMemory()

# After a failed run
card = memory.extract_card_from_events(result.events, task="deploy to production")
if card:
    card.lesson = "Always check the port is open before starting the deploy."
    memory.save_card(card)

# Before the next similar run
system_prompt = memory.inject_prompt(base_prompt, task="deploy to staging")
# β†’ system_prompt now includes the lesson above

Failure cards are plain JSONL files. You can version-control them, share them across agents, or hand-write them. They're just data.

Why this matters: Most agent frameworks have no concept of memory between runs. RuntimeX ships it as a first-class primitive, not an afterthought.


πŸ” Total Visibility β€” the event system

Every action in the agent loop emits a typed Pydantic event. You own the event stream β€” pipe it anywhere:

from runtimex import Agent, make_trace_callback, TraceStore
from runtimex.otel import OTelTracer

store = TraceStore()
tracer = OTelTracer()

def on_event(event):
    make_trace_callback(store)(event)  # β†’ SQLite
    tracer.handle_event(event)          # β†’ OpenTelemetry
    print(f"[{event.kind}] step={event.step}")  # β†’ stdout

agent = Agent(model=model, on_event=on_event)
Event Captured data
AgentStartEvent task, model, system_prompt
ModelRequestEvent exact messages + tools sent to the LLM
ModelResponseEvent content, tool_calls, token usage
ToolCallEvent tool_name, arguments, call_id
ToolResultEvent output, error, side_effects
AgentFinishEvent final_answer, reason, total_tokens

No event is synthetic or reconstructed. Every field is captured at the moment it occurs.


🧱 Model-agnostic by design

RuntimeX uses a simple Protocol β€” any object with a .complete() method is a valid model. There is no base class to inherit from.

from runtimex import LiteLLMModel

# 100+ providers via LiteLLM
model = LiteLLMModel("openai/gpt-4o")
model = LiteLLMModel("anthropic/claude-3-5-sonnet-20241022")
model = LiteLLMModel("gemini/gemini-2.0-flash")
model = LiteLLMModel("ollama/llama3.2", api_base="http://localhost:11434")

# Or bring your own
class MyModel:
    async def complete(self, messages, tools=None, **kwargs):
        ...  # call whatever API you want

For testing and CI β€” zero API calls, zero cost:

from runtimex import FakeModel, ModelResponse, ToolCall

model = FakeModel([
    ModelResponse(tool_calls=[ToolCall(name="shell", arguments={"cmd": "ls"})]),
    ModelResponse(content="Done. Found 3 Python files."),
])

πŸ”§ Tools that register themselves

The @tool decorator reads your type hints and docstring to generate the full JSON schema automatically. No schema boilerplate. No separate function definitions.

from runtimex import tool

@tool
def search_database(query: str, limit: int = 10, exact: bool = False) -> str:
    """Search the internal database.

    Args:
        query: The search query string.
        limit: Maximum number of results to return.
        exact: If true, use exact string matching.
    """
    ...

That's it. The schema {"type": "object", "properties": {"query": {"type": "string"}, ...}} is generated, validated, and passed to the model automatically.


πŸ” Permissions β€” safe by default

Grant or deny tool access at the call level. Plug in an approval callback for interactive or policy-based gating:

from runtimex import Agent, PermissionManager

permissions = PermissionManager(
    allowed=["file_read", "grep", "glob_search"],  # read-only tools
    denied=["shell", "file_write"],                 # no writes, no shell
)

agent = Agent(model=model, permissions=permissions)

The agent sees a Permission denied observation and can recover gracefully β€” it doesn't crash.


Quickstart

pip install -e ".[dev]"

# Set your API key
export OPENAI_API_KEY=sk-...

# Run your first agent
runtimex run "list all Python files in this project" --model openai/gpt-4o-mini -v
RuntimeX running: list all Python files in this project
  model: openai/gpt-4o-mini  max_steps: 30

  step 0  β–Ά START  list all Python files in this project
  step 1  πŸ”§ TOOLS  glob_search
  step 1  β†’ glob_search  12 file(s) found: ...
  step 2  πŸ’¬ REPLY  Found 12 Python files across src/ and tests/...

βœ“ Answer (2 steps, 312 tokens):
  Found 12 Python files across src/ and tests/...

  Run ID: d4f8a3c1...

Now replay it with no API call:

runtimex replay d4f8 -v

Built-in Tools

Tool What it does
shell Execute shell commands, capture stdout/stderr
file_read Read files with optional line ranges
file_write Create or overwrite files (creates parent dirs)
file_edit Find-and-replace in files
grep Regex content search across files
glob_search Find files matching a glob pattern
web_fetch HTTP GET with encoding detection + truncation

CLI Reference

runtimex run "task"                    # Run an agent
  --model openai/gpt-4o-mini           # Model to use
  --max-steps 30                       # Step limit
  --max-tokens 50000                   # Token budget
  --verbose                            # Stream events as they happen

runtimex trace ls                      # List recent runs
runtimex trace show <run_id>           # Inspect events for a run
runtimex trace export <run_id>         # Export to JSONL

runtimex replay <run_id>               # Deterministic replay (no API)
  --verbose                            # Stream replayed events

Project Structure

src/runtimex/
β”œβ”€β”€ agent.py          # The ReAct loop β€” readable top-to-bottom (~320 lines)
β”œβ”€β”€ models.py         # Model Protocol + LiteLLMModel + FakeModel
β”œβ”€β”€ types.py          # 8 typed Pydantic event models
β”œβ”€β”€ trace.py          # SQLite event store + JSONL export/import
β”œβ”€β”€ replay.py         # Deterministic replay + time-travel fork
β”œβ”€β”€ memory.py         # Persistent memory + failure learning
β”œβ”€β”€ permissions.py    # Tool access control
β”œβ”€β”€ otel.py           # OpenTelemetry GenAI spans (optional dep)
β”œβ”€β”€ cli.py            # CLI (Typer + Rich)
└── tools/
    β”œβ”€β”€ __init__.py   # @tool decorator + ToolRegistry + schema generation
    β”œβ”€β”€ shell.py
    β”œβ”€β”€ file_read.py
    β”œβ”€β”€ file_write.py
    β”œβ”€β”€ glob_tool.py
    β”œβ”€β”€ grep.py
    └── web_fetch.py

Design Philosophy

RuntimeX has five hard rules that every line of code is held to:

  1. Readable β€” The core loop is ~100 lines. No hidden control flow. An engineer who has never seen this codebase can understand the agent loop in 15 minutes.

  2. Debuggable β€” Every event is logged. Every run can be replayed. You can answer "what exactly did the model see at step 3?" without guessing.

  3. Small β€” ~1,500 lines of production code. The whole project fits in one afternoon of reading. Complexity is a cost, not a feature.

  4. No magic β€” Plain Python, structural typing via Protocol, Pydantic for data. If you grep for something, you find it.

  5. Local-first β€” SQLite and JSONL work offline. No mandatory cloud, no API keys required for tracing and replay.


Development

git clone https://github.com/vmore2/runtimex.git
cd runtimex
pip install -e ".[dev]"

pytest tests/ -v         # 96 tests
ruff check src/ tests/   # lint
mypy src/                # type check (strict)

Contributing

See CONTRIBUTING.md. PRs welcome β€” especially new tools, model adapters, and examples.


License

MIT β€” see LICENSE.


Built for engineers who want to understand their agents, not just run them.

Report a Bug Β· Request a Feature Β· Discussions

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages