# How Guided Tours Are Generated for Codebase Learning in Understand-Anything

> Discover how Understand Anything generates guided tours for code learning. It uses LLMs and topological sorting for a seamless codebase exploration experience.

- Repository: [Yuxiang Lin/Understand-Anything](https://github.com/Lum1104/Understand-Anything)
- Tags: how-to-guide
- Published: 2026-06-02

---

**Guided tours in Understand-Anything are generated through a dual-path pipeline that first attempts LLM-based generation from knowledge graph context, automatically falling back to a deterministic heuristic algorithm using topological sorting when the LLM is unavailable.**

The Understand-Anything project (`Lum1104/Understand-Anything`) provides an interactive "learn-mode" feature that transforms static code analysis into step-by-step educational walkthroughs. These guided tours help newcomers navigate complex codebases by highlighting relevant nodes and explaining architectural concepts in a logical sequence. The generation system lives entirely within the core analyzer package and combines large language model capabilities with graph theory algorithms to create coherent learning paths.

## The Three-Stage Tour Generation Pipeline

The tour generation process follows a strict pipeline implemented in [`tour-generator.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/tour-generator.ts), moving from raw knowledge graph data to UI-ready tour steps.

### Stage 1: Prompt Construction with Knowledge Graph Context

The process begins with `buildTourGenerationPrompt`, which constructs a plain-text LLM prompt from the project's **knowledge graph**. This prompt includes project metadata, a concise list of nodes, sample edges, and any detected architectural layers. The prompt instructs the model to act as a software-architecture educator and return a JSON object containing ordered tour steps with titles, descriptions, and node references.

### Stage 2: LLM Processing and Heuristic Fallback

The generated prompt is sent to the configured LLM provider. The `parseTourGenerationResponse` function extracts a `TourStep[]` array from well-formed JSON responses. However, when the LLM is unavailable or returns malformed data, the system automatically falls back to `generateHeuristicTour`. This pure-JavaScript implementation constructs tours using graph topology alone, ensuring the system remains functional offline or during API outages.

### Stage 3: Tour Consumption and UI Integration

The resulting `TourStep[]` array is stored on the `KnowledgeGraph.tour` field. The dashboard's Zustand store ([`store.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/store.ts)) reads this array, sorts steps by their `order` property, and drives navigation through `nextTourStep` and `prevTourStep` helpers. Simultaneously, the [`onboard-builder.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/onboard-builder.ts) module incorporates the tour into the "Getting Started" section of generated markdown guides.

## The Heuristic Tour Algorithm

When LLM generation fails, the `generateHeuristicTour` function (lines 35-92 of [`tour-generator.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/tour-generator.ts)) executes a deterministic algorithm that respects code dependencies:

1. **Separate concept nodes** from regular code nodes in the graph.
2. Build adjacency maps (`inDegree`, `adjacency`) for code nodes only.
3. Run **Kahn's topological sort** to obtain a dependency-aware ordering.
4. Group nodes by architectural layer if layers exist; otherwise batch every three nodes into a single step.
5. Append a final "Key Concepts" step if any concept nodes are present.
6. Assign sequential `order` numbers to each step.

This approach ensures that learners encounter files in dependency order, understanding foundational modules before dependent ones.

## TourStep Data Model and Schema

The `TourStep` interface, defined in [`types.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/types.ts), structures each step with the following properties:

- `order`: Numeric sequence indicator for sorting.
- `title`: Human-readable step name.
- `description`: Educational content explaining the step's significance.
- `nodeIds`: Array of knowledge graph node identifiers to highlight in the UI.
- `languageLesson`: Optional field for syntax or pattern explanations.

The [`schema.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/schema.ts) file validates and sanitizes these objects when persisting the knowledge graph to storage.

## Implementation Examples

### Building an LLM Prompt and Parsing the Response

```typescript
import {
  buildTourGenerationPrompt,
  parseTourGenerationResponse,
} from "@understand-anything/core";

// `graph` is a KnowledgeGraph obtained from the analysis pipeline
const prompt = buildTourGenerationPrompt(graph);

// Send `prompt` to your LLM (e.g. Claude, OpenAI)
const llmResponse = await myLLMProvider.ask(prompt);

// Extract the tour steps
const tour: TourStep[] = parseTourGenerationResponse(llmResponse);

```

### Generating a Fallback Tour Without LLM Access

```typescript
import { generateHeuristicTour } from "@understand-anything/core";

const tour = generateHeuristicTour(graph);
// `tour` is ready for UI consumption or markdown rendering

```

### Wiring the Tour into the Onboarding Guide

```typescript
import { buildOnboardingGuide } from "./onboard-builder";

const markdown = buildOnboardingGuide({
  ...graph,
  tour,               // either LLM-generated or heuristic
});
console.log(markdown);

```

### Consuming the Tour in the Dashboard Store

```typescript
import { create } from "zustand";
import type { KnowledgeGraph, TourStep } from "@understand-anything/core";

export const useDashboardStore = create((set, get) => ({
  graph: undefined as KnowledgeGraph | undefined,
  currentTourStep: 0,

  setGraph: (g: KnowledgeGraph) => set({ graph: g, currentTourStep: 0 }),

  getSortedTour: (): TourStep[] => {
    const { graph } = get();
    if (!graph?.tour) return [];
    return [...graph.tour].sort((a, b) => a.order - b.order);
  },

  nextTourStep: () => {
    const sorted = get().getSortedTour();
    const { currentTourStep } = get();
    if (currentTourStep < sorted.length - 1) {
      set({ currentTourStep: currentTourStep + 1 });
    }
  },

  // …similar `prevTourStep` implementation
}));

```

## Summary

- **Dual-generation strategy**: The system attempts LLM-based tour generation first, then falls back to a deterministic heuristic algorithm to ensure reliability.
- **Graph-aware ordering**: The heuristic fallback uses Kahn's topological sort in `generateHeuristicTour` to respect code dependencies and layer architecture.
- **Structured data model**: Tours consist of `TourStep` objects containing metadata, descriptions, and node references defined in [`types.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/types.ts).
- **Multi-platform consumption**: Generated tours power both interactive UI navigation via [`store.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/store.ts) and static documentation through [`onboard-builder.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/onboard-builder.ts).

## Frequently Asked Questions

### What happens if the LLM fails to generate a valid tour?

When the LLM returns malformed JSON or is unavailable, the system automatically invokes `generateHeuristicTour` in [`tour-generator.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/tour-generator.ts). This pure-JavaScript function analyzes the knowledge graph topology using Kahn's algorithm to produce a dependency-ordered tour without external API calls.

### How does the heuristic algorithm determine the order of tour steps?

The algorithm builds adjacency maps from the knowledge graph and executes a topological sort on code nodes, ensuring learners encounter foundation files before dependent modules. If architectural layers are detected, it groups nodes by layer; otherwise, it batches every three nodes into a single step.

### Can guided tours include educational content about programming concepts?

Yes. The `TourStep` interface includes an optional `languageLesson` field specifically designed to hold syntax explanations, design pattern descriptions, or framework-specific guidance. Additionally, the "Key Concepts" step automatically appended by the heuristic algorithm highlights abstract concept nodes separate from implementation files.

### Where is the tour data stored and how is it accessed by the UI?

Tour data is stored as a `TourStep[]` array on the `tour` property of the `KnowledgeGraph` object. The dashboard's Zustand store ([`store.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/store.ts)) accesses this field, sorts steps by their `order` property, and exposes navigation methods like `nextTourStep` and `prevTourStep` that update the UI state and highlight corresponding graph nodes.