Generate a structured tutorial (index, chapters, Mermaid diagram) from a GitHub repo or local directory. Aimed at developer onboarding: point at a codebase and get an auto-generated guide to its core abstractions, relationships, and how they work together.
Input: GitHub repository URL or local directory; optional project name and language.
Output: A project-named directory with index.md (summary + relationship diagram + chapter links) and one Markdown chapter per core abstraction (01_*.md, 02_*.md, β¦).
Code-IQ is built on Pocket Flow (graph + shared store). Entry points:
flowchart LR
subgraph clients["Entry points"]
CLI[CLI]
API[FastAPI]
UI[Streamlit UI]
end
subgraph pipeline["Pipeline"]
shared[(Shared store)]
end
CLI --> pipeline
API --> pipeline
UI --> API
The pipeline is a linear workflow plus a batch step for chapters:
flowchart TD
A[FetchRepo] --> B[SummarizeFiles]
B --> C[IdentifyAbstractions]
C --> D[AnalyzeRelationships]
D --> E[OrderChapters]
E --> F[Batch: WriteChapters]
F --> G[CombineTutorial]
| Step | Description |
|---|---|
| FetchRepo | Crawl GitHub (API or clone fallback) or local directory; load source files into shared store. |
| SummarizeFiles | For large codebases, summarize file set so the LLM can pick representative files; always keep README if present. |
| IdentifyAbstractions | LLM identifies ~5β10 core abstractions, descriptions, and related file indices. |
| AnalyzeRelationships | LLM produces project summary and relationship graph (from/to/label between abstractions). |
| OrderChapters | LLM determines tutorial order (indices) by importance and dependencies. |
| WriteChapters | BatchNode: for each abstraction in order, LLM writes one chapter (with prior chapters as context). |
| CombineTutorial | Writes output dir: index.md (summary + Mermaid diagram + chapter links) and 01_*.md β¦ files. |
Shared store schema and node contracts are in docs/design.md.
- Python 3.11+ (enforced in
pyproject.tomland.python-version)
Create a virtual environment with Python 3.11+ and install dependencies:
# If you have an existing .venv from Python 3.9, remove it first: rm -rf .venv
python3.11 -m venv .venv # or python3 -m venv .venv where python3 is 3.11+
source .venv/bin/activate # or .venv\Scripts\activate on Windows
pip install -r requirements.txtBuild and run the CLI in a container (pass env vars for LLM and optional GITHUB_TOKEN):
docker build -t code-iq .
docker run --rm -e GEMINI_API_KEY="$GEMINI_API_KEY" -v "$(pwd)/out:/app/output" code-iq --repo-url https://github.com/owner/repo --output-dir /app/outputUse --local-dir by mounting a host directory and passing the path inside the container (e.g. -v /path/on/host:/data and --local-dir /data).
Variables can be set in the shell or in a .env file in the project root (loaded automatically via python-dotenv). Do not commit .env; it is listed in .gitignore.
The pipeline uses call_llm (see utils/call_llm.py), which supports three backends via LLM_PROVIDER:
-
gemini(default): Google GenAIGEMINI_API_KEY(required): API key for Google GenAI.GEMINI_MODEL(optional): Model name (default:gemini-2.0-flash).- On 429 (quota/rate limit),
call_llmretries with backoff using the APIβs suggested delay (or 40s), up toLLM_RATE_LIMIT_MAX_RETRIES(default: 3). Set to 1 to disable retries.
-
gemini_aiplatform: Vertex AI express mode (REST with API key in URL).GEMINI_API_KEY(required),GEMINI_MODEL(optional).LLM_MAX_INPUT_CHARS(optional, default: 1000000): max prompt length; longer prompts are truncated. Set to 0 to disable. -
cursor: Cursor CLI via subprocessCURSOR_MODEL(optional): Model passed tocursor agent --model.CURSOR_TIMEOUT(optional): Timeout in seconds (default:120).CURSOR_API_KEY(optional): For headless Cursor agent.
Example:
export LLM_PROVIDER=gemini
export GEMINI_API_KEY=your-keyWhen using --repo-url, the tool automatically handles API limitations:
- GitHub API (preferred): Used when available for efficient file access
- Local clone fallback: If API fails (rate limits, authentication issues), automatically falls back to cloning the repository to a temporary directory
For best performance and to avoid rate limits:
GITHUB_TOKEN(optional): A GitHub personal access token. Setting it raises the limit (e.g. 5,000 requests/hour) and is recommended for crawling repos with many files.
The fallback mechanism ensures public repositories work even without authentication tokens.
export GITHUB_TOKEN=ghp_xxxx
python main.py --repo-url https://github.com/owner/repo --output-dir ./outWhen running the API and web app, the Tutorials page lists tutorial folders from a configurable output directory:
OUTPUT_DIR(optional, default:out): Directory scanned for tutorial subfolders (each must containindex.md). Set this to the same path you use for--output-dir(or a custom location) so the web app can browse existing tutorials.
For large codebases, Code-IQ intelligently filters files before analysis:
LLM_FILE_SUMMARY_CHUNK_SIZE(optional, default: 1000): Number of files processed per chunk during summarizationLLM_FILE_SUMMARY_MAX_FILES(optional, default: 400): Maximum number of representative files to analyze for abstractions
The system automatically selects the most representative files while ensuring README.md is always included if present.
One of --repo-url or --local-dir is required.
| Argument | Description |
|---|---|
--repo-url |
GitHub repository URL (e.g. https://github.com/owner/repo). |
--local-dir |
Local directory path to crawl (alternative to --repo-url). |
--project-name |
Override project name (default: derived from URL or directory). |
--output-dir |
Base directory for output (default: output). |
--language |
Tutorial language (default: english). Use e.g. spanish, french for translated names, descriptions, summary, and chapter content. |
Exit codes: 0 = success, 1 = pipeline error, 2 = invalid arguments (e.g. missing --repo-url / --local-dir).
From a local directory:
python main.py --local-dir /path/to/your/code --output-dir ./outFrom a GitHub repo:
python main.py --repo-url https://github.com/owner/repo --output-dir ./outWith language and project name:
python main.py --local-dir . --project-name MyApp --language spanish --output-dir ./tutorialsHelp:
python main.py --helpOn success, the tool writes a directory under output_dir named after the project (e.g. output/my_project/) containing:
index.mdβ Project summary, Mermaid relationship diagram, and links to chapters.01_*.md,02_*.md, β¦ β One Markdown chapter per core abstraction.
Logging goes to stderr (INFO level); the final line prints the output path.
pytest tests/ -v
# or
python -m pytest tests/ -v| Path | Purpose |
|---|---|
main.py |
CLI entrypoint; parses args, fills shared store, runs flow. |
flow.py |
Defines Pocket Flow: create_full_flow(), create_analysis_flow(), create_fetch_flow(). |
nodes.py |
All pipeline nodes: FetchRepo, SummarizeFiles, IdentifyAbstractions, AnalyzeRelationships, OrderChapters, WriteChapters, CombineTutorial. |
shared_schema.py |
Shared store default keys and structure. |
utils/ |
call_llm.py (LLM backends), crawl_github_files.py, crawl_local_files.py, context_helpers.py. |
api/ |
FastAPI app, build/jobs/projects routes, runner, job/project stores, webhooks. |
ui/ |
Streamlit app for GitHub URL or zip upload and viewing/downloading results. |
docs/ |
Design doc, guide, post-MVP plan, edit scope, Jekyll-style docs. |
A FastAPI server exposes sync and async build endpoints. Async jobs are stored in memory; jobs older than 24 hours are removed (configurable via JOB_RETENTION_SECONDS).
API-related environment variables:
| Variable | Default | Description |
|---|---|---|
BUILD_TIMEOUT_SECONDS |
300 |
Max duration (seconds) for sync POST /v1/build; excess returns 413. |
JOB_RETENTION_SECONDS |
86400 (24 h) |
Async jobs older than this are removed from the in-memory store. |
WEBHOOK_SECRET |
β | Secret for HMAC-SHA256 signing of webhook payloads; set when using webhook_url on async jobs. |
Run the API:
uv run uvicorn api.app:app --host 127.0.0.1 --port 8000
# Default: http://localhost:8000
# POST /v1/build (sync), POST /v1/jobs (async), GET /v1/jobs/{id}, GET /v1/jobs/{id}/resultUse this non-reload mode for normal local development when you run long tutorial jobs from the React or Streamlit UI. It keeps the API responsive for progress polling while jobs are running.
If you specifically need auto-reload while editing API code, you can still use:
uv run uvicorn api.app:app --reload --reload-exclude '.cache' --reload-exclude 'output'Avoid reload mode while running long jobs that clone repositories under .cache/, because file watcher restarts can interrupt progress polling and in-flight requests.
Webhooks: For async jobs, optional webhook_url in POST /v1/jobs. On completion or failure the server POSTs a signed payload (HMAC-SHA256 of body with WEBHOOK_SECRET). Set WEBHOOK_SECRET in the environment; clients verify using X-Webhook-Signature. Retries: 3 attempts with exponential backoff; Delivery-Attempt: 1..3 header.
Upload: POST /v1/jobs/upload accepts a zip of your project (multipart/form-data). Max size 50 MB. The zip is extracted server-side to a temp dir; the pipeline runs with that as local_dir; the temp dir is removed after the run.
Edit (optional): After a job completes, create a project via POST /v1/projects/from-job/{job_id}. Then PATCH /v1/projects/{id} to update summary/chapters, or POST /v1/projects/{id}/regenerate (scope=full) to enqueue a new run. See docs/edit-scope.md and ui/README.md (Edit button after completion).
The build_site.py script generates a beautiful, interactive static HTML site from tutorial markdown files. This section documents how to manually generate and host tutorial sites locally or in any output folder.
A tutorial directory must contain:
index.md(required): Overview with project name, description, relationship diagram01_*.md,02_*.md, etc. (required): Numbered chapter files in reading order- Optional subsystem folders: Subdirectories containing related markdown files (e.g.,
tools/,services/,schemas/)
Example structure:
output/
βββ langchain/
β βββ index.md # Project overview
β βββ 01_core_abstractions.md # Chapter 1
β βββ 02_chains.md # Chapter 2
β βββ tools/ # Optional subsystem
β β βββ index.md
β β βββ retriever_tools.md
β β βββ custom_tools.md
β βββ advanced/
β βββ index.md
β βββ performance_tuning.md
βββ claudeCode/
β βββ index.md
β βββ 01_state_management.md
β βββ 02_ink_ui_framework.md
β βββ ...
Use build_site.py to generate HTML from a tutorial directory:
# Basic usage: generates site to <tutorial_dir>/docs/
python3 build_site.py output/langchain
# Custom output directory (configurable)
python3 build_site.py output/langchain --out _site/langchain
# Override project metadata
python3 build_site.py output/langchain --out _site/langchain --name "My Custom Name" --github-url "https://github.com/user/repo"Output structure (defaults to <tutorial_dir>/docs/):
docs/
βββ index.html # Main landing page
βββ chapters/
β βββ 01-core-abstractions.html
β βββ 02-chains.html
β βββ ...
βββ subsystems/ # If subsystems exist
β βββ tools.html
β βββ services.html
β βββ ...
βββ assets/
β βββ style.css
β βββ mermaid diagrams, etc.
βββ .nojekyll # Prevents Jekyll processing
| Option | Default | Description |
|---|---|---|
tutorial_dir |
β | Required: Path to tutorial directory (relative or absolute) |
--out |
<tutorial_dir>/docs |
Output directory for generated HTML site |
--name |
Inferred from directory | Override project name (shown in sidebar, index) |
--github-url |
Extracted from index.md | Override GitHub repository URL |
To build multiple tutorial sites in one command, use the batch runner:
# Build all tutorials in output/ and generate sites to _site/
python3 build_site.py output/langchain --out _site/langchain
python3 build_site.py output/claudeCode --out _site/claudeCode
python3 build_site.py output/autogen --out _site/autogen
# Or iterate with a loop
for tutorial_dir in output/*/; do
name=$(basename "$tutorial_dir")
python3 build_site.py "$tutorial_dir" --out "_site/$name"
echo "β Built $name"
doneAfter building, serve the sites locally using Python's built-in HTTP server:
# Serve from _site/ directory (browse all generated sites)
cd _site
python3 -m http.server 8000
# Open browser to: http://localhost:8000
# Browse tutorials: http://localhost:8000/langchain/
# Browse a specific chapter: http://localhost:8000/langchain/chapters/01-core-abstractions.htmlAlternative: Using a modern server (handles CORS, etc.):
# If you have Node.js installed
npx http-server _site/ -p 8000 -c-1 # -c-1 disables caching
# Or with Python's newer http.server (Python 3.7+)
cd _site && python3 -m http.server --directory . 8000Once the server is running, you can browse all available sites:
-
Root directory index (with manual HTML):
http://localhost:8000/- Create a simple
_site/index.htmlwith links to all tutorials
- Create a simple
-
Direct tutorial access:
- Langchain:
http://localhost:8000/langchain/ - Claude Code:
http://localhost:8000/claudeCode/ - Autogen:
http://localhost:8000/autogen/
- Langchain:
#!/bin/bash
# build_all_tutorials.sh
OUTPUT_DIR="_site"
TUTORIAL_ROOT="output"
# Create output directory
mkdir -p "$OUTPUT_DIR"
# Build all tutorials
for tutorial_dir in "$TUTORIAL_ROOT"/*/; do
name=$(basename "$tutorial_dir")
echo "Building $name..."
python3 build_site.py "$tutorial_dir" --out "$OUTPUT_DIR/$name" 2>/dev/null
done
# Start server
echo "π Starting server on http://localhost:8000"
cd "$OUTPUT_DIR"
python3 -m http.server 8000Run it:
chmod +x build_all_tutorials.sh
./build_all_tutorials.shCreate a landing page to browse all sites (_site/index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Code-IQ Tutorials</title>
<style>
body { font-family: system-ui; padding: 40px; background: #f5f5f5; }
h1 { color: #333; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px; margin-top: 20px; }
.card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
.card:hover { box-shadow: 0 4px 16px rgba(0,0,0,0.15); }
.card a { color: #0066cc; text-decoration: none; font-weight: 600; }
.card a:hover { text-decoration: underline; }
</style>
</head>
<body>
<h1>π Code-IQ Tutorials</h1>
<p>All available tutorials are listed below. Click to explore.</p>
<div class="grid">
<!-- Auto-generated cards -->
<div class="card">
<h3><a href="langchain/">Langchain</a></h3>
<p>Langchain framework overview and core abstractions.</p>
</div>
<div class="card">
<h3><a href="claudeCode/">Claude Code</a></h3>
<p>Claude Code architecture and implementation guide.</p>
</div>
<div class="card">
<h3><a href="autogen/">AutoGen</a></h3>
<p>AutoGen multi-agent framework guide.</p>
</div>
</div>
</body>
</html>The generated sites include:
- π Responsive sidebar with active chapter highlighting
- π Pin/collapse sidebar with localStorage persistence
- π Table of Contents (TOC) with scroll-spy highlighting
- π¨ Dark/light theme toggle
- π Mermaid diagram support with zoom/pan controls
- β¨οΈ Code block syntax highlighting
- π± Mobile-friendly layout
- π Cross-chapter linking with automatic URL rewriting
The site generator looks for styling assets in:
_site_assets/style.css(main theme)_site_assets/(shared assets)
To customize, edit _site_assets/style.css before running build_site.py.
After running the pipeline:
- Run on one public GitHub repo and one local directory; verify the summary and chapter order in
index.md. - Optionally run with
--language spanish(or another language) and confirm names, summary, and chapter content are coherent in that language.
- docs/design.md β System design: flow, shared store, node steps, utilities.
- docs/post-mvp-plan.md β API contract (sync/async, webhooks), UI scope, frontend tech.
- docs/edit-scope.md β Editing projects and regenerating after a job.
- ui/README.md β Running the Streamlit UI and configuration.
This project uses Pocket Flow. See .cursor/rules/guide_for_pocketflow.mdc and Agentic Coding Guidance for development.