# How Guided Tours Are Automatically Generated from the Knowledge Graph in Understand-Anything

> Discover how Understand Anything automatically generates guided tours from its knowledge graph leveraging LLM queries or topological heuristics. Explore your code dependencies effortlessly.

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

---

**Understand-Anything synthesizes interactive guided tours by either querying an LLM with structured graph data or falling back to a topological heuristic that traverses code dependencies and architectural layers.**

The Understand-Anything open-source project transforms static repository analysis into interactive onboarding experiences. After the `GraphBuilder` constructs a knowledge graph from your codebase, the system automatically generates a step-by-step tour that helps new developers navigate complex architectures without external documentation.

## The Two-Phase Generation Pipeline

Tour creation occurs after the initial graph construction completes. The `KnowledgeGraph` object begins with an empty `tour` array that gets populated through one of two deterministic strategies.

### Phase 1: Graph Construction

In [`packages/core/src/analyzer/graph-builder.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/analyzer/graph-builder.ts), the `GraphBuilder` walks the repository to extract files, functions, concepts, and architectural layers. It produces a `KnowledgeGraph` with rich metadata including nodes, edges, and detected layers, leaving the `tour` field initially empty for the subsequent generation step.

### Phase 2: Tour Synthesis

The system attempts **LLM-based generation** first, falling back to a **heuristic algorithm** if the LLM is unavailable, the response is unparsable, or the user disables AI features. Both paths ultimately produce an array of `TourStep` objects that validate against the schema in [`packages/core/src/types.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/types.ts).

## LLM-Based Tour Generation

When AI assistance is enabled, the pipeline constructs a detailed prompt containing project context and structural metadata, then validates the model's JSON response.

### Building the Generation Prompt

The `buildTourGenerationPrompt(graph)` function in [`packages/core/src/analyzer/tour-generator.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/analyzer/tour-generator.ts) assembles a comprehensive context window that includes:

- Project metadata (name, description, languages, frameworks)
- Complete node inventory with types, file paths, and summaries
- First 50 edges representing key relationships
- Detected architectural layers (or placeholders if none exist)
- Explicit instructions to return only a JSON object containing a `"steps"` array

### Parsing and Validation

The `parseTourGenerationResponse` function handles raw LLM output by stripping Markdown fences, extracting the first JSON object, and strictly validating each step's `order`, `title`, `description`, and `nodeIds` fields. Invalid responses return an empty array, triggering the heuristic fallback automatically.

## Heuristic Fallback Algorithm

The `generateHeuristicTour(graph)` function provides a deterministic, AI-free alternative that analyzes graph topology to create a sensible walkthrough.

### Topological Sorting and Layer Grouping

The heuristic implementation applies **Kahn’s algorithm** to establish a dependency-respecting order based on incoming edge counts. The process:

1. **Separates concept nodes** from code nodes to distinguish architectural ideas from implementation files
2. **Builds adjacency and indegree maps** for code nodes only
3. **Executes topological sorting** to ensure dependencies appear before dependents
4. **Groups nodes by detected layers** when available, otherwise batches every three nodes
5. **Appends a "Key Concepts" step** at the end when conceptual nodes exist
6. **Assigns sequential 1-based order numbers** to the final `TourStep` array

This approach guarantees a coherent tour even in air-gapped environments or when LLM quotas are exhausted.

## Attaching and Consuming the Tour

Once generated, the tour integrates into the broader Understand-Anything ecosystem for immediate user consumption.

### Graph Attachment

The resulting `TourStep[]` array is stored in `graph.tour` by the orchestration layer. This field persists with the knowledge graph and travels through subsequent processing stages.

### Onboarding Documentation

In [`src/onboard-builder.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/src/onboard-builder.ts), the `buildOnboardingGuide` function reads `graph.tour` to inject a "Getting Started" section into the generated markdown. Each step renders with its title, description, and a bullet list of files to examine, creating a self-contained onboarding document alongside the graph data.

### Dashboard Navigation

The dashboard UI in [`packages/dashboard/src/store.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/dashboard/src/store.ts) loads the tour array to drive interactive navigation. It sorts steps by their `order` field, highlights involved nodes in the visualizer, and provides forward/backward controls for step-by-step exploration.

## Implementation Examples

### Generating a Heuristic Tour

The following example demonstrates the heuristic generator against a minimal TypeScript project:

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

const sampleGraph: KnowledgeGraph = {
  version: "0.0.1",
  project: {
    name: "Demo",
    description: "A tiny demo project",
    languages: ["typescript"],
    frameworks: [],
    analyzedAt: new Date().toISOString(),
  },
  nodes: [
    { id: "1", name: "src/index.ts", type: "file", summary: "Entry point", filePath: "src/index.ts" },
    { id: "2", name: "src/util.ts", type: "file", summary: "Utility helpers", filePath: "src/util.ts" },
    { id: "c1", name: "Event Loop", type: "concept", summary: "Node.js event loop" },
  ],
  edges: [{ source: "1", target: "2", type: "import" }],
  layers: [],
  tour: [],
};

const tour = generateHeuristicTour(sampleGraph);
console.log(JSON.stringify(tour, null, 2));

```

**Output:**

```json
[
  {
    "order": 1,
    "title": "Step 1: Code Walkthrough",
    "description": "Exploring: src/index.ts (Entry point); src/util.ts (Utility helpers).",
    "nodeIds": ["1", "2"]
  },
  {
    "order": 2,
    "title": "Key Concepts",
    "description": "Important architectural concepts: Event Loop (Node.js event loop).",
    "nodeIds": ["c1"]
  }
]

```

### Integrating LLM-Based Generation

To leverage AI for narrative tours, build the prompt and parse the response:

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

const prompt = buildTourGenerationPrompt(sampleGraph);
// Send 'prompt' to your LLM provider...

const llmReply = `
\`\`\`json
{
  "steps": [
    {
      "order": 1,
      "title": "Entry Point",
      "description": "Start with the main file to understand how the app boots.",
      "nodeIds": ["1"]
    },
    {
      "order": 2,
      "title": "Utility Helpers",
      "description": "Look at helper functions used throughout the code.",
      "nodeIds": ["2"]
    }
  ]
}
\`\`\`
`;

const steps = parseTourGenerationResponse(llmReply);
// steps is now a validated TourStep[] ready for graph.tour

```

## Summary

- **Understand-Anything** generates guided tours automatically from the knowledge graph using either LLM-based synthesis or a deterministic heuristic algorithm.
- **LLM path**: Constructs detailed prompts in `buildTourGenerationPrompt` and validates JSON responses via `parseTourGenerationResponse` in [`packages/core/src/analyzer/tour-generator.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/core/src/analyzer/tour-generator.ts).
- **Heuristic path**: Uses `generateHeuristicTour` applying Kahn's topological sort and layer grouping to create dependency-respecting walkthroughs without external APIs.
- **Integration**: The final `TourStep[]` array attaches to `graph.tour` and powers both markdown onboarding guides ([`src/onboard-builder.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/src/onboard-builder.ts)) and interactive dashboard navigation ([`packages/dashboard/src/store.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/dashboard/src/store.ts)).

## Frequently Asked Questions

### What triggers the heuristic fallback instead of LLM generation?

The system invokes `generateHeuristicTour` when the LLM is unavailable, the user disables AI features, or `parseTourGenerationResponse` fails to validate the model's JSON output. This ensures tour generation remains robust in offline environments or when API quotas are exhausted.

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

The algorithm applies **Kahn’s topological sort** to code nodes based on their import relationships, ensuring dependencies appear before the files that use them. When architectural layers are detected, it groups nodes layer-by-layer following this topological order; otherwise, it batches nodes in groups of three.

### Can I customize the guided tour after it is generated?

Yes. Since the tour is stored as a plain `TourStep[]` array in `graph.tour`, you can programmatically modify the steps, reorder them by adjusting the `order` field, or filter specific node types before the onboarding builder or dashboard consumes the data.

### Where is the tour data consumed in the Understand-Anything application?

The tour data flows into two primary interfaces: the `buildOnboardingGuide` function in [`src/onboard-builder.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/src/onboard-builder.ts) renders the tour as a "Getting Started" section in markdown documentation, while the dashboard state management in [`packages/dashboard/src/store.ts`](https://github.com/Lum1104/Understand-Anything/blob/main/packages/dashboard/src/store.ts) drives an interactive UI with forward/backward navigation and node highlighting.