# How the Tour Builder Generates Guided Learning Paths in Understand-Anything

> Discover how the Tour Builder generates guided learning paths using LLM queries or topological sorting on code dependencies in Understand Anything.

- Repository: [Egonex/Understand-Anything](https://github.com/Egonex-AI/Understand-Anything)
- Tags: how-to-guide
- Published: 2026-06-10

---

**The Tour Builder generates guided learning paths by either querying an LLM with a structured prompt derived from the knowledge graph or by applying a deterministic heuristic algorithm that performs topological sorting on code dependencies.**

The Tour Builder in Egonex-AI/Understand-Anything creates step-by-step learning tours to onboard developers to unfamiliar codebases. It transforms the `KnowledgeGraph` produced by the core analysis engine into an ordered sequence of educational steps using two distinct generation strategies. The core logic resides in [`tour-generator.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/tour-generator.ts) within the core analyzer package.

## Dual-Mode Architecture: LLM and Heuristic Generation

The system operates in two mutually exclusive modes to accommodate different runtime environments:

- **LLM-driven generation**: Constructs a detailed natural language prompt from graph data, sends it to an external language model, and parses the JSON response into ordered steps.
- **Heuristic generation**: Runs entirely locally using graph topology and algorithms to produce a sensible ordering without external API calls.

Both modes consume the same `KnowledgeGraph` structure, ensuring consistency regardless of which path is taken.

## LLM-Driven Tour Generation

When an LLM is available, the system crafts a rich textual description of the codebase and requests a structured learning path in return.

### Building the Structured Prompt

The `buildTourGenerationPrompt(graph)` function assembles a comprehensive prompt containing four distinct sections:

- **Project metadata**: Name, description, languages, and frameworks (e.g., `Project: ${project.name}`)
- **Node inventory**: Each node's type, name, optional file path, and summary (formatted as `- [${n.type}] ${n.name} (${n.filePath}): ${n.summary}`)
- **Relationship mapping**: The first 50 edges showing source-to-target relationships (e.g., `- ${e.source} --${e.type}--> ${e.target}`)
- **Architectural layers**: Optional grouping information when layers exist (e.g., `- ${l.name}: ${l.description} (nodes: …)`)

The prompt concludes with explicit instructions to return a JSON object containing an ordered `steps` array, ensuring machine-readable output.

### Parsing and Validating LLM Responses

The `parseTourGenerationResponse(response)` function safely extracts tour data through a four-stage pipeline:

1. **Strip markdown fences**: Removes ` ```json … ``` ` wrappers if present.
2. **Extract JSON object**: Locates the outermost `{ … }` block and parses it.
3. **Validate step schema**: Ensures each step contains `order` (number), `title`, `description`, and a non-empty `nodeIds` array.
4. **Normalize fields**: Filters `nodeIds` to strings only and optionally preserves `languageLesson` properties.

If any stage fails, the function returns an empty array, triggering the heuristic fallback rather than crashing the pipeline.

## Heuristic Tour Generation Without External Models

When LLM services are unavailable or return invalid data, `generateHeuristicTour(graph)` creates a deterministic tour using pure graph analysis.

### Topological Sorting of Code Dependencies

The algorithm separates **concept nodes** (type = `concept`) from executable code nodes to prioritize implementation logic. For code nodes, it builds adjacency and in-degree maps, then applies **Kahn's algorithm** to produce a dependency-aware topological order. This ensures that foundational modules appear before components that depend on them.

### Layer-Aware Step Grouping

If the knowledge graph includes architectural layers, the heuristic groups nodes by their assigned layer while maintaining topological order within each group. Unlayered nodes are collected into a "Supporting Components" step. When no layers exist, the algorithm batches every three consecutive nodes into a single tour step to prevent cognitive overload.

### Handling Concept Nodes

After processing all code dependencies, the generator appends a final "Key Concepts" step containing any concept nodes separated at the start. This places architectural abstractions after concrete implementations, mirroring how developers typically prefer to learn new systems.

## End-to-End Generation Flow

The tour builder implements a graceful degradation pattern, attempting LLM generation before falling back to heuristics:

```typescript
import {
  buildTourGenerationPrompt,
  parseTourGenerationResponse,
  generateHeuristicTour,
} from "./tour-generator.js";
import type { KnowledgeGraph } from "./types.js";

async function createTour(graph: KnowledgeGraph) {
  // 1️⃣ Attempt LLM-driven generation
  const prompt = buildTourGenerationPrompt(graph);
  const llmResponse = await callLLM(prompt);
  const stepsFromLLM = parseTourGenerationResponse(llmResponse);
  
  if (stepsFromLLM.length > 0) return stepsFromLLM;

  // 2️⃣ Fallback to deterministic heuristic generation
  return generateHeuristicTour(graph);
}

```

This approach prioritizes the nuanced understanding of LLMs while guaranteeing functional output through the deterministic algorithm when external services fail or return invalid JSON.

## Key Implementation Files

The tour generation system spans three primary locations in the Egonex-AI/Understand-Anything repository:

- **[`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)**: Contains `buildTourGenerationPrompt`, `parseTourGenerationResponse`, and `generateHeuristicTour` implementations.
- **[`understand-anything-plugin/packages/core/src/__tests__/tour-generator.test.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/understand-anything-plugin/packages/core/src/__tests__/tour-generator.test.ts)**: Unit tests verifying prompt formatting, JSON parsing edge cases, and heuristic correctness.
- **[`understand-anything-plugin/agents/tour-builder.md`](https://github.com/Egonex-AI/Understand-Anything/blob/main/understand-anything-plugin/agents/tour-builder.md)**: Documentation describing the Tour Builder agent's integration with the analysis pipeline.

## Summary

- The Tour Builder supports **two generation modes**: LLM-driven for nuanced understanding and heuristic for offline/edge cases.
- **LLM mode** constructs a detailed prompt from graph metadata, nodes, edges, and layers, then validates the JSON response rigorously.
- **Heuristic mode** uses **Kahn's algorithm** for topological sorting of code dependencies, with special handling for architectural layers and concept nodes.
- The system implements **graceful degradation**, automatically falling back from LLM to heuristic generation when parsing fails.
- All logic resides in [`tour-generator.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/tour-generator.ts), operating exclusively on the `KnowledgeGraph` data structure.

## Frequently Asked Questions

### What data structure serves as the source of truth for tour generation?

The `KnowledgeGraph` object produced by the core analysis engine serves as the sole input for both LLM and heuristic generation modes. This structure contains project metadata, typed nodes, relationship edges, and optional architectural layers, ensuring both generation paths work from identical codebase representations.

### How does the heuristic algorithm handle circular dependencies in code?

The heuristic implementation uses Kahn's algorithm for topological sorting, which requires the graph to be a directed acyclic graph (DAG). In `generateHeuristicTour`, the algorithm builds in-degree maps and processes nodes with zero dependencies first. While circular dependencies would theoretically break pure topological sorting, the implementation likely handles them through the adjacency map construction or by treating them as unlayered nodes, though the exact cycle-breaking mechanism isn't specified in the source analysis.

### What happens if the LLM returns invalid JSON or markdown?

The `parseTourGenerationResponse` function implements multiple defensive checks: it strips markdown code fences, extracts the outermost JSON object, validates required fields (`order`, `title`, `description`, `nodeIds`), and normalizes array contents. If any validation step fails, the function returns an empty array rather than throwing an exception, which triggers the heuristic fallback in the main generation flow.

### Can the tour builder operate in environments without internet access?

Yes. The **heuristic generation mode** runs entirely locally using only the `KnowledgeGraph` topology. When `createTour` detects that `parseTourGenerationResponse` returns an empty array (either due to missing LLM configuration or invalid responses), it automatically invokes `generateHeuristicTour`, making the system suitable for air-gapped or privacy-sensitive environments.