# Atlaso + DSPy

<!-- Canonical: https://www.atlaso.ai/docs/recipes/dspy -->

`pip install atlaso[dspy]` is reserved namespace. DSPy modules typically take a retriever as a kwarg — wrap Atlaso as a custom retriever:

```python
import dspy
from atlaso import Memory

memory = Memory()


class AtlasoRetrieve(dspy.Retrieve):
    """DSPy retriever backed by Atlaso. Carries dispersion fields in
    each Example so DSPy programs can branch on confidence."""

    def __init__(self, user_id: str, k: int = 5):
        super().__init__(k=k)
        self._user = memory.for_user(user_id)

    def forward(self, query_or_queries: str | list[str], k: int | None = None) -> dspy.Prediction:
        queries = (
            [query_or_queries] if isinstance(query_or_queries, str) else query_or_queries
        )
        passages = []
        for q in queries:
            results = self._user.recall(q, limit=k or self.k)
            for r in results:
                passages.append(
                    dspy.Example(
                        long_text=r.content,
                        is_confident=r.is_confident,
                        has_disagreement=r.has_disagreement,
                        agreement_score=r.agreement_score,
                    )
                )
        return dspy.Prediction(passages=passages)


# Use in a DSPy program:
class AssistantWithMemory(dspy.Module):
    def __init__(self, user_id: str):
        super().__init__()
        self.retrieve = AtlasoRetrieve(user_id=user_id, k=5)
        self.respond = dspy.Predict("question, context -> answer")

    def forward(self, question: str) -> dspy.Prediction:
        passages = self.retrieve(question).passages
        # Trust hierarchy: confident > unconfirmed > disagreement.
        # DSPy programs can use `is_confident` as a feature for the predictor
        # or filter conflicted passages out of context entirely.
        trusted = [p for p in passages if p.is_confident]
        ctx = "\n".join(p.long_text for p in (trusted or passages))
        return self.respond(question=question, context=ctx)
```

Atlaso's dispersion fields fit DSPy's example metadata cleanly — train your DSPy program on whether `is_confident` matters for downstream answer quality, and you get a confidence-aware retrieval pipeline without writing the confidence model yourself.

---

<!-- atlaso:doc-trailer -->
**Source:** <https://www.atlaso.ai/docs/recipes/dspy>  
**Edit on GitHub:** <https://github.com/imashishkh21/atlaso/tree/main/docs/recipes/dspy.md>  
**Updated:** 2026-05-12
