How the Tour-Builder Generates Guided Learning Tours in Understand-Anything
The tour-builder generates guided learning tours by either prompting an LLM with structured knowledge graph data or executing a deterministic heuristic algorithm that topologically sorts the codebase, ensuring a logical learning path even without external AI services.
The tour-builder in the Egonex-AI/Understand-Anything repository transforms static codebase analysis into interactive, step-by-step learning experiences. Located in understand-anything-plugin/packages/core/src/analyzer/tour-generator.ts, the system consumes a KnowledgeGraph and produces ordered TourStep arrays that guide newcomers through complex codebases. It operates through two distinct pipelines: an LLM-driven generation path for nuanced, context-aware tours, and a local heuristic fallback that guarantees functionality offline.
LLM-Driven Tour Generation
When available, the system prioritizes LLM-based generation to create contextually rich learning paths. This approach leverages the full semantic understanding of the knowledge graph to produce human-readable tour narratives.
Building the Generation Prompt
The buildTourGenerationPrompt(graph) function constructs a comprehensive text prompt that serializes the entire project structure. According to the source code in tour-generator.ts, the prompt includes four critical sections:
- Project metadata: Name, description, languages, and frameworks detected in the repository
- Graph nodes: Each node's type, name, file path, and summary formatted as
- [${type}] ${name} (${filePath}): ${summary} - Relationships: The first 50 edges showing dependencies as
- ${source} --${type}--> ${target} - Architectural layers: Optional grouping information describing high-level components
The prompt concludes with explicit instructions to return a JSON object containing an ordered steps array, ensuring machine-parseable output.
Parsing the LLM Response
The parseTourGenerationResponse(response) function handles robust extraction of the tour structure from raw LLM output. The implementation performs four validation steps:
- Strip markdown fences – Removes any surrounding
```json … ```formatting - Extract JSON object – Locates the outermost
{ … }structure and parses it - Validate step schema – Ensures each step contains
order(number),title,description, and a non-emptynodeIdsarray - Normalize data – Filters
nodeIdsto strings only and optionally preserveslanguageLessonfields
If validation fails at any stage, the function returns an empty array, triggering the heuristic fallback rather than crashing the pipeline.
Heuristic Tour Generation Without LLM
When LLM services are unavailable or return invalid data, generateHeuristicTour(graph) executes a deterministic algorithm using pure graph theory. This local-first approach guarantees tour generation regardless of network connectivity or API quotas.
Topological Sorting of Code Dependencies
The heuristic algorithm begins by separating concept nodes (type concept) from executable code nodes. For code nodes, it builds adjacency and in-degree maps, then applies Kahn's algorithm to produce a topological ordering that respects dependency relationships. This ensures learners encounter foundational modules before consuming code that depends on them.
Layer-Aware Step Grouping
The algorithm handles architectural complexity through intelligent grouping:
- Layered architectures: When the knowledge graph contains
layers, steps are grouped by layer in topological order, creating cohesive learning units aligned with the system's architecture - Unlayered nodes: Remaining nodes become a "Supporting Components" step
- Concept consolidation: All concept nodes are gathered into a final "Key Concepts" step
- Batching: In graphs without layers, every three consecutive nodes form a single tour step
End-to-End Implementation Flow
The following TypeScript implementation demonstrates the complete tour generation logic as implemented in the Understand-Anything codebase:
import {
buildTourGenerationPrompt,
parseTourGenerationResponse,
generateHeuristicTour,
} from "./tour-generator.js";
import type { KnowledgeGraph } from "./types.js";
async function createTour(graph: KnowledgeGraph) {
// Attempt LLM-driven generation first
const prompt = buildTourGenerationPrompt(graph);
const llmResponse = await callLLM(prompt);
const stepsFromLLM = parseTourGenerationResponse(llmResponse);
if (stepsFromLLM.length > 0) {
return stepsFromLLM;
}
// Fallback to deterministic heuristic generation
return generateHeuristicTour(graph);
}
This pipeline prioritizes AI-generated tours for richness but guarantees output through the topological heuristic method, ensuring the dashboard UI always receives a valid TourStep[] array.
Summary
- The tour-builder in
tour-generator.tssupports dual-mode generation: LLM-driven for nuanced tours and heuristic for offline reliability - LLM mode constructs detailed prompts from project metadata, nodes, edges, and layers, then parses JSON responses with strict validation
- Heuristic mode uses Kahn's algorithm to topologically sort code dependencies, grouping by architectural layers or batching every three nodes
- Concept nodes are always isolated into a dedicated "Key Concepts" step regardless of generation method
- The system gracefully degrades from LLM to heuristic generation when parsing fails or returns empty results
Frequently Asked Questions
What file contains the core tour generation logic?
The core implementation resides in understand-anything-plugin/packages/core/src/analyzer/tour-generator.ts. This file exports buildTourGenerationPrompt, parseTourGenerationResponse, and generateHeuristicTour, which handle the complete lifecycle from knowledge graph to ordered tour steps.
How does the tour-builder handle code dependencies?
The heuristic algorithm builds adjacency and in-degree maps from the knowledge graph's edges, then executes Kahn's topological sort algorithm. This produces a dependency-aware ordering where prerequisite modules appear before dependent code, ensuring logical progression through the learning path.
Can the tour-builder work without an LLM?
Yes. The generateHeuristicTour function operates entirely locally, analyzing graph topology to create valid tours without external API calls. This deterministic fallback activates automatically when LLM parsing fails or returns no valid steps, making the system resilient to network issues or rate limiting.
What determines how nodes are grouped into tour steps?
In LLM mode, the AI determines grouping based on semantic context. In heuristic mode, grouping follows architectural layers when present; otherwise, the algorithm batches every three consecutive nodes into a single step. Concept nodes are always separated into a final "Key Concepts" step regardless of the generation method.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →