Skip to main content

anchor

Context engineering toolkit for AI applications.

Docs · Quickstart · Cookbook · API Reference · Issues

PyPI Downloads Python License Stars


Stop duct-taping RAG, memory, and tools together. anchor gives you a single, token-aware pipeline that assembles context for any LLM — with smart budgets, hybrid retrieval, and provider-agnostic formatting out of the box.

Why anchor?

Feature LangChain LlamaIndex mem0 anchor
Hybrid RAG (Dense + BM25 + RRF) partial yes no yes
Token-aware Memory partial no yes yes
Token Budget Management no no no yes
Provider-agnostic Formatting no no no yes
Protocol-based Plugins (PEP 544) no partial no yes
Zero-config Defaults no no yes yes
2000+ tests, 94% coverage — — — yes

Quick Install

pip install astro-anchor
Optional extras
pip install astro-anchor[bm25]        # BM25 sparse retrieval
pip install astro-anchor[anthropic]   # Anthropic Claude support
pip install astro-anchor[claude-cli]  # Claude Code CLI — your subscription, no API key
pip install astro-anchor[cli]         # CLI tools (typer + rich)
pip install astro-anchor[flashrank]   # FlashRank reranking
pip install astro-anchor[otlp]        # OpenTelemetry tracing
pip install astro-anchor[all]         # Everything

30 Seconds to Your First Pipeline

from anchor import ContextPipeline, MemoryManager, AnthropicFormatter

pipeline = (
    ContextPipeline(max_tokens=8192)
    .with_memory(MemoryManager(conversation_tokens=4096))
    .with_formatter(AnthropicFormatter())
    .add_system_prompt("You are a helpful assistant.")
)

result = pipeline.build("What is context engineering?")
print(result.formatted_output)   # Ready for Claude API
print(result.diagnostics)        # Token usage, timing, overflow info

Features

  • Hybrid RAG — Dense embeddings + BM25 sparse retrieval with Reciprocal Rank Fusion
  • Smart Memory — Token-aware sliding window with automatic eviction
  • Knowledge Graph — Entities and evidenced, bi-temporal relations over memory and documents; scope-aware navigation (path, explain, backlinks), graph retrieval fused by RRF, anchor graph CLI
  • Token Budgets — Priority-ranked context assembly that never exceeds your window
  • LLM Providers — Unified interface for Anthropic, OpenAI, Gemini, Grok, Ollama, OpenRouter, LiteLLM with fallback
  • MCP Bridge — Bidirectional Model Context Protocol integration for consuming and exposing MCP tools
  • Provider Agnostic — Format output for Anthropic, OpenAI, or plain text
  • Protocol-Based — Plug in any vector store, tokenizer, or retriever via PEP 544 Protocols
  • Type-Safe — Pydantic v2 models throughout, full py.typed support
  • Agent Framework — Build tool-calling agents with @tool decorator and skills
  • Full Observability — OpenTelemetry tracing, cost tracking, per-step diagnostics
Hybrid Retrieval Example
import math
from anchor import (
    ContextPipeline, ContextItem, QueryBundle, SourceType,
    DenseRetriever, InMemoryContextStore, InMemoryVectorStore,
    retriever_step,
)

def my_embed_fn(text: str) -> list[float]:
    seed = sum(ord(c) for c in text) % 10000
    raw = [math.sin(seed * 1000 + i) for i in range(64)]
    norm = math.sqrt(sum(x * x for x in raw))
    return [x / norm for x in raw] if norm else raw

dense = DenseRetriever(
    vector_store=InMemoryVectorStore(),
    context_store=InMemoryContextStore(),
    embed_fn=my_embed_fn,
)

items = [
    ContextItem(content="Python is great for data science.", source=SourceType.RETRIEVAL),
    ContextItem(content="RAG combines retrieval with generation.", source=SourceType.RETRIEVAL),
]
dense.index(items)

pipeline = ContextPipeline(max_tokens=8192).add_step(retriever_step("search", dense, top_k=5))
query = QueryBundle(query_str="How does RAG work?", embedding=my_embed_fn("How does RAG work?"))
result = pipeline.build(query)
Memory Management Example
from anchor import ContextPipeline, QueryBundle, MemoryManager

memory = MemoryManager(conversation_tokens=4096)
memory.add_user_message("Help me migrate from MySQL to Postgres")
memory.add_assistant_message("Sure! What MySQL version are you using?")
memory.add_user_message("MySQL 8.0, about 50GB")

pipeline = ContextPipeline(max_tokens=8192).with_memory(memory)
result = pipeline.build(QueryBundle(query_str="What are the risks?"))
# Memory is automatically included, oldest turns evicted if over budget
Decorator API Example
from anchor import ContextPipeline, ContextItem, QueryBundle

pipeline = ContextPipeline(max_tokens=8192)

@pipeline.step
def boost_recent(items: list[ContextItem], query: QueryBundle) -> list[ContextItem]:
    return [
        item.model_copy(update={"score": min(1.0, item.score * 1.5)})
        if item.metadata.get("recent") else item
        for item in items
    ]

result = pipeline.build("What is context engineering?")
Provider Formatting
from anchor import AnthropicFormatter, OpenAIFormatter

# Anthropic: {"system": "...", "messages": [...]}
result = pipeline.with_formatter(AnthropicFormatter()).build(query)

# OpenAI: {"messages": [{"role": "system", ...}, ...]}
result = pipeline.with_formatter(OpenAIFormatter()).build(query)

Architecture

ContextPipeline
  │
  ├── System Prompts (priority=10)
  ├── Memory Manager (priority=7)
  ├── Pipeline Steps
  │     ├── Retriever Steps (append items)
  │     ├── PostProcessor Steps (transform items)
  │     └── Filter Steps (filter items)
  │
  ▼
ContextWindow (token-aware, priority-ranked)
  │
  ▼
Formatter (Anthropic / OpenAI / Generic)
  │
  ▼
ContextResult (formatted output + diagnostics)

Token Budgets

from anchor import ContextPipeline, default_chat_budget

budget = default_chat_budget(max_tokens=8192)
pipeline = ContextPipeline(max_tokens=8192).with_budget(budget)

Three presets available: default_chat_budget (conversational), default_rag_budget (retrieval-heavy), default_agent_budget (balanced).

Development

git clone https://github.com/Astrointelligence-dev/anchor.git
cd anchor
uv sync
uv run pytest     # 2000+ tests
uv run ruff check src/ tests/

Roadmap

  • v0.1.0 — Hybrid RAG, Memory, Pipeline, Formatters, Async, Decorator API, Agent Framework, Full docs
  • v0.2.0 (next) — Agent loop 2026: event stream, usage limits, subagents, hooks + approval seam, structured output, memory tool, MCP bridge; embeddings layer, sqlite-vec + pgvector (HNSW), skills to the agentskills.io spec; vaults, namespaces and RetrievalScope; knowledge graph over memory and documents
  • v0.3.0 — Production deployment guides, additional vector backends by demand
  • v0.4.0 — LangChain/LlamaIndex adapters, webhook-based event system, async navigation API for the Postgres graph
  • v1.0.0 — Stable public API, plugin ecosystem, managed cloud offering

License

MIT — see LICENSE for details.

Metadata

Release files for astro-anchor 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for astro-anchor 0.2.0
File Size Uploaded Provenance
astro_anchor-0.2.0.tar.gz 295.1 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for astro-anchor 0.2.0
File Interpreter ABI Platform
astro_anchor-0.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 696.9 kB

Release files / astro_anchor-0.2.0.tar.gz

Download URL astro_anchor-0.2.0.tar.gz
Size 295.1 kB
Tags Source
SHA-256 checksum
How to use checksums
94148701988ba08ddc95ec54e4054bbc66ee7f892bfe5ce1db8084c1044b93c6
BLAKE2b-256 checksum
How to use checksums
e0fa089514f43884fa487a385c9ba9c0ec9a4535ad5a521c1739a7a816b702d7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

Release files / astro_anchor-0.2.0-py3-none-any.whl

Download URL astro_anchor-0.2.0-py3-none-any.whl
Size 401.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
aa7e496654a1bd856c6f2cec7dfd6d228114044421b0e51da624cbeee16d7494
BLAKE2b-256 checksum
How to use checksums
907dc4849779cd05869c71d963cd0d820b598a9ebbfa92fa1b5f14c8f4e6f85e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

Security for astro-anchor 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for astro_anchor-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 9, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page