Long-程 AI Agents for End-to-End Ontology-Based Knowledge Graph Construction
This article explains how long-horizon AI agents can drive an entire ontology-based knowledge graph pipeline, from ontology design and extraction to graph storage, visualization, and evaluation. It covers why long-horizon tasks are the real dividing line for coding agents, how a plan-generate-evaluate loop converges, and the practical engineering choices at each stage: layered ontology definition, a minimal traceable extraction pipeline, graph modeling principles, cognitive-load-aware visualization, and an objective evaluation system. It also outlines observability and governance requirements for production, showing that real deployment depends less on the model itself and more on a rigorous ontology, quantifiable evaluation, and complete governance.
1. Background: Why Long-Horizon Tasks Are the Real Dividing Line
Most AI coding scenarios stay in short-horizon interactions, such as writing a function or patching a script. The work fits inside a context window, and mistakes are easy to roll back. Real engineering, however, is a long chain: requirement clarification, data exploration, model design, code generation, test execution, error localization, and rework, where a wrong judgment at any step gets amplified downstream. The value of a long-horizon agent lies in maintaining goal consistency within a single context and automatically advancing the “write-run-observe-fix” loop to convergence.
This article uses an “ontology-based knowledge graph extraction and visualization system” as the carrier for a long-horizon task. It spans natural language processing, graph database modeling, backend services, and frontend visualization, making it a typical cross-stack project and a good test of whether an agent runtime framework is genuinely usable.
2. Method Overview: How the Plan-Generate-Evaluate Loop Runs Automatically
Common agent runtime frameworks in the industry (Harness-style designs) usually write the loop explicitly in code: a planner produces a task tree, a generator produces code, and an evaluator runs tests and feeds failure information back. The difference with a long-horizon agent is that it plays both the generator and the evaluator roles itself, self-driving without external orchestration.
A simplified pseudocode can express the semantics of this loop (illustrative, not a specific product interface):
goal = "Build an ontology-driven knowledge graph extraction and visualization system"state = {"plan": [], "artifacts": {}, "metrics": {}}while not done(state):plan = agent.plan(goal, state) # Plan: decompose into verifiable subgoalspatch = agent.generate(plan, state) # Generate: write code/config/queriesresult = agent.evaluate(patch) # Evaluate: run tests, sample-check, inspect metricsstate = agent.reflect(state, result) # Reflect: locate root cause, update plan
Whether the loop converges depends on three things: whether subgoals are verifiable, whether evaluation signals are objective, and whether context is effectively compressed. The following sections expand on each.
3. Step 1: Ontology Design Sets the Ceiling
The quality ceiling of a knowledge graph system is determined by the ontology, not by the extraction model. The ontology defines what types exist in the world, what relations are allowed between types, and what constraints properties are subject to. In practice, it is recommended to proceed in three layers:
- Domain skeleton layer: define core entity types (such as person, organization, event, product, metric) and core relations (such as affiliation, participation, dependency, causality).
- Constraint layer: add domain and range for relations, cardinality constraints, temporal attributes (effective time, expiry time), and mutual-exclusion rules.
- Extension layer: reserve aliases, multi-source identifiers, confidence, and source references to leave room for later fusion and provenance.
Once the ontology is stable, it should be solidified into a machine-readable configuration file, letting code generate validation logic from the ontology rather than scattering type definitions as hardcoded values across the codebase. The benefit is that when the ontology evolves, the system has a predictable refactoring path.
4. Step 2: The Minimal Viable Form of the Extraction Pipeline
The goal of extraction is not to “extract more” but to “extract accurately and traceably.” A robust minimal pipeline includes:
- Text preprocessing and segmentation: preserve paragraph and sentence boundaries, record character offsets for tracing back to the source text.
- Candidate generation: combine rule templates with model extraction to output candidate sets of entities and relations, with confidence attached.
- Normalization and disambiguation: alias merging, splitting of same-name-different-referent cases, and alignment of cross-source identifiers; this step usually determines the final usability of the graph.
- Conflict resolution: when the same triple conflicts across sources, arbitrate by weighting source credibility, time freshness, and evidence strength.
- Persistence: when writing to the graph store, save source, timestamp, and confidence at the same time, ensuring every edge is explainable.
An illustrative extraction result structure:
{"subject": {"name": "Sample Entity A", "type": "Organization", "aliases": ["Company A"]},"predicate": "supplies","object": {"name": "Sample Entity B", "type": "Product"},"confidence": 0.82,"evidence": {"doc_id": "d-1024", "span": [120, 168]},"valid_from": "2025-01-01"}
5. Step 3: Graph Modeling and Storage Selection
Graph storage selection should follow the query shape: if the core operations are multi-hop neighborhood expansion and path retrieval, a native graph database is more natural; if point lookups and aggregations dominate, a relational store with adjacency tables can also do the job. Regardless of the choice, modeling should adhere to three principles:
- Edges are first-class citizens: relationship properties (time, source, confidence) must be queryable, not stuffed into a JSON field.
- Design indexes for multi-hop queries: build composite indexes by type, time window, and source to avoid full-graph scans during deep traversals.
- Separate writes from reads: batch imports go through an offline channel, and online services are read-only, reducing long transactions and lock contention.
6. Step 4: Visualization Is Not Drawing, It Is “Explorable Abstraction”
The first principle of visualization is controlling cognitive load. Once there are too many nodes, force-directed layout degrades into a hairball. Practical approaches include:
- Semantic zoom: aggregate by degree and community membership, supporting drill-down from “community-type-instance.”
- Neighborhood first: by default render only the k-hop neighborhood of the target node, expanding the rest on demand.
- Attribute panel linked with evidence: clicking an edge shows the source document fragment and confidence, making conclusions verifiable.
- Interaction performance budget: set an upper limit on the number of nodes rendered by the frontend, auto-aggregating beyond the limit to avoid blocking the main thread.
7. Step 5: The Evaluation System Is Key to Long-Horizon Convergence
Without objective evaluation, an agent’s “self-modification” degrades into a random walk. It is recommended to establish at least four types of signals:
- Extraction quality: entity-level and relation-level precision and recall, combined with manual sampling review.
- Graph structure: connected component distribution, isolated node ratio, and average degree anomalies.
- Query performance: latency percentiles for multi-hop queries, not averages.
- End-to-end usability: the first-pass success rate from raw text to visualization conclusion.
An illustrative evaluation configuration:
metrics:extraction: {precision_target: 0.85, recall_target: 0.70}graph: {isolated_node_ratio_max: 0.05}latency: {p95_ms: 800}sampling: {manual_review_per_run: 30}
8. Production Perspective: Observability and Governance Checklist
To truly reach production, a functional loop is not enough; governance capabilities must be added: full-chain logging and tracing, failure sample reflow, versioned ontology and prompt templates, canary release and rollback strategies, and access control and auditing. If running on the general cloud infrastructure of Baidu AI Cloud, you can correspondingly use object storage to hold raw corpora, a message queue to decouple extraction tasks, a container platform to host services, and logging and monitoring/alerting services to ensure observability, forming a dual-channel architecture of “offline batch processing + online query.”
9. Lessons Learned
Long-horizon agents internalize the “explicitly orchestrated loop” into their own reasoning and execution capabilities. The engineering benefits show in three places: iteration cycles compress from person-orchestrated days to hours; evaluation signals become objective, making the direction of modification clear; and continuous context compression keeps long-chain tasks from losing the goal. The real key to deployment is not the model itself, but whether the ontology is rigorous, whether evaluation is quantifiable, and whether governance is complete. Doing these three things solidly is what allows a long-horizon agent to move from demonstration to production.
