A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
feat: add Reasoning RAG with live reasoning trace and grounded citations
Tiioluwani508da870c842
diff --git a/rag_apps/reasoning_rag/.env.example b/rag_apps/reasoning_rag/.env.examplenew file mode 100644index 0000000..5b0bd71--- /dev/null+++ b/rag_apps/reasoning_rag/.env.example@@ -0,0 +1,9 @@+# Orq.ai API key — used by the OpenAI SDK pointed at the Orq router+ORQ_API_KEY=your_orq_api_key_here++# Model slug on the Orq router, in provider/model format.+# Examples: alibaba/qwen3.6-flash, alibaba/qwen3.5-flash, openai/gpt-4o-mini+ORQ_MODEL=alibaba/qwen3.6-flash++# Mistral API key — used for Mistral Embed embeddings+MISTRAL_API_KEY=your_mistral_api_key_herediff --git a/rag_apps/reasoning_rag/README.md b/rag_apps/reasoning_rag/README.mdnew file mode 100644index 0000000..b581a2f--- /dev/null+++ b/rag_apps/reasoning_rag/README.md@@ -0,0 +1,137 @@+# Reasoning RAG++> Ask questions against any web source and get cited answers with a live, step-by-step reasoning trace.++## Overview++Reasoning RAG turns any URL into a queryable knowledge base and answers your questions with full transparency. It fetches and embeds the page into a vector store, retrieves the most relevant passages for each question, and reasons over them step by step. The Gradio interface shows the model's reasoning unfold live on the left while the grounded, citation-backed answer builds on the right.++## Demo++++## Features++- **One-paste ingestion**: drop in a URL and the app fetches, cleans, chunks, embeds, and indexes the content automatically.+- **Semantic retrieval**: finds the most relevant passages for every question using dense embeddings and cosine similarity.+- **Two-agent pipeline**: a Retriever agent sharpens the search query and a Reasoning agent works through the evidence.+- **Live reasoning trace**: watch the model think step by step as tokens stream in, side by side with the answer.+- **Grounded citations**: every answer is tied to numbered source passages with relevance scores and links back to the origin.+- **Persistent knowledge base**: ingested sources are stored in ChromaDB and remain available across sessions.+- **Configurable model**: swap the underlying LLM with a single environment variable, no code changes required.++## Tech Stack++Frameworks & Libraries:+- [Agno](https://github.com/agno-agi/agno): agent orchestration for the Retriever and Reasoning agents+- [OpenAI Python SDK](https://github.com/openai/openai-python): LLM client pointed at the Orq.ai router+- [mistralai](https://github.com/mistralai/client-python): Mistral Embed embeddings+- [chromadb](https://github.com/chroma-core/chroma): persistent vector storage and similarity search+- [requests](https://github.com/psf/requests) + [BeautifulSoup4](https://www.crummy.com/software/BeautifulSoup/): URL fetching and HTML cleaning+- [python-dotenv](https://github.com/theskumar/python-dotenv): environment configuration++Additional Tools:+- Vector Database: ChromaDB+- Embeddings: Mistral Embed (`mistral-embed`)+- Web Framework: Gradio++## Prerequisites++- Python 3.10 or higher+- API keys for:+ - Orq.ai (ORQ_API_KEY)+ - Mistral (MISTRAL_API_KEY)++## Installation++### 1. Clone the Repository++```bash+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/reasoning-rag+```++### 2. Create Virtual Environment (Recommended)++```bash+python -m venv venv+# Windows:+venv\Scripts\activate+# macOS/Linux:+source venv/bin/activate+```++### 3. Install Dependencies++```bash+pip install -r requirements.txt+```++### 4. Set Up Environment Variables++```bash+cp .env.example .env+```++Edit `.env` and set your API keys:++```env+ORQ_API_KEY=your_orq_api_key_here+MISTRAL_API_KEY=your_mistral_api_key_here+# Optional. Defaults to alibaba/qwen3.6-flash. Must be a provider/model slug.+ORQ_MODEL=alibaba/qwen3.6-flash+```++## Usage++### Running the Application++Start the app from the project directory:++```bash+python app.py+```++Gradio prints a local URL (by default `http://127.0.0.1:7860`). Open it in your browser, add one or more source URLs, then ask questions. The reasoning trace streams on the left and the cited answer appears on the right.++### Example Usage++| Step | Action | Result |+| ---- | ------ | ------ |+| 1 | Paste `https://en.wikipedia.org/wiki/Retrieval-augmented_generation` and click **Add source** | The page is fetched, chunked, embedded, and indexed; a confirmation shows the title and chunk count |+| 2 | Type *"What problem does retrieval-augmented generation solve?"* and click **Ask** | The Retriever pulls the top passages and the Reasoning agent begins streaming |+| 3 | Read the left panel | A step-by-step reasoning trace referencing sources as `[1]`, `[2]`, etc. |+| 4 | Read the right panel | A concise answer with inline citations and a list of source snippets |++### What the Agent Returns++For every question the app produces three coordinated outputs:++- **Reasoning trace**: the agent's step-by-step thinking: which sources are relevant, what each one says, and how they combine to form an answer.+- **Grounded answer**: a concise final response that draws only on the retrieved sources, with inline citations such as `[1]` and `[2]`. If the sources don't contain the answer, the agent says so instead of guessing.+- **Citations**: a numbered list of the exact passages used, each with its source title, link, relevance score, and a snippet.++## Project Structure++```+reasoning-rag/+├── app.py # Gradio UI with two parallel panels (reasoning trace + cited answer)+├── rag.py # URL ingestion, chunking, embedding, and ChromaDB storage/retrieval+├── agents.py # Agno Retriever and Reasoning agents (OpenAI SDK -> Orq.ai router)+├── requirements.txt # Python dependencies+├── .env.example # Environment variable template+├── .gitignore # Ignores .env, .venv/, __pycache__/, and the local vector store+├── README.md # This file+└── assets/ # Demo GIF and other media+```++## How It Works++1. **Ingestion** (`rag.py`): When you add a URL, the app fetches the page with `requests`, strips non-content elements (scripts, nav, footers) with BeautifulSoup, and normalizes the remaining text.+2. **Chunking**: The cleaned text is split into overlapping word windows (~220 words with ~40-word overlap) so that context is preserved across chunk boundaries.+3. **Embedding**: Each chunk is converted into a dense vector using Mistral Embed (`mistral-embed`), batched for efficiency.+4. **Storage**: Chunks, their embeddings, and metadata (source URL, title, chunk index) are written to a persistent ChromaDB collection configured for cosine similarity.+5. **Retrieval** (`agents.py`): When you ask a question, the **Retriever agent** rewrites it into a focused search query (expanding entities and synonyms). That query is embedded and used to pull the top-k most semantically relevant chunks from ChromaDB.+6. **Reasoning**: The retrieved passages are formatted into a numbered SOURCES block and handed to the **Reasoning agent**, which is instructed to think step by step and then write a grounded answer. It responds in two sections, `### REASONING` and `### ANSWER`, citing sources as `[1]`, `[2]`, etc.+7. **Streaming to the UI** (`app.py`): As the Reasoning agent streams tokens, the app splits the output at the `### ANSWER` marker and routes the parts to the two panels: reasoning on the left, the final cited answer on the right. The citation list is rendered from the exact chunks that were retrieved, so every claim is traceable back to its source.+diff --git a/rag_apps/reasoning_rag/agents.py b/rag_apps/reasoning_rag/agents.pynew file mode 100644index 0000000..bd1668f--- /dev/null+++ b/rag_apps/reasoning_rag/agents.py@@ -0,0 +1,195 @@+"""Agno agents for Reasoning RAG.++Two agents collaborate:++* **Retriever agent** — turns a user question into a focused search query and+ pulls the most semantically relevant chunks out of ChromaDB.+* **Reasoning agent** — works through the retrieved evidence step by step and+ produces a grounded, cited answer.++Both agents use the OpenAI SDK pointed at the Orq.ai router.+"""++from __future__ import annotations++import os+from typing import Iterator, List, Tuple++from agno.agent import Agent+from agno.models.openai import OpenAIChat+from dotenv import load_dotenv++import rag+from rag import RetrievedChunk++load_dotenv()++ORQ_API_KEY = os.getenv("ORQ_API_KEY")+ORQ_BASE_URL = "https://api.orq.ai/v3/router"+# Orq requires a `provider/model` slug. `qwen3-6b-flash` from the original spec+# is not a real Orq model; `alibaba/qwen3.6-flash` is the current Qwen "flash"+# model. Override via the ORQ_MODEL env var if your workspace enables another.+MODEL_ID = os.getenv("ORQ_MODEL", "alibaba/qwen3.6-flash")++ANSWER_MARKER = "### ANSWER"+REASONING_MARKER = "### REASONING"++_llm: OpenAIChat | None = None+_retriever_agent: Agent | None = None+_reasoning_agent: Agent | None = None+++def build_llm() -> OpenAIChat:+ """Build the shared LLM (OpenAI SDK -> Orq.ai router)."""+ global _llm+ if _llm is None:+ if not ORQ_API_KEY:+ raise RuntimeError("ORQ_API_KEY is not set. Add it to your .env file.")+ _llm = OpenAIChat(+ id=MODEL_ID,+ base_url=ORQ_BASE_URL,+ api_key=ORQ_API_KEY,+ )+ return _llm+++def get_retriever_agent() -> Agent:+ """The Retriever agent rewrites a question into a tight search query."""+ global _retriever_agent+ if _retriever_agent is None:+ _retriever_agent = Agent(+ name="Retriever",+ model=build_llm(),+ instructions=[+ "You are a retrieval specialist for a semantic search system.",+ "Given a user's question, produce the single best search query "+ "to find relevant passages in a vector database.",+ "Expand abbreviations and include key entities and synonyms.",+ "Respond with ONLY the search query text — no quotes, no labels, "+ "no explanation.",+ ],+ markdown=False,+ )+ return _retriever_agent+++def get_reasoning_agent() -> Agent:+ """The Reasoning agent thinks step by step and writes the cited answer."""+ global _reasoning_agent+ if _reasoning_agent is None:+ _reasoning_agent = Agent(+ name="Reasoning",+ model=build_llm(),+ instructions=[+ "You are a careful analyst that answers strictly from the "+ "provided SOURCES.",+ "Always respond in exactly two sections using these headers:",+ f"{REASONING_MARKER}",+ " - Think step by step. Walk through which sources are relevant, "+ "what they say, and how they combine to answer the question. "+ "Refer to sources as [1], [2], etc.",+ f"{ANSWER_MARKER}",+ " - Give a concise, well-structured final answer grounded only in "+ "the sources, with inline citations like [1] or [2].",+ "If the sources do not contain the answer, say so explicitly in the "+ "ANSWER section instead of guessing.",+ "Never invent citations for sources that were not provided.",+ ],+ markdown=True,+ )+ return _reasoning_agent+++def _agent_text(question: str, agent: Agent) -> str:+ """Run an agent once (no streaming) and return its text content."""+ response = agent.run(question)+ return (getattr(response, "content", "") or "").strip()+++def run_retriever(question: str, k: int = 5) -> List[RetrievedChunk]:+ """Refine the query with the Retriever agent, then pull chunks from ChromaDB."""+ refined = question+ try:+ candidate = _agent_text(question, get_retriever_agent())+ # Guard against a chatty model; keep it to a single line.+ candidate = candidate.splitlines()[0].strip() if candidate else ""+ if candidate:+ refined = candidate+ except Exception:+ # If query refinement fails, fall back to the raw question.+ refined = question++ chunks = rag.retrieve(refined, k=k)+ # Safety net: if the refined query returned nothing, retry with the original.+ if not chunks and refined != question:+ chunks = rag.retrieve(question, k=k)+ return chunks+++def build_sources_block(chunks: List[RetrievedChunk]) -> str:+ """Format retrieved chunks into a numbered SOURCES block for the prompt."""+ lines = []+ for i, chunk in enumerate(chunks, start=1):+ header = f"[{i}] {chunk.title or chunk.url}".strip()+ lines.append(f"{header}\n{chunk.text}")+ return "\n\n".join(lines)+++def build_prompt(question: str, chunks: List[RetrievedChunk]) -> str:+ """Assemble the full reasoning-agent prompt."""+ sources = build_sources_block(chunks)+ return (+ f"QUESTION:\n{question}\n\n"+ f"SOURCES:\n{sources}\n\n"+ "Answer the question using the format described in your instructions."+ )+++def split_trace(buffer: str) -> Tuple[str, str]:+ """Split a streamed buffer into (reasoning, answer) for the two panels."""+ text = buffer.replace("<think>", "").replace("</think>", "")++ answer = ""+ reasoning = text++ if ANSWER_MARKER in text:+ reasoning, answer = text.split(ANSWER_MARKER, 1)++ reasoning = reasoning.replace(REASONING_MARKER, "").strip()+ answer = answer.strip()+ return reasoning, answer+++def stream_answer(+ question: str, chunks: List[RetrievedChunk]+) -> Iterator[Tuple[str, str]]:+ """Stream the Reasoning agent, yielding (reasoning, answer) snapshots."""+ if not chunks:+ yield (+ "No knowledge has been indexed yet, so there is nothing to reason over.",+ "I don't have any sources to answer from. Please add a URL as a "+ "knowledge source first.",+ )+ return++ agent = get_reasoning_agent()+ prompt = build_prompt(question, chunks)++ buffer = ""+ streamed_any = False+ try:+ for event in agent.run(prompt, stream=True):+ delta = getattr(event, "content", None)+ if not delta:+ continue+ streamed_any = True+ buffer += delta+ yield split_trace(buffer)+ except TypeError:+ # Some Agno versions don't accept stream kwarg on run(); fall back.+ streamed_any = False++ if not streamed_any:+ response = agent.run(prompt)+ buffer = getattr(response, "content", "") or ""+ yield split_trace(buffer)diff --git a/rag_apps/reasoning_rag/app.py b/rag_apps/reasoning_rag/app.pynew file mode 100644index 0000000..c08b1b8--- /dev/null+++ b/rag_apps/reasoning_rag/app.py@@ -0,0 +1,190 @@+"""Reasoning RAG — Gradio UI.++Two parallel panels:+* Left — the live, step-by-step reasoning trace.+* Right — the grounded final answer with numbered citations.+"""++from __future__ import annotations++import os++import gradio as gr+from dotenv import load_dotenv++import rag+from agents import run_retriever, stream_answer+from rag import RetrievedChunk++load_dotenv()++TOP_K = 5++CUSTOM_CSS = """+#reasoning-panel, #answer-panel {+ min-height: 360px;+ border-radius: 12px;+ padding: 8px 16px;+}+#reasoning-panel { background: #0f172a0a; border: 1px solid #6366f133; }+#answer-panel { background: #05966908; border: 1px solid #05966933; }+.panel-title { font-weight: 700; font-size: 1.05rem; margin-bottom: 2px; }+footer { visibility: hidden; }+"""+++def _missing_keys() -> list[str]:+ missing = []+ if not os.getenv("ORQ_API_KEY"):+ missing.append("ORQ_API_KEY")+ if not os.getenv("MISTRAL_API_KEY"):+ missing.append("MISTRAL_API_KEY")+ return missing+++def add_source(url: str) -> str:+ """Ingest a URL into ChromaDB and report what happened."""+ if not url or not url.strip():+ return "Please paste a URL first."+ try:+ result = rag.ingest_url(url)+ except Exception as exc: # surfaced to the user in the UI+ return f"Could not ingest the URL: {exc}"++ stats = rag.collection_stats()+ return (+ f"Added **{result.title}**\n\n"+ f"- Source: {result.url}\n"+ f"- Chunks indexed: {result.num_chunks}\n"+ f"- Characters: {result.num_chars:,}\n"+ f"- Total chunks in knowledge base: {stats['count']}"+ )+++def clear_knowledge() -> str:+ """Wipe the knowledge base."""+ rag.reset_knowledge()+ return "Knowledge base cleared. Add a URL to start again."+++def format_citations(chunks: list[RetrievedChunk]) -> str:+ """Render retrieved chunks as a numbered citation list."""+ if not chunks:+ return "_No citations yet._"+ lines = ["### Citations"]+ for i, chunk in enumerate(chunks, start=1):+ snippet = chunk.text.strip().replace("\n", " ")+ if len(snippet) > 240:+ snippet = snippet[:240].rstrip() + "…"+ title = chunk.title or chunk.url or "source"+ link = f"[{title}]({chunk.url})" if chunk.url else title+ lines.append(+ f"**[{i}]** {link} \n"+ f"<sub>relevance {chunk.score}</sub> \n"+ f"> {snippet}"+ )+ return "\n\n".join(lines)+++def ask(question: str):+ """Retrieve, then stream reasoning + answer into the two panels."""+ question = (question or "").strip()+ if not question:+ yield "", "Please enter a question.", "_No citations yet._"+ return++ yield "Retrieving the most relevant passages…", "", "_No citations yet._"++ try:+ chunks = run_retriever(question, k=TOP_K)+ except Exception as exc:+ yield "", f"Retrieval failed: {exc}", "_No citations yet._"+ return++ citations = format_citations(chunks)++ if not chunks:+ yield (+ "No knowledge has been indexed yet.",+ "Please add a knowledge source URL above before asking a question.",+ "_No citations yet._",+ )+ return++ yield "Reasoning over the retrieved sources…", "", citations++ try:+ for reasoning, answer in stream_answer(question, chunks):+ yield (reasoning or "_Thinking…_", answer or "", citations)+ except Exception as exc:+ yield (f"Reasoning failed: {exc}", "", citations)+++def build_demo() -> gr.Blocks:+ with gr.Blocks(title="Reasoning RAG", theme=gr.themes.Soft(), css=CUSTOM_CSS) as demo:+ gr.Markdown(+ "# Reasoning RAG\n"+ "Answer questions from your own knowledge sources with a **visible "+ "reasoning trace** and **cited answers**."+ )++ missing = _missing_keys()+ if missing:+ gr.Markdown(+ f"> ⚠️ Missing environment variable(s): **{', '.join(missing)}**. "+ "Copy `.env.example` to `.env` and fill them in."+ )++ with gr.Group():+ gr.Markdown("### 1. Add a knowledge source")+ with gr.Row():+ url_input = gr.Textbox(+ label="Source URL",+ placeholder="https://en.wikipedia.org/wiki/Retrieval-augmented_generation",+ scale=4,+ )+ add_btn = gr.Button("Add source", variant="primary", scale=1)+ clear_btn = gr.Button("Clear", variant="secondary", scale=1)+ source_status = gr.Markdown()++ with gr.Group():+ gr.Markdown("### 2. Ask a question")+ with gr.Row():+ question_input = gr.Textbox(+ label="Your question",+ placeholder="What is retrieval-augmented generation?",+ scale=4,+ )+ ask_btn = gr.Button("Ask", variant="primary", scale=1)++ gr.Markdown("### 3. Reasoning & answer")+ with gr.Row():+ with gr.Column():+ gr.Markdown("<div class='panel-title'>🧠 Reasoning trace</div>")+ reasoning_panel = gr.Markdown(elem_id="reasoning-panel")+ with gr.Column():+ gr.Markdown("<div class='panel-title'>✅ Grounded answer</div>")+ answer_panel = gr.Markdown(elem_id="answer-panel")+ citations_panel = gr.Markdown()++ add_btn.click(add_source, inputs=url_input, outputs=source_status)+ url_input.submit(add_source, inputs=url_input, outputs=source_status)+ clear_btn.click(clear_knowledge, inputs=None, outputs=source_status)++ ask_outputs = [reasoning_panel, answer_panel, citations_panel]+ ask_btn.click(ask, inputs=question_input, outputs=ask_outputs)+ question_input.submit(ask, inputs=question_input, outputs=ask_outputs)++ gr.Examples(+ examples=[+ "What is the main idea described in the source?",+ "Summarize the key points with citations.",+ ],+ inputs=question_input,+ )++ return demo+++if __name__ == "__main__":+ build_demo().queue().launch()diff --git a/rag_apps/reasoning_rag/assets/demo.gif b/rag_apps/reasoning_rag/assets/demo.gifnew file mode 100644index 0000000..a87c2f7Binary files /dev/null and b/rag_apps/reasoning_rag/assets/demo.gif differdiff --git a/rag_apps/reasoning_rag/rag.py b/rag_apps/reasoning_rag/rag.pynew file mode 100644index 0000000..3a01b26--- /dev/null+++ b/rag_apps/reasoning_rag/rag.py@@ -0,0 +1,239 @@+"""URL ingestion, chunking, embedding (Mistral Embed) and ChromaDB storage.++This module is the knowledge layer for Reasoning RAG. It knows how to:++1. Fetch and clean text from a URL.+2. Split that text into overlapping chunks.+3. Embed the chunks with Mistral Embed.+4. Store / query them in a persistent ChromaDB collection.+"""++from __future__ import annotations++import os+import re+import uuid+from dataclasses import dataclass+from typing import List++import chromadb+import requests+from bs4 import BeautifulSoup+from dotenv import load_dotenv+try:+ # mistralai 1.x exposes the client at the top level.+ from mistralai import Mistral+except ImportError:+ # mistralai 2.x moved it into the `client` subpackage and dropped the+ # top-level re-export, so the old import path no longer resolves.+ from mistralai.client import Mistral++load_dotenv()++MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")+EMBED_MODEL = "mistral-embed"+CHROMA_PATH = os.getenv("CHROMA_PATH", "chroma_db")+COLLECTION_NAME = "reasoning_rag"++# Mistral Embed accepts batches; keep them modest to stay under request limits.+EMBED_BATCH_SIZE = 32+CHUNK_SIZE_WORDS = 220+CHUNK_OVERLAP_WORDS = 40++_mistral_client: Mistral | None = None+_chroma_client: chromadb.ClientAPI | None = None+++@dataclass+class IngestResult:+ """Summary returned after ingesting a URL."""++ url: str+ title: str+ num_chunks: int+ num_chars: int+++def _get_mistral() -> Mistral:+ """Lazily build the Mistral client so import never fails without a key."""+ global _mistral_client+ if _mistral_client is None:+ if not MISTRAL_API_KEY:+ raise RuntimeError(+ "MISTRAL_API_KEY is not set. Add it to your .env file."+ )+ _mistral_client = Mistral(api_key=MISTRAL_API_KEY)+ return _mistral_client+++def _get_collection():+ """Return the persistent ChromaDB collection, creating it if needed."""+ global _chroma_client+ if _chroma_client is None:+ _chroma_client = chromadb.PersistentClient(path=CHROMA_PATH)+ return _chroma_client.get_or_create_collection(+ name=COLLECTION_NAME,+ metadata={"hnsw:space": "cosine"},+ )+++def embed_texts(texts: List[str]) -> List[List[float]]:+ """Embed a list of texts with Mistral Embed, batching the requests."""+ client = _get_mistral()+ vectors: List[List[float]] = []+ for start in range(0, len(texts), EMBED_BATCH_SIZE):+ batch = texts[start : start + EMBED_BATCH_SIZE]+ response = client.embeddings.create(model=EMBED_MODEL, inputs=batch)+ vectors.extend(item.embedding for item in response.data)+ return vectors+++def fetch_url(url: str) -> tuple[str, str]:+ """Fetch a URL and return (title, cleaned_text)."""+ headers = {+ "User-Agent": (+ "Mozilla/5.0 (compatible; ReasoningRAG/1.0; +https://example.com/bot)"+ )+ }+ response = requests.get(url, headers=headers, timeout=30)+ response.raise_for_status()++ soup = BeautifulSoup(response.text, "lxml")++ # Drop elements that never carry useful reading content.+ for tag in soup(["script", "style", "noscript", "header", "footer", "nav", "aside"]):+ tag.decompose()++ title = soup.title.get_text(strip=True) if soup.title else url++ text = soup.get_text(separator="\n")+ # Collapse runs of blank lines / whitespace.+ text = re.sub(r"\n\s*\n+", "\n\n", text)+ text = re.sub(r"[ \t]+", " ", text).strip()++ if not text:+ raise ValueError("No readable text could be extracted from the URL.")++ return title, text+++def chunk_text(+ text: str,+ chunk_size: int = CHUNK_SIZE_WORDS,+ overlap: int = CHUNK_OVERLAP_WORDS,+) -> List[str]:+ """Split text into overlapping word windows."""+ words = text.split()+ if not words:+ return []++ step = max(1, chunk_size - overlap)+ chunks: List[str] = []+ for start in range(0, len(words), step):+ window = words[start : start + chunk_size]+ if window:+ chunks.append(" ".join(window))+ if start + chunk_size >= len(words):+ break+ return chunks+++def ingest_url(url: str) -> IngestResult:+ """Run the full pipeline: fetch -> chunk -> embed -> store in ChromaDB."""+ url = url.strip()+ if not url:+ raise ValueError("Please provide a URL.")+ if not url.startswith(("http://", "https://")):+ url = "https://" + url++ title, text = fetch_url(url)+ chunks = chunk_text(text)+ if not chunks:+ raise ValueError("The page produced no chunks to index.")++ embeddings = embed_texts(chunks)++ collection = _get_collection()+ source_id = uuid.uuid4().hex[:8]+ ids = [f"{source_id}-{i}" for i in range(len(chunks))]+ metadatas = [+ {"url": url, "title": title, "chunk_index": i} for i in range(len(chunks))+ ]++ collection.add(+ ids=ids,+ documents=chunks,+ embeddings=embeddings,+ metadatas=metadatas,+ )++ return IngestResult(+ url=url,+ title=title,+ num_chunks=len(chunks),+ num_chars=len(text),+ )+++@dataclass+class RetrievedChunk:+ """A single retrieved passage with its provenance."""++ text: str+ url: str+ title: str+ score: float+++def retrieve(query: str, k: int = 5) -> List[RetrievedChunk]:+ """Return the top-k most semantically relevant chunks for a query."""+ query = query.strip()+ if not query:+ return []++ collection = _get_collection()+ if collection.count() == 0:+ return []++ query_embedding = embed_texts([query])[0]+ results = collection.query(+ query_embeddings=[query_embedding],+ n_results=min(k, collection.count()),+ include=["documents", "metadatas", "distances"],+ )++ documents = results.get("documents", [[]])[0]+ metadatas = results.get("metadatas", [[]])[0]+ distances = results.get("distances", [[]])[0]++ retrieved: List[RetrievedChunk] = []+ for doc, meta, dist in zip(documents, metadatas, distances):+ meta = meta or {}+ retrieved.append(+ RetrievedChunk(+ text=doc,+ url=meta.get("url", ""),+ title=meta.get("title", ""),+ # Cosine distance -> similarity score for display.+ score=round(1.0 - float(dist), 4),+ )+ )+ return retrieved+++def collection_stats() -> dict:+ """Return basic stats about what is currently indexed."""+ collection = _get_collection()+ return {"count": collection.count()}+++def reset_knowledge() -> None:+ """Drop all indexed content (used by the UI 'clear' control)."""+ global _chroma_client+ if _chroma_client is None:+ _chroma_client = chromadb.PersistentClient(path=CHROMA_PATH)+ try:+ _chroma_client.delete_collection(COLLECTION_NAME)+ except Exception:+ # Collection may not exist yet; that's fine.+ passdiff --git a/rag_apps/reasoning_rag/requirements.txt b/rag_apps/reasoning_rag/requirements.txtnew file mode 100644index 0000000..5e8411e--- /dev/null+++ b/rag_apps/reasoning_rag/requirements.txt@@ -0,0 +1,20 @@+# Core orchestration+agno++# LLM access (OpenAI SDK pointed at Orq.ai router)+openai++# Embeddings+mistralai++# Vector database+chromadb++# UI+gradio++# URL fetching, parsing & utilities+requests+beautifulsoup4+lxml+python-dotenv