# RAG Doctor: Audit & Repair Your AI Knowledge Base (`sanya_kumari/rag-doctor`) Actor

Audit and repair the content you feed your AI. Finds contradictions, stale facts, duplicates, dead links, and broken chunks that quietly poison RAG, agents, and custom GPTs. Returns a scored report, a prioritized fix list, and a cleaned, ready-to-index knowledge base.

- **URL**: https://apify.com/sanya\_kumari/rag-doctor.md
- **Developed by:** [Sanya Kumari](https://apify.com/sanya_kumari) (community)
- **Categories:** AI, Agents
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

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

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## RAG Doctor — Knowledge Base Health Check & Repair for AI

Your AI is only as good as the content you feed it. RAG Doctor audits that content the way a linter audits code: it finds the contradictions, stale facts, duplicates, and broken chunks that quietly poison RAG pipelines, agents, and custom GPTs, then hands you a prioritized fix list and an optional cleaned-up version.

Most tools **build** a knowledge base for you. RAG Doctor **fixes** the one you already have.

### Why this exists

Garbage in, confident garbage out. When two pages disagree, a RAG system retrieves one at random and the model states it as fact. When a chunk reads "as shown above," retrieval pulls it alone and the model fills the gap by guessing. These defects are invisible until a user gets a wrong answer. RAG Doctor surfaces them before your users do.

### What it checks

| Check | What it catches | Needs API key |
|-------|-----------------|:---:|
| **Contradictions** | Two pages stating facts that can't both be true (the #1 silent RAG killer) | Yes |
| **Stale facts** | Pages whose newest referenced date is past your freshness threshold | No |
| **Duplicates** | Near-identical pages that crowd out distinct facts at retrieval time | No |
| **Chunk health** | Chunks that lose meaning when retrieved alone (dangling references, orphan pronouns, too short) | No |
| **Dead links** | Cited URLs that 404 or time out | No |
| **AI extractability** | robots.txt blocking AI crawlers, missing sitemap, JavaScript-only content | No |
| **Coverage gaps** | Real user questions the knowledge base cannot answer | Yes |

### Input

Point it at a site to crawl, or hand it a dataset you already extracted.

```json
{
  "startUrls": [{ "url": "https://docs.example.com/" }],
  "maxPages": 100,
  "maxCrawlDepth": 2,
  "mode": "audit",
  "checks": ["staleness", "duplicates", "chunkHealth", "deadLinks", "extractability", "contradictions"],
  "stalenessThresholdDays": 540,
  "similarityThreshold": 0.85,
  "userQuestions": ["How do I rotate my API token?"],
  "anthropicApiKey": "sk-ant-...",
  "llmModel": "claude-haiku-4-5-20251001"
}
```

Crawling and link checks run over the Apify datacenter proxy automatically; there is no proxy option to configure.

Audit content you already crawled (composes with `apify/website-content-crawler`):

```json
{ "datasetId": "YOUR_DATASET_ID", "mode": "both" }
```

The LLM-backed checks (contradictions, coverage gaps) need an Anthropic API key. Without it, those two checks are skipped and every other check still runs.

### Output

- **Dataset** — one row per finding (severity, check, issue, detail, suggested fix, URL). Sorted most-severe first.
- **Key-value store**
  - `REPORT` — a shareable HTML report with the AI-readiness score and full fix list.
  - `SUMMARY` / `OUTPUT` — the score, grade, and severity counts as JSON.
- **`repaired-knowledge-base` dataset** (repair / both modes) — duplicates collapsed, thin pages dropped, stale pages flagged, content pre-chunked and ready for a vector DB or `llms.txt`.

The **AI-readiness score (0-100)** is defect density, not raw count, so a large knowledge base isn't penalized just for having more pages.

### Modes

- `audit` — report and fix list only.
- `repair` — also emit the cleaned corpus.
- `both` — everything.

### Local development

```bash
npm install
npm run build
apify run   # or: npm start
```

### Roadmap

- Expose as an MCP server tool (`audit_knowledge_base`) so an agent can call it mid-workflow before answering.
- Embedding-based duplicate and contradiction candidate selection for higher recall.
- Incremental re-audits that only re-check what changed.

# Actor input Schema

## `startUrls` (type: `array`):

Documentation, help center, or any pages you feed your AI. RAG Doctor crawls these and audits the content. Leave empty if you pass an existing dataset instead.

## `datasetId` (type: `string`):

Instead of crawling, audit content you already extracted. Expects items with a `url` and a `text` (or `markdown`) field. Composes with apify/website-content-crawler.

## `maxPages` (type: `integer`):

Upper bound on pages crawled when using Start URLs.

## `maxCrawlDepth` (type: `integer`):

How many link hops from the Start URLs to follow. 0 audits only the given URLs.

## `mode` (type: `string`):

audit returns a scored report + fix list. repair also outputs a cleaned, deduplicated knowledge set. both does everything.

## `checks` (type: `array`):

Which health checks to run. Contradictions require an Anthropic API key.

## `stalenessThresholdDays` (type: `integer`):

Flag content whose newest detected date is older than this.

## `similarityThreshold` (type: `number`):

Jaccard similarity (0-1) above which two pages are treated as near-duplicates.

## `userQuestions` (type: `array`):

Optional. Questions your users actually ask. Enables coverage-gap detection: which questions your knowledge base cannot answer. Requires an Anthropic API key.

## `anthropicApiKey` (type: `string`):

Required for contradiction detection and coverage gaps. Without it those checks are skipped and the rest still run.

## `llmModel` (type: `string`):

Anthropic model for the LLM-backed checks.

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://docs.apify.com/platform"
    }
  ],
  "maxPages": 100,
  "maxCrawlDepth": 2,
  "mode": "audit",
  "checks": [
    "staleness",
    "duplicates",
    "chunkHealth",
    "deadLinks",
    "extractability",
    "contradictions"
  ],
  "stalenessThresholdDays": 540,
  "similarityThreshold": 0.85,
  "llmModel": "claude-haiku-4-5-20251001"
}
```

# 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 = {
    "startUrls": [
        {
            "url": "https://docs.apify.com/platform"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("sanya_kumari/rag-doctor").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 = { "startUrls": [{ "url": "https://docs.apify.com/platform" }] }

# Run the Actor and wait for it to finish
run = client.actor("sanya_kumari/rag-doctor").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 '{
  "startUrls": [
    {
      "url": "https://docs.apify.com/platform"
    }
  ]
}' |
apify call sanya_kumari/rag-doctor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,sanya_kumari/rag-doctor"
        }
    }
}

```

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/HhyAQdhVmCpGyEjWQ/builds/2MaGjaihex2sNiGDV/openapi.json
