Accelerate multi-agent GPU inference with zero-copy context sharing
Context-Stitcher shares GPU KV cache blocks across multiple agents reading the same long document, skipping the prefill phase entirely.
Why it matters
Enable multiple AI agents to process the same long document context without redundant GPU prefill operations, dramatically reducing latency and memory usage when agents work sequentially on shared text.
Outcomes
What it gets done
Bridge KV cache blocks between agents using cryptographic fingerprints to eliminate duplicate prefill phases
Reduce time-to-first-token by 25x when subsequent agents process the same document context
Save 43% GPU memory by sharing physical cache blocks across authorized agent sessions
Enforce zero-trust security policies controlling which agents can access shared memory blocks
Install
Add it to your toolbox
Run in your project directory:
curl -fsSL https://spark.entire.vc/get/daqulalin-memstitch | bash Overview
MemStitch
Context-Stitcher is a zero-copy context bridging gateway that shares GPU KV cache blocks across multiple agents reading the same long document, mapping a later agent's attention table directly onto an earlier agent's already-cached memory blocks to bypass prefill entirely, gated by a zero-trust access policy per agent pair. Use it in multi-agent pipelines where several agents sequentially process the same large shared context and repeated prefill is a real cost; the benefit is largest on long documents, and cache sharing safety depends entirely on correctly configured per-agent access policies.
What it does
Context-Stitcher is a zero-copy context bridging gateway for multi-agent GPU inference. In multi-agent workflows where separate agents process the same long text sequentially - the source's example is a legal auditor agent and a financial compliance agent both reading the same 200-page contract - standard inference engines force every subsequent agent to repeat the expensive prefill phase, duplicating GPU KV-cache activations and taking a large time-to-first-token hit. Context-Stitcher bridges the caches at the memory level instead: it segments prompts into fixed physical block sizes and maps them to cryptographic fingerprints via Merkle-chain hashing (context topological hashing), then for matched prefixes it maps a second agent's logical attention table directly onto the first agent's already-computed physical GPU memory blocks, bypassing prefill entirely rather than copying the cached data. A zero-trust secure gate enforces boundary control lists so an agent session can only stitch into another agent's cache blocks if explicitly authorized.
The project's own benchmark, run against standard vLLM cold prefills over a shared 200-page document, reports a second agent's prefill response time dropping from 1200ms to 48ms (a 25x speedup) and total GPU physical cache blocks allocated dropping from 53 to 30 (43.4% memory saved), since the shared blocks aren't duplicated per agent.
When to use - and when NOT to
Use Context-Stitcher when running multi-agent pipelines where several agents sequentially process the same long context (a shared document, transcript, or codebase) and you want later agents to skip re-running prefill on text an earlier agent already cached, cutting both latency and GPU memory use. It fits both Python-native agent orchestration and cross-language clients that just need an OpenAI-compatible endpoint - Dify, Flowise, or any HTTP client - by adding agent_id/session_id metadata to a standard chat completions request.
It's specifically valuable when the shared context is large enough that prefill cost dominates (the source's benchmark uses a 200-page document); for short prompts where prefill is already cheap, the cache-stitching machinery adds coordination overhead without a meaningful latency win. Cache sharing across agents is only as safe as the configured security policy - access must be explicitly granted per agent pair via the zero-trust gate, so a misconfigured policy could either block legitimate sharing or, if over-permissioned, let an unintended agent read another's cached context.
Inputs and outputs
Install and launch the gateway plus its developer dashboard:
pip install -r requirements.txt
python run.py
This serves an OpenAI-compatible API at http://localhost:8000/v1/chat/completions and a real-time dashboard (at http://localhost:8000) showing physical cache block states - idle, private allocations, shared/stitched pages, and security alarms. Input is either a Python-decorated agent function (@stitch_agent against a StitcherMesh instance, generating with a fingerprint identifying the shared document) or a standard chat completions request carrying agent_id and session_id in extra_body (Python SDK) or the JSON body (raw HTTP). Output is the generated response plus, for the Python SDK path, an explicit prefill_time_saved_ms figure. Security policies are managed via REST: GET /policies to inspect, POST /policy to authorize one agent to read another's cache, DELETE /policy to revoke it.
Integrations
Context-Stitcher's StitcherMesh is built as a pointer-sharing inference control layer referencing vLLM as its backend, and its gateway exposes OpenAI-compatible REST endpoints so any client that speaks the OpenAI chat completions API - the official Python SDK, cURL, or no-code agent platforms like Dify and Flowise - can activate cache sharing just by pointing its base URL at the gateway and adding agent and session metadata.
Who it's for
Teams building multi-agent pipelines on shared, long-context documents (legal, financial, compliance, codebase-review workflows) who are hitting redundant prefill cost and GPU memory duplication when multiple agents read the same context sequentially, and who run or can route through a vLLM-backed inference stack.
Source README
Context-Stitcher ๐ชก
Zero-Copy Context Bridging Gateway for Multi-Agent GPU Inference.
๐ก Core Value Proposition
In multi-agent collaborative workflows, separate agents often process the same long text context sequentially. For example:
- Agent A (Legal Auditor): Reads a 200-page contract and runs compliance analyses (populating the GPU KV Cache).
- Agent B (Financial Compliance): Reads the same 200-page contract and audits financial liabilities.
Under standard inference engines, Agent B is forced to repeat the expensive prefill phase, duplicate GPU activations, and suffer from high Time-to-First-Token (TTFT) latency.
Context-Stitcher solves this by bridging caches at the memory level:
- Context Topological Hashing: Segmenting prompts into physical block-sizes and mapping them to cryptographic fingerprints (Merkle-chains).
- Zero-Copy Block Stitching: Bypassing prefill for matched prefixes by mapping the logical attention table of Agent B directly to the physical GPU memory address of Agent A's cache blocks.
- Zero-Trust Secure Gate: Enforcing boundary control lists so unauthorized agent sessions cannot access shared physical blocks.
๐ Performance Profiles
Below is the benchmark analysis of Context-Stitcher compared to standard vLLM cold-prefills when executing consecutive agents over a shared 200-page document:
โก TTFT Prefill Latency (Agent B Response Time) โ Lower is better
Baseline (vLLM Cold): โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 1200 ms
Context-Stitcher: โ 48 ms ( 25.0x Prefill Speedup! ๐ )
๐พ GPU Physical Cache Blocks Allocated (Total VRAM) โ Lower is better
Baseline (vLLM Cold): โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ 53 blocks (No sharing)
Context-Stitcher: โโโโโโโโโโโโโโโโ 30 blocks ( 43.4% Memory Saved! ๐ )
โ๏ธ Installation & Quick Start
1. Install Dependencies
pip install -r requirements.txt
2. Launch the Gateway & Dashboard
python run.py
Once booted, the gateway routes are active on http://localhost:8000:
- API Proxy Gateway:
http://localhost:8000/v1/chat/completions - Real-time Developer Console: Open
http://localhost:8000in your web browser.
๐ฅ๏ธ Visual Developer Portal
Context-Stitcher includes a responsive developer portal to monitor physical cache block states (idle, private allocations, shared/stitched pages, security alarms) in real time.
๐ ๏ธ Client Integration & Usage Guide
Context-Stitcher supports Python SDK Decorators and OpenAI-Compatible REST APIs for cross-application integrations:
Pattern A: Python SDK Decorator (For Python-based Agent Orchestration)
If your agent pipelines are written in Python, you can utilize the StitcherMesh and @stitch_agent decorators to link context memory:
from context_stitcher import StitcherMesh, stitch_agent
# 1. Initialize the pointer-sharing inference control mesh (ref: vLLM)
mesh = StitcherMesh(backend="vllm", model="meta-llama/Llama-3.1-8B-Instruct")
# Configure secure gate policy: allow Agent B to read Agent A's KV Cache blocks
mesh.sg.add_policy("agent_a", "agent_b")
# 2. Decorate your agent workflows
@stitch_agent(mesh)
def agent_a():
prompt = "[Long Document Context...]\nAnalyze the intellectual property clauses."
# First execution: Prefills the cache and registers topological hashes
res = mesh.generate(prompt=prompt, fingerprint="legal_doc_v1")
return "legal_doc_v1"
@stitch_agent(mesh)
def agent_b(context_fingerprint):
prompt = "[Long Document Context...]\nEvaluate the financial compliance risk."
# Subsequent execution: Automatically stitches blocks, bypassing prefill phase
res = mesh.generate(prompt=prompt, fingerprint=context_fingerprint)
print(f"Agent B Response: {res['generated_text']}")
print(f"Time Saved: {res['prefill_time_saved_ms']}ms")
Pattern B: OpenAI-Compatible REST API (For multi-language clients, Dify, or Flowise)
The gateway exposes standard OpenAI endpoints. Point your LLM client base URL to Context-Stitcher to activate sharing.
1. Python OpenAI SDK Client:
from openai import OpenAI
# Direct client to the Context-Stitcher proxy gateway
client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")
# Send standard completions request with agent_id metadata inside extra_body
response = client.chat.completions.create(
model="context-stitcher-sim",
messages=[
{"role": "user", "content": "[Long Document Context...]\nEvaluate compliance risk."}
],
extra_body={
"agent_id": "AgentB", # Identifies the requesting Agent
"session_id": "session_legal_audit" # Identifies the shared session cache
}
)
print("Generated Output:", response.choices[0].message.content)
2. Raw HTTP cURL Request:
curl -X POST http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "context-stitcher-sim",
"messages": [
{"role": "user", "content": "[Long Document Context...]\nEvaluate compliance risk."}
],
"agent_id": "AgentB",
"session_id": "session_legal_audit"
}'
Pattern C: Controlling Security Rules via API (Zero-Trust Gate)
You can inspect, add, or revoke access authorization rules dynamically between agents.
1. Retrieve all active policy rules:
curl -X GET http://localhost:8000/policies
2. Authorize AgentB to stitch AgentA's KV Cache:
curl -X POST http://localhost:8000/policy \
-H "Content-Type: application/json" \
-d '{"owner_agent": "AgentA", "allowed_reader": "AgentB"}'
3. Revoke AgentB's permission to read AgentA's Cache:
curl -X DELETE http://localhost:8000/policy \
-H "Content-Type: application/json" \
-d '{"owner_agent": "AgentA", "allowed_reader": "AgentB"}'
FAQ
Common questions
Discussion
Questions & comments ยท 0
Sign In Sign in to leave a comment.