CoolFace
Apppublic

AnukulChandra/Mini-AI_Assistant

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
App README

title: Mini AI Assistant emoji: ๐Ÿค– colorFrom: indigo colorTo: purple sdk: docker app_port: 7860 pinned: false ---

Mini AI Assistant ๐Ÿค–

A lightweight RAG (Retrieval-Augmented Generation) API built with FastAPI. Upload documents, ask questions, and get answers powered by your preferred LLM โ€” all through a clean REST API.


Overview ๐Ÿ“‹

Mini AI Assistant lets you:

  • โ€”Upload PDF, TXT, and Markdown documents
  • โ€”Automatically chunk and index them into a FAISS vector store
  • โ€”Ask questions about the uploaded documents
  • โ€”Retrieve the most relevant chunks and generate answers via an LLM
  • โ€”Look up orders and products from local JSON files via smart tool routing
  • โ€”Keep conversation history across turns

Features โœจ

FeatureDescription
Document IngestionUpload .pdf, .txt, or .md files โ€” automatically validated, read, chunked, and indexed
Vector SearchFAISS-powered similarity search over document chunks
Multi-Provider LLMSwitch between OpenAI, Google Gemini, Hugging Face, and Groq via an environment variable
RAG PipelineRetrieves the most relevant context before generating answers
Tool RoutingDetects order IDs (ORD-1001) and product IDs (PRD-1001) in questions and returns structured JSON data
Conversation MemoryRemembers the last 10 question-answer pairs and includes them in context
Error HandlingGraceful error messages with proper HTTP status codes and logging

Architecture ๐Ÿ—๏ธ

mermaid
graph TD
    User -->|Question| Frontend
    Frontend -->|POST /chat/ask| FastAPI
    FastAPI --> Memory[Conversation Memory]

    Memory --> Intent[Intent Detection]
    Intent -->|Knowledge| FAISS[(FAISS Vector Store)]
    Intent -->|Order| Orders[(orders.json)]
    Intent -->|Product| Products[(products.json)]
    Intent -->|Direct| LLM[Groq LLM]

    FAISS --> Context[Retrieved Context + Memory + Tool Output]
    Orders --> Context
    Products --> Context
    Context --> Prompt[Prompt Builder]

    Prompt --> LLM
    LLM --> Response
    Response --> Frontend

Document ingestion flow: POST /upload/document โ†’ validate โ†’ read โ†’ splittext โ†’ createvector_store โ†’ save to disk.


AI Pipeline ๐Ÿง 

  1. 1.User uploads a document โ€” Upload a PDF, TXT, or Markdown file via the frontend.
  2. 2.Document validation โ€” The file extension and content are validated against allowed types.
  3. 3.Text extraction โ€” Text is extracted from PDFs using PyPDF or read directly from plain-text files.
  4. 4.Chunking โ€” Extracted text is split into overlapping chunks using RecursiveCharacterTextSplitter.
  5. 5.Embedding generation โ€” Each chunk is converted into a vector embedding using sentence-transformers/all-MiniLM-L6-v2.
  6. 6.FAISS indexing โ€” Embeddings are indexed in a FAISS vector store and persisted to disk.
  7. 7.User asks a question โ€” The question is submitted through the chat interface.
  8. 8.Load conversation memory โ€” Previous question-answer pairs are loaded from in-memory history.
  9. 9.Intent detection โ€” The system classifies the question as Knowledge, Order, Product, or Direct LLM.
  10. 10.Route to:
  11. 11.Knowledge Retrieval โ€” Perform similarity search over the FAISS index for relevant chunks.
  12. 12.Order Tool โ€” Look up order status from orders.json.
  13. 13.Product Tool โ€” Search product details in products.json.
  14. 14.Build prompt โ€” Retrieved context, tool output, and conversation history are assembled into a structured prompt.
  15. 15.Generate answer using Groq โ€” The prompt is sent to the Groq LLM (llama-3.3-70b-versatile) for response generation.
  16. 16.Return response โ€” The answer is sent back to the frontend and displayed to the user.

Prompt Design ๐Ÿ“

The system prompt instructs the assistant to answer only using the provided information. Conversation history is included when available so follow-up questions maintain context. Tool results (order status, product details) are injected directly into the response without querying the vector store.

  • โ€”Knowledge questions โ€” Retrieved document chunks are placed in the prompt as context. The assistant must answer from those chunks alone.
  • โ€”Memory questions โ€” Previous conversation turns are prepended so the assistant can reference past exchanges.
  • โ€”Tool queries โ€” The tool result is formatted into a natural-language answer and returned immediately without LLM generation.

If the answer cannot be found in the uploaded documents, the assistant replies:

"I couldn't find that information in the uploaded documents."

Screenshots ๐Ÿ“ธ

InterfacePreview
Home Interface![Home Interface](screenshots/home.png)
Upload Document![Upload Document](screenshots/upload.png)
Chat Example![Chat Example](screenshots/chat.png)
Order Tool![Order Tool](screenshots/order-tool.png)
Product Tool![Product Tool](screenshots/product-tool.png)

Project Structure ๐Ÿ“

Mini-Ai-Assistant/
โ”œโ”€โ”€ api/
โ”‚   โ”œโ”€โ”€ chat.py            # POST /chat/ask endpoint
โ”‚   โ””โ”€โ”€ upload.py          # POST /upload/document endpoint
โ”œโ”€โ”€ services/
โ”‚   โ”œโ”€โ”€ chunking.py        # Text splitting
โ”‚   โ”œโ”€โ”€ embeddings.py      # HuggingFace embedding model
โ”‚   โ”œโ”€โ”€ ingestion.py       # File validation & text extraction
โ”‚   โ”œโ”€โ”€ llm.py             # Multi-provider LLM dispatch
โ”‚   โ”œโ”€โ”€ memory.py          # In-memory conversation history
โ”‚   โ”œโ”€โ”€ prompt_builder.py  # RAG prompt construction
โ”‚   โ”œโ”€โ”€ retrieval.py       # FAISS vector search
โ”‚   โ”œโ”€โ”€ tools.py           # Order/product lookup tools
โ”‚   โ””โ”€โ”€ vector_store.py    # FAISS create/save/load
โ”œโ”€โ”€ data/
โ”‚   โ”œโ”€โ”€ orders.json        # Sample order data
โ”‚   โ”œโ”€โ”€ products.json      # Sample product data
โ”‚   โ””โ”€โ”€ vector_store/      # Persisted FAISS index
โ”œโ”€โ”€ main.py                # FastAPI entry point
โ”œโ”€โ”€ .env.example           # Environment template
โ”œโ”€โ”€ requirements.txt       # Python dependencies
โ””โ”€โ”€ README.md              # This file

Installation ๐Ÿ› ๏ธ

Prerequisites

  • โ€”Python 3.10+
  • โ€”pip

Steps

bash
# Clone the repository
git clone https://github.com/Anukul-Chandra/Mini-Ai-Assistant.git
cd Mini-Ai-Assistant

# Create and activate a virtual environment
python -m venv .venv
source .venv/bin/activate    # Linux/macOS
.venv\Scripts\activate       # Windows

# Install dependencies
pip install -r requirements.txt

Environment Variables ๐Ÿ”

Copy .env.example to .env and fill in your API keys:

bash
cp .env.example .env
VariableDescriptionDefault
LLM_PROVIDERActive LLM backendopenai, gemini, huggingface, or groq
OPENAI_API_KEYOpenAI API keyโ€”
GEMINI_API_KEYGoogle Gemini API keyโ€”
GROQ_API_KEYGroq API keyโ€”
HF_API_KEYHugging Face Inference API keyโ€”
HF_TOKENHugging Face token (for embedding model)โ€”
Set LLM_PROVIDER to your chosen backend. Only the corresponding API key is required โ€” the rest can be left blank.

Running the Project ๐Ÿš€

bash
uvicorn main:app --reload

The API will be available at http://localhost:8000.

Interactive API docs: http://localhost:8000/docs (Swagger UI)


API Endpoints ๐Ÿ“ก

GET /

Health check.

Response:

json
{
  "message": "Mini AI Assistant API is running"
}

POST /upload/document

Upload a document for indexing.

ParameterTypeDescription
filemultipart/form-dataPDF, TXT, or Markdown file

Response `200`:

json
{
  "filename": "report.pdf",
  "chunks": 12,
  "message": "Document processed and indexed successfully."
}

Response `400`: Invalid file type or unreadable document.


POST /chat/ask

Ask a question about your documents.

Request:

json
{
  "question": "What is this document about?"
}

Response `200` (RAG):

json
{
  "question": "What is this document about?",
  "answer": "The document discusses quarterly sales performance...",
  "retrieved_chunks": 3
}

Response `200` (Tool):

json
{
  "source": "tool",
  "answer": {
    "order_id": "ORD-1001",
    "status": "shipped",
    "total": 245.99
  }
}

Response `400`: No document uploaded or LLM configuration error.


Supported LLM Providers ๐Ÿง 

ProviderEnv ValueModelSDK
OpenAIopenaigpt-4o-miniopenai
Google Geminigeminigemini-2.0-flashgoogle-generativeai
Hugging Facehuggingfacemicrosoft/Phi-3.5-mini-instructhuggingface-hub
Groqgroqllama-3.3-70b-versatilegroq

Switch between them by changing the LLM_PROVIDER environment variable.


Example Requests ๐Ÿ’ป

Upload a document

bash
curl -X POST http://localhost:8000/upload/document \
  -F "file=@document.pdf"

Ask a question (RAG)

bash
curl -X POST http://localhost:8000/chat/ask \
  -H "Content-Type: application/json" \
  -d '{"question": "What are the key findings?"}'

Ask about an order (tool routing)

bash
curl -X POST http://localhost:8000/chat/ask \
  -H "Content-Type: application/json" \
  -d '{"question": "Show me order ORD-1001"}'

Example Responses ๐Ÿ“ค

RAG answer:

json
{
  "question": "What is the revenue for Q3?",
  "answer": "Based on the uploaded document, the revenue for Q3 was $1.2 million, representing a 15% increase over Q2.",
  "retrieved_chunks": 3
}

Tool lookup:

json
{
  "source": "tool",
  "answer": {
    "order_id": "ORD-1001",
    "customer": "John Doe",
    "status": "delivered",
    "items": ["Laptop", "Mouse"],
    "total": 1249.99
  }
}

Error:

json
{
  "detail": "No vector store found. Please upload a document first."
}

Technology Stack ๐Ÿ› ๏ธ

CategoryTechnology
FrameworkFastAPI
ServerUvicorn
Embeddingssentence-transformers (all-MiniLM-L6-v2)
Vector StoreFAISS (CPU)
PDF ParsingPyPDF
LLM SDKsOpenAI, Google Generative AI, Hugging Face Hub, Groq
Environmentpython-dotenv

Future Improvements ๐Ÿšง

  • โ€”[ ] Authentication and API key management
  • โ€”[ ] Persistent conversation storage (SQLite / PostgreSQL)
  • โ€”[ ] Multi-document upload and per-document scoping
  • โ€”[ ] Streaming responses via Server-Sent Events
  • โ€”[ ] Document deletion and re-indexing
  • โ€”[ ] Evaluation metrics for RAG quality (faithfulness, relevance)
  • โ€”[ ] Docker image for one-command deployment

License ๐Ÿ“„

This project is licensed under the MIT License.