Building an Ontology Knowledge Graph System via Long-Horizon Agent Closed Loops

    This article explores a reusable engineering method for long-horizon complex tasks using an ontology-driven knowledge graph extraction and visualization system as an example. By organizing agent workflows into a "Plan-Generate-Evaluate" closed loop and breaking the project into eight verifiable stages, the system can be delivered from requirements to a runnable state in a controlled practice. The article details the task definition, layered architecture, stage planning, in-model self-repair loop, and key engineering risk controls for production-level delivery.

    The challenge of long-horizon complex tasks is usually not “whether an agent can generate a piece of code,” but whether cross-stage states remain consistent: requirements understanding, architecture design, data modeling, API contracts, testing, and visualization. Any deviation can be amplified in later stages. Using an “ontology-driven knowledge graph extraction and visualization system” as an example, this article discusses a reusable engineering method: organizing long-horizon agent work through a “Plan-Generate-Evaluate” closed loop. In a controlled practice, an agent delivered a runnable system from requirements in about three hours. This article focuses on general technical paths and acceptance methods, not product rankings or tool comparisons.

    1. Task Definition: Why a Knowledge Graph System?

    Knowledge graph (KG) extraction and visualization is a typical long-horizon complex task involving at least five coupled capabilities:

    1. Understanding Ontology Definition: For example, establishing entity types, properties, and relationship constraints around “Work—Character—Organization.” The ontology is not a static table but the system’s semantic contract, determining what to extract, how to disambiguate, and how to validate relationship legality.
    2. Extracting Entities and Relations from Unstructured Text: Requires handling text splitting, entity recognition, relationship classification, confidence filtering, and conflict merging.
    3. Graph Database Modeling: Mapping entities, relationships, and properties to graph structures, designing indexes, constraints, and query paths.
    4. RDF (Resource Description Framework) Export: Providing standardized expressions for knowledge reuse and exchange while ensuring consistency between the graph model and the exported model.
    5. Frontend Visualization and Interactive Query: Allowing users to explore by entity type, relationship path, and keyword while maintaining usability with large-scale data.

    The value of this task lies in the fact that the ontology is not just a “storage schema” but a self-improving knowledge contract. It constrains extraction results, validates relationship legality, and evolves continuously with data feedback. If any stage fails, the system struggles to truly deliver. Therefore, it tests the agent’s planning, execution, and self-evaluation capabilities better than a simple frontend demo.

    2. Architecture Research and Layered Design

    Upon receiving the goal, a capable agent should not rush to write code but should first complete technical research and architectural convergence. A practical layered architecture includes:

    • Access Layer: Receives text, files, or batch tasks; manages task status and error retries.
    • Extraction Layer: Performs text preprocessing, entity recognition, relation extraction, confidence filtering, and result merging.
    • Ontology and Schema Layer: Maintains entity types, properties, relationship constraints, versioning, and evolution rules.
    • Storage Layer: A graph database for entity-relationship storage, with auxiliary storage for raw text, extraction evidence, and task logs.
    • Query Service Layer: Provides entity retrieval, relationship path querying, subgraph aggregation, and pagination.
    • Visualization Layer: Offers a graph canvas, filters, node details, path highlighting, and interactive exploration.
    • Evaluation Layer: Continuously verifies with unit tests, contract tests, end-to-end tests, and data quality metrics.

    The key to architectural design is placing the “ontology” at the center. Extraction layer outputs must conform to ontology constraints; the storage layer validates schemas before writing; the query layer exposes semantic queries based on the ontology; and the frontend generates filter dimensions based on the ontology. Thus, the system is not “extract then display,” but is threaded by the ontology across extraction, storage, querying, and visualization.

    3. 8-Stage Task Planning and Acceptance Criteria

    Breaking long-horizon tasks into verifiable stages is core to controlling context drift and rework costs. In one practice, the agent divided the task into eight stages:

    1. Backend Basics and Configuration: Establish the engineering skeleton, configuration management, logging, and error handling. Acceptance criteria: Service starts, health check passes, configurations can be switched.
    2. Schema Engine: Implement ontology definition loading, type validation, relationship constraints, and version management. Acceptance criteria: Illegal entities or relations are rejected, schema changes are traceable.
    3. Extraction API: Implement text input, extraction pipeline, confidence filtering, and structured output. Acceptance criteria: Fixed sample sets produce repeatable results, field contracts are stable.
    4. Ontology CRUD: Support adding, deleting, modifying, and querying entity types, properties, and relations. Acceptance criteria: Operations have permission boundaries and audit records.
    5. RDF Export: Map graph data to standard triple expressions. Acceptance criteria: Exported results can be read back for validation without losing entities or relations.
    6. Frontend Scaffold: Establish page routing, state management, request encapsulation, and error prompts. Acceptance criteria: Main flow works, exception states are visible.
    7. Graph Visualization: Implement node rendering, relation expansion, filtering, path highlighting, and detail panel. Acceptance criteria: Small-to-medium graphs are interactive, large graphs have a tiered loading strategy.
    8. Integration Testing: Connect extraction, storage, querying, visualization, and export. Acceptance criteria: End-to-end test cases pass, key metrics have baselines.

    Each stage should produce “verifiable deliverables”: API contracts, test cases, sample data, screenshots, or run logs. Stage acceptance is not formalism but provides a clear completion signal for the agent in long contexts, avoiding the “looks finished but cannot run” scenario.

    4. In-Model Closed Loop: Code, Test, Self-Repair

    Compared to traditional external orchestration, highly capable long-horizon agents can fulfill the “generator + evaluator” responsibilities within the same task context: generate the implementation, run tests or static checks, read failure information, locate the problem, and fix it. The pseudocode can be abstracted as:

    1. goal = "Build an ontology-driven knowledge graph extraction and visualization system"
    2. ontology = load_ontology_schema()
    3. plan = planner(goal, ontology, constraints)
    4. for stage in plan.stages:
    5. artifact = generator(stage, context, ontology)
    6. verdict = evaluator(artifact, stage.acceptance_tests)
    7. while not verdict.passed:
    8. context.update(verdict.feedback)
    9. artifact = repair(artifact, verdict.feedback)
    10. verdict = evaluator(artifact, stage.acceptance_tests)
    11. context.commit(stage, artifact, verdict.evidence)
    12. final_system = integrate(plan.artifacts)
    13. run_end_to_end_tests(final_system)

    This internal loop significantly reduces manual back-and-forth communication, but it does not mean external engineering scaffolding can be entirely removed. Production environments still require continuous integration, code review, access control, observability, data governance, and release rollbacks. More accurately: as model capabilities improve, some “evaluation and repair” can be internalized; however, engineering controls involving security, compliance, stability, and multi-person collaboration should remain external.

    5. Key Engineering Details and Risk Control

    Context Management: Long-horizon tasks are prone to context bloat. Stage artifacts should be consolidated into structured summaries, such as API contracts, test results, and unresolved issues, rather than repeatedly carrying the full code.

    Test-First: The extraction layer needs fixed sample sets and field contract tests; the graph database layer needs constraint validation; the frontend needs end-to-end main flow tests. The automatic evaluator should not only check “whether there are errors” but also inspect data quality metrics, such as entity hit rate, relationship validity rate, duplication rate, and manual spot-check results.

    Data Quality: Entity disambiguation, relationship conflicts, and confidence thresholds need to be configurable. Low-confidence results should enter a pending review queue rather than directly polluting the graph.

    Visualization Performance: Large graphs should not be fully rendered at once; tiered loading, neighborhood expansion, node aggregation, and query drill-down should be used. Frontend acceptance must cover empty graphs, oversized nodes, circular relationships, and anomalous data.

    Security and Governance: Ontology changes, bulk imports, and export operations should have permission boundaries and audit logs. When deployed externally, general container platforms, object storage, logging, and monitoring/alerting capabilities can be used, but interfaces and permissions must be designed according to the actual environment.

    6. Conclusion

    This practice demonstrates that the value of long-horizon agents is not just “generating code faster,” but organizing planning, implementation, testing, and repair into a convergent closed loop. For ontology-driven knowledge graph systems, the correct approach is not to have the agent write all modules at once, but to divide stages around the ontology, define acceptance criteria, accumulate evidence, and let evaluation results drive the next round of repair. The in-model closed loop can reduce repetitive communication, but production-level delivery still requires external engineering controls. Combining both is the key to the stable landing of long-horizon complex tasks.