Home / Articles / Practical notes: From Retrieval to Reasoning: Building Production-Ready Agentic

This article is published in English.

Practical notes: From Retrieval to Reasoning: Building Production-Ready Agentic

Operable walkthrough of Practical notes: From Retrieval to Reasoning: Building Production-Ready Agentic: contracts, checks, and drop-in code slots for teams shipping this pattern.

1845 words

Use this as an operator-facing rebuild of the ideas in “From Retrieval to Reasoning: Building Production-Ready Agentic AI Systems with Knowledge Graphs”: clear stages, ordered code slots, and recovery notes that survive a handoff. The Overview stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

from neo4j import GraphDatabase
import json

def get_grounded_context(user_query: str, entity_extractor, driver) -> str:
    # Step 1: Extract entities from the user query
    entities = entity_extractor(user_query)  # e.g., ["Product X", "Supplier Y"]

    # Step 2: Pull a relevant subgraph from Neo4j
    with driver.session() as session:
        result = session.run(
            """
            MATCH (e)-[r]-(connected)
            WHERE e.name IN $entities
            RETURN e.name AS entity,
                   type(r) AS relationship,
                   connected.name AS related_entity,
                   connected.attributes AS attributes
            LIMIT 50
            """,
            entities=entities
        )
        subgraph = [record.data() for record in result]

    # Step 3: Format subgraph as structured context
    context_str = json.dumps(subgraph, indent=2)

    grounded_prompt = f"""
    You are a reasoning agent. Use ONLY the following structured knowledge to answer.
    If the answer isn't derivable from this context, say so explicitly.

    KNOWLEDGE GRAPH CONTEXT:
    {context_str}

    USER QUERY: {user_query}
    """
    return grounded_prompt
def plan_with_graph(goal: str, graph_schema: dict, llm) -> list[dict]:
    schema_str = json.dumps(graph_schema, indent=2)

    planning_prompt = f"""
    You are a planning agent. Given the goal below, decompose it into steps.
    Each step must reference a valid entity type or relationship from the schema.
    Do not invent steps that require knowledge outside this schema.

    GRAPH SCHEMA:
    {schema_str}

    GOAL: {goal}

    Return a JSON list of steps. Each step must include:
    - "action": what to do
    - "graph_query": the Cypher query to retrieve required context
    - "depends_on": list of prior step indices this step requires
    """

    raw_plan = llm.complete(planning_prompt)
    plan = json.loads(raw_plan)
    return plan
def execute_with_validation(step: dict, intermediate_result: str, driver, llm) -> dict:
    # Extract claims from the intermediate result
    claim_extraction_prompt = f"""
    Extract all factual claims from this text as a list of (subject, predicate, object) triples.
    TEXT: {intermediate_result}
    Return as JSON array.
    """
    claims = json.loads(llm.complete(claim_extraction_prompt))

    validation_results = []
    with driver.session() as session:
        for claim in claims:
            result = session.run(
                """
                MATCH (s {name: $subject})-[r]-(o {name: $object})
                WHERE type(r) = $predicate OR $predicate IN r.aliases
                RETURN count(r) AS match_count
                """,
                subject=claim["subject"],
                predicate=claim["predicate"],
                object=claim["object"]
            )
            record = result.single()
            validation_results.append({
                "claim": claim,
                "validated": record["match_count"] > 0
            })

    unvalidated = [v for v in validation_results if not v["validated"]]

    return {
        "result": intermediate_result,
        "validated": len(unvalidated) == 0,
        "flagged_claims": unvalidated
    }

Operational checklist

When working through the Operational checklist stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest.

Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.

Cache stable system instructions and tool schemas. Re-sending identical preamble is a common source of burn.

Separate chunking policy from retrieval policy. Changing one should not force a rewrite of the other when quality metrics move.

Put human approval on edges that spend money or change production data. Compile-time wiring does not equal business completeness.

Track cost and latency beside quality. A slightly worse answer that costs 10x less may be the right production trade.

Before promoting the stack, freeze versions, capture a golden transcript for the critical path, and confirm rollback steps. Shared environments need rate limits, tenancy checks, and a clear owner for secret rotation. Prefer boring reliability over clever one-off demos.

Batch note for 7e5e1dbfc22b: keep provider keys out of the repo, set a per-session token ceiling, and store transcripts next to the eval fixtures so later model swaps stay comparable.

The hardening note 0 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.

Hardening detail 0/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

For the hardening note 1 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.

Hardening detail 1/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

When working through the hardening note 2 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.

Hardening detail 2/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

The hardening note 3 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

Hardening detail 3/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

For the hardening note 4 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

Hardening detail 4/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

When working through the hardening note 5 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.

Hardening detail 5/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

The hardening note 6 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.

Hardening detail 6/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

For the hardening note 7 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.

Hardening detail 7/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

When working through the hardening note 8 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

Hardening detail 8/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

The hardening note 9 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

Hardening detail 9/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

For the hardening note 10 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.

Hardening detail 10/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

When working through the hardening note 11 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.

Hardening detail 11/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

The hardening note 12 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.

Hardening detail 12/956: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.