Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

feat: add Documentation QnA Agent using Fetch MCP and DeepSeek V4 Flash on NVIDIA NIM

Tiioluwani0f406b7f7867
diff --git a/ai_agents/documentation_qna_agent/.env.example b/ai_agents/documentation_qna_agent/.env.example
new file mode 100644
index 0000000..de4da52
--- /dev/null
+++ b/ai_agents/documentation_qna_agent/.env.example
@@ -0,0 +1,4 @@
+NVIDIA_API_KEY=your_nvidia_api_key_here
+NVIDIA_MODEL=deepseek-ai/deepseek-v4-flash
+# Set to 1 if a documentation site blocks autonomous fetchers via robots.txt
+# FETCH_IGNORE_ROBOTS=0
diff --git a/ai_agents/documentation_qna_agent/README.md b/ai_agents/documentation_qna_agent/README.md
new file mode 100644
index 0000000..b4f4eb2
--- /dev/null
+++ b/ai_agents/documentation_qna_agent/README.md
@@ -0,0 +1,123 @@
+# Documentation QnA Agent
+
+> Chat with any documentation by URL using Fetch MCP and DeepSeek V4 Flash on NVIDIA NIM.
+
+## Overview
+
+Documentation QnA Agent is a Streamlit application that lets you load documentation from any public URL and ask questions about it in natural language. The Fetch MCP server retrieves page content, a summary is generated automatically, and DeepSeek V4 Flash answers follow-up questions grounded in the fetched material. Conversation history is preserved for the duration of the session.
+
+## Demo
+
+![Demo](assets/demo.png)
+
+## Features
+
+- Load documentation from any HTTP or HTTPS URL
+- Fetch and navigate content via the Fetch MCP server
+- Automatic documentation summary on load
+- Chat interface for follow-up questions
+- Answers grounded in fetched documentation content
+- Session-based conversation history across multiple questions
+- Graceful handling of invalid URLs and fetch errors
+
+## Tech Stack
+
+| Layer | Technology |
+|-------|------------|
+| Agent Orchestration | LangChain + langchain-mcp-adapters |
+| LLM | DeepSeek V4 Flash (`deepseek-ai/deepseek-v4-flash`) via NVIDIA NIM |
+| Documentation Access | Fetch MCP Server (`mcp-server-fetch`) |
+| UI | Streamlit |
+| API Base URL | `https://integrate.api.nvidia.com/v1` |
+
+## Prerequisites
+
+- Python 3.10 or later
+- An [NVIDIA API key](https://build.nvidia.com) (free, no credit card required)
+- Git
+
+## Installation
+
+Clone the repository and navigate to the project directory:
+
+```bash
+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git
+cd Hands-On-AI-Engineering/ai_agents/documentation_qna_agent
+```
+
+Create and activate a virtual environment.
+
+**Windows (PowerShell):**
+
+```bash
+py -m venv .venv
+.\.venv\Scripts\Activate.ps1
+```
+
+**macOS / Linux:**
+
+```bash
+python3 -m venv .venv
+source .venv/bin/activate
+```
+
+Install dependencies and configure environment variables:
+
+```bash
+pip install -r requirements.txt
+copy .env.example .env
+```
+
+On macOS / Linux, use `cp .env.example .env` instead of `copy`.
+
+Edit `.env` and set your `NVIDIA_API_KEY`.
+
+## Usage
+
+Start the Streamlit app:
+
+```bash
+streamlit run app.py
+```
+
+Open the URL shown in the terminal (typically `http://localhost:8501`).
+
+1. Enter a documentation URL and click **Load**.
+2. Review the generated summary in the expander.
+3. Ask questions in the chat input at the bottom.
+
+**Example:**
+
+| Step | Input |
+|------|-------|
+| Documentation URL | `https://docs.python.org/3/` |
+| Question | What is the latest stable Python version covered in this documentation? |
+| Answer | Based on the fetched documentation, the site covers Python 3.14.5, which is listed as the current documentation release. |
+
+## Environment Variables
+
+| Variable | Required | Default | Description |
+|----------|----------|---------|-------------|
+| `NVIDIA_API_KEY` | Yes | — | API key from [build.nvidia.com](https://build.nvidia.com) (free, no credit card) |
+| `NVIDIA_MODEL` | No | `deepseek-ai/deepseek-v4-flash` | NVIDIA NIM model ID used for summarization and Q&A |
+| `FETCH_IGNORE_ROBOTS` | No | `0` | Set to `1` to bypass robots.txt restrictions for autonomous fetching |
+
+Copy `.env.example` to `.env` before running the app:
+
+```env
+NVIDIA_API_KEY=your_nvidia_api_key_here
+NVIDIA_MODEL=deepseek-ai/deepseek-v4-flash
+```
+
+## Project Structure
+
+```text
+documentation-qna-agent/
+├── app.py # Streamlit UI and session state
+├── agent_service.py # LangChain agent, MCP fetch, and NVIDIA NIM integration
+├── requirements.txt # Python dependencies
+├── .env.example # Environment variable template
+├── assets/
+│ └── demo.png # Application screenshot
+└── README.md
+```
diff --git a/ai_agents/documentation_qna_agent/agent_service.py b/ai_agents/documentation_qna_agent/agent_service.py
new file mode 100644
index 0000000..24cef61
--- /dev/null
+++ b/ai_agents/documentation_qna_agent/agent_service.py
@@ -0,0 +1,206 @@
+"""LangChain agent orchestration with Fetch MCP and NVIDIA NIM."""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+from typing import Any
+
+from dotenv import load_dotenv
+from langchain.agents import create_agent
+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
+from langchain_mcp_adapters.client import MultiServerMCPClient
+from langchain_openai import ChatOpenAI
+
+load_dotenv(override=True)
+
+NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
+MODEL_ID = os.getenv("NVIDIA_MODEL", "deepseek-ai/deepseek-v4-flash")
+print(f"Using NVIDIA model: {MODEL_ID}")
+
+SYSTEM_PROMPT = """You are a Documentation QnA Agent. You help users understand documentation
+using the fetched documentation content provided in the conversation.
+
+When answering questions:
+- Prefer the documentation content already provided in the conversation.
+- Use the fetch tool only when you need additional pages or sections from the
+ same documentation site. Always pass the exact documentation URL given by the
+ user — never invent or modify URLs.
+- For long pages, use start_index to read additional sections in chunks.
+- Base your answers only on the fetched documentation content.
+- If the information is not in the documentation, say so clearly.
+- Be concise, accurate, and helpful.
+"""
+
+TRUNCATION_RE = re.compile(r"start_index of (\d+)")
+
+
+def get_llm() -> ChatOpenAI:
+ api_key = os.getenv("NVIDIA_API_KEY")
+ if not api_key:
+ raise ValueError(
+ "NVIDIA_API_KEY is not set. Add it to your .env file."
+ )
+ return ChatOpenAI(
+ model=MODEL_ID,
+ base_url=NVIDIA_BASE_URL,
+ api_key=api_key,
+ temperature=0.2,
+ )
+
+
+def get_mcp_config() -> dict[str, dict[str, Any]]:
+ args = ["-m", "mcp_server_fetch"]
+ if os.getenv("FETCH_IGNORE_ROBOTS", "").lower() in {"1", "true", "yes"}:
+ args.append("--ignore-robots-txt")
+
+ return {
+ "fetch": {
+ "transport": "stdio",
+ "command": sys.executable,
+ "args": args,
+ "env": {**os.environ, "PYTHONIOENCODING": "utf-8"},
+ }
+ }
+
+
+async def get_fetch_tool():
+ client = MultiServerMCPClient(get_mcp_config())
+ tools = await client.get_tools()
+ for tool in tools:
+ if tool.name == "fetch":
+ return tool
+ raise RuntimeError("Fetch MCP server did not expose a 'fetch' tool.")
+
+
+def extract_tool_text(result: Any) -> str:
+ if isinstance(result, str):
+ return result
+ if isinstance(result, list):
+ parts: list[str] = []
+ for item in result:
+ if isinstance(item, dict) and item.get("type") == "text":
+ parts.append(str(item.get("text", "")))
+ else:
+ parts.append(str(item))
+ return "\n".join(part for part in parts if part)
+ if isinstance(result, dict) and result.get("type") == "text":
+ return str(result.get("text", ""))
+ return str(result)
+
+
+def next_start_index(text: str) -> int | None:
+ match = TRUNCATION_RE.search(text)
+ if not match:
+ return None
+ return int(match.group(1))
+
+
+async def fetch_page_content(url: str, max_chunks: int = 20) -> str:
+ """Fetch a URL directly through MCP using the exact user-provided URL."""
+ fetch_tool = await get_fetch_tool()
+ chunks: list[str] = []
+ start_index = 0
+
+ for _ in range(max_chunks):
+ result = await fetch_tool.ainvoke(
+ {
+ "url": url,
+ "start_index": start_index,
+ "max_length": 50000,
+ }
+ )
+ text = extract_tool_text(result)
+
+ if "Failed to fetch" in text and "status code 404" in text:
+ raise RuntimeError(
+ f"The documentation URL returned HTTP 404: {url}"
+ )
+ if "Failed to fetch" in text:
+ raise RuntimeError(text.strip())
+
+ chunks.append(text)
+ next_index = next_start_index(text)
+ if next_index is None:
+ break
+ start_index = next_index
+
+ return "\n\n".join(chunks)
+
+
+async def build_agent():
+ client = MultiServerMCPClient(get_mcp_config())
+ tools = await client.get_tools()
+ return create_agent(get_llm(), tools, system_prompt=SYSTEM_PROMPT)
+
+
+def to_langchain_messages(history: list[dict[str, str]]) -> list[BaseMessage]:
+ messages: list[BaseMessage] = []
+ for item in history:
+ if item["role"] == "user":
+ messages.append(HumanMessage(content=item["content"]))
+ elif item["role"] == "assistant":
+ messages.append(AIMessage(content=item["content"]))
+ return messages
+
+
+def extract_response(result: dict[str, Any]) -> str:
+ messages = result.get("messages", [])
+ if not messages:
+ return str(result)
+
+ last = messages[-1]
+ content = getattr(last, "content", last)
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts = []
+ for block in content:
+ if isinstance(block, dict) and block.get("type") == "text":
+ parts.append(block.get("text", ""))
+ elif isinstance(block, str):
+ parts.append(block)
+ return "\n".join(part for part in parts if part)
+ return str(content)
+
+
+async def summarize_documentation(url: str, content: str) -> str:
+ llm = get_llm()
+ prompt = (
+ f"The following content was fetched from {url}.\n\n"
+ f"{content[:12000]}\n\n"
+ "Provide a brief summary (3-5 sentences) of what this documentation "
+ "covers and confirm it was loaded successfully."
+ )
+ response = await llm.ainvoke([HumanMessage(content=prompt)])
+ return extract_response({"messages": [response]})
+
+
+async def fetch_documentation(url: str) -> tuple[str, str]:
+ """Fetch documentation via MCP, then summarize with the LLM."""
+ content = await fetch_page_content(url)
+ summary = await summarize_documentation(url, content)
+ return content, summary
+
+
+async def answer_question(
+ url: str,
+ question: str,
+ history: list[dict[str, str]],
+ doc_content: str,
+) -> str:
+ agent = await build_agent()
+ messages = to_langchain_messages(history)
+ messages.append(
+ HumanMessage(
+ content=(
+ f"Documentation URL (use this exact URL with the fetch tool if needed): "
+ f"{url}\n\n"
+ f"Fetched documentation content:\n{doc_content[:12000]}\n\n"
+ f"User question: {question}"
+ )
+ )
+ )
+ result = await agent.ainvoke({"messages": messages})
+ return extract_response(result)
diff --git a/ai_agents/documentation_qna_agent/app.py b/ai_agents/documentation_qna_agent/app.py
new file mode 100644
index 0000000..a8fa6f3
--- /dev/null
+++ b/ai_agents/documentation_qna_agent/app.py
@@ -0,0 +1,151 @@
+"""Documentation QnA Agent — Streamlit chat UI."""
+
+from __future__ import annotations
+
+import asyncio
+from urllib.parse import urlparse
+
+import streamlit as st
+from dotenv import load_dotenv
+
+from agent_service import answer_question, fetch_documentation
+
+load_dotenv()
+
+st.set_page_config(
+ page_title="Documentation QnA Agent",
+ page_icon="📚",
+ layout="wide",
+)
+
+
+def init_session_state() -> None:
+ defaults = {
+ "messages": [],
+ "doc_url": None,
+ "doc_loaded": False,
+ "doc_content": None,
+ "load_summary": None,
+ }
+ for key, value in defaults.items():
+ if key not in st.session_state:
+ st.session_state[key] = value
+
+
+def is_valid_url(url: str) -> bool:
+ try:
+ parsed = urlparse(url.strip())
+ return parsed.scheme in {"http", "https"} and bool(parsed.netloc)
+ except Exception:
+ return False
+
+
+def run_async(coro):
+ return asyncio.run(coro)
+
+
+def reset_conversation() -> None:
+ st.session_state.messages = []
+ st.session_state.doc_loaded = False
+ st.session_state.doc_content = None
+ st.session_state.load_summary = None
+
+
+def main() -> None:
+ init_session_state()
+
+ st.title("Documentation QnA Agent")
+ st.caption(
+ "Chat with any documentation by URL. Powered by Fetch MCP and DeepSeek V4 Flash."
+ )
+
+ with st.container():
+ col_input, col_button = st.columns([5, 1])
+ with col_input:
+ doc_url = st.text_input(
+ "Documentation URL",
+ placeholder="https://docs.example.com/getting-started",
+ label_visibility="collapsed",
+ )
+ with col_button:
+ load_clicked = st.button("Load", type="primary", use_container_width=True)
+
+ if load_clicked:
+ url = doc_url.strip()
+ if not is_valid_url(url):
+ st.error(
+ "Invalid URL. Enter a valid HTTP or HTTPS link, "
+ "for example https://docs.python.org/3/"
+ )
+ else:
+ if st.session_state.doc_url != url:
+ reset_conversation()
+ st.session_state.doc_url = url
+ with st.spinner("Fetching documentation..."):
+ try:
+ content, summary = run_async(fetch_documentation(url))
+ st.session_state.doc_loaded = True
+ st.session_state.doc_content = content
+ st.session_state.load_summary = summary
+ except Exception as exc:
+ st.session_state.doc_loaded = False
+ st.session_state.doc_content = None
+ st.session_state.load_summary = None
+ message = str(exc)
+ if "404 page not found" in message and "status code 404" not in message:
+ st.error(
+ "The NVIDIA NIM model endpoint returned 404. "
+ f"Check NVIDIA_MODEL in .env (current default: moonshotai/kimi-k2.5). "
+ f"Details: {exc}"
+ )
+ else:
+ st.error(f"Failed to fetch documentation: {exc}")
+
+ if st.session_state.doc_url and st.session_state.doc_loaded:
+ st.success(f"Loaded: {st.session_state.doc_url}")
+ if st.session_state.load_summary:
+ with st.expander("Documentation summary", expanded=False):
+ st.markdown(st.session_state.load_summary)
+ elif st.session_state.doc_url and not st.session_state.doc_loaded:
+ st.warning("Documentation is not loaded yet. Click Load to fetch it.")
+
+ for message in st.session_state.messages:
+ with st.chat_message(message["role"]):
+ st.markdown(message["content"])
+
+ if prompt := st.chat_input("Ask a question about the documentation..."):
+ if not st.session_state.doc_url:
+ st.warning("Enter and load a documentation URL before asking questions.")
+ return
+
+ if not st.session_state.doc_loaded:
+ st.warning("Load the documentation URL first.")
+ return
+
+ st.session_state.messages.append({"role": "user", "content": prompt})
+ with st.chat_message("user"):
+ st.markdown(prompt)
+
+ with st.chat_message("assistant"):
+ with st.spinner("Thinking..."):
+ try:
+ history = st.session_state.messages[:-1]
+ response = run_async(
+ answer_question(
+ st.session_state.doc_url,
+ prompt,
+ history,
+ st.session_state.doc_content or "",
+ )
+ )
+ except Exception as exc:
+ response = f"Sorry, I could not answer that question: {exc}"
+ st.markdown(response)
+
+ st.session_state.messages.append(
+ {"role": "assistant", "content": response}
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/documentation_qna_agent/assets/demo.png b/ai_agents/documentation_qna_agent/assets/demo.png
new file mode 100644
index 0000000..4c2137f
Binary files /dev/null and b/ai_agents/documentation_qna_agent/assets/demo.png differ
diff --git a/ai_agents/documentation_qna_agent/requirements.txt b/ai_agents/documentation_qna_agent/requirements.txt
new file mode 100644
index 0000000..4a5ed0c
--- /dev/null
+++ b/ai_agents/documentation_qna_agent/requirements.txt
@@ -0,0 +1,7 @@
+streamlit>=1.32.0
+langchain>=0.3.0
+langchain-openai>=0.3.0
+langchain-mcp-adapters>=0.1.0
+mcp-server-fetch>=2025.4.7
+python-dotenv>=1.0.0
+openai>=1.0.0