How to Use SharedContext for Multi-Agent Workflows in Headroom
Headroom's SharedContext class compresses and stores large data payloads so multiple AI agents can exchange context efficiently without exceeding token limits or polluting individual prompts.
The chopratejas/headroom repository provides a TypeScript SDK that implements SharedContext as a centralized compression layer for multi-agent applications. By storing compressed representations of agent outputs in memory, subsequent agents can retrieve only the essential compressed data—or optionally decompress it—while the system tracks metadata, TTL, and usage statistics automatically.
Architecture of SharedContext
The SharedContext class in sdk/typescript/src/shared-context.ts operates as a specialized key-value store with built-in compression and eviction policies. It wraps the Headroom proxy service to minimize token transmission costs between workflow stages.
Compression Layer
Internally, the class instantiates a HeadroomClient and invokes the compress endpoint via client.compress. This sends large message payloads to the Headroom proxy service, which returns a CompressResult containing a compressed representation. The SDK stores this compressed payload alongside metadata including original length, token counts, agent name, timestamps, and applied transforms.
Storage and Eviction Mechanics
Data resides in an in-memory Map<string, ContextEntry> identified as entries. The implementation enforces resource limits through two configurable parameters:
ttl(seconds): Defines how long each entry remains valid before expirationmaxEntries: Caps the total number of stored contexts
Expired entries are removed lazily on every read or write operation via evictExpired(). When the map reaches maxEntries capacity, the evictIfFull method automatically removes the oldest entry to accommodate new data.
API Surface
The class exposes methods designed for agent-to-agent handoffs:
put(key, content, {agent}): Compresses content and stores it with metadataget(key, {full}): Retrieves the compressed value; setfull: trueto return the original uncompressed textgetEntry(key): Returns the completeContextEntrymetadata objectkeys(),stats(),clear(): Utility methods for inspection and cleanup
Implementing Multi-Agent Workflows
A typical implementation involves initializing the context, having agents store research or intermediate results, and retrieving compressed data for downstream processing. The default compression model is claude-sonnet-4-5-20250929, though you can override this in the constructor.
Step-by-Step Workflow
- Initialize SharedContext: Pass optional
model,ttl, andmaxEntriesparameters - Agent A stores data: Use
put()with an identifier and agent name to compress and persist large objects - Agent B retrieves data: Call
get()to obtain the compressed payload for input into the next model - Monitor efficiency: Use
stats()to track aggregated token savings across the workflow
The official example in sdk/typescript/examples/shared-context-multi-agent.ts demonstrates a complete handoff between a researcher agent and a writer agent.
Practical Code Example
import { SharedContext } from "headroom-ai";
import { withHeadroom } from "headroom-ai/vercel-ai";
import { openai } from "@ai-sdk/openai";
import { generateText } from "ai";
// Initialize with custom model and capacity limits
const ctx = new SharedContext({ model: "gpt-4o", maxEntries: 50 });
const model = withHeadroom(openai("gpt-4o"));
// Agent A: Research phase - stores large structured data
const researchData = {
topic: "Kubernetes autoscaling",
findings: [/* ... extensive research results ... */],
sources: [/* ... citation data ... */]
};
const entry = await ctx.put("k8s-research", JSON.stringify(researchData), {
agent: "researcher",
});
console.log(
`Stored ${entry.originalTokens} → ${entry.compressedTokens} tokens ` +
`(${entry.savingsPercent.toFixed(0)}% saved)`
);
// Agent B: Writing phase - retrieves compressed context
const compressed = ctx.get("k8s-research");
const { text } = await generateText({
model,
messages: [
{ role: "system", content: "You are a technical writer." },
{ role: "user", content: `Create a blog outline from this research:\n${compressed}` },
],
});
console.log("Generated outline:", text);
// Optional: View aggregated statistics
console.log("SharedContext stats:", ctx.stats());
Configuration and Performance Tuning
TTL and Memory Management
Set ttl based on your workflow duration to ensure stale data doesn't accumulate. The maxEntries parameter prevents unbounded memory growth in long-running applications. Since eviction occurs lazily (triggered by get, put, or other access methods), the system maintains performance without background garbage collection overhead.
Cross-Language Compatibility
The TypeScript implementation mirrors the Python headroom.shared_context.SharedContext class, enabling teams to share context across language boundaries within the same application. Both implementations use the same compression protocol and metadata schema, ensuring consistent behavior whether your agents run in Node.js or Python environments.
Summary
SharedContextcreates aHeadroomClientinternally to call thecompressendpoint, reducing token payloads between agents- Storage uses an in-memory Map with configurable
ttl(time-to-live) andmaxEntrieslimits, evicting expired or oldest entries automatically - API methods include
put(),get(),getEntry(), andstats()for managing compressed data and monitoring savings - Default model is
claude-sonnet-4-5-20250929, configurable via constructor options - Cross-platform support allows sharing context between TypeScript and Python implementations of Headroom
Frequently Asked Questions
How does SharedContext reduce token usage in multi-agent workflows?
SharedContext minimizes token consumption by compressing large payloads through the Headroom proxy service's compress endpoint before storage. Agents pass compressed references instead of full text, and the CompressResult metadata tracks exact savings. According to the implementation in sdk/typescript/src/shared-context.ts, this allows downstream agents to receive substantial context without the token cost of repeating full conversation histories.
What happens when the SharedContext reaches its maximum capacity?
When the internal Map reaches the maxEntries limit, the evictIfFull method automatically removes the oldest entry based on insertion time. This FIFO (first-in-first-out) eviction ensures recent context remains available while maintaining strict memory boundaries. You can monitor current utilization through the stats() method.
Can I retrieve the original uncompressed data from SharedContext?
Yes. While get(key) returns the compressed representation by default, passing {full: true} as the second parameter returns the original uncompressed content. The getEntry(key) method provides access to the full ContextEntry metadata including both original and compressed token counts, timestamps, and the agent identifier.
Is SharedContext compatible with the Vercel AI SDK?
Yes. The Headroom SDK provides a withHeadroom wrapper specifically for the Vercel AI SDK, as shown in sdk/typescript/examples/shared-context-multi-agent.ts. You can use SharedContext alongside generateText and other AI SDK functions by injecting compressed context directly into message contents, maintaining full compatibility with OpenAI, Anthropic, and other providers supported by the Vercel AI SDK.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →