Building LLM Agents: State Orchestration and Graph-Based Retrieval
A practical guide to building reliable LLM agent systems with task graphs, shared state, and graph-based knowledge retrieval. Learn how to define task boundaries, build traceable knowledge indexes, coordinate local and global retrieval, constrain multi-agent workflows, and validate system quality through a staged implementation process.
1. An End-to-End Implementation Path
Building an LLM agent system involves more than connecting model calls, vector retrieval, and database queries. A deployable system must also address how tasks progress, how knowledge is organized, how results are verified, and how failures are recovered.
A complete implementation follows three complementary tracks:
- Execution: Organize nodes, edges, and shared state into a task graph so that complex tasks run according to explicit rules.
- Knowledge: Extract text chunks, entities, and relationships from source documents, then build community summaries and retrieval indexes to provide the model with traceable context.
- Engineering: Establish safeguards for data versioning, execution logs, access control, quality evaluation, and failure recovery.
Together, these tracks form an end-to-end workflow: a user asks a question, the system determines what retrieval is needed, selects appropriate data-access methods, combines evidence, generates an answer, and checks whether the evidence supports it.
2. Define Business Boundaries Before Designing Agents
At the start of a project, the most important decision is not how many agents to use. It is defining what the system should accomplish—and what it should not do automatically.
For an enterprise knowledge question-answering system, clarify at least the following:
- Is the input a natural-language question, or a composite request containing attachments, conversation history, and business identifiers?
- Should the output be a short explanation, a structured analysis, or an action recommendation requiring approval?
- Which documents provide the data, and do access permissions differ across departments?
- Is external information allowed? Is real-time data required?
- When should the system stop answering, request clarification, or hand the task over to a person?
For tasks that only require consulting a single document, a fixed workflow is often easier to validate than multi-agent collaboration. Multiple roles become worthwhile when a task has independent subgoals, different tool permissions, or a genuine need for cross-checking.
Agent count is not a measure of system maturity. Clear task boundaries, complete evidence, and controlled behavior are.
3. Designing the Task Graph: Nodes, Edges, and Shared State
3.1 Give Each Node a Clear Responsibility
Task-graph nodes can handle question parsing, document retrieval, relationship expansion, answer generation, or result review. Each node needs explicit input requirements, a defined output structure, and a failure-handling strategy.
For example, a retrieval node should return more than concatenated text. Its output should include document identifiers, chunk identifiers, ranking information, and access-control labels. Downstream nodes can then determine whether the evidence is relevant, permitted, and suitable for citation.
Favor a single responsibility per node. Combining retrieval, reasoning, database writes, and output formatting in one node makes fault diagnosis and unit testing more difficult.
3.2 Use Edges to Express Execution Rules
Sequential edges suit deterministic steps, such as “parse question → retrieve evidence → generate answer.” Conditional edges handle branches, such as expanding a search when evidence is insufficient or requesting clarification when a question is ambiguous.
Loop edges can support a limited number of additional retrieval attempts or answer revisions, but they must have termination conditions. These may include:
- Evidence coverage meeting the required threshold.
- Consecutive iterations producing no new information.
- Exhaustion of the call budget.
- Reaching the maximum number of attempts.
Do not leave the decision to continue or stop entirely to the model. Otherwise, the system may enter an unproductive loop.
3.3 Treat Shared State as the Execution Record
Shared state should contain what the workflow actually needs, rather than every intermediate output. Separate it into categories such as:
- Request data: User question, request identifier, and authorization scope.
- Task data: Current stage, subtasks, and remaining budget.
- Evidence data: Retrieved chunks, entities, relationships, and sources.
- Result data: Candidate answer, review feedback, and final output.
- Execution data: Error types, retry counts, and timing records.
The following illustrates a possible structure. Its implementation depends on the development environment:
execution_state = {request: {question: "...",authorization_scope: ["..."]},task: {current_stage: "retrieval",remaining_attempts: 2},evidence: [],candidate_answer: "",review_result: {passed: false,reasons: []},error_records: []}
These fields are illustrative design choices, not an interface definition for any particular framework.
3.4 Define State-Merging Rules Explicitly
State updates are relatively straightforward during sequential execution. With parallel execution, multiple nodes may write to the same field simultaneously.
Define a separate merge rule for each field:
- Append evidence while deduplicating by stable identifiers.
- Preserve the occurrence order of error records.
- Let scheduling logic control task-stage updates.
- Allow only a designated node to submit the final answer.
Nodes that modify external data also need idempotency safeguards. Retrying a request after a timeout must not create duplicate records or repeatedly trigger the same business operation.
4. Building Knowledge Indexes: From Documents to Searchable Relationships
4.1 Preserve Sources and Versions During Document Loading
Document loading should retain not only the body text but also titles, sections, update times, source identifiers, and access permissions.
When multiple versions of a document exist, explicitly identify which version belongs in the current index. Otherwise, a highly relevant retrieval result may still cite an obsolete policy or procedure.
Record documents whose text extraction fails, whose content is empty, or whose format is invalid, and place them in a queue for follow-up processing rather than silently skipping them.
4.2 Balance Semantic Boundaries Against the Context Budget
Chunks that are too small can lose conditions, exceptions, and references between passages. Chunks that are too large can reduce retrieval precision and consume excessive model context.
A more robust approach is to split first by sections, paragraphs, and semantic boundaries, then apply length limits where necessary. Moderate overlap between consecutive passages can reduce information loss at chunk boundaries, but it also increases index size and duplicate evidence.
Every text unit should retain its document identifier and source location so that answers can be traced back to the original text.
4.3 Apply Consistent Constraints to Entity and Relationship Extraction
Entities may represent people, organizations, policies, business objects, or technical concepts. Relationships represent evidence-backed connections between those entities.
Before extraction, define the allowed entity types and relationship directions. For example, “a process depends on a policy” and “a policy constrains a process” may express related facts. Without consistent rules, however, they can produce a mixed structure that is difficult to query.
After extraction, resolve aliases, duplicate entities, and identical names with different meanings. Do not merge entities solely because their names match; consider their types, context, and business identifiers.
Ideally, every relationship should link to supporting source text. Model-inferred relationships must remain distinguishable from relationships explicitly stated in documents.
4.4 Treat Summaries and Community Reports as Derived Information
As the number of entities and relationships grows, connectivity patterns in the graph can be used to form communities and generate thematic reports for them.
Community reports help summarize related knowledge, but they are derived content. They should not replace source documents as the sole factual basis for an answer. Each report should record the entities, relationships, and evidence it covers, along with the index version.
Communities may also overlap. An entity can participate in several business themes, so community boundaries should not be treated as business boundaries.
4.5 Combine Vector and Graph Indexes Where They Add Value
Vector indexes are useful for finding semantically similar text. Graph indexes are useful for expanding context along explicit relationships. The two can complement each other, but not every data field needs a vector representation.
Start by indexing text chunks, entity descriptions, or thematic summaries, then use evaluation results to decide whether to expand coverage. Indiscriminate indexing increases storage, update, and troubleshooting costs without necessarily improving answer quality.
5. Loading Graph Data: Structural Integrity and Controlled Updates
A practical import sequence is to load foundational objects first and establish dependent relationships afterward:
- Import documents and text units.
- Import entities.
- Create entity relationships and evidence links.
- Write community information and reports.
Typical data objects include:
- Documents: Sources, versions, and permissions.
- Text units: Content and original source locations.
- Entities: Types, canonical names, and descriptions.
- Relationships: Directions, categories, and evidence links.
- Communities: Membership and hierarchy information.
- Community reports: Thematic summaries and generation versions.
During ingestion, check that both endpoints of each relationship exist, source identifiers are valid, and duplicate objects can be merged consistently. When a batch import fails, the system must be able to identify and retry the failed batch instead of reimporting all data.
The query layer should also limit relationship-expansion depth, candidate counts, and returned fields. Unbounded graph traversal can produce large volumes of weakly relevant results, filling the answer context with noise.
6. Coordinating Local and Global Retrieval
6.1 Use Local Retrieval for Specific Objects
When a user asks which processes a policy applies to, or which stages a business object depends on, the system can first locate the target entity. It can then expand along relevant relationships and supplement the results with source passages.
The goal is not to traverse as deeply as possible. It is to find the shortest effective evidence chain that supports the question. Excessive expansion introduces weakly related information into the answer.
6.2 Use Global Retrieval for Cross-Topic Synthesis
Questions about overall trends, major risks, or common patterns across themes may require broader coverage than a few semantically similar chunks can provide.
For these questions, first select relevant community reports, produce evidence-constrained analyses for each, and then synthesize an overall conclusion. Preserve disagreements during synthesis rather than smoothing away differences in conditions across documents.
Global retrieval does not mean sending every summary to the model. Scope still needs to be limited, report freshness checked, and key conclusions verified against original evidence.
6.3 Evaluate Retrieval Routing Rather Than Relying on Intuition
A system can route questions to local, global, or hybrid workflows based on their characteristics, but automatic routing can itself be wrong.
Build a test set covering entity queries, relationship queries, cross-document summaries, and questions with no available answer. Compare workflows on evidence coverage, answer quality, and cost.
For low-confidence routing decisions, use a more conservative hybrid retrieval strategy or ask the user to clarify the scope.
7. Multi-Agent Collaboration Requires Constraints, Not Just Roles
Different agents can handle task decomposition, text retrieval, relationship retrieval, synthesis, and evidence review. All roles, however, should work toward the same task objective and evidence standard.
Handoffs should be structured and include at least:
- Conclusions.
- Evidence identifiers.
- Unresolved questions.
- Recommended next steps.
Passing only long, free-form text makes it easier for downstream agents to mistake speculation for fact.
Parallel retrieval suits independent subtasks. Tasks that depend on earlier conclusions should run sequentially. A reviewer that reads only the final answer, without examining its sources, will struggle to detect factual errors effectively.
Restrict tool permissions by role. An agent that reads a knowledge base generally does not need permission to modify business data. External writes or irreversible actions require explicit authorization and, where necessary, human confirmation.
8. Establish Repeatable Validation and Deployment Practices
Validation should cover three layers.
Data Layer
Check loading completeness, source traceability, entity-merge quality, and the validity of relationship evidence.
Retrieval Layer
Check whether relevant evidence is retrieved, permission filters work, outdated content is excluded, and local and global workflows cover the intended questions.
Answer Layer
Check whether evidence supports the conclusions, citations are accurate, qualifying conditions are preserved, and insufficient information is clearly acknowledged.
Beyond answer quality, track end-to-end latency, failure rates by node, model-call volume, and index-update costs. Do not judge the system by a single demonstration. Compare results continuously using a fixed test set and the same data version.
After deployment, retain request identifiers, node traces, retrieved-object identifiers, and index versions while minimizing sensitive source text in logs.
Treat instructions found inside documents as data to analyze. They must not be allowed to change system permissions or execution rules.
9. A Recommended Minimum Implementation Sequence
Stage 1: Establish a Source-Backed Retrieval Workflow
Build a single workflow for document loading, text retrieval, and answers with source references. Validate the underlying data and evaluation method.
Stage 2: Make Execution Controllable
Add shared state, conditional branches, bounded retries, and a review node.
Stage 3: Validate the Value of Graph Retrieval
Introduce entity and relationship extraction, graph ingestion, and local relationship retrieval. Verify that the graph genuinely fills gaps in text retrieval.
Stage 4: Add Broader Synthesis When Needed
When cross-document synthesis requirements are clear, add community reports and global retrieval. Introduce multi-agent collaboration only where it is necessary.
The principle is to demonstrate the value of each capability incrementally. Reliable LLM agent systems are not defined by the number of components they contain, but by clear inputs, interpretable outputs, traceable evidence, and verifiable quality boundaries at every step.
