# GitHub Repository to Clean Markdown for LLM & RAG (`sequined_lacework/github-repo-to-markdown`) Actor

Convert any public GitHub repository (or private with a token) into one clean Markdown document with a file tree, ready for LLM context and RAG. Skips lockfiles, binaries and build folders, supports include/exclude filters and chunking. No git clone, pay per file.

- **URL**: https://apify.com/sequined_lacework/github-repo-to-markdown.md
- **Developed by:** [Egor Kramskoy](https://apify.com/sequined_lacework) (community)
- **Categories:** AI, Developer tools
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.00 / 1,000 files processed

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## GitHub Repository to Clean Markdown for LLM & RAG

**GitHub repo to Markdown** in one Apify Actor: send repository URLs and get the whole codebase as one clean Markdown document with a file tree. Use it for **repository to LLM context**, **codebase to Markdown for RAG**, or **GitHub to text for ChatGPT / Claude**. It downloads a single zip archive per repository (no `git clone`, no browser), skips lockfiles, binaries and build folders, and can split the result into RAG-ready chunks.

### What it does

- Accepts `https://github.com/owner/repo`, `.../repo.git`, `.../tree/<branch>`, `git@github.com:owner/repo.git` and plain `owner/repo`.
- Finds the default branch through the GitHub API (renamed repositories are followed). If the API is rate limited it falls back to `main`, then `master`.
- Downloads the branch archive from `codeload.github.com` and reads it in memory.
- Keeps text files only: lockfiles, `node_modules`, `dist`, images, fonts, archives, minified files and binaries are skipped by default.
- Puts the README first, then all other files in path order, each in a fenced code block with the right language tag. Fences are lengthened automatically when a file already contains triple backticks (for example Markdown docs).
- Adds an ASCII file tree, word count and a token estimate. Optionally splits the Markdown into overlapping chunks.

### Why use it

- **LLM-ready**: one document you can paste into ChatGPT, Claude or Gemini, or feed into an embedding pipeline.
- **Fast and cheap**: one HTTP download per repository, pay per file.
- **Controllable**: `includeExtensions`, `excludePatterns`, `maxFiles` and `maxFileSizeKb` keep the context small.
- **Safe failures**: a missing repository or a bad URL gives one item with `status: "error"`; the run continues with the next URL.

### Input example

```json
{
    "repoUrls": ["https://github.com/tiangolo/typer"],
    "maxFiles": 20,
    "includeExtensions": [".py", ".md"],
    "includeTree": true,
    "chunkSize": 1500,
    "chunkOverlap": 200
}
```

| Field | Default | Description |
|---|---|---|
| `repoUrls` | tiangolo/typer (demo) | Repository URLs or `owner/repo` |
| `branch` | empty | Branch to download; empty = branch from the URL or the default branch |
| `githubToken` | empty | Optional token (stored as a secret) for private repositories and higher rate limits |
| `maxFiles` | 100 | Max files per repository (1-1000); README first, then alphabetical by path |
| `includeExtensions` | empty | Only these extensions, e.g. `[".py", ".md"]` (case-insensitive, dot optional) |
| `excludePatterns` | built-in list | `dir/` excludes a folder anywhere; other patterns match the file name or full path with `*` and `?`. Replaces the default list |
| `includeTree` | true | Add the ASCII file tree to the Markdown |
| `chunkSize` | 0 | Chunk size in characters; 0 disables chunking (max 16000) |
| `chunkOverlap` | 200 | Overlap between chunks; reduced to `chunkSize / 4` if not smaller than `chunkSize` |
| `maxFileSizeKb` | 200 | Files larger than this are skipped (1-2000) |

### Output example

One dataset item per repository (long fields shortened):

````json
{
    "repo_url": "https://github.com/tiangolo/typer",
    "owner": "fastapi",
    "repo": "typer",
    "branch": "master",
    "files_processed": 20,
    "files_skipped": 640,
    "tree": "typer/\n├── docs/\n│   └── index.md\n├── typer/\n│   ├── __init__.py\n│   └── main.py\n└── README.md",
    "markdown": "# fastapi/typer\n\n**Branch:** master\n**Files:** 20\n\n## Repository structure\n\n```text\ntyper/\n...\n```\n\n## Files\n\n### `README.md`\n\n```markdown\n...\n```\n",
    "chunks": ["# fastapi/typer\n\n**Branch:** master ...", "...next chunk..."],
    "word_count": 18250,
    "estimated_tokens": 31200,
    "status": "ok",
    "error_message": null
}
````

The values are illustrative. `owner` and `repo` are the resolved names, so they can differ from the input URL for renamed repositories. `files_skipped` counts every file that was left out: excluded, binary, too large, filtered by extension, empty or over `maxFiles`.

### Pricing

Pay-per-event: **$0.02 per run start** (the `run-started` event, charged once per run that has at least one URL) plus **$0.001 per file** (the `file-processed` event, charged for every file included in the Markdown). Example: one repository with 100 files costs $0.02 + 100 x $0.001 = **$0.12**. Repositories that fail are not charged per file; runs with no URLs are not charged at all.

The prices are not stored in the Actor code. `.actor/pay_per_event.json` documents the events and the suggested prices. The real prices are set in Apify Console (Actor > Publication > Monetization).

### Use with Claude Desktop / Cursor (MCP)

Connect the Actor to any MCP client through the Apify MCP server: https://mcp.apify.com/?actors=sequined_lacework/github-repo-to-markdown

Add this to your Claude Desktop or Cursor MCP config (`mcpServers`):

```json
{
    "mcpServers": {
        "apify": {
            "url": "https://mcp.apify.com/?actors=sequined_lacework/github-repo-to-markdown",
            "headers": {
                "Authorization": "Bearer <YOUR_APIFY_TOKEN>"
            }
        }
    }
}
```

An AI agent can pass a GitHub repository URL and get the file tree plus the source files as one Markdown document, so it can read and explain a codebase without cloning it.

### Integrations: n8n and LangChain

#### n8n

Use the **Apify** node (operation: Run Actor, then Get Dataset Items) with the Actor ID `sequined_lacework/github-repo-to-markdown`, or an **HTTP Request** node (method `POST`, body type JSON) pointing at the synchronous endpoint, which returns the dataset items directly:

```
https://api.apify.com/v2/acts/sequined_lacework~github-repo-to-markdown/run-sync-get-dataset-items?token=<YOUR_APIFY_TOKEN>
```

Body:

```json
{
    "repoUrls": ["https://github.com/tiangolo/typer"],
    "maxFiles": 30,
    "includeExtensions": [".py", ".md"]
}
```

Synchronous runs time out after 300 seconds, so use the regular run endpoint for large inputs.

#### LangChain (Python)

Install `langchain-apify` and `langchain-core`, and set the `APIFY_API_TOKEN` environment variable. The Markdown is in the `markdown` field and becomes the document `page_content`.

```python
from langchain_apify import ApifyWrapper
from langchain_core.documents import Document

apify = ApifyWrapper()
loader = apify.call_actor(
    actor_id="sequined_lacework/github-repo-to-markdown",
    run_input={"repoUrls": ["https://github.com/tiangolo/typer"], "maxFiles": 30, "includeExtensions": [".py", ".md"]},
    dataset_mapping_function=lambda item: Document(
        page_content=item["markdown"] or "",
        metadata={"source": item["repo_url"], "repo": f'{item["owner"]}/{item["repo"]}', "branch": item["branch"]},
    ),
)
docs = [d for d in loader.load() if d.page_content]
```

To load an existing run instead, use `ApifyDatasetLoader(dataset_id="<DATASET_ID>", dataset_mapping_function=...)` from `langchain_apify` with the same mapping function. If you set `chunkSize`, the `chunks` field already holds ready-to-embed pieces, so no extra text splitter is needed.

### Free plan limits

On the free Apify plan the Actor runs in demo mode:

- At most **1 repository** per run; extra repositories are skipped.
- At most **10 files** per repository (the lower of 10 and `maxFiles`).
- You are charged only for files actually processed.

The run never fails because of these limits, and the log and status message say when something was skipped. Upgrade to a paid Apify plan to process the full input.

### Related Actors for RAG Pipelines

Build a complete RAG ingestion pipeline with the same clean Markdown output, chunking options and pay-per-event pricing:

- [PDF to Markdown for RAG & LLM](https://apify.com/sequined_lacework/pdf-to-markdown-rag): PDFs (arXiv, Google Drive, any URL) with tables preserved
- [Website & Sitemap to Markdown for RAG & LLM](https://apify.com/sequined_lacework/website-to-markdown-rag): docs sites, blogs and sitemaps, code blocks preserved
- [Podcast RSS & Transcript Extractor for AI/RAG](https://apify.com/sequined_lacework/podcast-transcript-rag): podcast episodes with publisher transcripts
- [GitHub Repository to Clean Markdown for LLM & RAG](https://apify.com/sequined_lacework/github-repo-to-markdown) *(this Actor)*: whole codebases as one Markdown context with a file tree
- [RSS, Atom & Substack to Clean Markdown for RAG](https://apify.com/sequined_lacework/rss-article-markdown): blogs and newsletters, full articles from teaser feeds

### Limits

- **Public repositories work without a token.** GitHub allows about 60 API calls per hour per IP address without authentication, and Apify IPs are shared. The Actor makes one API call per repository to find the default branch; when the limit is hit it tries `main` and then `master`. Pass `githubToken` for private repositories and higher limits, or set `branch` explicitly to skip the API call.
- Output is capped at about 8 million characters per repository so that it fits the Apify dataset item limit (~9 MB). Files beyond the cap are skipped and `error_message` says so (status stays `ok`). Lower `maxFiles` or use `includeExtensions`. With `chunkSize` above 0 the chunks must fit in the same limit, so very large repositories get truncated chunks.
- Archives larger than 200 MB are rejected.
- No Git LFS: LFS files are pointer stubs in the archive and are included as such.
- Binary files, non-UTF-8 files, empty files and files larger than `maxFileSizeKb` are skipped.
- Only branches are supported (not tags or commit hashes). A branch name with a slash in a `/tree/...` URL is not parsed; use the `branch` field instead.
- You are responsible for following the license terms of the code you process.

### FAQ

**Can I convert a private repository?**
Yes. Create a GitHub personal access token with read access to the repository and put it in `githubToken`. The token is stored as a secret and never written to logs or results.

**Why do I see `repository or branch not found`?**
The repository does not exist, the branch name is wrong, or the repository is private and no token was given. GitHub answers 404 for private repositories without access.

**How do I fit a big repository into an LLM context?**
Set `includeExtensions` (for example `[".py"]`), add `excludePatterns` such as `tests/` or `docs/`, and lower `maxFiles`. Use `estimated_tokens` to check the size before sending it to a model.

**How are tokens estimated?**
Roughly 4 characters per token, which is a rough figure for English text and code. Use your model's tokenizer for exact counts.

**Can I process a subfolder only?**
Not directly. Use `includeExtensions` and `excludePatterns` to drop the folders you do not need.

**Do I need to do anything to run it locally?**
`pip install -r requirements.txt`, then `apify run` (Apify CLI). Local runs skip charging automatically.

# Actor input Schema

## `repoUrls` (type: `array`):

Repository URLs: https://github.com/owner/repo, .../tree/<branch>, git@github.com:owner/repo.git or owner/repo.

## `branch` (type: `string`):

Branch to download. Leave empty to use the branch from the URL or the repository default branch.

## `githubToken` (type: `string`):

Optional personal access token. Needed for private repositories and raises GitHub API rate limits. Stored as a secret.

## `maxFiles` (type: `integer`):

Maximum number of files included per repository (README first, then alphabetical by path).

## `includeExtensions` (type: `array`):

If set, only files with these extensions are included, e.g. \[".py", ".md"]. Empty means all text files.

## `excludePatterns` (type: `array`):

Patterns to skip. "dir/" excludes a folder anywhere in the path; other patterns are matched against the file name and the full path (wildcards \* and ?). Replaces the default list.

## `includeTree` (type: `boolean`):

Add an ASCII tree of the included files to the Markdown.

## `chunkSize` (type: `integer`):

If greater than 0, the Markdown is also split into RAG-ready chunks of at most this many characters. 0 disables chunking.

## `chunkOverlap` (type: `integer`):

Approximate overlap between neighbouring chunks. Reduced automatically if not smaller than the chunk size.

## `maxFileSizeKb` (type: `integer`):

Files larger than this are skipped.

## Actor input object example

```json
{
  "repoUrls": [
    "https://github.com/tiangolo/typer"
  ],
  "maxFiles": 20,
  "excludePatterns": [
    ".git/",
    ".env",
    ".env.*",
    "*.pem",
    "*.key",
    "node_modules/",
    "__pycache__/",
    ".venv/",
    "venv/",
    "dist/",
    "build/",
    ".idea/",
    ".vscode/",
    ".mypy_cache/",
    ".pytest_cache/",
    ".tox/",
    "vendor/",
    "*.lock",
    "package-lock.json",
    "yarn.lock",
    "pnpm-lock.yaml",
    "poetry.lock",
    "Cargo.lock",
    "*.min.js",
    "*.min.css",
    "*.map",
    "*.png",
    "*.jpg",
    "*.jpeg",
    "*.gif",
    "*.webp",
    "*.ico",
    "*.bmp",
    "*.svg",
    "*.woff",
    "*.woff2",
    "*.ttf",
    "*.otf",
    "*.eot",
    "*.zip",
    "*.tar",
    "*.gz",
    "*.tgz",
    "*.7z",
    "*.rar",
    "*.jar",
    "*.war",
    "*.exe",
    "*.dll",
    "*.so",
    "*.dylib",
    "*.bin",
    "*.pdf",
    "*.mp3",
    "*.mp4",
    "*.mov",
    "*.wav",
    "*.pyc",
    "*.class",
    "*.o",
    "*.a",
    "*.whl",
    "*.parquet",
    "*.db",
    "*.sqlite"
  ],
  "includeTree": true,
  "chunkSize": 0,
  "chunkOverlap": 200,
  "maxFileSizeKb": 200
}
```

# Actor output Schema

## `results` (type: `string`):

Dataset with one item per repository: file tree, full Markdown, optional RAG chunks and statistics.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "repoUrls": [
        "https://github.com/tiangolo/typer"
    ],
    "maxFiles": 20
};

// Run the Actor and wait for it to finish
const run = await client.actor("sequined_lacework/github-repo-to-markdown").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "repoUrls": ["https://github.com/tiangolo/typer"],
    "maxFiles": 20,
}

# Run the Actor and wait for it to finish
run = client.actor("sequined_lacework/github-repo-to-markdown").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "repoUrls": [
    "https://github.com/tiangolo/typer"
  ],
  "maxFiles": 20
}' |
apify call sequined_lacework/github-repo-to-markdown --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,sequined_lacework/github-repo-to-markdown"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/Xov0S1zr4CL4RfHgY/builds/pnBUY2y5PgXwlcjFC/openapi.json
