spec-ptc README

The project's README from github.com/alexzhang13/spec-ptc. As one markdown file: README.md.

Speculative Programmatic Tool Calling

Speculative programmatic tool-calling (sPTC) is a technique for harnesses that use tools like sub-agents / sub-calls in code. While the LLM is streaming tokens to generate a REPL call, sPTC speculates and queues up tool calls in the partially-generated code that act as Futures when the actual code is executed.

Learn more in the blogpost here.

sPTC vs serial comparison

Many harness designs like Recursive Language Models (RLMs) and CodeAct rely on programmatic tool-calling (PTC), where all tools are embedded as functions inside a single code REPL tool that is generated per turn. For RLMs in particular, sub-LLM and sub-RLM calls are expensive, often blocking tools in code that take up a majority of the runtime. sPTC is the general technique of speculating tool and sub-LLM calls that will happen as the root LLM is generating the codeblock, allowing the RLM to batch and asynchronously compute these expensive calls while the full codeblock is still being generated to overlap these calls with the logic of the code REPL.

baseline   tokens──────────────────▶ exec: call₁──▶call₂──▶…──▶callₙ──▶ answer
spec-ptc   tokens──────────────────▶ exec: claim·claim·claim ──▶ answer
                 ╲ call₁ ▶▶▶ done ╱
                  ╲ call₂ ▶▶▶ done╱     (calls run inside generation time)

This repository is a simple library and demo for this technique.

Getting Started

You can either clone this repository (uses uv), or install with:

pip install spec-ptc

The Speculator object is used to track and store tools to be speculated, as well as the shadow REPL that is used to speculate. You can add tools with the spec.tool decorator and control whether you want them to be speculated or not.

The simplest example is to install tool hooks into the REPL you already have, feed tokens as they stream and feed them to the speculator, then exec as usual when finished:

from spec_ptc import Speculator

spec = Speculator()


# tools can also be async
@spec.tool(speculatable=True, pure=True)  # add as tool to be speculated
def llm_query(prompt: str) -> str:
    return sub_lm.complete(prompt)


@spec.tool()  # side effects: never speculated
def send_report(text: str) -> str:
    return mail.send(text)


ns.update(spec.hooks())  # same names, claim-or-run

code = ""
with spec.turn(repl_locals=ns) as t:  # snapshot → discarded shadow fork
    for delta in model_stream:
        code += delta
        t.feed(delta)  # closed stmts launch calls now
exec(code, ns)  # hits return immediately

For the RLM this is one line: from demo.rlm import patch_rlm; patch_rlm().

example.py is an example you can start with for looking how this is done for the RLM.

For arbitrary harness, we provide a simple daemon spec-ptc-daemon that runs the same shadow + store out of process (default socket /tmp/spec-ptc.sock) with four JSON-lines messages:

turn_begin {vars}      snapshot REPL variables into the shadow
feed {delta}           stream tokens; the daemon launches calls
resolve {tool, args}   → hit{result} | miss   (miss: run the tool yourself)
turn_end               evict leftovers, return hit/miss counts
from plugins.client import SpecClient  # ~60 lines, stdlib only — copy it

c = SpecClient()
c.turn_begin({"context": doc})
c.feed(delta)  # per streamed token
hit = c.resolve("llm_query", [prompt])  # result, or None → call it yourself
c.turn_end()

Wrappers in plugins/: Claude Code (PreToolUse), OpenCode, Pi-mono.

spec-ptc (alexzhang13/spec-ptc)

Searching Database…

Что это?sPTC (speculative programmatic tool-calling) — это техника и небольшая библиотека, которые предугадывают и ставят в очередь вызовы инструментов, спрятанные внутри частично сгенерированного блока REPL-кода, чтобы обвязки вроде RLM или CodeAct могли запускать дорогие вызовы суб-LLM и инструментов ещё до того, как модель допишет код.
Это полноценная агентская обвязка или то, что я добавляю к уже существующей?Это лёгкая библиотека плюс демо, созданная, чтобы пристраиваться к обвязкам программных вызовов инструментов, которые у вас уже есть (RLM, CodeAct и т.д.), а не заменять саму обвязку.
Как встроить sPTC в свою обвязку?Склонируйте репозиторий (он использует uv) или установите пакет, создайте Speculator, пометьте декоратором spec.tool функции, которые хотите предугадывать, передавайте в него стримящиеся токены по мере генерации REPL-кода, а затем выполняйте готовый код как обычно.
Что уже должно быть настроено, чтобы этим пользоваться?Нужны Python и существующая обвязка программных вызовов инструментов, к которой можно подключиться — для RLM это один вызов demo.rlm.patchrlm, а готовые обёртки есть для Claude Code, OpenCode и Pi-mono.
Это работает с любой агентской конфигурацией или только с внутрипроцессными?Она построена вокруг обвязок, у которых вызовы инструментов живут внутри одного REPL-кода на каждый ход (в стиле PTC); для конфигураций не в одном процессе есть отдельный внешний демон spec-ptc-daemon, зеркалирующий тот же теневой REPL через Unix-сокет.
Кто реально будет этим пользоваться?Разработчики, которые строят или настраивают агентские обвязки, генерирующие вызовы инструментов через код-REPL на каждом ходу, — вроде Recursive Language Models или агентов в стиле CodeAct, где вызовы суб-LLM доминируют в задержке.
Что такое RLM в этом контексте?RLM расшифровывается как Recursive Language Model — обвязка, где вызовы суб-LLM и суб-RLM встроены как функции внутрь одного инструмента код-REPL, генерируемого на каждый ход, и такие вызовы часто занимают большую часть времени выполнения.
Для каких обвязок уже есть готовые обёртки?В каталоге plugins/ лежат обёртки для Claude Code (подключается через PreToolUse), OpenCode и Pi-mono — не считая однострочного патча для RLM.
Как предугадывание вызовов инструментов реально экономит время?Пока корневая LLM стримит токены REPL-вызова, sPTC разбирает частично сгенерированный код, заранее запускает распознанные вызовы инструментов и суб-LLM как Futures и совмещает эту работу с оставшейся генерацией кода и последующим выполнением, вместо того чтобы сначала ждать завершения всего блока.
Size
114.4 MB
Stars
223
Age
1mo
Commits · 90 Days