Building a Long-Context LLM Knowledge Graph Extraction and Visualization System with an Internal Plan-Generate-Evaluate Loop

    This article walks through a production-oriented practice of using a long-context code model to build an ontology-driven knowledge graph extraction and visualization system within a single long session. It covers task definition, layered architecture design, an internal plan-generate-evaluate loop, key implementation details such as the ontology schema engine, extraction alignment, graph database modeling, and integration testing, plus lessons on keeping engineering guardrails in place when model capabilities improve.

    Building a Long-Context LLM Knowledge Graph Extraction and Visualization System with an Internal Plan-Generate-Evaluate Loop

    Why Long-Horizon Tasks Need a “Closed-Loop Engineering” Approach

    The hard part of long-running application development is rarely single-point code generation. The real challenges are long task chains, heavy dependencies, and complex acceptance criteria. Take an “ontology-driven knowledge graph extraction and visualization system” as an example: it spans natural language processing, ontology modeling, graph database storage, backend APIs, frontend interaction, and integration testing. A deviation in any one of these areas can leave the final system non-functional.

    One approach gaining traction in the industry is to break long-horizon tasks into a “plan–generate–evaluate” loop: the planning stage decomposes tasks and defines acceptance criteria, the generation stage produces code or configuration, and the evaluation stage runs tests and feeds issues back. Traditionally, this requires engineering teams to explicitly write a large amount of scaffolding to hard-code the loop into a process. A code model with long-horizon capabilities, however, can run the internal loop of “write code, run tests, read feedback, fix issues” within the same context, significantly reducing external scaffolding complexity.

    That said, stronger model capabilities do not mean engineering constraints can be dropped. The key to production readiness is combining clear goals, executable acceptance criteria, context management, and human review. This article documents a production-oriented practice: completing an automatically runnable system from data extraction to graph visualization within a multi-hour, multi-hundred-thousand-token long session, along with a retrospective of reusable methods.

    Task Definition: Choosing a Topic That “Cannot Afford to Fail”

    This task was not a frontend demo but a complete engineering effort. The goals can be summarized as:

    1. Understand ontology definitions, such as schema constraints like “Movie–Director–Actor”;
    2. Extract entities and relationships from unstructured text;
    3. Write extraction results into a graph database;
    4. Provide a visualization interface supporting interactive queries;
    5. Run the entire pipeline automatically, with basic testing and acceptance.

    The value of an ontology is that it gives a knowledge graph the ability to self-improve: it not only stores data but also understands, validates, and continuously evolves according to schema constraints. The core of the task, therefore, is not “extracting a few entities” but keeping extraction results consistent with the ontology schema and producing a queryable, displayable, and verifiable structure in the graph database.

    The initial requirements can be very concise, but they must include the goal, boundaries, and acceptance criteria. For example:

    1. Goal: Build an ontology-driven knowledge graph extraction and visualization system.
    2. Input: Unstructured text and an ontology schema definition.
    3. Output: Entity-relationship data in a graph database, plus an interactive visualization interface.
    4. Constraints: Extraction results must pass schema validation; the system must provide automated integration tests.
    5. Acceptance: Given sample text, after an end-to-end run, entities and relationships conforming to the ontology must be queryable in the interface.

    A one-line requirement can kick off a long-horizon task, but acceptance criteria must be executable—otherwise the model can only “appear to be done.”

    Architecture Design: Research First, Then Plan, Then Generate

    After receiving the requirements, the model did not immediately start stacking code. Instead, it first conducted a technology stack review and architecture design. This is a critical step in long-horizon tasks: defining boundaries and data flows before implementation significantly reduces rework later.

    The overall architecture can be abstracted into five layers:

    • Input layer: receives unstructured text and ontology schema files;
    • Extraction layer: performs entity recognition, relation extraction, and schema alignment;
    • Storage layer: writes entities, relationships, and properties into a graph database;
    • Service layer: provides ontology CRUD, extraction APIs, RDF export, and related capabilities;
    • Presentation layer: provides graph visualization and an interactive query interface.

    With the architecture confirmed, the model produced an eight-stage task plan:

    1. Backend foundation;
    2. Schema engine;
    3. Extraction API;
    4. Ontology CRUD;
    5. RDF export;
    6. Frontend scaffolding;
    7. Graph visualization;
    8. Integration testing.

    The value of this plan is that it breaks a “big system” into small, verifiable stages. Each stage should have its own inputs, outputs, and checkpoints. For example, the schema engine stage must be able to load an ontology and reject invalid relationships; the extraction API stage must return structured results for sample text; the integration testing stage must launch the full pipeline and verify query results.

    The Internal Loop: How the Model Finds and Fixes Its Own Problems

    The biggest difference between this practice and an explicit engineering loop is that the model played both the generator and evaluator roles within the same context. Its operating logic can be abstracted as:

    1. while not accepted:
    2. plan = analyze(goal, context, acceptance)
    3. patch = generate(plan)
    4. result = run_tests_and_checks(patch)
    5. if result.passed and meets_acceptance(result):
    6. accepted = true
    7. else:
    8. context = context + result.feedback

    The key here is not “letting the model declare itself done,” but making evaluation results come from executable checks. Common checks include:

    • Whether the ontology schema loads successfully;
    • Whether invalid relationships are rejected;
    • Whether extraction result fields are complete;
    • Whether data written to the graph database can be queried by entity relationships;
    • Whether frontend APIs return the correct structure;
    • Whether integration tests pass end to end.

    When tests fail, feedback should be as structured as possible—for example, “a stage output is missing relation types,” “query results are empty,” or “schema validation was not triggered.” Structured feedback reduces blind modifications by the model and improves loop convergence efficiency.

    Key Implementation Details and Acceptance Points

    1. Ontology Schema Engine

    The schema engine defines entity types, relation types, property constraints, and cardinality constraints. During implementation, the ontology should be treated as a first-class configuration rather than hard-coded rules scattered throughout the code. Acceptance points: valid samples pass, invalid samples are explicitly rejected, and readable error messages are returned.

    2. Extraction and Schema Alignment

    The extraction layer must not only recognize entities but also map results onto the ontology. A three-stage “extract–normalize–validate” approach is recommended: first produce candidate entities and relationships, then normalize types against the ontology, and finally perform schema validation. This keeps the inherent uncertainty of model-based extraction within a controllable range.

    3. Graph Database Modeling

    Graph database modeling should be designed around query scenarios. Entities become nodes, relationships become edges, and properties are stored redundantly depending on query frequency. Acceptance cannot stop at “write succeeded”—typical query paths must be verified, such as “movies and actors associated with a given director.” If deployed on a general-purpose cloud environment such as Baidu AI Cloud, object storage, container platforms, logging services, and monitoring/alerting can be mapped as general infrastructure categories, but the core remains data model and query correctness.

    4. Visualization and Interaction

    The frontend visualization should at minimum support graph rendering, node expansion, relationship filtering, and keyword search. Acceptance focuses on stable API contracts, helpful messages for empty results, and traceable errors. Visualization is not a decorative layer—it is an observation window for verifying whether the graph structure is reasonable.

    5. Integration Testing

    Integration tests should cover the full pipeline: “text input—extraction—storage—query—display.” Test data should include normal samples, boundary samples, and invalid schema samples. Only when end-to-end tests pass can the system be considered ready for production.

    Lessons Learned: Model Loops Cannot Replace Engineering Baselines

    This practice shows that long-context models can indeed internalize work that previously required extensive scaffolding into a session-level loop, dramatically accelerating the path from requirements to a runnable system. But for stable production deployment, several baselines still apply:

    1. Clear goals: a one-line requirement can start the task, but acceptance criteria must be explicit;
    2. Verifiable stages: every stage needs executable checkpoints;
    3. Structured feedback: the more specific the test failure information, the faster the loop converges;
    4. Controlled context: long sessions should periodically consolidate architecture decisions and API contracts;
    5. Human review is essential: schema design, data security, permissions, and deployment strategy still require engineering team oversight.

    Overall, the “plan–generate–evaluate” loop is an effective engineering pattern for long-horizon tasks. The stronger the model, the thinner the external scaffolding can be—but engineering constraints, acceptance criteria, and risk control do not disappear. They simply shift from “writing processes” to “defining goals, setting standards, and conducting reviews.” That may be the new capability teams most need to build as long-context models enter production environments.