Skip to main content

Lifecycle instrumentation for DSPy's RLM (Recursive Language Model).

Project description

DSPy RLM Hooks

Lifecycle instrumentation for DSPy's RLM (Recursive Language Model).
Explore the Documentation »
Report Bug · Request Feature

Table of Contents
  1. About
  2. Quick Start
  3. Usage
  4. Development
  5. Contributing
  6. License

About

DSPy RLM Hooks injects lifecycle hooks into DSPy's internal RLM iteration loop, giving you full control over every stage of code generation, execution, and history tracking.

  • Code Rewriting — Fix or augment LLM-generated code before it runs
  • Variable Injection — Seed the interpreter with persistent variables and imports
  • Result Auditing — Transform, validate, or retry on errors
  • History Management — Inspect and modify the REPL history between iterations
  • Sync & Async — Hooks work in either mode; coroutines are auto-detected

Requires DSPy 3.1+ and Pydantic 2+.

(back to top)

Architecture

RLM Hook Lifecycle

flowchart LR
    subgraph Iteration["RLM Iteration"]
        PreIter["pre_iteration_hook"] --> Gen["Generate Code"]
        Gen --> PreExec["pre_execution_hook"]
        PreExec --> Exec["Execute Code"]
        Exec --> PostExec["post_execution_hook"]
        PostExec --> PostIter["post_iteration_hook"]
    end

    PreIter -.->|inject vars, prepend code| Gen
    PreExec -.->|rewrite code| Exec
    PostExec -.->|transform result| PostIter

Hooks fire at each stage of an RLM iteration, allowing inspection and modification of behaviour.

(back to top)

Quick Start

Install

Install dspy-rlm-hooks with uv (recommended):

uv add dspy-rlm-hooks

Or with pip:

pip install dspy-rlm-hooks

Basic Usage

import dspy
from dspy_rlm_hooks import enable_rlm_hooks, PreIterationOutput

rlm = dspy.RLM(...)

def inject_math(iteration, variables, history, input_args):
    return PreIterationOutput(
        extra_vars={"tool": "calculator"},
        python_code="import math",
    )

enable_rlm_hooks(rlm, pre_iteration_hook=inject_math)

result = rlm(question="What is the square root of 1764?")

(back to top)

Usage

All Four Hooks

A realistic example showing how each hook can be used to build a safe, instrumented agent:

from dspy_rlm_hooks import (
    enable_rlm_hooks,
    PreIterationOutput,
    PreExecutionOutput,
    PostExecutionOutput,
    PostIterationOutput,
)
from dspy.primitives.repl_types import REPLHistory
import re

# ── Pre-iteration: seed interpreter with a regex toolkit ──

def pre_iteration(iteration, variables, history, input_args):
    """Inject a regex helper and seed variables before every iteration."""
    return PreIterationOutput(
        extra_vars={"search_pattern": r"TODO|FIXME|HACK"},
        python_code="""
import re

def grep(pattern, text):
    return re.findall(pattern, text)
""",
    )

# ── Pre-execution: block dangerous code ──

FORBIDDEN = re.compile(r"\b(eval|exec|compile|__import__)\b")

def pre_execution(iteration, code, variables, history, input_args):
    """Sanitise generated code before it reaches the interpreter."""
    if FORBIDDEN.search(code):
        safe_code = FORBIDDEN.sub("# BLOCKED", code)
        return PreExecutionOutput(code=safe_code)
    return PreExecutionOutput(code=code)

# ── Post-execution: retry on error ──

def post_execution(iteration, code, result, variables, history, input_args):
    """If execution raised an error, wrap a hint so the LLM retries next round."""
    if isinstance(result, str) and result.startswith("[Error]"):
        return PostExecutionOutput(
            result=f"{result}\n# Hint: the variable 'search_pattern' is already in scope."
        )
    return PostExecutionOutput(result=result)

# ── Post-iteration: enforce iteration budget ──

MAX_ITERATIONS = 5
current_iter_count = 0

def post_iteration(iteration, pred, code, result, history: REPLHistory):
    """Track iterations and stop early if the budget is exhausted."""
    global current_iter_count
    current_iter_count += 1
    if current_iter_count >= MAX_ITERATIONS:
        # Return empty history to signal stop
        return PostIterationOutput(history=REPLHistory(entries=[]))
    return PostIterationOutput(history=history)

# ── Wire everything up ──

enable_rlm_hooks(
    rlm,
    pre_iteration_hook=pre_iteration,
    pre_execution_hook=pre_execution,
    post_execution_hook=post_execution,
    post_iteration_hook=post_iteration,
)

result = rlm(question="Find all TODO comments in the codebase")

Async Hooks

Return a coroutine and the system handles it automatically:

async def fetch_context(iteration, variables, history, input_args):
    context = await remote_cache.get(input_args["question"])
    return PreIterationOutput(extra_vars={"cached_context": context})

enable_rlm_hooks(rlm, pre_iteration_hook=fetch_context)

Disabling Hooks

from dspy_rlm_hooks import disable_rlm_hooks

disable_rlm_hooks(rlm)

Removes all monkey-patched overrides and reverts to original behaviour.

(back to top)

Hook Reference

Hook When it fires What it can do
PreIteration Before action generation Inject variables (extra_vars) and persistent code (python_code)
PreExecution After code generation, before running Rewrite or sanitise the generated code string
PostExecution After code runs, before history processing Transform, audit, or replace the raw result
PostIteration After result is folded into history Save learnings, trigger side effects, or modify history

(back to top)

Development

Code Quality

This project uses several tools to maintain code quality:

  • Ruff: Linting and formatting
  • isort: Import sorting
  • pytest: Testing framework
  • ty: Type checking
  • deptry: Dependency analysis

Available commands:

# Run all quality checks
uv run poe clean-full

# Individual checks
uv run poe lint          # Ruff linting
uv run poe format        # Ruff formatting
uv run poe sort          # Import sorting
uv run poe typecheck     # Type checking
uv run poe deptry        # Dependency analysis

Testing

Run tests using pytest:

# Run all tests
uv run pytest

# Run specific test
uv run pytest path/to/test.py::test_name

(back to top)

Contributing

Quick workflow:

  1. Fork and branch: git checkout -b feature/name
  2. Make changes
  3. Run checks: uv run poe clean-full
  4. Commit and push
  5. Open a Pull Request

(back to top)

License

MIT (as declared in pyproject.toml).


Built by thememium

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dspy_rlm_hooks-0.1.3.tar.gz (10.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dspy_rlm_hooks-0.1.3-py3-none-any.whl (12.0 kB view details)

Uploaded Python 3

File details

Details for the file dspy_rlm_hooks-0.1.3.tar.gz.

File metadata

  • Download URL: dspy_rlm_hooks-0.1.3.tar.gz
  • Upload date:
  • Size: 10.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.14 {"installer":{"name":"uv","version":"0.11.14","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for dspy_rlm_hooks-0.1.3.tar.gz
Algorithm Hash digest
SHA256 7ba9d0b9b1854e1e952ea3b18d4bd9260a7449cebdc81d1efb2efed1d7bc1a4d
MD5 16ad2e2dbc8d0ec10e184a6ce18d1b85
BLAKE2b-256 0e843f4325097ffefb4b700946874ec8864faf0b606fe68535d07229b8c25424

See more details on using hashes here.

File details

Details for the file dspy_rlm_hooks-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: dspy_rlm_hooks-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 12.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.14 {"installer":{"name":"uv","version":"0.11.14","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for dspy_rlm_hooks-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 10953cd02ea7a11c9f84d46be1e2e27cc30040d1790622a68629d5d31a8676ff
MD5 a0c278ec3ed3f97967bbdd038d6e307a
BLAKE2b-256 7fe9142c13e2e87eaaf9fd6667ba0af5a4096990c2a0fefa09fa4edf38bf8167

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page