Module 5 · Data agents & production

Deployment, index refresh and observability

5 min read

A knowledge base in production is a living system: documents change, questions evolve, models are updated. Three concerns come on top of the code of the previous lessons: serving requests reliably, keeping the index up to date, and observing what happens to detect problems before users do. This lesson assembles Lumen's service and concludes the course.

The HTTP service

Lumen exposes its capabilities through a FastAPI API:

RouteRole
POST /askQuestion → sourced answer, via the router; reports the engine used
POST /chat/{session}Conversation with memory
POST /agentTool-using agent (documentation, warranty, graph)
POST /extractCustomer email → structured warranty claim
POST /admin/refreshIncremental ingestion, protected by a token
GET /metricsCounters of model calls and retrievals

The base is built once, at startup, in the lifespan function:

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.metrics = observability.install()
    location = os.environ.get("LUMEN_VECTOR_LOCATION")  # ":memory:" pour les tests
    state_dir = None if location == ":memory:" else Path(config.STORAGE_DIR / "pipeline")
    app.state.kb = await KnowledgeBase.build(location=location, state_dir=state_dir)
    app.state.chats = {}
    yield

KnowledgeBase.build runs incremental ingestion (instant if nothing changed, thanks to the persisted docstore), then rebuilds the indexes and engines. The six tests in tests/test_server.py exercise every route in memory, without network.

Keeping the index up to date

The /admin/refresh route calls the same pipeline as startup (lesson 2.4). In production, several strategies combine:

StrategyTriggerFor
ScheduledHourly, nightlySources without change notifications
Event-drivenWebhook from the documentation tool on each publicationMaximum freshness, minimal cost
ManualAdmin buttonUrgent fix of a document
Full rebuildChange of embedding model or chunkingAlways into a new index, then switch

The last case deserves a precaution: changing the embedding model or the chunking strategy invalidates every vector. Don't rebuild "in place" — the index would be inconsistent for hours. Build a new collection in parallel, evaluate it (lesson 5.3), then switch the service to it at once (a Qdrant collection alias, or a configuration variable).

The other indexes follow their own rhythm: document summaries (lesson 3.2) must be recomputed for modified documents; the catalog graph (lesson 3.3), at each catalog update.

Observing: LlamaIndex instrumentation

Every LlamaIndex component emits instrumentation events: start and end of an LLM call, a retrieval, a synthesis, a tool call… A handler attached to the root dispatcher receives them all:

from llama_index.core.instrumentation import get_dispatcher
from llama_index.core.instrumentation.event_handlers import BaseEventHandler


class MetricsHandler(BaseEventHandler):
    counts: Counter = Counter()
    retrieved_nodes: int = 0

    def handle(self, event: BaseEvent, **kwargs: Any) -> None:
        self.counts[event.class_name()] += 1
        if isinstance(event, RetrievalEndEvent):
            self.retrieved_nodes += len(event.nodes)


get_dispatcher().add_event_handler(MetricsHandler())

Lumen thus keeps counters exposed on /metrics. In production, you'd rather send these events to a specialized tool: OpenTelemetry (llama-index-observability-otel package), Arize Phoenix, Langfuse and others have integrations. There you find, for each request, the full tree: question, sub-questions, retrieved passages with their scores, prompts sent, answers, durations and tokens.

What to monitor?

IndicatorWhat it reveals
Latency per step (retrieval, LLM)The step to optimize
Tokens and cost per requestCost drift, prompts that are too long
Rate of "I can't find it" answersGaps in the base, or a badly tuned similarity threshold
Score of the best passageQuestions outside the base's scope
Distribution of engines chosen by the routerEngine descriptions to revise
User feedback (thumbs up/down)Perceived quality, to be linked to traces
Date of the last successful refreshStale index

The "I can't find it" rate is particularly instructive: the questions concerned sketch the list of documents missing from the base. Reread them every week: it's the best source of content improvement.

Security and data

  • Access rights: an assistant everyone can query must only index documents everyone can read. For differentiated rights, store the authorized groups as metadata and systematically filter at query time according to the user.
  • Personal data: documents, conversations and traces contain it. Retention periods, masking before sending to observability tools (PIINodePostprocessor for passages), deletion on request.
  • Indexed content = untrusted content: a document may contain malicious instructions (indirect injection). Answers must remain sourced, and agent tools read-only.

Course conclusion

You built Lumen step by step: readers that produce clean documents with stable identifiers, an incremental ingestion pipeline, reliable PDF parsing, chunking that respects structure, useful metadata, three complementary indexes — vector, summaries, graph —, a router, a sub-question engine, a chat with memory, a corrective RAG workflow, a tool-using agent, structured extraction, quantified evaluation and an observable service. All of it tested offline by 27 tests.

Above all, remember the method: quality is decided in the data, every setting is measured, each index answers one type of question, and what isn't observed eventually degrades in silence.

Key takeaways

  • A service builds the base at startup; incremental ingestion makes it instant when nothing changed.
  • Scheduled, event-driven or manual refreshes; a full rebuild goes into a new index, evaluated, then switched.
  • Instrumentation emits one event per step; a handler sends them to your metrics or an observability tool.
  • Monitor latency, cost, "I can't find it" rate, routing and user feedback.
  • Access rights through metadata filters, personal data under control, indexed content treated as untrusted.

Practice

  1. Run the service offline (LUMEN_FAKE_LLM=1 uvicorn lumen.server:app), ask questions on /docs and watch /metrics.
  2. Add a counter of "je ne trouve pas" answers to the MetricsHandler and expose it on /metrics.
  3. Add an audience metadata field ("support" or "direction") to documents, and filter searches according to an X-User-Role header.

Resources