# How the Tour-Builder Agent Generates Ordered Learning Tours Based on Dependency

> Discover how the tour-builder agent creates dependency-aware learning tours using LLMs or topological sort. Explore codebases logically with Egonex AI.

- Repository: [Egonex/Understand-Anything](https://github.com/Egonex-AI/Understand-Anything)
- Tags: deep-dive
- Published: 2026-06-12

---

**The Tour-Builder agent creates dependency-aware learning tours by either orchestrating an LLM to analyze the full knowledge graph or executing a deterministic topological sort that respects code dependencies, ensuring learners explore codebases in a logical sequence.**

The Egonex-AI/Understand-Anything project transforms complex repositories into navigable knowledge graphs. At the heart of this system, the **Tour-Builder agent** generates ordered learning tours based on dependency relationships, allowing developers to understand code in the correct sequence rather than jumping between unrelated files. The implementation resides primarily in [`understand-anything-plugin/packages/core/src/analyzer/tour-generator.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/understand-anything-plugin/packages/core/src/analyzer/tour-generator.ts).

## The Dual-Path Architecture

The agent follows a decision workflow defined in [`agents/tour-builder.md`](https://github.com/Egonex-AI/Understand-Anything/blob/main/agents/tour-builder.md). It first attempts LLM-based generation for intelligent narrative flow, then falls back to a deterministic heuristic if the model is unavailable or returns invalid data.

The orchestration logic follows this pattern:

1. If an LLM is configured and the prompt succeeds, parse the LLM response
2. If the parsed steps are empty or invalid, invoke the heuristic fallback
3. Otherwise, generate the tour entirely from the heuristic algorithm

## Stage 1: LLM-Based Tour Generation

When a language model is available, the agent constructs a detailed prompt that describes the entire knowledge graph structure.

### Building the Prompt

The `buildTourGenerationPrompt` function (line 7 in [`tour-generator.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/tour-generator.ts)) enumerates every node and edge in the graph:

- **Nodes** are listed as `- [type] name (path): summary`
- **Edges** are formatted as `- source --type--> target`

The prompt specifies the required JSON output shape, including ordered steps with titles, descriptions, node IDs, and optional language notes. This gives the LLM complete context to generate a pedagogically sound learning path.

### Parsing the Response

The `parseTourGenerationResponse` function (line 70) handles raw LLM output that may contain markdown code fences or explanatory text. It extracts the JSON block and validates each step against the `TourStep` schema:

- Numeric `order` field
- Non-empty `title` and `description`
- At least one `nodeIds` entry

If parsing fails, the function returns an empty array, triggering the heuristic fallback.

## Stage 2: Heuristic Fallback Algorithm

When LLM generation fails or is disabled, the `generateHeuristicTour` function (line 122) synthesizes a tour directly from graph topology using **Kahn's algorithm** for topological sorting.

### Dependency Mapping

The algorithm first separates **concept nodes** (type `concept`) from regular code nodes. It then builds adjacency and indegree maps for code nodes only, identifying entry points as nodes with zero incoming edges.

### Topological Sorting

The core logic performs a topological sort:

1. Initialize a queue with all entry points (nodes with no dependencies)
2. Process nodes in batches, removing edges and updating indegrees
3. Respect **layer boundaries** if the graph contains explicit layers, grouping nodes by layer while preserving dependency order
4. If no layers exist, batch three nodes per step for readability

### Concept Integration

After processing all code nodes, the algorithm appends a final "Key Concepts" step containing any separated concept nodes. Finally, it assigns sequential order numbers to every step.

## Implementation Examples

### Generating a Tour Using the Heuristic Algorithm

```typescript
import { generateHeuristicTour } from '@understand-anything/core/analyzer/tour-generator';
import type { KnowledgeGraph } from '@understand-anything/core/types';

// Assume `graph` is the KnowledgeGraph produced by the analysis pipeline
const tourSteps = generateHeuristicTour(graph);

// `tourSteps` is an array of TourStep objects ready for the UI
console.log(tourSteps);

```

### Using an LLM with Fallback to Heuristic

```typescript
import {
  buildTourGenerationPrompt,
  parseTourGenerationResponse,
  generateHeuristicTour,
} from '@understand-anything/core/analyzer/tour-generator';
import type { KnowledgeGraph, TourStep } from '@understand-anything/core/types';
import { callLLM } from '@understand-anything/core/llm';

async function getTour(graph: KnowledgeGraph): Promise<TourStep[]> {
  const prompt = buildTourGenerationPrompt(graph);
  const llmReply = await callLLM(prompt);

  const parsed = parseTourGenerationResponse(llmReply);
  return parsed.length ? parsed : generateHeuristicTour(graph);
}

```

### Rendering the Tour in a React Dashboard

```tsx
import { useTour } from '@/hooks/useTour';

function TourPanel() {
  const { steps } = useTour();
  return (
    <ul>
      {steps.map((s) => (
        <li key={s.order}>
          <strong>{s.title}</strong> – {s.description}
        </li>
      ))}
    </ul>
  );
}

```

## Summary

- **Dual-path generation**: The agent attempts LLM-based generation first, falling back to a deterministic topological sort if needed.
- **Prompt engineering**: `buildTourGenerationPrompt` creates structured LLM inputs describing the complete knowledge graph with nodes, edges, and layers.
- **Topological sorting**: `generateHeuristicTour` uses Kahn's algorithm on code nodes to respect dependency ordering, separating concept nodes for a final summary step.
- **Layer awareness**: The heuristic algorithm groups nodes by architectural layers when available, otherwise batching three nodes per step.
- **Validation**: `parseTourGenerationResponse` sanitizes LLM output and validates step structure before accepting the generated tour.

## Frequently Asked Questions

### What happens if the LLM returns malformed JSON?

The `parseTourGenerationResponse` function extracts JSON blocks from markdown-wrapped responses and validates the schema. If validation fails or the response is empty, the system immediately falls back to `generateHeuristicTour`, ensuring the tour generation never fails completely.

### How does the heuristic algorithm handle cyclic dependencies?

The topological sort in `generateHeuristicTour` uses Kahn's algorithm, which naturally handles cycles by only processing nodes whose indegree has reached zero. While the source analysis does not specify explicit cycle breaking, standard Kahn's implementation will process all reachable nodes; any remaining nodes in cycles would typically be handled by the graph construction phase ensuring acyclicity for valid dependency graphs.

### Can the tour-builder work without an LLM?

Yes. The `generateHeuristicTour` function operates entirely on the knowledge graph structure without external API calls. It separates concept nodes, performs topological sorting on code dependencies, and respects layer boundaries, producing a valid learning tour using only the repository's structural metadata.

### What is the difference between concept nodes and code nodes in the tour?

**Code nodes** represent actual source files, classes, or functions that participate in the dependency graph and are ordered by the topological sort. **Concept nodes** represent abstract architectural concepts or high-level explanations; they are excluded from the dependency ordering and appended as a final "Key Concepts" step to avoid interrupting the code flow while ensuring comprehensive coverage.