Skip to content
adityasoni99Public

About

🧠 AI-powered codebase analysis tool that automatically generates comprehensive tutorials from GitHub repositories or local directories. Features FastAPI backend, Streamlit UI, multi-language support, and intelligent file filtering using multi-agent LLM pipeline.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

31 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Code-IQ

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, …).


Architecture

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
Loading

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]
Loading
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.


Requirements

  • Python 3.11+ (enforced in pyproject.toml and .python-version)

Setup

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.txt

Docker

Build 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/output

Use --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).

Environment variables

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.

LLM

The pipeline uses call_llm (see utils/call_llm.py), which supports three backends via LLM_PROVIDER:

  • gemini (default): Google GenAI

    • GEMINI_API_KEY (required): API key for Google GenAI.
    • GEMINI_MODEL (optional): Model name (default: gemini-2.0-flash).
    • On 429 (quota/rate limit), call_llm retries with backoff using the API’s suggested delay (or 40s), up to LLM_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 subprocess

    • CURSOR_MODEL (optional): Model passed to cursor 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-key

GitHub

When using --repo-url, the tool automatically handles API limitations:

  1. GitHub API (preferred): Used when available for efficient file access
  2. 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 ./out

Tutorial browser (web app)

When 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 contain index.md). Set this to the same path you use for --output-dir (or a custom location) so the web app can browse existing tutorials.

File Processing

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 summarization
  • LLM_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.

CLI usage

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).

Running

From a local directory:

python main.py --local-dir /path/to/your/code --output-dir ./out

From a GitHub repo:

python main.py --repo-url https://github.com/owner/repo --output-dir ./out

With language and project name:

python main.py --local-dir . --project-name MyApp --language spanish --output-dir ./tutorials

Help:

python main.py --help

On 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.

Tests

pytest tests/ -v
# or
python -m pytest tests/ -v

Repository structure

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.

API (post-MVP)

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}/result

Use 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).

Generating and Hosting Tutorial Sites (Documentation)

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.

Tutorial Directory Structure

A tutorial directory must contain:

  • index.md (required): Overview with project name, description, relationship diagram
  • 01_*.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
β”‚   └── ...

Building a Static Site

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

Command-Line Options

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

Batch Generate Multiple Sites

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"
done

Launching a Local Server

After 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.html

Alternative: 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 . 8000

Browsing Multiple Tutorial Sites

Once the server is running, you can browse all available sites:

  1. Root directory index (with manual HTML): http://localhost:8000/

    • Create a simple _site/index.html with links to all tutorials
  2. Direct tutorial access:

    • Langchain: http://localhost:8000/langchain/
    • Claude Code: http://localhost:8000/claudeCode/
    • Autogen: http://localhost:8000/autogen/

Example: Full Workflow

#!/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 8000

Run it:

chmod +x build_all_tutorials.sh
./build_all_tutorials.sh

Creating an Index for All Tutorials

Create 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>

Features of Generated Sites

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

Configuration & Customization

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.

Manual quality checks (optional)

After running the pipeline:

  1. Run on one public GitHub repo and one local directory; verify the summary and chapter order in index.md.
  2. Optionally run with --language spanish (or another language) and confirm names, summary, and chapter content are coherent in that language.

Documentation


This project uses Pocket Flow. See .cursor/rules/guide_for_pocketflow.mdc and Agentic Coding Guidance for development.

About

🧠 AI-powered codebase analysis tool that automatically generates comprehensive tutorials from GitHub repositories or local directories. Features FastAPI backend, Streamlit UI, multi-language support, and intelligent file filtering using multi-agent LLM pipeline.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages