Skip to content
المشاريع

حول

Open-source RAG engine for ingesting, indexing, and querying unstructured documents

الذكاء الاصطناعي وتعلّم الآلة

كيف تُقاس هذه الأرقام

النمو المقاس للنجوم

خلال 24 ساعة
٠
خلال 7 أيام
٠
خلال 15 يومًا
٠
خلال شهر
جارٍ جمع السجل

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

ChatVector

Open-Source Backend-First RAG Engine for Document Intelligence

ChatVector is an open-source Retrieval-Augmented Generation (RAG) engine for ingesting, indexing, and querying unstructured documents: PDF, plain text, Markdown, HTML, and DOCX.

Think of it as an engine developers can use to build document-aware applications — such as research assistants, contract analysis tools, or internal knowledge systems — without having to reinvent the RAG pipeline.

Status PRs Welcome AI RAG CI

Python Version FastAPI Version


Star the repo to follow progress and support the project!

GitHub stars


Quick Links

Documentation Good First Issues Roadmap Quick Setup Project Board Dev Notes Deployment Architecture License: MIT Contributing Docs Contributing Video Discussions


Table of Contents


What is ChatVector?

ChatVector provides a clean, extensible backend foundation for RAG-based document intelligence. It handles the full lifecycle of document Q&A:

  • Document ingestion (PDF, plain text, Markdown, HTML, DOCX) with configurable chunking
  • Session-aware retrieval by default, without rewriting every standalone question
  • Optional per-request retrieval controls: hybrid search, reranking, metadata filters, and named presets
  • Text extraction, cleaning, and semantic chunking
  • Vector embedding and storage via pgvector
  • LLM-powered answer generation with cited responses
  • Background ingestion with retries, job status, optional webhooks, and durable artifacts
  • Python and TypeScript SDKs for server-side integration

The goal is to offer a developer-focused RAG engine you can deploy as a service and integrate via HTTP — not a polished end-user SaaS, and not a framework you have to assemble yourself.


ChatVector vs Frameworks

ChatVector is designed as a production-ready backend service, not a general-purpose framework. Here's how it compares:

Aspect ChatVector (This Project) General AI Framework (e.g., LangChain)
Primary Goal Deliver a deployable backend service for document intelligence. Provide modular components to build a wide variety of AI applications.
Out-of-the-Box Experience A fully functional FastAPI service with logging, testing, rate limiting, and a clean API. A collection of tools and abstractions you must wire together and productionize.
Architecture Batteries-included, opinionated engine. Get a working system for one use case. Modular building blocks. Assemble and customize components for many use cases.
Best For Developers, startups, or teams who need a document Q&A API now and want to focus on their application layer. Developers and researchers building novel, complex AI agents or exploring multiple LLM patterns from the ground up.
Path to Production Short. Configure, deploy, and integrate via API. Built-in observability, rate limiting, and scaling patterns. Long. Requires significant additional work on API layers, monitoring, deployment, and performance tuning.

Who is this for?

ChatVector is designed for:

  • Developers building document intelligence tools or internal knowledge systems
  • Backend engineers who want a solid RAG foundation without heavy abstractions
  • AI/ML practitioners experimenting with chunking, retrieval, and prompt strategies
  • Open-source contributors interested in retrieval systems, embeddings, and LLM orchestration

Current Status

Current product

ChatVector is a backend-first RAG engine with strong defaults. History-aware sessions, vector retrieval, and cited answers work without extra configuration. Hybrid search, reranking, query rewrite/expand/step-back, metadata filters, named presets, the embedding cache, webhooks, and experimental GraphRAG stay off until you turn them on.

Ingestion and documents

  • PDF, plain text, Markdown, HTML, and DOCX, with a pluggable extractor registry
  • Flat document metadata and exact-match / in retrieval filters, scoped to the tenant
  • In-place replacement (replace_document_id) that keeps the last good content retrievable until cutover; this is not historical versioning
  • Job status over HTTP and SSE, including non-terminal retrying until retries are exhausted
  • Optional HMAC webhooks for terminal ingestion.completed and ingestion.failed only
  • Local artifact spill by default; S3-compatible storage when API hosts do not share a disk
  • Idempotency keys on POST /upload and POST /sessions (no automatic SDK POST retries)

Retrieval and chat

  • Session-scoped retrieval by default, or tenant-wide scope
  • Separate retrieval-history and generation-history windows
  • Gated follow-up resolution: ambiguous follow-ups use prior turns; standalone questions and topic switches do not spend an extra LLM call
  • Optional hybrid retrieval, similarity or Cohere reranking (hosted failures fall back to retrieval order), and rewrite / expand / step-back
  • Named presets loaded from a file or env at startup; a preset is an alias for the same retrieval config, not a separate system
  • debug_retrieval for effective config, queries, history decisions, timings, and component scores
  • Retrieval evaluation CLI (python -m backend.cli eval) over the real retrieval path; it does not generate answers and bypasses the embedding cache unless you opt in

Platform

  • PostgreSQL/pgvector via SQLAlchemy; pluggable LLM and embedding providers
  • Bearer API keys and tenant isolation in production; auth bypass only in development/test
  • One API process per container by default; multiple API containers are supported with Redis, S3 artifacts, and MULTI_API_INSTANCE=true
  • Python and TypeScript SDKs for server-side upload, chat, streaming, sessions, bulk ingest, replacement, feedback, and retrieval config
  • React helpers in sdk/typescript/examples/next-proxy call your own proxy; the API key stays on the server

GraphRAG (ENABLE_GRAPH_RETRIEVAL) is experimental and default-off. It does not change retrieval unless enabled, and it is not the production retrieval architecture. See backend/rfcs/graph-retrieval.md.

Feedback (POST /feedback) records tenant-scoped signals. It does not retune retrieval.

See documentation/content/getting-started.md for a first run and documentation/content/api-reference.md for request shapes.

Frontend Demo

  • Document upload with live pipeline stage display and ingestion SSE progress
  • RAG chat with /chat/stream SSE (fallback to POST /chat when streaming is disabled)
  • Source citations, retrieval controls, and retrieval inspector
  • Batch compare and synthesize demos (document list from GET /documents)
  • Live system status page
  • Structured API error display and grouped Demo/Docs navigation
  • Postgres-backed session sidebar with dark/light theme

Architecture Overview

Backend Layer (Core)

  • FastAPI — modern Python API framework
  • Uvicorn — high-performance ASGI server
  • slowapi — per-tenant rate limiting
  • Design goals: clarity, extensibility, resilience, and security by default

AI & Retrieval Layer

  • Pluggable providers — Gemini, OpenAI, Ollama, Anthropic Claude (LLM), and Voyage AI (embeddings); mix and match independently
  • Hybrid retrieval — optional vector + PostgreSQL full-text fusion (off by default)
  • Reranking — optional in-process similarity reranker or Cohere (off by default)
  • Retrieval scopes — session-scoped (default) or tenant-wide search
  • Configurable chunking — fixed, paragraph, or semantic strategies
  • Query transformations — optional rewrite, expand, or step-back; history resolution is separate and gated
  • Response personas — default, concise, conversational, academic, technical

Data Layer

  • PostgreSQL + pgvector — vector similarity search via SQLAlchemy in all environments
  • DATABASE_URL controls the target database — local Docker, Neon, RDS, Cloud SQL, Supabase Postgres, etc.
  • Strategy pattern — DB operations isolated behind a factory; business logic is database-agnostic

Reference Frontend (Non-Core)

  • Next.js + TypeScript
  • Full end-to-end demo — upload, ingest, chat, citations
  • Not production-ready — exists to demonstrate and test backend capabilities

See ARCHITECTURE.md for full system design details.


Quick Start

After installing Docker and Node.js, start the complete ChatVector development environment with one command.

Prerequisites

  • Docker with Docker Compose (docker compose)
  • Node.js and npm
  • Either:
    • an API key for a supported hosted provider (Gemini or OpenAI), or
    • a local Ollama installation

Gemini is the recommended default and the simplest guided setup.

One-command setup

make quickstart

The command creates the env file, pauses while you add provider credentials, then continues after you press Enter. It installs frontend dependencies, builds the backend Docker image, starts backend services and the non-containerized frontend demo, waits for both to become ready, and opens the frontend and API docs when supported.

Setup is safe to rerun — existing backend/.env and frontend-demo/.env.local files are never overwritten.

If provider configuration is already complete, make quickstart continues immediately without pausing.

Provider configuration

Edit backend/.env to choose providers and set credentials. Gemini is the recommended default:

LLM_PROVIDER=gemini
EMBEDDING_PROVIDER=gemini
GEN_AI_KEY=your_google_ai_studio_api_key

Supported combinations include Gemini, OpenAI, Ollama, Anthropic Claude (generation), and Voyage AI (embeddings), including mixed setups (for example Claude + Voyage). See backend/.env.example for all variables.

Ollama with Docker

make quickstart and docker compose run the API in a container while Ollama usually runs on your host. Set:

LLM_PROVIDER=ollama
EMBEDDING_PROVIDER=ollama
OLLAMA_BASE_URL=http://host.docker.internal:11434

Inside the container, localhost is the container itself, not your machine — http://localhost:11434 is refused. host.docker.internal reaches Ollama on the host. On Linux, Compose maps that hostname through extra_hosts: host.docker.internal:host-gateway on the api service (already in docker-compose.yml).

Default models when LLM_MODEL and EMBEDDING_MODEL are unset: llama3 (generation) and nomic-embed-text (embeddings). Pull them on the host before ingesting:

ollama pull llama3
ollama pull nomic-embed-text

Or set LLM_MODEL and EMBEDDING_MODEL to models you already have installed.

Startup logs Provider configuration validated, but Ollama has no credentials to check — startup does not verify reachability or installed models. A wrong URL often appears at ingestion as provider_unreachable; a missing or incompatible model can surface on chat as a soft llm_unexpected error.

If you run the API outside Docker (native Python on the host), use OLLAMA_BASE_URL=http://localhost:11434.

URLs

Alternative non-interactive flow

make setup
# edit backend/.env
make
  • make setup — create env files, install dependencies, and build Docker images (prints editing instructions if configuration is incomplete; does not wait)
  • make — start backend and frontend, then open browser tabs

Returning contributors

Returning contributors normally use:

make

Start without browser tabs

make dev

Useful for SSH sessions, CI, or when you prefer to open URLs yourself.

Useful commands

Command Purpose
make quickstart Create env, pause for credentials, then start everything
make setup Create env files, install dependencies, and build Docker images
make Start backend + frontend, open browser tabs (default)
make dev Start backend + frontend without opening tabs
make backend Start only the backend Docker stack
make frontend Start only the frontend demo
make open Open the frontend and API docs URLs
make stop Stop this repo's frontend process and Docker services
make help Show all Make commands

Notes:

  • Setup is safe to rerun and preserves existing env files.
  • Provider credentials are edited in backend/.env — the setup scripts do not prompt for or read API keys in the terminal.
  • Press Ctrl+C while make, make dev, or make quickstart is running to stop the frontend; backend containers keep running until you run make stop.
  • The frontend demo is a non-core, non-containerized reference UI for testing the backend.

Try the API

  1. POST /upload — upload a PDF, get a document_id and status_endpoint
  2. GET /documents/{document_id}/status — poll ingestion stage and progress
  3. GET /documents — list document summaries for the authenticated tenant
  4. POST /chat or POST /chat/stream — ask questions using the document_id

Extra Docker Commands

Command Purpose
docker compose up Start containers without rebuilding
docker compose down Stop containers, preserve data
docker compose down -v Stop containers and delete all DB data
docker compose up --build Rebuild containers after code changes
docker compose logs -f api Follow API logs in real time
docker compose exec db psql -U postgres Connect to Postgres directly

Or use the Makefile shortcuts above — run make help for the full list.


Manual setup (alternative)

If you prefer not to use Make, copy backend/.env.example to backend/.env and configure your providers. Gemini is the simplest default:

LLM_PROVIDER=gemini
EMBEDDING_PROVIDER=gemini
GEN_AI_KEY=your_key_here

See backend/.env.example for OpenAI, Ollama, Anthropic Claude, Voyage AI, and mixed-provider configurations. Then:

docker compose up --build

cd frontend-demo
npm ci
echo "NEXT_PUBLIC_API_URL=http://localhost:8000" > .env.local
npm run dev

Frontend runs at http://localhost:3000


Python SDK

A synchronous Python client covers upload, status polling, non-streaming and streaming chat, batch chat, session management, and retrieval scope options. A Node.js/TypeScript SDK (@chatvector/sdk) is also available under sdk/typescript/.

pip install ./sdk/python
from chatvector import ChatVectorClient

with ChatVectorClient("http://localhost:8000", api_key="cv_live_...") as client:
    doc = client.upload_document("report.pdf")
    client.wait_for_ready(doc.document_id, timeout=90)

    session = client.create_session()
    answer = client.chat(
        "What are the key findings?",
        doc.document_id,
        session_id=session.id,
        scope="session",
    )
    print(answer.answer, answer.latency_ms, answer.model)
    for source in answer.sources:
        print(source.file_name, source.page_number, source.score, source.score_type)

    for event in client.stream_chat("Summarize in one paragraph.", doc.document_id, session_id=session.id):
        if event.type == "token":
            print(event.content, end="")
        elif event.type == "complete":
            print(event.latency_ms, event.model, len(event.sources))

In development (APP_ENV=development), the api_key parameter can be omitted — the backend bypasses authentication and attributes requests to DEV_TENANT_ID.

See sdk/python/README.md for authentication, error handling, runnable examples, and the FastAPI proxy example.

TypeScript SDK

The Node.js/TypeScript client is published on npm as @chatvector/sdk:

npm install @chatvector/sdk
import { ChatVectorClient } from "@chatvector/sdk";

const client = new ChatVectorClient({
  baseUrl: process.env.CHATVECTOR_BASE_URL!,
  apiKey: process.env.CHATVECTOR_API_KEY!,
});

const uploaded = await client.uploadDocument({ path: "./report.pdf" });
await client.waitForReady(uploaded.documentId, { timeoutMs: 90_000 });

const session = await client.createSession();
const answer = await client.chat({
  question: "What are the key findings?",
  docId: uploaded.documentId,
  sessionId: session.id,
  scope: "session",
});
console.log(answer.answer);

See sdk/typescript/README.md for streaming chat, error handling, and the Fastify proxy example. Maintainers: see sdk/typescript/RELEASING.md for publish steps.


Contributing

High-impact contribution areas:

  • Ingestion & indexing pipelines
  • Retrieval quality & evaluation
  • Chunking and query transformation strategies
  • API design & refactoring
  • Performance & scaling
  • Security hardening
  • SDK development
  • Documentation & examples

Frontend contributions are welcome but considered non-core.

Pick an open issue and start working — no permission or assignment needed. See CONTRIBUTING.md for details and Good First Issues to get started.


License

License: MIT

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…