Knowledge Graph from Ontology: A Three-Hour End-to-End Practice with AI Coding Agents

    This article walks through a three-hour practice of building an ontology-driven knowledge graph extraction and visualization system as a long-horizon agent task. It explains why this kind of multi-stage workflow is a realistic test of autonomous engineering, how the plan-generate-evaluate loop becomes an internal model capability instead of an external scaffold, and how to turn a one-line requirement into a verifiable engineering contract. It also covers the five-layer architecture, an eight-stage task breakdown, self-correction driven by clear evaluation signals, ontology modeling and extraction quality practices, visualization and query design, and the production-readiness items needed to move from demo to operable system.

    1. Why an Ontology-Driven Knowledge Graph Is a Good Long-Horizon Test Case

    In discussions about AI agents and AI coding tools, the most underestimated category of work is the long-horizon complex task. It is not a single hard algorithm problem. It is a chain of stages that must run in sequence, and if any stage fails, the whole system is unusable. An ontology-driven knowledge graph extraction and visualization system is a typical example.

    The difficulty concentrates in four areas:

    • Strong semantic constraints: The ontology defines entity types, attributes, relation types, and constraints (for example, a “movie—director—actor” schema). Extraction output must conform to that schema rather than being a pile of free-text triples.
    • Multiple coupled technology stacks: The work spans natural language processing, graph data modeling, graph database writes, backend services, and frontend visualization interaction, so cross-layer integration is expensive.
    • Quality requires closed-loop verification: Extraction accuracy, relation validity, graph query performance, and frontend rendering stability all need to be measured and regression-tested.
    • Clear delivery standard: The deliverable is not a demo page, but a complete pipeline that runs automatically from unstructured text all the way to graph display.

    The value of choosing this kind of task is that it genuinely tests whether an AI coding tool can complete an engineering loop on its own, instead of only autocompleting code snippets.

    2. Core Observation: The Loop Moves from External Scaffold to Internal Capability

    Completing a similar task in the past usually required a manually built external process: the model generated a plan, a human reviewed it; after code was generated, a human configured tests, read logs, located problems, and fed context back in, iterating repeatedly. That process is essentially the explicit engineering of a “plan—generate—evaluate” loop.

    The key difference in this practice is that the loop no longer depends on an external scaffold. It is internalized by the model as continuous behavior within the same context: first research and architecture design, then task decomposition, then step-by-step execution. At each step, the model runs verification itself, reads failure information, and fixes the implementation until the delivery conditions are met. What the user has to do is state the goal, constraints, and acceptance criteria clearly, rather than constantly shuttling context back and forth.

    The engineering implication is this: when a model has sufficient code comprehension and self-evaluation ability, the value of scaffolding shifts from driving execution to constraining boundaries and ensuring observability.

    3. Task Definition: Turning a One-Line Requirement into a Verifiable Engineering Contract

    High-quality delivery starts with a verifiable requirement. In practice, the requirement description should contain at least four kinds of information:

    1. Inputs and outputs: The input is unstructured text plus an ontology definition; the output is entities and relations in a graph database, plus an interactive query and visualization interface.
    2. Ontology constraints: Entity types, relation types, attribute fields, uniqueness constraints, and validity rules must be explicit.
    3. Non-functional requirements: The extraction process must be re-runnable, results must be verifiable, interfaces must be testable, and the frontend must support interactive queries.
    4. Acceptance method: Automated tests and an end-to-end demo serve as the completion criteria.

    An illustrative requirement contract (pseudocode):

    1. goal: build an ontology-driven knowledge graph extraction and visualization system
    2. inputs:
    3. - ontology_schema: entity types / relation types / attributes / constraints
    4. - corpus: a collection of unstructured text
    5. outputs:
    6. - graph_store: entities and relations that conform to the schema
    7. - api: query, filter, and statistics interfaces
    8. - ui: graph browsing and interactive query
    9. acceptance:
    10. - schema validation pass rate meets the target
    11. - the end-to-end pipeline can be re-run with one command
    12. - tests for key query interfaces pass

    When acceptance criteria are defined up front, later self-evaluation has a stable anchor.

    4. Architecture Design: Layered Decoupling Is a Prerequisite for Reliable Automation

    Before any real coding, settling technology choices and layered design is what keeps a long-horizon task from drifting. A robust architecture usually has five layers:

    • Ontology layer: Responsible for schema definition, type constraints, and validity rules. It is the single source of truth for all downstream modules.
    • Extraction layer: Handles text preprocessing, candidate entity recognition, relation extraction, and entity alignment, producing an intermediate structure constrained by the schema.
    • Validation layer: Performs type checks, relation validity checks, deduplication, and conflict resolution, blocking results that “look plausible but are not valid”.
    • Storage layer: Models validated data as a graph structure, builds indexes and constraints, and guarantees query performance and consistency.
    • Service and presentation layer: Provides query APIs and visualization interaction, supporting filtering by type, neighborhood expansion, and path queries.

    The core value of layering is that every layer has clear inputs, outputs, and testable boundaries. During automated execution, the model can localize a problem instead of rewriting everything because one part failed.

    5. Task Breakdown: Eight Stages That Keep Long-Horizon Execution Controllable

    After the architecture is settled, splitting the work into independently verifiable stages is the second prerequisite for keeping automation under control. A practical eight-stage breakdown:

    1. Initialize the project structure and dependency management, and unify code conventions and directory layout.
    2. Define the ontology schema and constraint rules, producing a machine-verifiable schema file.
    3. Implement the text preprocessing and candidate entity extraction pipeline.
    4. Implement relation extraction and entity alignment, producing an intermediate representation.
    5. Implement the validation layer: type and relation validity, deduplication, and conflict handling.
    6. Implement graph storage writes and index/constraint creation.
    7. Implement the query API and an end-to-end integration script.
    8. Implement the visualization interface and interactive queries, then complete regression verification.

    Each stage needs a “definition of done”, such as unit tests passing, schema validation passing, or the end-to-end script being re-runnable. That is what allows the model to self-evaluate inside a stage instead of leaving problems to the end.

    6. Execution and Self-Correction: Make the Evaluation Signal Clear Enough

    Automated execution does not mean hands-off. It means designing the evaluation signal clearly enough for the model to act on. Practical points:

    • Tests first: Prepare a minimal runnable test for each layer so interface contracts stay stable.
    • Readable errors: Unify log and exception formats so a failure can be traced to a specific layer and a specific rule.
    • Small commits: Advance stage by stage, avoiding one oversized code block that makes rollback expensive.
    • Regression re-runs: After each fix, re-run the end-to-end script to confirm no new problems were introduced.
    • Constraints up front: Treat the schema and acceptance criteria as constant inputs to reduce room for improvisation.

    Illustrative validation pseudocode:

    1. def validate(triple, schema):
    2. if triple.relation not in schema.relations:
    3. return False, "relation_not_allowed"
    4. if not schema.relations[triple.relation].type_check(triple):
    5. return False, "type_mismatch"
    6. if schema.is_duplicate(triple):
    7. return False, "duplicate"
    8. return True, "ok"

    Once evaluation dimensions are reduced to decidable rules, self-correction turns from guessing into targeted repair.

    7. Ontology Modeling and Extraction Quality: The Factor That Sets the Ceiling

    No matter how high the automation level, ontology design still determines the system’s ceiling. Engineering recommendations:

    • Keep the schema small and stable: Cover core entities and relations first, then expand gradually, avoiding over-design at the start.
    • Make constraints explicit: Uniqueness, domain/range, and relation direction should all be written out so machines can validate them.
    • Define the entity alignment strategy: Synonym entities, aliases, and abbreviations need unified merging rules.
    • Separate extraction from validation: Extraction pursues recall, validation pursues precision; the two have different goals and should not be tuned together.
    • Keep traceable information: Retain the source snippet and confidence for each entity and relation to support manual spot checks and later iteration.

    An ontology is not a static document but a “living contract” that evolves with the data. Schema versioning and migration strategy should therefore be part of the design from day one.

    8. Visualization and Query: Making the Graph Usable, Not Just Storable

    The goal of the visualization layer is not to show off, but to lower the barrier to use. Three capabilities are worth implementing first:

    • Neighborhood browsing: Expand one-hop or multi-hop neighbors around a node, with filtering by type.
    • Path query: Given two entities, find the relation path between them for exploratory analysis.
    • Statistics views: Distribution statistics by entity type and relation type, helping reveal data gaps.

    For interaction, keep a three-part feedback flow of “query—highlight—details” so users do not get lost in a large graph. For performance, the frontend renders only the current viewport and expanded levels, while heavy queries are pushed down to backend interfaces.

    9. Production Perspective: From Demo to Operable System

    Real production use requires the engineering elements that demos usually skip:

    • Re-runnable: The data pipeline supports idempotent writes and failure retries.
    • Observable: Key stages expose metrics and logs, making it easier to locate extraction quality or query performance problems.
    • Configurable: The ontology schema, extraction parameters, and query limits are all externalized configuration.
    • Regression-safe: The end-to-end script is part of routine regression to prevent degradation across iterations.
    • Extensible: When adding entity or relation types, ideally only the schema and configuration change, not the core logic.

    10. Conclusion: After the Loop Is Internalized, Human Value Lies in Definition and Constraints

    This practice shows that the efficiency gain in delivering long-horizon complex tasks comes mainly from internalizing the “plan—generate—evaluate” loop: the model generates and self-evaluates within the same context, while the human focuses on defining the goal, setting constraints, and designing acceptance criteria. For engineering teams, what needs to be accumulated is not the usage of a particular tool but three things: the ability to design a clear ontology and schema, a decidable evaluation system, and the habit of layered decoupling. Get those three right, and no matter how AI coding tools evolve, complex tasks can be reliably turned into production-ready systems.