Skip to content

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

modified customer_query_agent assets

cyberholics41452b32dae9
diff --cc OCR/image_to_structured_data/.env.example
index e6c1b53,95109a5..bcb47db
--- a/OCR/image_to_structured_data/.env.example
+++ b/OCR/image_to_structured_data/.env.example
@@@ -1,1 -1,3 +1,6 @@@
++<<<<<<< HEAD
++=======
+ # Mistral API key used for visual extraction with Mistral Large 3.
+ # Get one free at https://console.mistral.ai
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
MISTRAL_API_KEY=your_mistral_key_here
diff --cc OCR/image_to_structured_data/README.md
index 8e3da2e,db1961c..66ab0b4
--- a/OCR/image_to_structured_data/README.md
+++ b/OCR/image_to_structured_data/README.md
@@@ -2,6 -2,10 +2,13 @@@
A high-fidelity, visual extraction framework that converts images into validated, structured JSON using Mistral Large 3 and Pydantic.
++<<<<<<< HEAD
++=======
+ ## Demo
+
+ ![Demo](assets/demo.png)
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Overview
This project demonstrates how to move beyond raw text OCR to **Structured Visual Extraction**. Instead of getting a messy block of text, this tool uses the `instructor` library to force the VLM (Vision Language Model) to output data that fits a strict Pydantic schema.
@@@ -37,7 -41,7 +44,11 @@@ Before you begin, ensure you have
- Python 3.10 or higher (Recommended)
- API keys for:
++<<<<<<< HEAD
+ - [ ] [Mistral AI Console](https://console.mistral.ai/)
++=======
+ - [Mistral AI Console](https://console.mistral.ai/)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
- Basic understanding of Pydantic and Multimodal LLMs.
## Installation
diff --cc OCR/image_to_structured_data/app.py
index 43dd8b3,fbf0a9c..4fb1e5b
--- a/OCR/image_to_structured_data/app.py
+++ b/OCR/image_to_structured_data/app.py
@@@ -1,3 -1,8 +1,11 @@@
++<<<<<<< HEAD
++=======
+ """
+ Image-to-Structured-Data Extractor Streamlit app: upload an image and extract
+ validated, structured JSON from it using Mistral Large 3 and Instructor.
+ """
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import streamlit as st
from processor import extract_structured_data
from schemas import ProductCollection, InvoiceCollection
@@@ -11,11 -16,13 +19,21 @@@ st.set_page_config(page_title="Mistral
st.title("πŸ“Έ Image-to-Structured-Data")
st.write("Using **Mistral Large 3** for high-fidelity visual OCR and structured extraction.")
++<<<<<<< HEAD
+with st.sidebar:
+ # Use the MISTRAL_API_KEY from .env if available
+ api_key = st.text_input("Mistral API Key", value=os.getenv("MISTRAL_API_KEY", ""), type="password")
+ schema_choice = st.selectbox("Select Extraction Schema", ["Product", "Invoice"])
+
++=======
+ api_key = os.getenv("MISTRAL_API_KEY", "")
+
+ with st.sidebar:
+ if not api_key:
+ st.warning("MISTRAL_API_KEY is not set in your .env file.")
+ schema_choice = st.selectbox("Select Extraction Schema", ["Product", "Invoice"])
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# These names now match the updated import above
schema_map = {
"Product": ProductCollection,
diff --cc OCR/image_to_structured_data/processor.py
index 3786aaa,5eaf0bf..2fb336b
--- a/OCR/image_to_structured_data/processor.py
+++ b/OCR/image_to_structured_data/processor.py
@@@ -1,6 -1,6 +1,10 @@@
import base64
import instructor
++<<<<<<< HEAD
+from mistralai import Mistral
++=======
+ from mistralai.client import Mistral
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
from PIL import Image
import io
@@@ -17,6 -17,7 +21,10 @@@ def process_and_encode_image(image_file
return base64.b64encode(buffered.getvalue()).decode('utf-8')
def extract_structured_data(image_file, schema_model, api_key: str):
++<<<<<<< HEAD
++=======
+ """Send the image to Mistral Large 3 and return data validated against the given schema."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
client = instructor.from_mistral(Mistral(api_key=api_key))
base64_image = process_and_encode_image(image_file)
diff --cc OCR/image_to_structured_data/schemas.py
index 84f1f26,284298f..12db5de
--- a/OCR/image_to_structured_data/schemas.py
+++ b/OCR/image_to_structured_data/schemas.py
@@@ -2,10 -2,12 +2,18 @@@ from pydantic import BaseModel, Fiel
from typing import List, Optional
class ProductAttribute(BaseModel):
++<<<<<<< HEAD
++=======
+ """A single key-value attribute describing a product."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
key: str
value: str
class StructuredProduct(BaseModel):
++<<<<<<< HEAD
++=======
+ """A single product extracted from an image, with pricing and attributes."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
name: str
brand: Optional[str]
price: Optional[float]
@@@ -19,6 -21,7 +27,10 @@@ class ProductCollection(BaseModel)
products: List[StructuredProduct]
class InvoiceData(BaseModel):
++<<<<<<< HEAD
++=======
+ """A single invoice extracted from an image, with vendor, total, and line items."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
vendor_name: str
date: str
total_amount: float
diff --cc OCR/latex_formula_ocr/README.md
index eb198bf,43a3da1..5467786
--- a/OCR/latex_formula_ocr/README.md
+++ b/OCR/latex_formula_ocr/README.md
@@@ -1,23 -1,29 +1,52 @@@
++<<<<<<< HEAD
+# LaTeX Formula OCR β€” Extract and render math formulas from images using local AI
+
+## Overview
+
+Reading mathematical formulas from images or scanned documents is tedious and error-prone when done by hand. This tool solves that by running a vision-language model entirely on your machine β€” no cloud services, no API keys β€” to detect every equation in an uploaded image or PDF and instantly render it in a polished, browser-native display.
+
+It works by sending the image to **GLM-OCR** (served locally via Ollama), which returns raw LaTeX source for each detected formula. The app then parses those results and renders them visually using **KaTeX**, all within a Streamlit web interface.
+
+Students, researchers, engineers, and anyone who regularly works with mathematical documents will benefit from this tool β€” particularly when digitising textbooks, lecture slides, or handwritten notes.
+
+## Features
+
+- **Fully local inference** β€” GLM-OCR runs via Ollama; no API keys or internet access required for OCR
+- **Image and PDF support** β€” upload PNG, JPG/JPEG, or single-page PDFs (first page rendered automatically)
+- **Multi-formula extraction** β€” detects and extracts every equation in the image in one pass
+- **In-browser KaTeX rendering** β€” formulas are rendered in display mode with proper mathematical typesetting
+- **LaTeX source viewer** β€” each formula card shows the raw LaTeX alongside the rendered output
+- **One-click copy** β€” copy any formula's LaTeX source to the clipboard instantly
+- **Live Ollama status** β€” sidebar shows whether Ollama is running and whether glm-ocr is installed
+- **Auto image resizing** β€” large images are downscaled before inference to keep requests fast
++=======
+ # LaTeX Formula OCR
+
+ > Extract and render math formulas from images using local AI, powered by GLM-OCR and KaTeX.
+
+ ## Demo
+
+ ![Demo](assets/demo.gif)
+
+ ## Overview
+
+ Reading mathematical formulas from images or scanned documents is tedious and error-prone when done by hand. This tool solves that by running a vision-language model entirely on your machine, requiring no cloud services or API keys, to detect every equation in an uploaded image or PDF and instantly render it in a polished, browser-native display.
+
+ It works by sending the image to **GLM-OCR** (served locally via Ollama), which returns raw LaTeX source for each detected formula. The app then parses those results and renders them visually using **KaTeX**, all within a Streamlit web interface.
+
+ Students, researchers, engineers, and anyone who regularly works with mathematical documents will benefit from this tool, particularly when digitising textbooks, lecture slides, or handwritten notes.
+
+ ## Features
+
+ - **Fully local inference**: GLM-OCR runs via Ollama; no API keys or internet access required for OCR
+ - **Image and PDF support**: upload PNG, JPG/JPEG, or single-page PDFs (first page rendered automatically)
+ - **Multi-formula extraction**: detects and extracts every equation in the image in one pass
+ - **In-browser KaTeX rendering**: formulas are rendered in display mode with proper mathematical typesetting
+ - **LaTeX source viewer**: each formula card shows the raw LaTeX alongside the rendered output
+ - **One-click copy**: copy any formula's LaTeX source to the clipboard instantly
+ - **Live Ollama status**: sidebar shows whether Ollama is running and whether glm-ocr is installed
+ - **Auto image resizing**: large images are downscaled before inference to keep requests fast
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Tech Stack
@@@ -104,3 -110,7 +133,10 @@@ latex-formula-ocr
β”œβ”€β”€ requirements.txt # Python dependencies
└── README.md # Project documentation
```
++<<<<<<< HEAD
++=======
+
+ ---
+
+ [Back to top](#latex-formula-ocr)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc OCR/medical_prescription_digitizer/.env.example
index b263636,a430094..d17f3ad
--- a/OCR/medical_prescription_digitizer/.env.example
+++ b/OCR/medical_prescription_digitizer/.env.example
@@@ -1,1 -1,2 +1,5 @@@
++<<<<<<< HEAD
++=======
+ # Your Mistral API key. Get one for free at https://platform.mistral.ai
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
MISTRAL_API_KEY=your_mistral_api_key_here
diff --cc OCR/medical_prescription_digitizer/README.md
index dfe0cdd,ad992fe..6ac1d0f
--- a/OCR/medical_prescription_digitizer/README.md
+++ b/OCR/medical_prescription_digitizer/README.md
@@@ -2,9 -2,13 +2,19 @@@
> Extract, structure, and validate handwritten or printed prescriptions using Mistral Large 3 and RxNorm.
++<<<<<<< HEAD
+## Overview
+
+Upload a prescription image β€” handwritten or printed β€” and the app uses Mistral Large 3's vision capabilities to read and interpret it, including messy handwriting and medical abbreviations. Extracted drug names are then validated against the [RxNorm](https://rxnav.nlm.nih.gov/) drug database (free, no API key required). Validated drugs are highlighted in green; unrecognised or flagged ones appear in red.
++=======
+ ## Demo
+
+ ![Demo](assets/demo.gif)
+
+ ## Overview
+
+ Upload a prescription image (handwritten or printed) and the app uses Mistral Large 3's vision capabilities to read and interpret it, including messy handwriting and medical abbreviations. Extracted drug names are then validated against the [RxNorm](https://rxnav.nlm.nih.gov/) drug database (free, no API key required). Validated drugs are highlighted in green; unrecognised or flagged ones appear in red.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Features
@@@ -28,13 -32,13 +38,21 @@@
## Prerequisites
- Python 3.10 or higher
++<<<<<<< HEAD
+- A Mistral API key β€” get one at [platform.mistral.ai](https://platform.mistral.ai)
++=======
+ - A Mistral API key. Get one at [platform.mistral.ai](https://platform.mistral.ai)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Installation
```bash
git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git
++<<<<<<< HEAD
+cd Hands-On-AI-Engineering/ocr/medical-prescription-digitizer
++=======
+ cd Hands-On-AI-Engineering/OCR/medical_prescription_digitizer
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```
**Windows**
@@@ -74,9 -78,9 +92,15 @@@ Patient: John Smith Date: 04/1
Dr. Sarah Lee, MD
Rx:
++<<<<<<< HEAD
+1. Amoxicillin 500mg β€” TID x 7 days
+2. Ibuprofen 400mg β€” BID PRN pain
+3. [illegible] 10mg β€” QD
++=======
+ 1. Amoxicillin 500mg, TID x 7 days
+ 2. Ibuprofen 400mg, BID PRN pain
+ 3. [illegible] 10mg, QD
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```
**Structured output:**
@@@ -89,7 -93,7 +113,11 @@@ Date 04/18/202
Medications
βœ… Amoxicillin 500 mg Β· three times daily Β· 7 days [RxNorm ID: 723]
βœ… Ibuprofen 400 mg Β· twice daily Β· as needed [RxNorm ID: 5640]
++<<<<<<< HEAD
+⚠️ [illegible] 10 mg Β· once daily Drug name not found in RxNorm β€” possible misread
++=======
+ ⚠️ [illegible] 10 mg · once daily Drug name not found in RxNorm, possible misread
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
Illegible fields
β€’ Medication 3 drug name unclear
@@@ -105,10 -109,14 +133,21 @@@
```text
medical-prescription-digitizer/
++<<<<<<< HEAD
+β”œβ”€β”€ app.py # Streamlit UI β€” upload, display, and orchestration
++=======
+ β”œβ”€β”€ app.py # Streamlit UI: upload, display, and orchestration
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
β”œβ”€β”€ extractor.py # Sends image to Mistral Large 3 and returns a Prescription object
β”œβ”€β”€ schemas.py # Pydantic models: Prescription and Medication
β”œβ”€β”€ validator.py # Queries RxNorm API to validate each drug name
β”œβ”€β”€ requirements.txt # Python dependencies
└── .env.example # Environment variable template
```
++<<<<<<< HEAD
++=======
+
+ ---
+
+ [Back to top](#medical-prescription-digitizer)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc OCR/medical_prescription_digitizer/app.py
index 3ea3aea,d96cc39..3140bb1
--- a/OCR/medical_prescription_digitizer/app.py
+++ b/OCR/medical_prescription_digitizer/app.py
@@@ -1,3 -1,4 +1,7 @@@
++<<<<<<< HEAD
++=======
+ """Streamlit app that extracts and validates structured prescription data from uploaded images using Mistral Large 3 and RxNorm."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import os
import io
@@@ -43,16 -44,10 +47,23 @@@ st.caption("Upload a prescription imag
st.divider()
++<<<<<<< HEAD
+# ── Sidebar: API key ──────────────────────────────────────────────────────────
+with st.sidebar:
+ st.header("βš™οΈ Configuration")
+ api_key = st.text_input(
+ "Mistral API Key",
+ value=os.getenv("MISTRAL_API_KEY", ""),
+ type="password",
+ help="Your Mistral API key. Store it in .env as MISTRAL_API_KEY to avoid re-entering.",
+ )
+ st.markdown("---")
++=======
+ api_key = os.getenv("MISTRAL_API_KEY")
+
+ # ── Sidebar ───────────────────────────────────────────────────────────────────
+ with st.sidebar:
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
st.markdown("**How it works**")
st.markdown(
"1. Upload a prescription image\n"
@@@ -84,7 -79,7 +95,11 @@@ if uploaded_file
st.subheader("Extraction & Validation")
if not api_key:
++<<<<<<< HEAD
+ st.error("Please enter your Mistral API key in the sidebar to proceed.")
++=======
+ st.error("MISTRAL_API_KEY not found. Add it to your .env file and restart the app.")
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
st.stop()
if st.button("πŸ” Digitize Prescription", type="primary", use_container_width=True):
diff --cc ai_agents/agent_discovery_agent/.env.example
index 39bb49f,f8e267e..5243250
--- a/ai_agents/agent_discovery_agent/.env.example
+++ b/ai_agents/agent_discovery_agent/.env.example
@@@ -1,1 -1,2 +1,5 @@@
++<<<<<<< HEAD
++=======
+ # Google API key used to authenticate Gemini 3 Flash requests. Get one free at https://aistudio.google.com
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
GOOGLE_API_KEY=your_google_api_key_here
diff --cc ai_agents/agent_discovery_agent/README.md
index 15859a0,3c27af2..c608ace
--- a/ai_agents/agent_discovery_agent/README.md
+++ b/ai_agents/agent_discovery_agent/README.md
@@@ -8,14 -8,14 +8,22 @@@
## Overview
++<<<<<<< HEAD
+Instead of manually browsing five separate agent registries, this agent lets you ask in plain English β€” "find code review agents", "show me trading bots on Virtuals", "what MCP servers handle databases?" β€” and get structured results back in seconds.
++=======
+ Instead of manually browsing five separate agent registries, this agent lets you ask in plain English: "find code review agents", "show me trading bots on Virtuals", "what MCP servers handle databases?" It returns structured results in seconds.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
The agent connects to the [Registry Broker API](https://hol.org/registry/docs), a universal index that abstracts NANDA, MCP, Virtuals Protocol, A2A, and ERC-8004 into a single interface. No registry-specific integrations needed.
## Features
- **Universal Search:** Query AI agents across 5 registries with a single natural language request
++<<<<<<< HEAD
+- **Agent Details:** Full metadata for any agent β€” capabilities, endpoints, trust score, and verification status
++=======
+ - **Agent Details:** Full metadata for any agent including capabilities, endpoints, trust score, and verification status
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
- **Similar Agents:** Find alternatives and compare agents with similar functionality
- **Faceted Browsing:** Explore available categories, registries, and capability filters
- **Streamlit Chat UI:** Dark-themed conversational interface with example queries and session history
@@@ -36,14 -36,15 +44,23 @@@
|---|---|
| LLM | Gemini 3 Flash (`gemini-3-flash-preview`) |
| Agent SDK | [Google GenAI SDK](https://github.com/googleapis/python-genai) (`google-genai`) |
++<<<<<<< HEAD
+| Registry API | [Registry Broker API](https://hol.org/registry/docs) β€” public, no key required |
++=======
+ | Registry API | [Registry Broker API](https://hol.org/registry/docs) (public, no key required) |
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
| HTTP client | httpx |
| UI | Streamlit |
## Prerequisites
- Python 3.10 or later
++<<<<<<< HEAD
+- A Google API key β€” get one free at [aistudio.google.com](https://aistudio.google.com)
++=======
+ - [uv](https://docs.astral.sh/uv/getting-started/installation/) (Python package manager)
+ - A Google API key. Get one free at [aistudio.google.com](https://aistudio.google.com)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Installation
@@@ -62,6 -63,12 +79,15 @@@ cp .env.example .en
Open `.env` and add your Google API key.
++<<<<<<< HEAD
++=======
+ **Install dependencies**
+
+ ```bash
+ uv sync
+ ```
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Usage
```bash
diff --cc ai_agents/agent_discovery_agent/app.py
index 24b2bb5,dbc8816..ad2c5d3
--- a/ai_agents/agent_discovery_agent/app.py
+++ b/ai_agents/agent_discovery_agent/app.py
@@@ -1,5 -1,5 +1,9 @@@
"""
++<<<<<<< HEAD
+Agent Discovery Agent β€” Streamlit UI
++=======
+ Agent Discovery Agent: Streamlit UI for searching and comparing AI agents across multiple registries.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
"""
import json
@@@ -228,6 -228,7 +232,10 @@@ if "total_queries" not in st.session_st
# ── Agent logic ────────────────────────────────────────────────────────────────
def get_client(api_key: str) -> genai.Client:
++<<<<<<< HEAD
++=======
+ """Create and return a Google GenAI client authenticated with the provided API key."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return genai.Client(api_key=api_key)
diff --cc ai_agents/ai_travel_planning_agent/.env.example
index f811add,8e67145..f437276
--- a/ai_agents/ai_travel_planning_agent/.env.example
+++ b/ai_agents/ai_travel_planning_agent/.env.example
@@@ -1,2 -1,7 +1,11 @@@
++<<<<<<< HEAD
+GOOGLE_API_KEY=your_google_api_key_here
++=======
+ # Google AI Studio API key used to authenticate Gemini requests for all agents.
+ # Get one at https://aistudio.google.com/app/apikey
+ GOOGLE_API_KEY=your_google_api_key_here
+
+ # Tavily API key used for real-time web search by the flight, hotel, and itinerary agents.
+ # Get one at https://app.tavily.com
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
TAVILY_API_KEY=your_tavily_api_key_here
diff --cc ai_agents/ai_travel_planning_agent/README.md
index 9db5761,f709ec5..60003ff
--- a/ai_agents/ai_travel_planning_agent/README.md
+++ b/ai_agents/ai_travel_planning_agent/README.md
@@@ -1,10 -1,15 +1,24 @@@
++<<<<<<< HEAD
++=======
+ <a id="top"></a>
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# AI Travel Planning Agent
> Multi-agent travel planner that turns a single natural language request into a complete trip plan with flights, hotels, and a day-by-day itinerary.
++<<<<<<< HEAD
+## Overview
+
+The AI Travel Planning Agent uses a root Google ADK agent to coordinate three specialist sub-agents β€” Flight Agent, Hotel Agent, and Itinerary Agent. Each sub-agent independently searches the web in real time, and the root agent combines their results into one cohesive travel plan. Users interact through a Streamlit chat interface and can ask follow-up questions within the same conversational session.
++=======
+ ## Demo
+
+ ![Demo](assets/demo.png)
+
+ ## Overview
+
+ The AI Travel Planning Agent uses a root Google ADK agent to coordinate three specialist sub-agents: a Flight Agent, a Hotel Agent, and an Itinerary Agent. Each sub-agent independently searches the web in real time, and the root agent combines their results into one cohesive travel plan. Users interact through a Streamlit chat interface and can ask follow-up questions within the same conversational session.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Features
@@@ -12,14 -17,14 +26,22 @@@
- Parallel specialist agents for flights, hotels, and itineraries
- Real-time web search via Tavily on every query
- Nearby place discovery using OpenStreetMap/Nominatim (no extra API key)
++<<<<<<< HEAD
+- Multi-turn conversation β€” ask follow-ups after the initial plan
++=======
+ - Multi-turn conversation, so you can ask follow-ups after the initial plan
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Tech Stack
| Layer | Technology |
|---|---|
| Agent framework | Google ADK (`google-adk`) |
++<<<<<<< HEAD
+| LLM | Gemini 3 Flash (`gemini-3-flash-preview`) |
++=======
+ | LLM | Gemini 3.5 Flash (`gemini-3.5-flash`) |
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
| Web search | Tavily Search API |
| Location data | geopy + Nominatim (OpenStreetMap) |
| UI | Streamlit |
@@@ -112,5 -117,9 +134,14 @@@ ai-travel-planning-agent
β”œβ”€β”€ tools.py # Tavily search and Nominatim location tools
β”œβ”€β”€ requirements.txt # Python dependencies
β”œβ”€β”€ .env.example # Environment variable template
++<<<<<<< HEAD
+└── .env # Your local API keys (git-ignored)
+```
++=======
+ β”œβ”€β”€ .env # Your local API keys (git-ignored)
+ └── assets/
+ └── demo.png # Demo screenshot
+ ```
+
+ [Back to top](#top)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc ai_agents/ai_travel_planning_agent/agents.py
index 65c5281,a1d6ca3..ca857d3
--- a/ai_agents/ai_travel_planning_agent/agents.py
+++ b/ai_agents/ai_travel_planning_agent/agents.py
@@@ -2,7 -2,7 +2,11 @@@ from google.adk.agents import LlmAgen
from google.adk.tools.agent_tool import AgentTool
from tools import tavily_search, find_nearby_places
++<<<<<<< HEAD
+MODEL = "gemini-3-flash-preview"
++=======
+ MODEL = "gemini-3.5-flash"
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# ---------------------------------------------------------------------------
# Specialist sub-agents
diff --cc ai_agents/ai_travel_planning_agent/app.py
index d61d6c5,f858565..85b6fbc
--- a/ai_agents/ai_travel_planning_agent/app.py
+++ b/ai_agents/ai_travel_planning_agent/app.py
@@@ -1,11 -1,22 +1,30 @@@
++<<<<<<< HEAD
+import os
+import asyncio
++=======
+ """Streamlit chat app that coordinates flight, hotel, and itinerary agents into one travel plan."""
+ import os
+ import asyncio
+ import logging
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import uuid
# Load .env before any ADK/Google imports so API keys are available
from dotenv import load_dotenv
load_dotenv()
++<<<<<<< HEAD
++=======
+ # ADK logs the full traceback for every transient model error (even ones it
+ # or our own retry logic recovers from). We surface failures via the UI
+ # instead, so quiet this logger to keep the terminal readable.
+ logging.getLogger("google_adk").setLevel(logging.CRITICAL)
+
+ _TRANSIENT_ERROR_MARKERS = ("503", "UNAVAILABLE", "high demand")
+ _QUOTA_ERROR_MARKERS = ("429", "RESOURCE_EXHAUSTED")
+ _QUOTA_RETRY_DELAY_SECONDS = 8
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import nest_asyncio
nest_asyncio.apply() # Allow asyncio.run() inside Streamlit's existing event loop
@@@ -13,6 -24,7 +32,10 @@@ import streamlit as s
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
++<<<<<<< HEAD
++=======
+ from google.genai.errors import ServerError
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
from agents import root_agent
@@@ -96,23 -108,76 +119,96 @@@ if "adk_runner" not in st.session_state
# Agent runner helper
# ---------------------------------------------------------------------------
++<<<<<<< HEAD
+async def _stream_response(runner: Runner, session_id: str, user_id: str, content: types.Content) -> str:
+ """Collect the final response text from a single runner.run_async() call."""
+ final_text = ""
+ async for event in runner.run_async(
+ session_id=session_id,
+ user_id=user_id,
+ new_message=content,
+ ):
+ if event.is_final_response():
+ if event.content and event.content.parts:
+ final_text = "\n".join(
+ part.text for part in event.content.parts if hasattr(part, "text")
+ )
+ break
+ return final_text
+
+
++=======
+ def _is_transient_error(message: str) -> bool:
+ """Check whether an error message looks like a temporary model-overload error."""
+ return any(marker in message for marker in _TRANSIENT_ERROR_MARKERS)
+
+
+ def _is_quota_error(message: str) -> bool:
+ """Check whether an error message looks like a 429 quota/rate-limit error."""
+ return any(marker in message for marker in _QUOTA_ERROR_MARKERS)
+
+
+ async def _stream_response(runner: Runner, session_id: str, user_id: str, content: types.Content) -> str:
+ """Collect the final response text from a single runner.run_async() call."""
+ final_text = ""
+ agen = runner.run_async(
+ session_id=session_id,
+ user_id=user_id,
+ new_message=content,
+ )
+ try:
+ async for event in agen:
+ # Some failures surface as an error event on the stream rather than
+ # a raised exception, so check for that before looking for the final response.
+ if getattr(event, "error_code", None):
+ raise RuntimeError(event.error_message or event.error_code)
+ if event.is_final_response():
+ if event.content and event.content.parts:
+ final_text = "\n".join(
+ part.text for part in event.content.parts if hasattr(part, "text")
+ )
+ break
+ finally:
+ # Close the generator here, in the same task/context it was opened in,
+ # so a retry doesn't start a new one while this one is still mid-teardown
+ # (that's what was producing the GeneratorExit / OpenTelemetry cleanup errors).
+ await agen.aclose()
+ return final_text
+
+
+ async def _stream_response_with_retry(
+ runner: Runner,
+ session_id: str,
+ user_id: str,
+ content: types.Content,
+ max_attempts: int = 2,
+ ) -> str:
+ """Call _stream_response, retrying on transient model errors.
+
+ 503/UNAVAILABLE overload errors use the existing short exponential backoff.
+ 429/RESOURCE_EXHAUSTED quota errors get exactly one retry after a longer delay,
+ since retrying quota errors quickly just makes the exhaustion worse.
+ """
+ quota_retried = False
+ for attempt in range(1, max_attempts + 1):
+ try:
+ return await _stream_response(runner, session_id, user_id, content)
+ except (ServerError, RuntimeError) as e:
+ message = str(e)
+ if _is_quota_error(message):
+ if attempt == max_attempts or quota_retried:
+ raise
+ quota_retried = True
+ await asyncio.sleep(_QUOTA_RETRY_DELAY_SECONDS)
+ elif _is_transient_error(message):
+ if attempt == max_attempts:
+ raise
+ await asyncio.sleep(2 ** attempt)
+ else:
+ raise
+
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
async def _run_agent_async(runner: Runner, session_id: str, user_id: str, message: str) -> str:
"""Run the ADK agent and collect the final response text."""
content = types.Content(
@@@ -138,7 -203,7 +234,11 @@@
)
try:
++<<<<<<< HEAD
+ final_text = await _stream_response(runner, session_id, user_id, content)
++=======
+ final_text = await _stream_response_with_retry(runner, session_id, user_id, content)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
except Exception as e:
if "Session not found" in str(e):
new_session_id = str(uuid.uuid4())
@@@ -148,7 -213,11 +248,15 @@@
session_id=new_session_id,
)
st.session_state.session_id = new_session_id
++<<<<<<< HEAD
+ final_text = await _stream_response(runner, new_session_id, user_id, content)
++=======
+ final_text = await _stream_response_with_retry(runner, new_session_id, user_id, content)
+ elif isinstance(e, (ServerError, RuntimeError)) and _is_quota_error(str(e)):
+ return "The AI model's quota is temporarily exhausted. Please wait a bit before trying again."
+ elif isinstance(e, (ServerError, RuntimeError)) and _is_transient_error(str(e)):
+ return "The AI model is temporarily overloaded. Please try again in a moment."
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
else:
raise
diff --cc ai_agents/cal_scheduling_agent/.env.example
index 7d9e270,9e2c6dc..0ea5a2a
--- a/ai_agents/cal_scheduling_agent/.env.example
+++ b/ai_agents/cal_scheduling_agent/.env.example
@@@ -1,3 -1,8 +1,14 @@@
++<<<<<<< HEAD
+GOOGLE_API_KEY=your_google_api_key_here
+CALCOM_API_KEY=your_calcom_api_key_here
+CALCOM_EVENT_TYPE_ID= # optional β€” scopes availability to a specific event type
++=======
+ # Google API key used to authenticate Gemini 3 Flash requests. Get one free at https://aistudio.google.com
+ GOOGLE_API_KEY=your_google_api_key_here
+
+ # Cal.com API key for reading and managing calendar data. Generate one at https://app.cal.com/settings/developer/api-keys
+ CALCOM_API_KEY=your_calcom_api_key_here
+
+ # Optional. Scopes availability checks to a specific event type. Find the ID in the URL when editing an event type on your Cal.com dashboard.
+ CALCOM_EVENT_TYPE_ID=
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc ai_agents/cal_scheduling_agent/README.md
index c52fdaa,8810e99..b045484
--- a/ai_agents/cal_scheduling_agent/README.md
+++ b/ai_agents/cal_scheduling_agent/README.md
@@@ -1,6 -1,6 +1,10 @@@
# Cal Scheduling Agent
++<<<<<<< HEAD
+> A conversational scheduling assistant that manages Cal.com appointments through natural language β€” check availability, book, reschedule, and cancel, with automatic timezone handling. Powered by Gemini 3 Flash and Streamlit.
++=======
+ > A conversational scheduling assistant that manages Cal.com appointments through natural language. Check availability, book, reschedule, and cancel with automatic timezone handling. Powered by Gemini 3 Flash and Streamlit.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Demo
@@@ -8,7 -8,7 +12,11 @@@
## Overview
++<<<<<<< HEAD
+Instead of logging into Cal.com and manually navigating availability calendars, this agent lets you ask in plain English β€” "what slots are free next week?", "book a meeting with Sarah for Tuesday at 3pm GMT", "cancel my appointment on Friday" β€” and handles everything through a conversational interface.
++=======
+ Instead of logging into Cal.com and manually navigating availability calendars, this agent lets you ask in plain English: "what slots are free next week?", "book a meeting with Sarah for Tuesday at 3pm GMT", "cancel my appointment on Friday". It handles everything through a conversational interface.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
The agent connects to the [Cal.com REST API](https://cal.com/docs/api-reference) to read availability, create bookings, and manage existing appointments in real time.
@@@ -33,7 -33,8 +41,12 @@@
## Prerequisites
- Python 3.10 or later
++<<<<<<< HEAD
+- A Google API key β€” get one free at [aistudio.google.com](https://aistudio.google.com)
++=======
+ - [uv](https://docs.astral.sh/uv/getting-started/installation/) (Python package manager)
+ - A Google API key. Get one free at [aistudio.google.com](https://aistudio.google.com)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
- A Cal.com account with API access
- A Cal.com Event Type ID
@@@ -54,6 -55,12 +67,15 @@@ cp .env.example .en
Open `.env` and add your credentials.
++<<<<<<< HEAD
++=======
+ **Install dependencies**
+
+ ```bash
+ uv sync
+ ```
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Usage
```bash
@@@ -81,7 -88,7 +103,11 @@@ What's open next Monday morning
|---|---|
| Google API Key | [aistudio.google.com](https://aistudio.google.com) |
| Cal.com API Key | [cal.com/settings/developer/api-keys](https://app.cal.com/settings/developer/api-keys) |
++<<<<<<< HEAD
+| Event Type ID | Your Cal.com dashboard β€” visible in the URL when editing an event type |
++=======
+ | Event Type ID | Your Cal.com dashboard (visible in the URL when editing an event type) |
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Environment Variables
diff --cc ai_agents/cal_scheduling_agent/app.py
index 6f11866,8d9c26e..055438a
--- a/ai_agents/cal_scheduling_agent/app.py
+++ b/ai_agents/cal_scheduling_agent/app.py
@@@ -1,5 -1,5 +1,9 @@@
"""
++<<<<<<< HEAD
+Cal Scheduling Agent β€” Streamlit UI
++=======
+ Cal Scheduling Agent: Streamlit UI for managing Cal.com appointments through natural language.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
"""
import os
@@@ -30,6 -30,7 +34,10 @@@ EXAMPLE_QUERIES =
def build_instructions(timezone: str = "UTC") -> str:
++<<<<<<< HEAD
++=======
+ """Return the system instruction string for the agent, injecting today's date and the user's timezone."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
today = datetime.now().strftime("%A, %B %d, %Y")
return f"""\
You are a friendly and efficient calendar scheduling assistant with access to \
diff --cc ai_agents/cal_scheduling_agent/cal_scheduling_agent/agent.py
index 3a4ed33,ae08e11..1c35025
--- a/ai_agents/cal_scheduling_agent/cal_scheduling_agent/agent.py
+++ b/ai_agents/cal_scheduling_agent/cal_scheduling_agent/agent.py
@@@ -1,5 -1,5 +1,9 @@@
"""
++<<<<<<< HEAD
+Cal Scheduling Agent β€” Agno agent definition.
++=======
+ Cal Scheduling Agent: Agno agent definition for managing Cal.com appointments.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
"""
import os
diff --cc ai_agents/competitive_intelligence_agent/.env.example
index 61a33ac,3ddf94a..0d6e633
--- a/ai_agents/competitive_intelligence_agent/.env.example
+++ b/ai_agents/competitive_intelligence_agent/.env.example
@@@ -1,2 -1,4 +1,8 @@@
++<<<<<<< HEAD
+GEMINI_API_KEY=your_gemini_api_key_here
++=======
+ # Google AI Studio API key used to access Gemma 4 via the Gemini API. Get yours free at https://aistudio.google.com
+ GEMINI_API_KEY=your_gemini_api_key_here
+ # Tavily Search API key used for real-time web research by the CrewAI agents. Get yours free at https://tavily.com
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
TAVILY_API_KEY=tvly-your_tavily_key_here
diff --cc ai_agents/competitive_intelligence_agent/README.md
index b42974d,3b9c89a..b727d81
--- a/ai_agents/competitive_intelligence_agent/README.md
+++ b/ai_agents/competitive_intelligence_agent/README.md
@@@ -1,12 -1,18 +1,27 @@@
# Competitive Intelligence Agent
++<<<<<<< HEAD
+A multi-agent AI system that generates strategic sales battlecards by analyzing competitors through the unique lens of your own business context.
+
++=======
+ > Generate strategic sales battlecards by analyzing competitors through the unique lens of your own business context.
+
+ A multi-agent AI system that generates strategic sales battlecards by analyzing competitors through the unique lens of your own business context.
+
+ ## Demo
+
+ ![Demo](assets/demo.png)
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Overview
The **Competitive Intelligence Agent** solves the "generic research" problem by moving away from broad, impersonal reports. Instead of searching the web for everything about a competitor, this system uses specialized AI agents to analyze a competitor specifically in relation to *your* company's value proposition, your customers' specific pain points, and your strategic sales goals.
++<<<<<<< HEAD
+It uses **CrewAI** to orchestrate specialized agentsβ€”a Market Scout, a Product Strategist, and a Battlecard Authorβ€”to research, compare, and synthesize actionable sales intelligence.
++=======
+ It uses **CrewAI** to orchestrate three specialized agents that research, compare, and synthesize actionable sales intelligence: a Market Scout, a Product Strategist, and a Battlecard Author.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
This tool is designed for:
- **Sales Teams:** Who need immediate, punchy arguments to win against specific competitors.
@@@ -40,8 -46,8 +55,13 @@@ Before you begin, ensure you have
- Python 3.12 or higher
- [uv](https://github.com/astral-sh/uv) (Recommended for dependency management)
- API keys for:
++<<<<<<< HEAD
+ - [ ] Google AI Studio (for Gemini/Gemma)
+ - [ ] Tavily Search API
++=======
+ - [Google AI Studio](https://aistudio.google.com) for Gemini/Gemma (free tier available)
+ - [Tavily Search API](https://tavily.com) (free tier available)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Installation
@@@ -95,6 -101,8 +115,11 @@@ competitive_intelligence_agent
β”œβ”€β”€ .env.example # Template for API keys
β”œβ”€β”€ pyproject.toml # uv project configuration
β”œβ”€β”€ uv.lock # Locked dependencies for consistency
++<<<<<<< HEAD
++=======
+ β”œβ”€β”€ assets/
+ β”‚ └── demo.png # Demo screenshot
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
└── .venv/ # Virtual environment (auto-generated)
```
diff --cc ai_agents/competitive_intelligence_agent/agents_logic.py
index 879e551,e6beb79..7d5db8e
--- a/ai_agents/competitive_intelligence_agent/agents_logic.py
+++ b/ai_agents/competitive_intelligence_agent/agents_logic.py
@@@ -1,7 -1,11 +1,18 @@@
++<<<<<<< HEAD
+import os
+from crewai import Agent, Task, Crew, Process, LLM
+from crewai_tools import TavilySearchTool
+
++=======
+ """CrewAI agent and task definitions for the Competitive Intelligence Agent."""
+ import os
+ from dotenv import load_dotenv
+ from crewai import Agent, Task, Crew, Process, LLM
+ from crewai_tools import TavilySearchTool
+
+ load_dotenv()
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# Gemma 4 via LiteLLM/Gemini API
gemma_llm = LLM(
model="gemini/gemma-4-26b-a4b-it",
@@@ -9,6 -13,7 +20,10 @@@
)
def get_research_crew(my_company, competitor, pain_point, goal):
++<<<<<<< HEAD
++=======
+ """Build and return a sequential CrewAI crew configured for the given company context and competitor."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# Specialized Tools
search_tool = TavilySearchTool(api_key=os.getenv("TAVILY_API_KEY"), max_results=3)
diff --cc ai_agents/competitive_intelligence_agent/main.py
index 8852d41,6f543e7..e96eb02
--- a/ai_agents/competitive_intelligence_agent/main.py
+++ b/ai_agents/competitive_intelligence_agent/main.py
@@@ -1,25 -1,44 +1,62 @@@
++<<<<<<< HEAD
++=======
+ """Gradio UI for the Competitive Intelligence Agent, which generates AI-powered sales battlecards using a CrewAI multi-agent pipeline."""
+ import re
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import gradio as gr
import io
from contextlib import redirect_stdout
from agents_logic import get_research_crew
++<<<<<<< HEAD
+def run_analysis(my_company, competitor, pain_point, goal):
++=======
+
+ def strip_ansi(text: str) -> str:
+ """Remove ANSI color and formatting escape sequences from a string."""
+ return re.sub(r'\x1b\[[0-9;]*m', '', text)
+
+
+ def clean_log(raw: str) -> str:
+ """Remove blank lines and decorative separator lines from captured CrewAI stdout."""
+ kept = []
+ for line in raw.splitlines():
+ stripped = line.strip()
+ if stripped and re.search(r'[A-Za-z0-9]', stripped):
+ kept.append(stripped)
+ return '\n'.join(kept)
+
+
+ def run_analysis(my_company, competitor, pain_point, goal):
+ """Run the three-agent CrewAI pipeline and return the reasoning log and final battlecard."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# Progress logging
f = io.StringIO()
with redirect_stdout(f):
try:
crew = get_research_crew(my_company, competitor, pain_point, goal)
result = crew.kickoff(inputs={
++<<<<<<< HEAD
+ "my_company": my_company,
+ "competitor": competitor,
+ "pain_point": pain_point,
++=======
+ "my_company": my_company,
+ "competitor": competitor,
+ "pain_point": pain_point,
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
"goal": goal
})
final_output = result.raw
except Exception as e:
final_output = f"Error: {str(e)}"
++<<<<<<< HEAD
+
+ return f.getvalue(), final_output
++=======
+
+ return clean_log(strip_ansi(f.getvalue())), final_output
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
with gr.Blocks(title="Strategic Intel System") as demo:
gr.Markdown("# βš”οΈ Competitive Intelligence Engine")
@@@ -34,7 -53,8 +71,12 @@@
submit_btn = gr.Button("Generate Battlecard", variant="primary")
with gr.Column():
++<<<<<<< HEAD
+ logs = gr.Textbox(label="Agent Reasoning Process", lines=10)
++=======
+ with gr.Accordion("Agent Reasoning Process", open=False):
+ logs = gr.Textbox(label="Agent Reasoning Process", lines=10)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
output = gr.Markdown(label="Final Battlecard")
submit_btn.click(
diff --cc ai_agents/competitive_intelligence_agent/pyproject.toml
index 9c81729,5850245..aeb9158
--- a/ai_agents/competitive_intelligence_agent/pyproject.toml
+++ b/ai_agents/competitive_intelligence_agent/pyproject.toml
@@@ -1,7 -1,7 +1,11 @@@
[project]
name = "competitive-intelligence-agent"
version = "0.1.0"
++<<<<<<< HEAD
+description = "Add your description here"
++=======
+ description = "Multi-agent CrewAI system that generates strategic sales battlecards by analyzing competitors against your own business context"
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
diff --cc ai_agents/customer_query_routing_agent/README.md
index 32851c9,32851c9..1d9615f
--- a/ai_agents/customer_query_routing_agent/README.md
+++ b/ai_agents/customer_query_routing_agent/README.md
@@@ -30,7 -30,7 +30,7 @@@ The memory layer is what sets this apar
## Architecture
--![Architecture diagram](assets/architecture.png)
++![Architecture diagram](assets/architecture_nobg.png)
The orchestrator agent is the routing brain. It receives the raw query, the VectorAI DB confidence score, and pre-detected signals from a fast regex pass. It reasons over all of that and outputs a structured JSON decision, which path to take and why, before any response-generation LLM call happens.
diff --cc ai_agents/customer_query_routing_agent/assets/architecture.png
index b05ead5,b05ead5..0000000
deleted file mode 100644,100644
Binary files differ
diff --cc ai_agents/customer_query_routing_agent/assets/architecture_nobg.png
index 0000000,0000000..8ba7dca
new file mode 100644
Binary files differ
diff --cc ai_agents/daily-news-digest/.env.example
index de7c527,4c5ab88..6a7ed71
--- a/ai_agents/daily-news-digest/.env.example
+++ b/ai_agents/daily-news-digest/.env.example
@@@ -1,3 -1,10 +1,15 @@@
++<<<<<<< HEAD
+MINIMAX_API_KEY=your_minimax_api_key_here
+TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
++=======
+ # MiniMax API key used to score and rank articles by significance.
+ # Get one at https://platform.minimax.io
+ MINIMAX_API_KEY=your_minimax_api_key_here
+
+ # Telegram bot token used to send the daily digest message.
+ # Create a bot and get a token from @BotFather on Telegram: https://t.me/BotFather
+ TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
+
+ # ID of the Telegram chat or channel the digest should be delivered to.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
TELEGRAM_CHAT_ID=your_telegram_chat_id_here
diff --cc ai_agents/daily-news-digest/README.md
index 37f1438,aa67e24..6b4970c
--- a/ai_agents/daily-news-digest/README.md
+++ b/ai_agents/daily-news-digest/README.md
@@@ -2,6 -2,14 +2,17 @@@
Automated daily digest from 92 Karpathy-curated tech blogs, delivered to Telegram at 8 AM every morning. MiniMax M2.7 scores every article fetched in the last 24 hours and picks the 3 most significant stories.
++<<<<<<< HEAD
++=======
+ ## Architecture
+
+ ![Architecture diagram](docs/architecture.svg)
+
+ ## Demo
+
+ ![Daily AI Digest demo](assets/demo.png)
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## How it works
```text
@@@ -10,7 -18,7 +21,11 @@@
1. `scripts/fetch_rss.py` fetches all feeds in parallel and keeps only articles published in the last 24 hours
2. `skill.py` sends the article list to MiniMax M2.7, which scores each one and returns the top 3 as structured JSON
++<<<<<<< HEAD
+3. Articles are grouped into categories β€” **Breaking**, **Important**, or **Notable** β€” and formatted as a Telegram message
++=======
+ 3. Articles are grouped into categories (**Breaking**, **Important**, or **Notable**) and formatted as a Telegram message
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
4. Empty categories are omitted automatically
@@@ -23,13 -31,13 +38,23 @@@
## Tech Stack
**Models & Frameworks:**
++<<<<<<< HEAD
+- MiniMax M2.7 β€” article scoring and ranking
+- OpenClaw β€” skill orchestration and cron scheduling
+
+**Libraries:**
+- `feedparser` β€” RSS feed parsing
+- `python-dotenv` β€” environment variable management
+- `requests` β€” HTTP requests for RSS feed fetching
++=======
+ - MiniMax M2.7: article scoring and ranking
+ - OpenClaw: skill orchestration and cron scheduling
+
+ **Libraries:**
+ - `feedparser`: RSS feed parsing
+ - `python-dotenv`: environment variable management
+ - `requests`: HTTP requests for RSS feed fetching
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Prerequisites
@@@ -101,7 -109,7 +126,11 @@@ cp -r . ~/.openclaw/skills/daily-ai-new
openclaw cron add "0 8 * * *" skill.py
```
++<<<<<<< HEAD
+This schedules the digest to run every day at **08:00 UTC**. Adjust the cron expression to change the time β€” for example `"0 7 * * 1-5"` for weekdays at 07:00 UTC.
++=======
+ This schedules the digest to run every day at **08:00 UTC**. Adjust the cron expression to change the time. For example, `"0 7 * * 1-5"` schedules it for weekdays at 07:00 UTC.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Running manually
@@@ -112,18 -120,18 +141,33 @@@ python skill.p
## Output format
```text
++<<<<<<< HEAD
+πŸ—žοΈ Daily AI Digest β€” April 1, 2026
+
+πŸ”΄ BREAKING
+πŸ”΄ Article Title β€” Summary sentence one. Sentence two.
+Source: Blog Name | [Read more](https://...)
+
+🟑 IMPORTANT
+🟑 Article Title β€” Summary sentence one. Sentence two.
+Source: Blog Name | [Read more](https://...)
+
+πŸ”΅ NOTABLE
+πŸ”΅ Article Title β€” Summary sentence one. Sentence two.
++=======
+ πŸ—žοΈ Daily AI Digest: April 1, 2026
+
+ πŸ”΄ BREAKING
+ πŸ”΄ Article Title: Summary sentence one. Sentence two.
+ Source: Blog Name | [Read more](https://...)
+
+ 🟑 IMPORTANT
+ 🟑 Article Title: Summary sentence one. Sentence two.
+ Source: Blog Name | [Read more](https://...)
+
+ πŸ”΅ NOTABLE
+ πŸ”΅ Article Title: Summary sentence one. Sentence two.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
Source: Blog Name | [Read more](https://...)
```
@@@ -131,7 -139,7 +175,11 @@@
```text
daily-ai-news-digest/
++<<<<<<< HEAD
+β”œβ”€β”€ skill.py # Main pipeline β€” fetch, score, format, send
++=======
+ β”œβ”€β”€ skill.py # Main pipeline: fetch, score, format, send
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
β”œβ”€β”€ scripts/
β”‚ └── fetch_rss.py # Parallel RSS fetcher with 24h date filter
β”œβ”€β”€ sources.json # 92 Karpathy-curated RSS feed sources
@@@ -143,10 -151,10 +191,20 @@@
## Customisation
++<<<<<<< HEAD
+**Change the number of top articles** β€” edit the system prompt in `skill.py` and update the instruction from "top 3" to your preferred number.
+
+**Change the lookback window** β€” the `--hours` argument in `fetch_articles()` defaults to 24. Pass a different value to cast a wider or narrower net.
+
+**Add or remove sources** β€” edit `sources.json`. Each entry needs a `name`, `xmlUrl` (the feed URL), and `htmlUrl` (the site URL).
+
+**Change the schedule** β€” update the cron expression in the `trigger` field of `SKILL.md` and re-register with `openclaw cron add`.
++=======
+ **Change the number of top articles**: edit the system prompt in `skill.py` and update the instruction from "top 3" to your preferred number.
+
+ **Change the lookback window**: the `--hours` argument in `fetch_articles()` defaults to 24. Pass a different value to cast a wider or narrower net.
+
+ **Add or remove sources**: edit `sources.json`. Each entry needs a `name`, `xmlUrl` (the feed URL), and `htmlUrl` (the site URL).
+
+ **Change the schedule**: update the cron expression in the `trigger` field of `SKILL.md` and re-register with `openclaw cron add`.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc ai_agents/daily-news-digest/skill.py
index 05c63b3,fc8b55e..3663543
--- a/ai_agents/daily-news-digest/skill.py
+++ b/ai_agents/daily-news-digest/skill.py
@@@ -175,7 -175,7 +175,11 @@@ for article in selected
cat = article.get("category", "Notable")
grouped.setdefault(cat, []).append(article)
++<<<<<<< HEAD
+message_parts = [f"πŸ—žοΈ *Daily AI Digest β€” {today}*"]
++=======
+ message_parts = [f"πŸ—žοΈ *Daily AI Digest: {today}*"]
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
for cat in CATEGORY_ORDER:
if cat not in grouped:
@@@ -189,7 -189,7 +193,11 @@@
source = art["source"]
url = art["url"]
message_parts.append(
++<<<<<<< HEAD
+ f"{emoji} *{title}* β€” {summary}\n"
++=======
+ f"{emoji} *{title}*: {summary}\n"
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
f"Source: {source} | [Read more]({url})"
)
diff --cc ai_agents/eagle_eye/README.md
index 037ab72,60f06e8..2638cfe
--- a/ai_agents/eagle_eye/README.md
+++ b/ai_agents/eagle_eye/README.md
@@@ -1,9 -1,25 +1,31 @@@
++<<<<<<< HEAD
++=======
+ <a id="top"></a>
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# πŸ¦… Eagle Eye
AI-powered GitHub PR review agent using [OpenClaw](https://openclaw.dev), MiniMax M2.7, and GitHub MCP. Triggered via Telegram.
---
++<<<<<<< HEAD
++=======
+ ## βœ… Prerequisites
+
+ - [OpenClaw](https://openclaw.dev) installed
+ - A Telegram bot, created via [@BotFather](https://t.me/BotFather)
+ - A GitHub Personal Access Token with repo and pull request scopes, created at [GitHub's token settings page](https://github.com/settings/tokens)
+
+ ---
+
+ ## πŸ“Έ Demo
+
+ ![Eagle Eye demo](assets/demo.png)
+
+ ---
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## πŸ“½οΈ Project Overview
**Eagle Eye** is a Telegram-triggered code review assistant that analyzes GitHub pull requests and delivers structured feedback directly to your chat.
@@@ -97,3 -113,7 +119,10 @@@ The agent will respond with the review
- **Scope**: Does not see CI/CD logs or test results unless pasted into the chat.
- **Large PRs**: For very large changes, the agent prioritizes security and correctness.
- **Stateless**: Each Telegram session starts fresh; previous review context is not retained unless manually provided.
++<<<<<<< HEAD
++=======
+
+ ---
+
+ [Back to top](#top)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc ai_agents/finagent/.env.example
index 3cac181,cf8f5e6..0a7f0b1
--- a/ai_agents/finagent/.env.example
+++ b/ai_agents/finagent/.env.example
@@@ -1,1 -1,7 +1,11 @@@
++<<<<<<< HEAD
+OPENAI_API_KEY=your_openai_api_key_here
++=======
+ # Mistral API key for the Mistral Small 4 (mistral-small-latest) model used by the financial analysis agents.
+ # Get one at https://console.mistral.ai/api-keys
+ MISTRAL_API_KEY=your_mistral_api_key_here
+
+ # Optional: Firecrawl API key used for enhanced news scraping features.
+ # Get one at https://firecrawl.dev
+ FIRECRAWL_API_KEY=your_firecrawl_api_key_here
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc ai_agents/finagent/README.md
index 140d8a3,09ea10f..8d0e40b
--- a/ai_agents/finagent/README.md
+++ b/ai_agents/finagent/README.md
@@@ -1,6 -1,10 +1,14 @@@
# Finagent - AI-Powered Financial Analysis Tool
++<<<<<<< HEAD
+A sophisticated financial analysis system that leverages Google's Gemini AI and real-time market data to provide comprehensive stock analysis, automated code generation, and investment insights.
++=======
+ A sophisticated financial analysis system that leverages Mistral Small 4 (mistral-small-latest) and real-time market data to provide comprehensive stock analysis, automated code generation, and investment insights.
+
+ ## Demo
+
+ ![Finagent demo](assets/demo.gif)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Features
@@@ -9,13 -13,12 +17,20 @@@
- **Automated Code Generation**: Creates executable Python code for financial analysis
- **News Integration**: Incorporates latest market news into analysis
- **MCP Server**: Modern Model Context Protocol server for Claude Desktop integration
++<<<<<<< HEAD
+- **Professional Visualizations**: Generates matplotlib charts and technical analysis plots
++=======
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
- **Risk Assessment**: Provides balanced investment recommendations with proper disclaimers
## Prerequisites
- Python 3.8+
++<<<<<<< HEAD
+- Google Gemini API key
++=======
+ - Mistral API key (for the Mistral Small 4 / mistral-small-latest model)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
- Claude Desktop (for MCP integration)
- Firecrawl API key (optional, for enhanced news features)
@@@ -44,22 -47,22 +59,36 @@@ cd finagen
2. **Install required packages**:
```bash
++<<<<<<< HEAD
+pip install google-generativeai yfinance pandas matplotlib numpy mcp python-dotenv
++=======
+ pip install -r requirements.txt
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```
3. **Set up environment variables**:
Create a `.env` file in the project root:
```env
++<<<<<<< HEAD
+GEMINI_API_KEY=your_gemini_api_key_here
++=======
+ MISTRAL_API_KEY=your_mistral_api_key_here
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
FIRECRAWL_API_KEY=your_firecrawl_api_key_here # Optional
```
## API Keys Setup
++<<<<<<< HEAD
+### Gemini API Key (Required)
+
+1. Visit [Google AI Studio](https://makersuite.google.com/app/apikey)
++=======
+ ### Mistral API Key (Required)
+
+ 1. Visit [Mistral Console](https://console.mistral.ai/api-keys)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
2. Create a new API key
3. Add it to your `.env` file
@@@ -96,7 -99,7 +125,11 @@@
"command": "python",
"args": ["/absolute/path/to/finagent/main.py"],
"env": {
++<<<<<<< HEAD
+ "GEMINI_API_KEY": "your_gemini_api_key_here",
++=======
+ "MISTRAL_API_KEY": "your_mistral_api_key_here",
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
"FIRECRAWL_API_KEY": "your_firecrawl_api_key_here"
}
}
@@@ -167,15 -170,12 +200,23 @@@ python main.p
from financial_agents import FinancialAnalysisTeam
team = FinancialAnalysisTeam(
++<<<<<<< HEAD
+ gemini_api_key="your_gemini_key",
+ firecrawl_api_key="your_firecrawl_key"
++=======
+ mistral_api_key="your_mistral_key"
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
)
result = team.analyze("Analyze Apple stock over the last 6 months")
++<<<<<<< HEAD
+print(f"Insights: {result.insights}")
+print(f"Recommendations: {result.recommendations}")
+print(f"Generated Code:\n{result.code}")
++=======
+ print(result)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```
## Example Queries
@@@ -193,7 -193,7 +234,11 @@@ The system understands natural languag
### Core Components
1. **FinancialAnalysisTeam**: Main orchestrator class
++<<<<<<< HEAD
+2. **GeminiAgent**: Base agent class using Gemini AI
++=======
+ 2. **MistralAgent**: Base agent class using Mistral Small 4 (mistral-small-latest)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
3. **FinancialTools**: Data acquisition utilities
4. **MCP Server**: Model Context Protocol server for Claude Desktop
@@@ -208,7 -208,6 +253,10 @@@
- **Technical Indicators**: RSI, MACD, Moving averages, Bollinger bands
- **Price Analysis**: Trend analysis, support/resistance levels
- **Risk Metrics**: Volatility calculations, drawdown analysis
++<<<<<<< HEAD
+- **Visualizations**: Professional charts with technical overlays
++=======
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
- **News Integration**: Latest market sentiment and news impact
- **Investment Recommendations**: Buy/Hold/Sell with rationale
@@@ -233,7 -232,7 +281,11 @@@
2. **Import Errors**:
```bash
++<<<<<<< HEAD
+pip install google-generativeai yfinance pandas mcp python-dotenv
++=======
+ pip install -r requirements.txt
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```
3. **API Key Issues**:
@@@ -291,4 -290,4 +343,8 @@@ For questions and support
---
++<<<<<<< HEAD
+**Made with Google Gemini AI & Claude Desktop**
++=======
+ **Made with Mistral Small 4 & Claude Desktop**
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc ai_agents/finagent/financial_agents.py
index 4f293e8,c9eb02f..d88e016
--- a/ai_agents/finagent/financial_agents.py
+++ b/ai_agents/finagent/financial_agents.py
@@@ -1,10 -1,16 +1,25 @@@
++<<<<<<< HEAD
++=======
+ """Multi-agent financial analysis pipeline built on Mistral Small 4 and Yahoo Finance market data."""
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import os
import re
import json
import yfinance as yf
++<<<<<<< HEAD
+import google.generativeai as genai
+
+def _normalize_period(period: str) -> str:
++=======
+ from dotenv import load_dotenv
+ from mistralai.client import Mistral
+
+ load_dotenv()
+
+ def _normalize_period(period: str) -> str:
+ """Normalizes a user-supplied time period string into a yfinance-compatible period code."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if not period:
return '6mo'
p = str(period).strip().lower()
@@@ -17,30 -23,62 +32,84 @@@
return p
++<<<<<<< HEAD
+class GeminiAgent:
+ def __init__(self, api_key: str, role: str, system_prompt: str):
+ genai.configure(api_key=api_key)
+ self.model = genai.GenerativeModel('gemini-2.5-flash')
++=======
+ def _summarize_stock_data(stock_data) -> str:
+ """Builds a compact text summary of real OHLCV price data to ground the analysis prompt."""
+ first = stock_data.iloc[0]
+ latest = stock_data.iloc[-1]
+ start_price = float(first['Close'])
+ end_price = float(latest['Close'])
+ pct_change = ((end_price - start_price) / start_price) * 100 if start_price else 0.0
+ period_high = float(stock_data['High'].max())
+ period_low = float(stock_data['Low'].min())
+ first_date = stock_data.index[0].strftime('%Y-%m-%d')
+ latest_date = stock_data.index[-1].strftime('%Y-%m-%d')
+
+ return (
+ f"Data range: {first_date} to {latest_date}\n"
+ f"Starting close: {start_price:.2f}\n"
+ f"Latest close: {end_price:.2f}\n"
+ f"Change over period: {pct_change:.2f}%\n"
+ f"Period high: {period_high:.2f}\n"
+ f"Period low: {period_low:.2f}\n"
+ f"Latest volume: {int(latest['Volume'])}"
+ )
+
+
+ class MistralAgent:
+ """Wraps a single Mistral Small 4 chat role with its own system prompt."""
+
+ def __init__(self, api_key: str, role: str, system_prompt: str):
+ self.client = Mistral(api_key=api_key)
+ self.model = 'mistral-small-latest'
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
self.role = role
self.system_prompt = system_prompt
def generate(self, prompt: str) -> str:
full_prompt = f"{self.system_prompt}\n\nUser Request: {prompt}"
++<<<<<<< HEAD
+ response = self.model.generate_content(full_prompt)
+ return response.text
+
+
+class FinancialTools:
++=======
+ response = self.client.chat.complete(
+ model=self.model,
+ messages=[{"role": "user", "content": full_prompt}],
+ )
+ return response.choices[0].message.content
+
+
+ class FinancialTools:
+ """Provides access to the market data needed by the analysis agents."""
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
def get_stock_data(self, symbol: str, period: str = "6mo"):
ticker = yf.Ticker(symbol)
return ticker.history(period=period)
class FinancialAnalysisTeam:
++<<<<<<< HEAD
+ def __init__(self, gemini_api_key: str):
+ self.tools = FinancialTools()
+ self.query_parser = GeminiAgent(
+ gemini_api_key,
++=======
+ """Coordinates the query parser and market analyst agents to produce a stock analysis."""
+
+ def __init__(self, mistral_api_key: str):
+ self.tools = FinancialTools()
+ self.query_parser = MistralAgent(
+ mistral_api_key,
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
"Query Parser",
"""You are a financial query parser. Extract from the user query:
- Stock symbol (ticker)
@@@ -48,14 -86,15 +117,23 @@@
- Time period (like 1d, 1mo, 6mo, 1y)
Return a JSON object with keys: symbol, analysis_type, time_period."""
)
++<<<<<<< HEAD
+ self.market_analyst = GeminiAgent(
+ gemini_api_key,
++=======
+ self.market_analyst = MistralAgent(
+ mistral_api_key,
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
"Market Analyst",
"""You are a senior financial analyst. Provide a clear, professional, and actionable analysis for the stock.
Include market trends, price action, risk assessment and investment recommendations."""
)
def parse_query(self, query: str):
++<<<<<<< HEAD
++=======
+ """Parses a natural language query into a symbol, analysis type, and time period."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
response = self.query_parser.generate(query)
try:
json_match = re.search(r"\{.*\}", response, re.DOTALL)
@@@ -74,14 -113,19 +152,29 @@@
return data
def analyze_market(self, query_info, stock_data) -> str:
++<<<<<<< HEAD
+ prompt = (
+ f"Analyze the stock symbol {query_info['symbol']} for the period "
+ f"{query_info.get('time_period', '6mo')}. Use recent price data and technical indicators "
+ f"to provide market trends, risk factors, and recommendations."
++=======
+ """Asks the market analyst agent for a written analysis grounded in the fetched stock data."""
+ data_summary = _summarize_stock_data(stock_data)
+ prompt = (
+ f"Analyze the stock symbol {query_info['symbol']} for the period "
+ f"{query_info.get('time_period', '6mo')} using the following real market data:\n\n"
+ f"{data_summary}\n\n"
+ f"Base your trends, risk factors, and recommendations only on this data. "
+ f"Do not assume any other price information."
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
)
return self.market_analyst.generate(prompt)
def analyze(self, query: str) -> str:
++<<<<<<< HEAD
++=======
+ """Runs the full parse, fetch, and analyze pipeline for a query and returns the analysis text."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
query_info = self.parse_query(query)
period = _normalize_period(query_info.get("time_period", "6mo"))
stock_data = self.tools.get_stock_data(query_info["symbol"], period)
@@@ -93,10 -137,11 +186,18 @@@
def run_financial_analysis(query: str) -> str:
++<<<<<<< HEAD
+ gemini_api_key = os.getenv("GEMINI_API_KEY")
+ if not gemini_api_key:
+ return "Error: GEMINI_API_KEY environment variable is not set."
+ team = FinancialAnalysisTeam(gemini_api_key)
++=======
+ """Builds a FinancialAnalysisTeam from the configured Mistral API key and runs the given query."""
+ mistral_api_key = os.getenv("MISTRAL_API_KEY")
+ if not mistral_api_key:
+ return "Error: MISTRAL_API_KEY environment variable is not set."
+ team = FinancialAnalysisTeam(mistral_api_key)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
try:
return team.analyze(query)
except Exception as e:
diff --cc ai_agents/finagent/main.py
index 3b1a217,702e677..cc82ad0
--- a/ai_agents/finagent/main.py
+++ b/ai_agents/finagent/main.py
@@@ -1,6 -1,10 +1,16 @@@
++<<<<<<< HEAD
+from mcp.server.fastmcp import FastMCP
+from financial_agents import run_financial_analysis
+
++=======
+ """MCP server exposing the financial stock analysis tools backed by Mistral Small 4."""
+
+ from dotenv import load_dotenv
+ from mcp.server.fastmcp import FastMCP
+ from financial_agents import run_financial_analysis
+
+ load_dotenv()
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# Create FastMCP instance
mcp = FastMCP("financial-analyst")
diff --cc ai_agents/finagent/requirements.txt
index cdf3f28,4daf2c8..ed238e8
--- a/ai_agents/finagent/requirements.txt
+++ b/ai_agents/finagent/requirements.txt
@@@ -1,7 -1,4 +1,13 @@@
++<<<<<<< HEAD
+google-generativeai>=0.3.0
+mcp>=0.1.0
+yfinance>=0.2.18
+pandas>=1.5.0
+numpy>=1.21.0
+matplotlib>=3.5.0
++=======
+ mistralai>=1.0.0
+ mcp>=0.1.0
+ yfinance>=0.2.18
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
python-dotenv>=0.19.0
diff --cc ai_agents/github_intelligence_agent/.env.example
index e2c5776,df67822..7dcae0c
--- a/ai_agents/github_intelligence_agent/.env.example
+++ b/ai_agents/github_intelligence_agent/.env.example
@@@ -1,8 -1,6 +1,16 @@@
++<<<<<<< HEAD
+# Google Gemini β€” required
+# Get your free API key at https://aistudio.google.com
+GEMINI_API_KEY=your_gemini_api_key_here
+
+# GitHub Personal Access Token β€” required
+# GitHub β†’ Settings β†’ Developer Settings β†’ Personal Access Tokens β†’ Fine-grained
+# Read-only access to public repositories is enough
++=======
+ # Google Gemini API key (required). Get one free at https://aistudio.google.com
+ GEMINI_API_KEY=your_gemini_api_key_here
+
+ # GitHub Personal Access Token (required). Generate one at GitHub Settings > Developer Settings > Personal Access Tokens > Fine-grained.
+ # Read-only access to public repositories is enough.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
GITHUB_PAT=your_github_pat_here
diff --cc ai_agents/github_intelligence_agent/README.md
index 540e33d,09ca9d3..03ee596
--- a/ai_agents/github_intelligence_agent/README.md
+++ b/ai_agents/github_intelligence_agent/README.md
@@@ -6,7 -6,7 +6,11 @@@
## Overview
++<<<<<<< HEAD
+GitHub Intelligence Agent connects Gemini 3 Flash to GitHub's official MCP server through Haystack, giving you a conversational interface to the entire GitHub API. Ask it anything β€” surface trending repositories, profile a contributor, summarise open issues, or explore a codebase β€” and it figures out which tools to call on its own.
++=======
+ GitHub Intelligence Agent connects Gemini 3 Flash to GitHub's official MCP server through Haystack, giving you a conversational interface to the entire GitHub API. Ask it anything: surface trending repositories, profile a contributor, summarise open issues, or explore a codebase. It figures out which tools to call on its own.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
The agent uses Haystack's **SearchableToolset** to dynamically discover tools from GitHub's catalog of 40+ API endpoints. Instead of loading every tool schema upfront (which would blow the context limit), it searches for relevant tools by keyword and loads only what it needs. This keeps the context lean and the agent focused.
@@@ -22,25 -22,25 +26,44 @@@
## Tech Stack
**Frameworks and Libraries:**
++<<<<<<< HEAD
+- [Haystack](https://haystack.deepset.ai/) β€” agent framework and tool orchestration
+- [Streamlit](https://streamlit.io/) β€” chat UI with streaming support
+
+**Models and APIs:**
+- [Gemini 3 Flash](https://aistudio.google.com/) via Google AI β€” reasoning and tool calling
+- [GitHub MCP Server](https://api.githubcopilot.com/mcp/) β€” official GitHub API over MCP
+
+**Key Haystack Components:**
+- `MCPToolset` β€” connects to GitHub's MCP server
+- `SearchableToolset` β€” dynamically discovers tools to keep context lean
+- `GoogleAIGeminiChatGenerator` β€” Gemini 3 Flash integration
++=======
+ - [Haystack](https://haystack.deepset.ai/): agent framework and tool orchestration
+ - [Streamlit](https://streamlit.io/): chat UI with streaming support
+
+ **Models and APIs:**
+ - [Gemini 3 Flash](https://aistudio.google.com/) via Google AI: reasoning and tool calling
+ - [GitHub MCP Server](https://api.githubcopilot.com/mcp/): official GitHub API over MCP
+
+ **Key Haystack Components:**
+ - `MCPToolset`: connects to GitHub's MCP server
+ - `SearchableToolset`: dynamically discovers tools to keep context lean
+ - `GoogleAIGeminiChatGenerator`: Gemini 3 Flash integration
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Prerequisites
- Python 3.11 or higher
- [uv](https://docs.astral.sh/uv/) (recommended) or pip
- API keys for:
++<<<<<<< HEAD
+ - [ ] Google Gemini β€” free at https://aistudio.google.com
+ - [ ] GitHub Personal Access Token β€” read-only permissions are enough
++=======
+ - [ ] Google Gemini (free at https://aistudio.google.com)
+ - [ ] GitHub Personal Access Token (read-only permissions are enough)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
### Getting a GitHub PAT
@@@ -66,12 -66,6 +89,15 @@@ cd Hands-On-AI-Engineering/ai_agents/gi
uv sync
```
++<<<<<<< HEAD
+Or with pip:
+
+```bash
+pip install -r requirements.txt
+```
+
++=======
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
### 3. Set Up Environment Variables
```bash
diff --cc ai_agents/github_intelligence_agent/app.py
index e955407,8e1c08b..20203b0
--- a/ai_agents/github_intelligence_agent/app.py
+++ b/ai_agents/github_intelligence_agent/app.py
@@@ -1,5 -1,5 +1,9 @@@
"""
++<<<<<<< HEAD
+GitHub Intelligence Agent β€” Streamlit UI
++=======
+ GitHub Intelligence Agent: Streamlit UI
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
Research anything on GitHub through natural language.
Powered by Gemini 3 Flash + GitHub MCP Server via Haystack.
diff --cc ai_agents/multi_agent_financial_analyst/README.md
index 75ae4d1,b6a90c6..4aae820
--- a/ai_agents/multi_agent_financial_analyst/README.md
+++ b/ai_agents/multi_agent_financial_analyst/README.md
@@@ -1,7 -1,25 +1,31 @@@
++<<<<<<< HEAD
++=======
+ <a id="top"></a>
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# 🎯 Multi-Agent AI Financial Analyst
A powerful multi-agent system that performs comprehensive stock analysis and generates detailed financial reports.
++<<<<<<< HEAD
++=======
+ ## Demo
+
+ ![Demo](assets/demo.png)
+
+ ## Tech Stack
+
+ - **Provider:** Orq.ai
+ - **Model:** alibaba/qwen3.6-flash via Orq.ai
+ - **Agent framework:** CrewAI
+ - **UI:** Streamlit
+ - **Market data:** yfinance
+
+ ## Prerequisites
+
+ - Python 3.10 or higher
+ - An Orq.ai account and API key, available at https://orq.ai
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Features
- Stock Analysis Agent: Performs thorough analysis of stocks using fundamental and technical indicators
@@@ -23,9 -41,9 +47,15 @@@
pip install -r requirements.txt
```
++<<<<<<< HEAD
+3. Create a `.env` file in the root directory and add your SambaNova API key:
+```bash
+SAMBANOVA_API_KEY=your_api_key_here
++=======
+ 3. Create a `.env` file in the root directory and add your Orq.ai API key:
+ ```bash
+ ORQ_API_KEY=your_orq_api_key_here
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```
## Usage
@@@ -63,4 -81,6 +93,10 @@@ Contributions are welcome! Please feel
## License
- This project is licensed under the MIT License - see the LICENSE file for details.
++<<<<<<< HEAD
++This project is licensed under the MIT License - see the LICENSE file for details.
++=======
+ This project is licensed under the MIT License - see the LICENSE file for details.
+
-[Back to top](#top)
++[Back to top](#top)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc ai_agents/multi_agent_financial_analyst/financial_analyst.py
index f7eba00,e5b4fb5..641bd61
--- a/ai_agents/multi_agent_financial_analyst/financial_analyst.py
+++ b/ai_agents/multi_agent_financial_analyst/financial_analyst.py
@@@ -1,3 -1,4 +1,7 @@@
++<<<<<<< HEAD
++=======
+ """Streamlit app that runs a multi-agent CrewAI pipeline to analyze a stock and generate a markdown investment report."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import streamlit as st
import os
import pandas as pd
@@@ -23,17 -24,20 +27,32 @@@ class StockAnalysis(BaseModel)
technical_indicators: dict
fundamental_metrics: dict
++<<<<<<< HEAD
+# Initialize SambaNova LLM
+def load_llm():
+ return LLM(
+ model="sambanova/Llama-4-Maverick-17B-128E-Instruct",
+ api_key=os.getenv("SAMBANOVA_API_KEY"),
++=======
+ # Initialize Orq.ai LLM
+ @st.cache_resource
+ def load_llm():
+ """Create and cache the Orq.ai LLM client used by the agents."""
+ return LLM(
+ model="openai/alibaba/qwen3.6-flash",
+ base_url="https://api.orq.ai/v3/router",
+ api_key=os.getenv("ORQ_API_KEY"),
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
temperature=0.3
)
# Create agents and tasks
def create_agents_and_tasks(symbol: str):
++<<<<<<< HEAD
++=======
+ """Build the stock analysis and report writing agents, their tasks, and the crew that runs them for the given symbol."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
llm = load_llm()
# Initialize tools
@@@ -170,16 -174,6 +189,19 @@@ st.title("🎯 Multi-Agent AI Financia
# Sidebar
with st.sidebar:
st.header("Configuration")
++<<<<<<< HEAD
+
+ # API Key input
+ api_key = st.text_input(
+ "SambaNova API Key",
+ type="password",
+ value=os.getenv("SAMBANOVA_API_KEY", ""),
+ help="Enter your SambaNova API key"
+ )
+ if api_key:
+ os.environ["SAMBANOVA_API_KEY"] = api_key
++=======
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# Stock Symbol input
symbol = st.text_input(
diff --cc ai_agents/multi_agent_financial_analyst/requirements.txt
index 6d51798,ad7ec33..2a54162
--- a/ai_agents/multi_agent_financial_analyst/requirements.txt
+++ b/ai_agents/multi_agent_financial_analyst/requirements.txt
@@@ -4,4 -4,6 +4,10 @@@ python-dotenv>=1.0.
pydantic>=2.5.0
yfinance>=0.2.35
pandas>=2.1.0
- plotly>=5.18.0
++<<<<<<< HEAD
++plotly>=5.18.0
++=======
+ plotly>=5.18.0
+ openai>=1.0.0
-litellm>=1.0.0
++litellm>=1.0.0
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc ai_agents/multi_agent_financial_analyst/tools/financial_tools.py
index 71885ca,b9f42da..cd75154
--- a/ai_agents/multi_agent_financial_analyst/tools/financial_tools.py
+++ b/ai_agents/multi_agent_financial_analyst/tools/financial_tools.py
@@@ -9,6 -9,7 +9,10 @@@ class StockInput(BaseModel)
symbol: str = Field(..., description="The stock symbol to analyze (e.g., 'AAPL', 'GOOGL')")
class YFinanceStockTool(BaseTool):
++<<<<<<< HEAD
++=======
+ """CrewAI tool that fetches real-time and historical stock data from Yahoo Finance."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
name: str = "stock_data_tool"
description: str = """
A tool for getting real-time and historical stock market data.
@@@ -22,6 -23,7 +26,10 @@@
args_schema: type[BaseModel] = StockInput
def _run(self, symbol: str) -> str:
++<<<<<<< HEAD
++=======
+ """Fetch latest trading data, 52-week range, and key financial metrics for the given stock symbol."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
try:
stock = yf.Ticker(symbol)
@@@ -70,5 -72,6 +78,9 @@@
return f"Error fetching data for {symbol}: {str(e)}"
def _arun(self, symbol: str) -> str:
++<<<<<<< HEAD
++=======
+ """Async counterpart of _run, not implemented for this tool."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# Async implementation if needed
raise NotImplementedError("Async version not implemented")
diff --cc ai_agents/multi_agent_research_assistant_ag2/.env.example
index 1650210,48e13ce..31e8faf
--- a/ai_agents/multi_agent_research_assistant_ag2/.env.example
+++ b/ai_agents/multi_agent_research_assistant_ag2/.env.example
@@@ -1,3 -1,4 +1,10 @@@
++<<<<<<< HEAD
+OPENAI_API_KEY=your_openai_api_key_here
+OPENAI_BASE_URL=https://api.openai.com/v1 # override for SambaNova, Azure, etc.
+LLM_MODEL=gpt-4o-mini
++=======
+ # Mistral API key used by the researcher, analyst, and writer agents (Mistral Small 4).
+ # Get one at https://console.mistral.ai/api-keys
+ MISTRAL_API_KEY=your_mistral_api_key_here
+ LLM_MODEL=mistral-small-latest
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc ai_agents/multi_agent_research_assistant_ag2/README.md
index e34805b,198e5c0..11a5a61
--- a/ai_agents/multi_agent_research_assistant_ag2/README.md
+++ b/ai_agents/multi_agent_research_assistant_ag2/README.md
@@@ -1,25 -1,31 +1,54 @@@
++<<<<<<< HEAD
+# Multi-Agent Research Assistant with AG2
+
+A production-grade multi-agent research pipeline using [AG2](https://github.com/ag2ai/ag2)
+(formerly AutoGen). Three specialists collaborate under GroupChat with LLM-driven speaker
+selection to research any topic and produce a structured Markdown report.
+
+## Features
+- Multi-agent collaboration (researcher, analyst, writer) under GroupChat
+- LLM-driven dynamic speaker selection β€” no hardcoded turn order
+- AG2's `register_function(caller=, executor=)` tool registration pattern
+- OpenAI-compatible endpoint (works with SambaNova, Azure OpenAI, local models via Ollama)
+- Download report as Markdown
+
+## Prerequisites
+- Python 3.10+
+- OpenAI API key (or compatible endpoint)
++=======
+ <a id="top"></a>
+
+ # Multi-Agent Research Assistant with AG2
+
+ A production-grade multi-agent research pipeline using [AG2](https://github.com/ag2ai/ag2)
+ (formerly AutoGen). Three specialists collaborate under GroupChat to research any topic
+ and produce a structured Markdown report, powered by Mistral Small 4
+ (`mistral-small-latest`) via AG2's native Mistral integration.
+
+ ## Features
+ - Multi-agent collaboration (researcher, analyst, writer) under GroupChat
+ - AG2's `register_function(caller=, executor=)` tool registration pattern
+ - Native Mistral support via AG2's `api_type: "mistral"` config entry
+ - Download report as Markdown
+
+ ## Demo
+
+ ![Demo](assets/demo.gif)
+
+ ## Prerequisites
+ - Python 3.10+
+ - Mistral API key from [console.mistral.ai](https://console.mistral.ai/api-keys)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Installation
```bash
cd multi_agent_research_assistant_ag2
pip install -r requirements.txt
++<<<<<<< HEAD
+cp .env.example .env # add your API key
++=======
+ cp .env.example .env # add your Mistral API key
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```
## Usage
@@@ -32,12 -38,13 +61,22 @@@ streamlit run research_assistant.p
1. **Researcher** searches the web using DuckDuckGo API and summarises findings
2. **Analyst** critically reviews the research and identifies gaps
3. **Writer** synthesises all inputs into a structured Markdown report
++<<<<<<< HEAD
+4. **GroupChatManager** uses LLM-based speaker selection to orchestrate the conversation
+
+## AG2 Concepts Demonstrated
+- `GroupChat` with `speaker_selection_method="auto"`
+- `register_function(caller=, executor=)` β€” separates tool description from execution
+- `UserProxyAgent` with `code_execution_config` β€” built-in code execution sandbox
++=======
+ 4. **GroupChatManager** orchestrates the analyst and writer in round-robin order
+
+ ## AG2 Concepts Demonstrated
+ - `GroupChat` with `speaker_selection_method="round_robin"`
+ - `register_function(caller=, executor=)`, which separates tool description from execution
+ - `UserProxyAgent` with `code_execution_config`, providing a built-in code execution sandbox
+ - Native Mistral integration via `{"api_type": "mistral", "model": "mistral-small-latest", ...}` in `LLMConfig`, instead of pointing an OpenAI-compatible `base_url` at Mistral's endpoint
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
> **Security note:** `use_docker=False` in `code_execution_config` means any agent-generated
> code runs directly in your process. For production use, set `use_docker=True` or run in
@@@ -45,7 -52,7 +84,11 @@@
## Running Tests
++<<<<<<< HEAD
+Tests are fully mocked β€” no API keys or network access required.
++=======
+ Tests are fully mocked and require no API keys or network access.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```bash
pip install pytest
@@@ -66,3 -73,7 +109,10 @@@ multi_agent_research_assistant_ag2
β”œβ”€β”€ requirements.txt
└── .env.example
```
++<<<<<<< HEAD
++=======
+
+ ---
+
+ [Back to top](#top)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc ai_agents/multi_agent_research_assistant_ag2/requirements.txt
index 340ceea,4cf915d..2bedb67
--- a/ai_agents/multi_agent_research_assistant_ag2/requirements.txt
+++ b/ai_agents/multi_agent_research_assistant_ag2/requirements.txt
@@@ -1,3 -1,4 +1,7 @@@
ag2>=0.11.0
++<<<<<<< HEAD
++=======
+ mistralai>=2.0.0
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
streamlit>=1.31.0
python-dotenv>=1.0.0
diff --cc ai_agents/multi_agent_research_assistant_ag2/research_assistant.py
index abbf300,f8d9354..301bbae
--- a/ai_agents/multi_agent_research_assistant_ag2/research_assistant.py
+++ b/ai_agents/multi_agent_research_assistant_ag2/research_assistant.py
@@@ -1,4 -1,5 +1,9 @@@
++<<<<<<< HEAD
+# research_assistant.py
++=======
+ """Multi-agent research pipeline using AG2 (AutoGen): researcher, analyst, and writer
+ agents collaborate under GroupChat, powered by Mistral Small 4, with a Streamlit UI."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import os
import streamlit as st
from datetime import datetime
@@@ -9,32 -10,69 +14,92 @@@ from tools.research_tools import web_se
load_dotenv()
++<<<<<<< HEAD
+# ── AG2 (formerly AutoGen) requires ag2>=0.11 ──────────────────────────────────
+
+def build_llm_config() -> LLMConfig:
+ api_key = os.getenv("OPENAI_API_KEY", "")
+ if not api_key:
+ raise ValueError("OPENAI_API_KEY is not set. Add it to .env or the sidebar.")
+ return LLMConfig(
+ {"model": os.getenv("LLM_MODEL", "gpt-4o-mini"),
+ "api_key": api_key,
+ "base_url": os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")},
++=======
+ # ── Patch: normalize Mistral citation chunks before AG2's message parser sees them ──
+ # Mistral's grounding/web-search feature returns AssistantMessage.content as
+ # list[TextChunk | ReferenceChunk] instead of a plain str. AG2's ChatCompletionMessage
+ # expects str | dict | list[dict] | None, so passing Pydantic objects causes validation
+ # errors. We replace the ChatCompletionMessage name in autogen.oai.mistral's module
+ # namespace with a factory that flattens the list to a string first.
+ import autogen.oai.mistral as _mistral_module
+ from autogen.oai.oai_models import ChatCompletionMessage as _RealCCM
+ from mistralai.client.models import TextChunk as _TextChunk
+
+
+ def _normalize_mistral_content(content):
+ if not isinstance(content, list):
+ return content
+ return "".join(
+ chunk.text if isinstance(chunk, _TextChunk) else
+ (chunk.text if hasattr(chunk, "text") else "")
+ for chunk in content
+ )
+
+
+ def _CCMFactory(**kwargs):
+ content = kwargs.get("content")
+ if isinstance(content, list):
+ kwargs["content"] = _normalize_mistral_content(content)
+ return _RealCCM(**kwargs)
+
+
+ _mistral_module.ChatCompletionMessage = _CCMFactory
+ # ── End patch ──────────────────────────────────────────────────────────────────
+
+
+ def build_llm_config() -> LLMConfig:
+ """Builds the AG2 LLMConfig for Mistral Small 4 using AG2's native Mistral client."""
+ api_key = os.getenv("MISTRAL_API_KEY", "")
+ if not api_key:
+ raise ValueError("MISTRAL_API_KEY is not set. Add it to .env or the sidebar.")
+ return LLMConfig(
+ {"api_type": "mistral",
+ "model": os.getenv("LLM_MODEL", "mistral-small-latest"),
+ "api_key": api_key},
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
temperature=0.3,
cache_seed=None, # always fetch fresh data
)
def run_research(topic: str) -> str:
++<<<<<<< HEAD
++=======
+ """Runs the researcher, analyst, and writer agents and returns the final report.
+
+ Tool calls are confined to an isolated researcher/executor exchange, separate from
+ the analyst/writer GroupChat. Mistral's API rejects message histories where the
+ number of function calls and responses don't match, which happens when GroupChat's
+ "auto" speaker selection asks the LLM who should speak next while a tool call from
+ researcher is still awaiting its response from executor.
+ """
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
llm_config = build_llm_config()
# ── Agents ─────────────────────────────────────────────────────────────────
researcher = AssistantAgent(
name="researcher",
++<<<<<<< HEAD
+ system_message="""You are a research specialist. Your job is to gather
+comprehensive information about the given topic using web_search and fetch_page_content.
+Perform at least 3 searches and fetch content from 2+ pages.
+Summarise all findings clearly. End with: RESEARCH COMPLETE.""",
++=======
+ system_message="""You are a research specialist. Search for information about the given topic using web_search.
+ Perform exactly 2 searches, then summarise the findings clearly. End with: RESEARCH COMPLETE.""",
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
llm_config=llm_config,
)
@@@ -63,7 -101,9 +128,13 @@@ End with: REPORT COMPLETE"""
name="executor",
human_input_mode="NEVER",
code_execution_config={"work_dir": "workspace", "use_docker": False},
++<<<<<<< HEAD
+ is_termination_msg=lambda msg: "REPORT COMPLETE" in (msg.get("content") or ""),
++=======
+ is_termination_msg=lambda msg: any(
+ phrase in (msg.get("content") or "") for phrase in ("RESEARCH COMPLETE", "REPORT COMPLETE")
+ ),
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
default_auto_reply="",
)
@@@ -81,18 -121,37 +152,50 @@@
description=(fn.__doc__ or "").strip().split("\n")[0],
)
++<<<<<<< HEAD
+ # ── GroupChat orchestration ────────────────────────────────────────────────
+ groupchat = GroupChat(
+ agents=[executor, researcher, analyst, writer],
+ messages=[],
+ max_round=20,
+ speaker_selection_method="auto", # LLM selects the next speaker
++=======
+ # ── Phase 1: isolated researcher/executor exchange ─────────────────────────
+ # A plain two-agent chat always pairs a tool call with its response in the
+ # same turn, so there is never an orphaned tool call in the history.
+
+ executor.initiate_chat(
+ researcher,
+ message=f"Research the following topic thoroughly: {topic}",
+ clear_history=True,
+ )
+ research_notes = researcher.last_message(executor)["content"]
+ # Strip the Phase 1 sentinel before handing off to Phase 2. Without this,
+ # executor's is_termination_msg fires on the GroupChat kickoff message
+ # (which contains the raw notes) and terminates the chat before analyst
+ # or writer ever speak.
+ research_notes = research_notes.replace("RESEARCH COMPLETE", "").strip()
+
+ # ── Phase 2: GroupChat orchestration for analyst and writer ────────────────
+ # Neither agent calls tools, so the LLM-driven speaker selection below never
+ # sees an unanswered tool call in the shared history.
+
+ groupchat = GroupChat(
+ agents=[executor, analyst, writer],
+ messages=[],
+ max_round=6,
+ speaker_selection_method="round_robin", # analyst then writer, no extra LLM call per round
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
)
manager = GroupChatManager(groupchat=groupchat, llm_config=llm_config)
executor.initiate_chat(
manager,
++<<<<<<< HEAD
+ message=f"Research the following topic thoroughly: {topic}",
++=======
+ message=f"Research on '{topic}' is complete. Analyst, please critically evaluate the findings below:\n\n{research_notes}",
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
clear_history=True,
)
@@@ -109,19 -168,10 +212,26 @@@
st.set_page_config(page_title="Multi-Agent Research Assistant (AG2)", layout="wide")
st.title("Multi-Agent Research Assistant")
++<<<<<<< HEAD
+st.caption("Powered by AG2 (formerly AutoGen) β€” multi-agent research orchestration")
+
+with st.sidebar:
+ st.header("Configuration")
+ api_key = st.text_input("OpenAI API Key", type="password",
+ value=os.getenv("OPENAI_API_KEY", ""))
+ if api_key:
+ os.environ["OPENAI_API_KEY"] = api_key
+ model = st.text_input("Model", value=os.getenv("LLM_MODEL", "gpt-4o-mini"))
+ if model:
+ os.environ["LLM_MODEL"] = model
+ topic = st.text_area("Research Topic", placeholder="e.g. 'Latest advances in quantum computing'")
+ run_btn = st.button("Start Research", type="primary")
++=======
+ st.caption("Powered by AG2 (formerly AutoGen): multi-agent research orchestration")
+
+ topic = st.text_area("Research Topic", placeholder="e.g. 'Latest advances in quantum computing'")
+ run_btn = st.button("Start Research", type="primary")
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if "report" not in st.session_state:
st.session_state.report = None
diff --cc ai_agents/multi_agent_research_assistant_ag2/tests/test_agent_setup.py
index 5749132,a3a2c52..781a90a
--- a/ai_agents/multi_agent_research_assistant_ag2/tests/test_agent_setup.py
+++ b/ai_agents/multi_agent_research_assistant_ag2/tests/test_agent_setup.py
@@@ -1,6 -1,6 +1,10 @@@
import os
import pytest
++<<<<<<< HEAD
+os.environ.setdefault("OPENAI_API_KEY", "test-key-no-llm-calls")
++=======
+ os.environ.setdefault("MISTRAL_API_KEY", "test-key-no-llm-calls")
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
def test_agents_instantiate():
"""Verify agent setup does not raise β€” no LLM calls made."""
@@@ -34,7 -34,7 +38,11 @@@ def test_tool_registration()
from tools.research_tools import web_search, fetch_page_content
from autogen import AssistantAgent, UserProxyAgent, LLMConfig, register_function
++<<<<<<< HEAD
+ llm = LLMConfig({"model": "gpt-4o-mini", "api_key": "test"})
++=======
+ llm = LLMConfig({"api_type": "mistral", "model": "mistral-small-latest", "api_key": "test"})
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
researcher = AssistantAgent(name="r", system_message="test", llm_config=llm)
executor = UserProxyAgent(name="e", human_input_mode="NEVER", code_execution_config=False)
for fn in (web_search, fetch_page_content):
diff --cc ai_agents/research_team/.env.example
index c798c95,7b2e989..8944a47
--- a/ai_agents/research_team/.env.example
+++ b/ai_agents/research_team/.env.example
@@@ -1,3 -1,2 +1,7 @@@
++<<<<<<< HEAD
+# OpenRouter β€” required
+# Get your API key at https://openrouter.ai
++=======
+ # OpenRouter API key (required). Get yours at https://openrouter.ai
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
OPENROUTER_API_KEY=your_openrouter_api_key_here
diff --cc ai_agents/research_team/README.md
index f67086b,7cb16cf..d09e96a
--- a/ai_agents/research_team/README.md
+++ b/ai_agents/research_team/README.md
@@@ -8,7 -8,7 +8,11 @@@
Research Team is a two-agent AI system that tackles deep research questions by splitting work between specialists. Seek searches the web for external information while Scout looks through local documents. A team leader powered by **MiniMax M2.5** coordinates both, then synthesises their findings into a clean, structured report.
++<<<<<<< HEAD
+You give it a question like "Research Anthropic β€” their products, key people, and recent developments" and it comes back with an executive summary, sourced key findings, and open questions.
++=======
+ You give it a question like "Research Anthropic: their products, key people, and recent developments" and it comes back with an executive summary, sourced key findings, and open questions.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Features
@@@ -16,24 -16,24 +20,41 @@@
- **Scout agent**: Reads local files from the `knowledge/` directory to surface internal context
- **Team leader**: Delegates work to each specialist, cross-references findings, and produces a unified report
- **Streaming UI**: Report appears progressively in the Gradio interface as the team works
++<<<<<<< HEAD
+- **File upload**: Upload `.txt`, `.md`, or `.pdf` files directly from the UI β€” Scout reads them instantly on the next query
++=======
+ - **File upload**: Upload `.txt`, `.md`, or `.pdf` files directly from the UI. Scout reads them instantly on the next query.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Tech Stack
**Frameworks and Libraries:**
++<<<<<<< HEAD
+- [Agno](https://github.com/agno-agi/agno) β€” agent and team framework
+- [Gradio](https://www.gradio.app/) β€” web UI with streaming support
+
+**Models and APIs:**
+- [MiniMax M2.5](https://openrouter.ai/minimax/minimax-m2.5) via [OpenRouter](https://openrouter.ai/) β€” team leader and both agents
+- [DuckDuckGo Search](https://pypi.org/project/duckduckgo-search/) β€” web search for Seek
++=======
+ - [Agno](https://github.com/agno-agi/agno): agent and team framework
+ - [Gradio](https://www.gradio.app/): web UI with streaming support
+
+ **Models and APIs:**
+ - [MiniMax M2.5](https://openrouter.ai/minimax/minimax-m2.5) via [OpenRouter](https://openrouter.ai/): team leader and both agents
+ - [DuckDuckGo Search](https://pypi.org/project/duckduckgo-search/): web search for Seek
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Prerequisites
- Python 3.11 or higher
- [uv](https://docs.astral.sh/uv/) (recommended) or pip
- API keys for:
++<<<<<<< HEAD
+ - [ ] OpenRouter β€” get yours at https://openrouter.ai
++=======
+ - [ ] OpenRouter (get yours at https://openrouter.ai)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Installation
@@@ -50,12 -50,6 +71,15 @@@ cd Hands-On-AI-Engineering/ai_agents/re
uv sync
```
++<<<<<<< HEAD
+Or with pip:
+
+```bash
+pip install -r requirements.txt
+```
+
++=======
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
### 3. Set Up Environment Variables
```bash
@@@ -83,7 -77,7 +107,11 @@@ Then open http://localhost:7860 in you
Enter a research query like:
```
++<<<<<<< HEAD
+Research Anthropic β€” their products, key people, and recent developments
++=======
+ Research Anthropic: their products, key people, and recent developments
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```
The team will search the web, check local docs, and stream back a structured report.
@@@ -112,6 -106,6 +140,10 @@@ The team leader receives a research que
Once both agents respond, the leader cross-references their findings, flags anything contradictory, and writes a final report with an executive summary, sourced key findings, and open questions.
++<<<<<<< HEAD
+The Gradio app uses the same stream-buffering technique as the other projects in this repo β€” output is held until the first markdown heading appears, so the UI never shows raw model narration.
++=======
+ The Gradio app uses the same stream-buffering technique as the other projects in this repo. Output is held until the first markdown heading appears, so the UI never shows raw model narration.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
[Back to Top](#research-team)
diff --cc ai_agents/research_team/agents/scout.py
index caff2ca,efa201b..b9e55fd
--- a/ai_agents/research_team/agents/scout.py
+++ b/ai_agents/research_team/agents/scout.py
@@@ -12,6 -12,7 +12,10 @@@ KNOWLEDGE_DIR = Path(__file__).parent.p
def get_scout() -> Agent:
++<<<<<<< HEAD
++=======
+ """Build and return the Scout agent configured to read and surface information from local files in the knowledge directory."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return Agent(
name="Scout",
role="Internal knowledge navigator",
diff --cc ai_agents/research_team/agents/seek.py
index 9ec1962,f544922..abdf14f
--- a/ai_agents/research_team/agents/seek.py
+++ b/ai_agents/research_team/agents/seek.py
@@@ -11,6 -11,7 +11,10 @@@ from models import get_mode
def get_seek() -> Agent:
++<<<<<<< HEAD
++=======
+ """Build and return the Seek agent configured for external web research using DuckDuckGo and WebsiteTools."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return Agent(
name="Seek",
role="External web researcher",
diff --cc ai_agents/research_team/app.py
index ccff855,23ca025..ded2280
--- a/ai_agents/research_team/app.py
+++ b/ai_agents/research_team/app.py
@@@ -1,5 -1,5 +1,9 @@@
"""
++<<<<<<< HEAD
+Research Team β€” Gradio UI
++=======
+ Research Team: Gradio UI
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
Seek + Scout powered by MiniMax M2.5 via OpenRouter.
Usage:
@@@ -64,6 -64,7 +68,10 @@@ def list_docs() -> str
# ── Research Function ──────────────────────────────────────────────────────────
def run_research(query: str):
++<<<<<<< HEAD
++=======
+ """Run the research team on the given query and yield the report and status as it streams."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
query = query.strip()
if not query:
yield PLACEHOLDER, ""
@@@ -82,6 -83,7 +90,10 @@@
def clear_all():
++<<<<<<< HEAD
++=======
+ """Reset the query input, report output, and status box to their default empty state."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return "", PLACEHOLDER, ""
diff --cc ai_agents/research_team/models.py
index 2fb6925,0c6724a..a73ad2d
--- a/ai_agents/research_team/models.py
+++ b/ai_agents/research_team/models.py
@@@ -6,6 -6,7 +6,10 @@@ MODEL_ID = "minimax/minimax-m2.5:free
def get_model() -> OpenAILike:
++<<<<<<< HEAD
++=======
+ """Return a configured OpenAILike model instance pointed at MiniMax M2.5 via OpenRouter."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return OpenAILike(
id=MODEL_ID,
api_key=os.getenv("OPENROUTER_API_KEY"),
diff --cc ai_agents/research_team/team.py
index ffb2882,2c4d332..0c7fa60
--- a/ai_agents/research_team/team.py
+++ b/ai_agents/research_team/team.py
@@@ -36,6 -36,7 +36,10 @@@ def _has_knowledge() -> bool
def build_instructions() -> str:
++<<<<<<< HEAD
++=======
+ """Build the team leader's instruction string, adapting the workflow based on whether the knowledge directory has files."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if _has_knowledge():
scout_note = (
"- Scout: Internal knowledge navigator. Use Scout to search the "
diff --cc ai_agents/smolagents_code_agent/README.md
index c98eb5a,b9281ab..8d279b6
--- a/ai_agents/smolagents_code_agent/README.md
+++ b/ai_agents/smolagents_code_agent/README.md
@@@ -4,7 -4,7 +4,11 @@@
## Overview
++<<<<<<< HEAD
+Smolagents Code Agent wires together HuggingFace's **smolagents** `CodeAgent` and **Mistral Small** (via LiteLLM) into a Gradio web app. You type a task, the agent writes and executes Python code using DuckDuckGo and Wikipedia, and every reasoning step appears in the UI as it happens β€” no waiting for a final answer to see what the model was thinking.
++=======
+ Smolagents Code Agent wires together HuggingFace's **smolagents** `CodeAgent` and **Mistral Small** (via LiteLLM) into a Gradio web app. You type a task, the agent writes and executes Python code using DuckDuckGo and Wikipedia, and every reasoning step appears in the UI as it happens. No waiting for a final answer to see what the model was thinking.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Demo
@@@ -12,18 -12,18 +16,31 @@@
## Features
++<<<<<<< HEAD
+- **Real-time trace streaming** β€” every Think, Act, and Observe step appears in the UI as the agent works, powered by `step_callbacks` and a background thread queue
+- **Code-first reasoning** β€” the agent writes and executes Python code at each step rather than calling fixed tool APIs
+- **Two built-in tools** β€” `DuckDuckGoSearchTool` for live web search and a custom `WikipediaTool` that fetches 5-sentence article summaries
+- **Clean final answer** β€” the agent's conclusion is extracted and displayed separately from the full reasoning trace
+- **Swappable LLM** β€” change one line in `app.py` to switch from Mistral Small to DeepSeek V3 Flash via OpenRouter (see [Usage](#usage))
+- **Run/Clear controls** β€” a spinner confirms the agent is active; Clear resets all outputs instantly
++=======
+ - **Real-time trace streaming**: every Think, Act, and Observe step appears in the UI as the agent works, powered by `step_callbacks` and a background thread queue
+ - **Code-first reasoning**: the agent writes and executes Python code at each step rather than calling fixed tool APIs
+ - **Two built-in tools**: `DuckDuckGoSearchTool` for live web search and a custom `WikipediaTool` that fetches 5-sentence article summaries
+ - **Clean final answer**: the agent's conclusion is extracted and displayed separately from the full reasoning trace
+ - **Swappable LLM**: change one line in `app.py` to switch from Mistral Small to DeepSeek V3 Flash via OpenRouter (see [Usage](#usage))
+ - **Run/Clear controls**: a spinner confirms the agent is active; Clear resets all outputs instantly
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Tech Stack
| Layer | Technology |
|---|---|
++<<<<<<< HEAD
+| Agent framework | [HuggingFace smolagents](https://github.com/huggingface/smolagents) β€” `CodeAgent` |
++=======
+ | Agent framework | [HuggingFace smolagents](https://github.com/huggingface/smolagents) (`CodeAgent`) |
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
| LLM | Mistral Small 4 (`mistral-small-latest`) via `LiteLLMModel` |
| Web search | `DuckDuckGoSearchTool` (bundled with smolagents) |
| Knowledge tool | Custom `WikipediaTool` using the `wikipedia` package |
@@@ -32,7 -32,7 +49,11 @@@
## Prerequisites
- Python 3.10 or later
++<<<<<<< HEAD
+- A Mistral API key β€” get one at [platform.mistral.ai](https://platform.mistral.ai)
++=======
+ - A Mistral API key. Get one at [platform.mistral.ai](https://platform.mistral.ai)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Installation
@@@ -109,3 -109,5 +130,8 @@@ smolagents-code-agent
└── assets/
└── demo.png # Screenshot used in README
```
++<<<<<<< HEAD
++=======
+
+ [Back to Top](#smolagents-code-agent)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc ai_agents/smolagents_code_agent/app.py
index b4a63e0,63b145b..5bf1724
--- a/ai_agents/smolagents_code_agent/app.py
+++ b/ai_agents/smolagents_code_agent/app.py
@@@ -1,3 -1,4 +1,7 @@@
++<<<<<<< HEAD
++=======
+ """Smolagents Code Agent: a Gradio web app that streams live reasoning steps from a smolagents CodeAgent powered by Mistral Small via LiteLLM."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import os
import queue
import threading
diff --cc ai_agents/smolagents_code_agent/tools.py
index 1113870,9bebb36..fd4b666
--- a/ai_agents/smolagents_code_agent/tools.py
+++ b/ai_agents/smolagents_code_agent/tools.py
@@@ -3,6 -3,7 +3,10 @@@ from smolagents import Too
class WikipediaTool(Tool):
++<<<<<<< HEAD
++=======
+ """A smolagents tool that fetches a concise Wikipedia summary for any search query."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
name = "wikipedia"
description = (
"Searches Wikipedia and returns a summary of the most relevant article "
@@@ -18,6 -19,7 +22,10 @@@
output_type = "string"
def forward(self, query: str) -> str:
++<<<<<<< HEAD
++=======
+ """Search Wikipedia for the query and return a 5-sentence summary with title and URL."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
try:
results = wikipedia.search(query, results=3)
if not results:
diff --cc ai_agents/startup_analyst/README.md
index aa3e200,c26a9db..e5f4dac
--- a/ai_agents/startup_analyst/README.md
+++ b/ai_agents/startup_analyst/README.md
@@@ -23,12 -23,12 +23,21 @@@ The agent is powered by **MiniMax M2.5*
## Tech Stack
**Frameworks and Libraries:**
++<<<<<<< HEAD
+- [Agno](https://github.com/agno-agi/agno) β€” agent framework
+- [Gradio](https://www.gradio.app/) β€” web UI with streaming support
+
+**Models and APIs:**
+- [MiniMax M2.5](https://openrouter.ai/minimax/minimax-m2.5) via [OpenRouter](https://openrouter.ai/) β€” reasoning and report generation
+- [Firecrawl](https://firecrawl.dev/) β€” website scraping and crawling
++=======
+ - [Agno](https://github.com/agno-agi/agno) for the agent framework
+ - [Gradio](https://www.gradio.app/) for the web UI with streaming support
+
+ **Models and APIs:**
+ - [MiniMax M2.5](https://openrouter.ai/minimax/minimax-m2.5) via [OpenRouter](https://openrouter.ai/) for reasoning and report generation
+ - [Firecrawl](https://firecrawl.dev/) for website scraping and crawling
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Prerequisites
@@@ -53,12 -53,6 +62,15 @@@ cd Hands-On-AI-Engineering/ai_agents/st
uv sync
```
++<<<<<<< HEAD
+Or with pip:
+
+```bash
+pip install -r requirements.txt
+```
+
++=======
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
### 3. Set Up Environment Variables
```bash
diff --cc ai_agents/startup_analyst/agent.py
index c026735,cdd8711..189776e
--- a/ai_agents/startup_analyst/agent.py
+++ b/ai_agents/startup_analyst/agent.py
@@@ -14,6 -14,7 +14,10 @@@ MODEL_ID = "minimax/minimax-m2.5:free
def get_analyst() -> Agent:
++<<<<<<< HEAD
++=======
+ """Build and return a configured Startup Analyst agent with Firecrawl scraping and crawling tools."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return Agent(
name="Startup Analyst",
model=OpenAILike(
diff --cc ai_agents/startup_analyst/app.py
index c4cccdb,9219090..7b5a352
--- a/ai_agents/startup_analyst/app.py
+++ b/ai_agents/startup_analyst/app.py
@@@ -1,5 -1,5 +1,9 @@@
"""
++<<<<<<< HEAD
+Startup Analyst β€” Gradio UI
++=======
+ Startup Analyst - Gradio UI
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
Elite startup due-diligence powered by MiniMax M2.5 via OpenRouter.
Usage:
@@@ -10,6 -10,10 +14,13 @@@ from dotenv import load_doten
load_dotenv()
++<<<<<<< HEAD
++=======
+ import os
+ import re
+ import tempfile
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import gradio as gr
from agent import analyst
@@@ -32,15 -36,36 +43,48 @@@ EXAMPLES =
PLACEHOLDER = "_Your due-diligence report will appear here once you submit a company._"
++<<<<<<< HEAD
+# ── Analysis Function ──────────────────────────────────────────────────────────
+
+def run_analysis(prompt: str):
+ prompt = prompt.strip()
+ if not prompt:
+ yield PLACEHOLDER, ""
+ return
+
+ yield "_Analysing company β€” scraping website, crawling pages, gathering data..._", "Running..."
++=======
+ # ── Helpers ────────────────────────────────────────────────────────────────────
+
+ def _report_filename(prompt: str) -> str:
+ """Derive a sanitized .md filename from the company name in the prompt."""
+ match = re.search(r'\bon\s+(.+?)(?:\s*\(https?://)', prompt, re.IGNORECASE)
+ if match:
+ name = re.sub(r'[^\w\s]', '', match.group(1)).strip()
+ name = re.sub(r'\s+', '_', name).lower()
+ return f"{name}_analysis.md"
+ return "startup_analysis_report.md"
+
+
+ def _write_report_file(prompt: str, report: str) -> str:
+ """Write the report markdown to a temp file and return its path."""
+ path = os.path.join(tempfile.gettempdir(), _report_filename(prompt))
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(report)
+ return path
+
+
+ # ── Analysis Function ──────────────────────────────────────────────────────────
+
+ def run_analysis(prompt: str):
+ """Stream a startup intelligence report for the given prompt, yielding (report_markdown, status, download_update) tuples."""
+ prompt = prompt.strip()
+ if not prompt:
+ yield PLACEHOLDER, "", gr.update(visible=False)
+ return
+
+ yield "_Analysing company: scraping website, crawling pages, gathering data..._", "Running...", gr.update(visible=False)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
full_output = ""
try:
@@@ -50,22 -75,24 +94,42 @@@
# Only display once the structured report begins (first # heading)
heading_idx = full_output.find("#")
if heading_idx != -1:
++<<<<<<< HEAD
+ yield full_output[heading_idx:], "Running..."
+ except Exception as exc:
+ heading_idx = full_output.find("#")
+ report = full_output[heading_idx:] if heading_idx != -1 else full_output
+ yield (report or PLACEHOLDER) + f"\n\n---\n\n**Error:** {exc}", f"Error: {exc}"
++=======
+ yield full_output[heading_idx:], "Running...", gr.update(visible=False)
+ except Exception as exc:
+ heading_idx = full_output.find("#")
+ report = full_output[heading_idx:] if heading_idx != -1 else full_output
+ yield (report or PLACEHOLDER) + f"\n\n---\n\n**Error:** {exc}", f"Error: {exc}", gr.update(visible=False)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return
if full_output:
heading_idx = full_output.find("#")
++<<<<<<< HEAD
+ yield full_output[heading_idx:] if heading_idx != -1 else full_output, "Done."
+ else:
+ yield PLACEHOLDER, "No response received."
+
+
+def clear_all():
+ return "", PLACEHOLDER, ""
++=======
+ report = full_output[heading_idx:] if heading_idx != -1 else full_output
+ yield report, "Done.", gr.update(value=_write_report_file(prompt, report), visible=True)
+ else:
+ yield PLACEHOLDER, "No response received.", gr.update(visible=False)
+
+
+ def clear_all():
+ """Reset the prompt input, report output, status box, and download button to their default empty state."""
+ return "", PLACEHOLDER, "", gr.update(value=None, visible=False)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# ── Gradio UI ──────────────────────────────────────────────────────────────────
@@@ -75,7 -102,7 +139,11 @@@ with gr.Blocks(title="Startup Analyst"
gr.Markdown("# πŸ“Š Startup Analyst", elem_id="title")
gr.Markdown(
"Elite startup due-diligence powered by **MiniMax M2.5** via OpenRouter. "
++<<<<<<< HEAD
+ "Enter a company name and URL to get a comprehensive investment-grade analysis β€” "
++=======
+ "Enter a company name and URL to get a comprehensive investment-grade analysis "
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
"covering market position, financials, team, risks, and strategic recommendations.",
elem_id="subtitle",
)
@@@ -98,13 -125,14 +166,24 @@@
)
with gr.Row():
++<<<<<<< HEAD
+ status_box = gr.Textbox(label="Status", interactive=False, max_lines=1, scale=1)
+
+ report_output = gr.Markdown(value=PLACEHOLDER, elem_id="report")
+
+ submit_btn.click(fn=run_analysis, inputs=prompt_input, outputs=[report_output, status_box])
+ prompt_input.submit(fn=run_analysis, inputs=prompt_input, outputs=[report_output, status_box])
+ clear_btn.click(fn=clear_all, outputs=[prompt_input, report_output, status_box])
++=======
+ status_box = gr.Textbox(label="Status", interactive=False, max_lines=1, scale=3)
+ download_btn = gr.DownloadButton(label="⬇ Download Report (.md)", visible=False, scale=1)
+
+ report_output = gr.Markdown(value=PLACEHOLDER, elem_id="report")
+
+ submit_btn.click(fn=run_analysis, inputs=prompt_input, outputs=[report_output, status_box, download_btn])
+ prompt_input.submit(fn=run_analysis, inputs=prompt_input, outputs=[report_output, status_box, download_btn])
+ clear_btn.click(fn=clear_all, outputs=[prompt_input, report_output, status_box, download_btn])
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# ── Entry point ────────────────────────────────────────────────────────────────
diff --cc ai_agents/startup_analyst/pyproject.toml
index 5cb5633,4426fa6..538ae8c
--- a/ai_agents/startup_analyst/pyproject.toml
+++ b/ai_agents/startup_analyst/pyproject.toml
@@@ -1,7 -1,7 +1,11 @@@
[project]
name = "startup-analyst"
version = "0.1.0"
++<<<<<<< HEAD
+description = "Elite startup due-diligence agent powered by Qwen3-235B via the orq.ai router"
++=======
+ description = "Elite startup due-diligence agent powered by MiniMax M2.5 via OpenRouter"
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
requires-python = ">=3.11"
dependencies = [
diff --cc ai_agents/stock_portfolio_analyst/.env.example
index 78b5611,44ae38f..fa15963
--- a/ai_agents/stock_portfolio_analyst/.env.example
+++ b/ai_agents/stock_portfolio_analyst/.env.example
@@@ -1,1 -1,3 +1,6 @@@
++<<<<<<< HEAD
++=======
+ # NVIDIA API key (required)
+ # Get your free key at https://build.nvidia.com
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
NVIDIA_API_KEY=your_nvidia_api_key_here
diff --cc ai_agents/stock_portfolio_analyst/README.md
index 5f0c542,83aeef6..d99ec35
--- a/ai_agents/stock_portfolio_analyst/README.md
+++ b/ai_agents/stock_portfolio_analyst/README.md
@@@ -1,12 -1,12 +1,20 @@@
# πŸ“ˆ Stock Portfolio Analyst
++<<<<<<< HEAD
+> **Powered by [DeepSeek-V4-Flash](https://build.nvidia.com/deepseek-ai/deepseek-v4-flash) via NVIDIA API β€” fast, cost-efficient reasoning for real-time financial analysis**
++=======
+ > **Powered by [DeepSeek-V4-Flash](https://build.nvidia.com/deepseek-ai/deepseek-v4-flash) via NVIDIA API for fast, cost-efficient reasoning and real-time financial analysis**
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
![Stock Portfolio Analyst Demo](assets/demo.png)
## Overview
++<<<<<<< HEAD
+An AI-powered portfolio analysis agent that evaluates stock holdings using live market data. Enter your tickers, share counts, and average purchase prices, and the agent fetches real-time pricing and fundamentals via YFinance, searches for recent news via DuckDuckGo, and generates a comprehensive portfolio review β€” streamed live in the UI as it builds.
++=======
+ An AI-powered portfolio analysis agent that evaluates stock holdings using live market data. Enter your tickers, share counts, and average purchase prices, and the agent fetches real-time pricing and fundamentals via YFinance, searches for recent news via DuckDuckGo, and generates a comprehensive portfolio review, streamed live in the UI as it builds.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
The report covers P&L per position, portfolio-level metrics, concentration and valuation risk flags, sector breakdown, and specific rebalancing recommendations.
@@@ -30,7 -30,7 +38,11 @@@
- [CalculatorTools](https://docs.agno.com/): Precise P&L and concentration calculations
**Model:**
++<<<<<<< HEAD
+- **[DeepSeek-V4-Flash](https://build.nvidia.com/deepseek-ai/deepseek-v4-flash)** (`deepseek-ai/deepseek-v4-flash`) β€” fast and cost-efficient reasoning via the NVIDIA API
++=======
+ - **[DeepSeek-V4-Flash](https://build.nvidia.com/deepseek-ai/deepseek-v4-flash)** (`deepseek-ai/deepseek-v4-flash`): fast and cost-efficient reasoning via the NVIDIA API
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
**UI:**
- [Gradio](https://www.gradio.app/): Interactive web interface with streaming markdown output
diff --cc ai_agents/stock_portfolio_analyst/app.py
index 7472a16,16b9238..1649d33
--- a/ai_agents/stock_portfolio_analyst/app.py
+++ b/ai_agents/stock_portfolio_analyst/app.py
@@@ -66,6 -66,7 +66,10 @@@ def analyze(portfolio_df, question)
def reset():
++<<<<<<< HEAD
++=======
+ """Restore the portfolio table to the default example and clear the question and output."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return (
pd.DataFrame(DEFAULT_PORTFOLIO, columns=["Ticker (e.g. AAPL)", "Shares Owned", "Avg Purchase Price ($)"]),
"",
diff --cc audio/music_explorer/.env.example
index cda1e2f,c5773bf..4525987
--- a/audio/music_explorer/.env.example
+++ b/audio/music_explorer/.env.example
@@@ -1,1 -1,3 +1,6 @@@
++<<<<<<< HEAD
++=======
+ # Gemini API key used for audio understanding via Gemini 3 Flash.
+ # Get one free at https://aistudio.google.com/app/apikey
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
GEMINI_API_KEY=your_gemini_api_key_here
diff --cc audio/music_explorer/README.md
index 334877b,2c375ce..1a0a8bd
--- a/audio/music_explorer/README.md
+++ b/audio/music_explorer/README.md
@@@ -1,31 -1,31 +1,58 @@@
# 🎧 Music Explorer
++<<<<<<< HEAD
+> **Powered by [Gemini 3 Flash](https://ai.google.dev/gemini-api/docs/audio) β€” ask anything about any audio file or YouTube video**
++=======
+ > **Powered by [Gemini 3 Flash](https://ai.google.dev/gemini-api/docs/audio), ask anything about any audio file or YouTube video**
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
![Music Explorer Demo](assets/demo.gif)
## Overview
++<<<<<<< HEAD
+Music Explorer lets you analyze any audio through natural language. Upload a file or paste a YouTube URL, and ask questions β€” transcribe lyrics, identify instruments, detect emotion, break down track structure, or describe anything you hear. The conversation is multi-turn, so you can keep asking follow-ups without re-uploading.
+
+Gemini 3 Flash handles the audio understanding entirely via the Gemini Files API β€” no local model, no GPU required.
+
+## Features
+
+- **Multi-turn chat** β€” ask follow-up questions about the same audio without re-uploading
+- **YouTube support** β€” paste any YouTube URL to download and analyze the audio automatically
+- **Five quick-analysis presets** β€” one click to run full description, transcription, emotion analysis, instrument identification, or track structure breakdown
+- **Timestamp-aware responses** β€” Gemini can reference specific moments in the audio
+- **Microphone input** β€” record directly in the browser for live audio analysis
+- **No GPU needed** β€” runs entirely through the Gemini API
+
+## What You Can Ask
+
+- "Describe this track β€” genre, tempo, key, instruments, and mood"
+- "Transcribe the lyrics with timestamps"
+- "What emotion does this convey? Does it shift throughout?"
+- "List every instrument and when each one enters"
+- "Break down the structure β€” intro, verse, chorus β€” with timestamps"
++=======
+ Music Explorer lets you analyze any audio through natural language. Upload a file or paste a YouTube URL, and ask questions: transcribe lyrics, identify instruments, detect emotion, break down track structure, or describe anything you hear. The conversation is multi-turn, so you can keep asking follow-ups without re-uploading.
+
+ Gemini 3 Flash handles the audio understanding entirely via the Gemini Files API, no local model and no GPU required.
+
+ ## Features
+
+ - **Multi-turn chat**: ask follow-up questions about the same audio without re-uploading
+ - **YouTube support**: paste any YouTube URL to download and analyze the audio automatically
+ - **Five quick-analysis presets**: one click to run full description, transcription, emotion analysis, instrument identification, or track structure breakdown
+ - **Timestamp-aware responses**: Gemini can reference specific moments in the audio
+ - **Microphone input**: record directly in the browser for live audio analysis
+ - **No GPU needed**: runs entirely through the Gemini API
+
+ ## What You Can Ask
+
+ - "Describe this track: genre, tempo, key, instruments, and mood"
+ - "Transcribe the lyrics with timestamps"
+ - "What emotion does this convey? Does it shift throughout?"
+ - "List every instrument and when each one enters"
+ - "Break down the structure (intro, verse, chorus) with timestamps"
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
- "What language is being spoken?"
- "Summarize what's being said in this podcast clip"
- "What chord progression is used in the chorus?"
@@@ -65,7 -65,7 +92,11 @@@ winget install ffmpe
```bash
git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git
++<<<<<<< HEAD
+cd Hands-On-AI-Engineering/audio/audio_intelligence
++=======
+ cd Hands-On-AI-Engineering/audio/music_explorer
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```
### 2. Set Up Environment Variables
@@@ -98,7 -98,7 +129,11 @@@ Navigate to `http://localhost:7860`
1. **Upload an audio file** or paste a YouTube URL and click **Load YouTube Audio**
2. **Type a question** or click a **Quick Analysis** preset
++<<<<<<< HEAD
+3. **Keep asking follow-ups** β€” the conversation is multi-turn, no need to re-upload
++=======
+ 3. **Keep asking follow-ups**: the conversation is multi-turn, no need to re-upload
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## How It Works
@@@ -121,10 -121,10 +156,17 @@@ Audio file / YouTube UR
## Project Structure
```text
++<<<<<<< HEAD
+audio_intelligence/
+β”œβ”€β”€ app.py # Gradio UI and Gemini inference logic
+β”œβ”€β”€ assets/
+β”‚ └── demo.png # App screenshot
++=======
+ music_explorer/
+ β”œβ”€β”€ app.py # Gradio UI and Gemini inference logic
+ β”œβ”€β”€ assets/
+ β”‚ └── demo.gif # App demo
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
β”œβ”€β”€ .env.example # API key template
β”œβ”€β”€ pyproject.toml # Dependencies (uv)
└── README.md
diff --cc audio/music_explorer/app.py
index 9907c3c,9a710e6..94416a7
--- a/audio/music_explorer/app.py
+++ b/audio/music_explorer/app.py
@@@ -1,5 -1,5 +1,9 @@@
"""
++<<<<<<< HEAD
+Music Explorer β€” Gemini-powered audio analysis
++=======
+ Music Explorer: Gemini-powered audio analysis.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
Ask anything about any audio file or YouTube video.
Run: python app.py
"""
@@@ -27,6 -27,7 +31,10 @@@ _yt_cache: dict[str, tuple[str, str]]
def _extract_video_id(url: str) -> str | None:
++<<<<<<< HEAD
++=======
+ """Extract the 11-character video ID from a YouTube URL, or None if it doesn't match."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
patterns = [
r"(?:https?://)?(?:www\.)?youtube\.com/watch\?v=([^&=%?]{11})",
r"(?:https?://)?(?:www\.)?youtu\.be/([^&=%?]{11})",
@@@ -40,6 -41,7 +48,10 @@@
def _youtube_embed(url: str) -> str:
++<<<<<<< HEAD
++=======
+ """Build an HTML iframe embed for the given YouTube URL, or an empty string if invalid."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
vid = _extract_video_id(url)
if not vid:
return ""
@@@ -53,6 -55,7 +65,10 @@@
def download_youtube(url: str, force: bool = False) -> tuple[str | None, str]:
++<<<<<<< HEAD
++=======
+ """Download a YouTube video's audio as MP3, using a cached copy unless force is set."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
url = url.strip()
if not _extract_video_id(url):
return None, "❌ Invalid YouTube URL."
@@@ -348,6 -351,7 +364,10 @@@ with gr.Blocks(title="Music Explorer")
# ── Event wiring ──────────────────────────────────────────────────────────
def load_yt(url):
++<<<<<<< HEAD
++=======
+ """Download the YouTube URL's audio and return the audio path, status, and embed."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if not url.strip():
return None, gr.update(value="❌ Enter a URL first.", visible=True), gr.update(visible=False)
path, msg = download_youtube(url.strip(), force=True)
@@@ -365,6 -369,7 +385,10 @@@
)
def clear_yt():
++<<<<<<< HEAD
++=======
+ """Reset the YouTube URL field, audio input, status, and embed."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return "", None, gr.update(value="", visible=False), gr.update(visible=False)
yt_clear_btn.click(fn=clear_yt, outputs=[yt_url, audio_input, yt_status, yt_embed])
diff --cc multimodal/image_question_answering/.env.example
index fa40a94,1fd7173..49dbc6e
--- a/multimodal/image_question_answering/.env.example
+++ b/multimodal/image_question_answering/.env.example
@@@ -1,1 -1,3 +1,7 @@@
++<<<<<<< HEAD
+ο»ΏGOOGLE_API_KEY=your_api_key_here
++=======
+ ο»Ώ# Google AI Studio API key (required)
+ # Get your free key at https://aistudio.google.com
+ GOOGLE_API_KEY=your_api_key_here
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc multimodal/image_question_answering/README.md
index 8d50626,a563026..4a0deb5
--- a/multimodal/image_question_answering/README.md
+++ b/multimodal/image_question_answering/README.md
@@@ -4,7 -4,7 +4,11 @@@
## Overview
++<<<<<<< HEAD
+Upload a PDF, select a page, and ask a natural-language question about its visual content. PyMuPDF renders each page into a high-quality image, which is sent alongside your question to Gemma 4 (`gemma-4-31b-it`) via the Gemini API. The model reasons over the rendered image β€” including charts, tables, diagrams, and figures β€” and returns a grounded answer in the Gradio interface.
++=======
+ Upload a PDF, select a page, and ask a natural-language question about its visual content. PyMuPDF renders each page into a high-quality image, which is sent alongside your question to Gemma 4 (`gemma-4-31b-it`) via the Gemini API. The model reasons over the rendered image, including charts, tables, diagrams, and figures, and returns a grounded answer in the Gradio interface.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Demo
@@@ -16,7 -16,7 +20,11 @@@
- Page slider lets you navigate and preview any page before asking
- Answers visual questions grounded in the actual rendered content (charts, tables, figures)
- Gemma 4 thinking mode (`high`) for multi-step reasoning over complex layouts
++<<<<<<< HEAD
+- Clean two-column Gradio UI β€” page viewer on the left, Q&A on the right
++=======
+ - Clean two-column Gradio UI with the page viewer on the left and Q&A on the right
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Tech Stack
@@@ -88,7 -88,7 +96,11 @@@ Create a `.env` file in the project roo
| Variable | Description |
|---|---|
++<<<<<<< HEAD
+| `GOOGLE_API_KEY` | Gemini API key β€” obtain one at [aistudio.google.com](https://aistudio.google.com) |
++=======
+ | `GOOGLE_API_KEY` | Gemini API key; obtain one at [aistudio.google.com](https://aistudio.google.com) |
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```env
GOOGLE_API_KEY=your_api_key_here
@@@ -103,3 -103,7 +115,10 @@@ image-question-answering
β”œβ”€β”€ .env.example # Environment variable template
└── requirements.txt
```
++<<<<<<< HEAD
++=======
+
+ ---
+
+ [Back to Top](#image-question-answering)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc multimodal/image_question_answering/app.py
index 1919fb8,528fc24..10984c0
--- a/multimodal/image_question_answering/app.py
+++ b/multimodal/image_question_answering/app.py
@@@ -1,3 -1,5 +1,8 @@@
++<<<<<<< HEAD
++=======
+ """Image Question Answering: upload a PDF, select a page, and ask visual questions answered by Gemma 4 via the Gemini API."""
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import io
import os
@@@ -23,6 -25,7 +28,10 @@@ _page_images: list[Image.Image] = [
def pdf_to_images(path: str, dpi: int = 150) -> list[Image.Image]:
++<<<<<<< HEAD
++=======
+ """Render every page of the PDF at the given DPI and return them as a list of PIL images."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
doc = fitz.open(path)
zoom = dpi / 72.0
mat = fitz.Matrix(zoom, zoom)
@@@ -38,6 -41,7 +47,10 @@@
def on_pdf_upload(pdf_file):
++<<<<<<< HEAD
++=======
+ """Handle a PDF upload by rendering all pages and initialising the page slider."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
global _page_images
if pdf_file is None:
@@@ -62,6 -66,7 +75,10 @@@
def on_page_change(page_num: int):
++<<<<<<< HEAD
++=======
+ """Return the PIL image for the selected 1-based page number."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
idx = int(page_num) - 1
if _page_images and 0 <= idx < len(_page_images):
return _page_images[idx]
@@@ -69,6 -74,7 +86,10 @@@
def on_submit(page_num: int, question: str):
++<<<<<<< HEAD
++=======
+ """Send the selected page image and question to Gemma 4 and return the answer text."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if not _page_images:
return "Please upload a PDF first."
if not question.strip():
diff --cc multimodal/multimodal_rag/.env.example
index 39bb49f,4c745b4..67f637a
--- a/multimodal/multimodal_rag/.env.example
+++ b/multimodal/multimodal_rag/.env.example
@@@ -1,1 -1,3 +1,6 @@@
++<<<<<<< HEAD
++=======
+ # Google API key (required)
+ # Get your free key at https://aistudio.google.com
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
GOOGLE_API_KEY=your_google_api_key_here
diff --cc multimodal/multimodal_rag/README.md
index 3d3d051,669bfd0..3b84760
--- a/multimodal/multimodal_rag/README.md
+++ b/multimodal/multimodal_rag/README.md
@@@ -36,6 -36,7 +36,10 @@@ For media files (images, audio, video)
## Prerequisites
- Python 3.10 or later
++<<<<<<< HEAD
++=======
+ - [uv](https://docs.astral.sh/uv/) for dependency management
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
- A Google API key. Get one free at [aistudio.google.com](https://aistudio.google.com)
## Installation
@@@ -48,6 -49,12 +52,15 @@@ cp .env.example .en
Add your Google API key to `.env`.
++<<<<<<< HEAD
++=======
+ Install dependencies:
+
+ ```bash
+ uv sync
+ ```
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Usage
```bash
@@@ -116,3 -123,7 +129,10 @@@ Content parts assembled for Gemini 3 Fl
β–Ό
Gemini 3 Flash generates a grounded answer with source citations
```
++<<<<<<< HEAD
++=======
+
+ ---
+
+ [Back to Top](#multimodal-rag)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc multimodal/multimodal_weather_app/.env.example
index b263636,9c47f26..3f60270
--- a/multimodal/multimodal_weather_app/.env.example
+++ b/multimodal/multimodal_weather_app/.env.example
@@@ -1,1 -1,3 +1,6 @@@
++<<<<<<< HEAD
++=======
+ # Mistral AI API key (required)
+ # Get your free key at https://platform.mistral.ai
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
MISTRAL_API_KEY=your_mistral_api_key_here
diff --cc multimodal/multimodal_weather_app/README.md
index ee9c45d,ac1e239..99f7038
--- a/multimodal/multimodal_weather_app/README.md
+++ b/multimodal/multimodal_weather_app/README.md
@@@ -1,6 -1,6 +1,10 @@@
# Multimodal Weather App
++<<<<<<< HEAD
+> Upload a map image and get live weather β€” Mistral Small identifies the city via vision, then fetches real-time conditions through native tool calling.
++=======
+ > Upload a map image and get live weather: Mistral Small identifies the city via vision, then fetches real-time conditions through native tool calling.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Overview
@@@ -12,11 -12,11 +16,19 @@@ This app combines two AI capabilities i
## Features
++<<<<<<< HEAD
+- **Vision-powered city detection** β€” Mistral Small 4 reads map images and extracts the city name
+- **Native tool calling** β€” Mistral Small 4 decides when and how to invoke the weather tool
+- **Live weather data** β€” temperature, conditions, humidity, and wind speed fetched in real time
+- **No weather API key needed** β€” uses `python_weather`, a free weather client
+- **Simple one-click UI** β€” built with Gradio Blocks
++=======
+ - **Vision-powered city detection:** Mistral Small 4 reads map images and extracts the city name
+ - **Native tool calling:** Mistral Small 4 decides when and how to invoke the weather tool
+ - **Live weather data:** temperature, conditions, humidity, and wind speed fetched in real time
+ - **No weather API key needed:** uses `python_weather`, a free weather client
+ - **Simple one-click UI:** built with Gradio Blocks
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Tech Stack
@@@ -30,7 -30,7 +42,11 @@@
## Prerequisites
- Python 3.10 or higher
++<<<<<<< HEAD
+- A Mistral AI API key β€” get one at [platform.mistral.ai](https://platform.mistral.ai)
++=======
+ - A Mistral AI API key; get one at [platform.mistral.ai](https://platform.mistral.ai)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Installation
@@@ -93,7 -93,7 +109,11 @@@ MISTRAL_API_KEY=your_mistral_api_key_he
| Variable | Required | Description |
|---|---|---|
++<<<<<<< HEAD
+| `MISTRAL_API_KEY` | Yes | Your Mistral AI API key β€” get one at [platform.mistral.ai](https://platform.mistral.ai) |
++=======
+ | `MISTRAL_API_KEY` | Yes | Your Mistral AI API key; get one at [platform.mistral.ai](https://platform.mistral.ai) |
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Project Structure
@@@ -104,3 -104,7 +124,10 @@@ multimodal-weather-app
β”œβ”€β”€ .env.example # Environment variable template
└── .env # Your local secrets (not committed)
```
++<<<<<<< HEAD
++=======
+
+ ---
+
+ [Back to Top](#multimodal-weather-app)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc multimodal/multimodal_weather_app/app.py
index c261230,3a7ff5c..c36077a
--- a/multimodal/multimodal_weather_app/app.py
+++ b/multimodal/multimodal_weather_app/app.py
@@@ -1,6 -1,9 +1,15 @@@
++<<<<<<< HEAD
+import os
+import base64
+import asyncio
++=======
+ """Multimodal weather app that uses Mistral Small vision to identify a city from a map image, then fetches live weather via native tool calling."""
+
+ import os
+ import base64
+ import asyncio
+ import logging
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import tempfile
import threading
import gradio as gr
@@@ -13,11 -16,13 +22,19 @@@ from langchain_core.messages import Hum
load_dotenv()
MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")
++<<<<<<< HEAD
++=======
+ logger = logging.getLogger(__name__)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# ── Image helpers ────────────────────────────────────────────────────────────
def image_to_base64(image: Image.Image) -> str:
++<<<<<<< HEAD
++=======
+ """Convert a PIL image to a base64-encoded JPEG string for use in API requests."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# Write to a real temp file first to ensure a complete, valid JPEG on disk
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
tmp_path = tmp.name
@@@ -25,13 -30,14 +42,21 @@@
with open(tmp_path, "rb") as f:
b64 = base64.b64encode(f.read()).decode("utf-8")
os.remove(tmp_path)
++<<<<<<< HEAD
+ print(f"[base64 preview]: {b64[:100]!r} (total length: {len(b64)})")
++=======
+ logger.debug("[base64 preview]: %r (total length: %d)", b64[:100], len(b64))
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return b64
# ── City identification via Mistral Small (vision) ───────────────────────────
def identify_city(image: Image.Image) -> str:
++<<<<<<< HEAD
++=======
+ """Use Mistral Small vision to read a map image and return the identified city name."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
b64 = image_to_base64(image)
llm = ChatMistralAI(model="mistral-small-latest", api_key=MISTRAL_API_KEY)
message = HumanMessage(content=[
@@@ -40,7 -46,7 +65,11 @@@
])
response = llm.invoke([message])
raw = response.content.strip()
++<<<<<<< HEAD
+ print(f"[mistral vision identified city]: {raw!r}")
++=======
+ logger.debug("[mistral vision identified city]: %r", raw)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return raw
@@@ -122,6 -128,7 +151,10 @@@ _WEATHER_TOOL_SCHEMA =
def call_weather_tool(city: str) -> str:
++<<<<<<< HEAD
++=======
+ """Ask Mistral Small to invoke the weather tool for the given city and return the formatted result."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
llm = ChatMistralAI(model="mistral-small-latest", api_key=MISTRAL_API_KEY)
llm_with_tools = llm.bind_tools([_WEATHER_TOOL_SCHEMA])
response = llm_with_tools.invoke([HumanMessage(content=f"Get the current weather for {city}.")])
@@@ -134,6 -141,7 +167,10 @@@
# ── Output parser ─────────────────────────────────────────────────────────────
def parse_weather(text: str) -> tuple:
++<<<<<<< HEAD
++=======
+ """Extract temperature, conditions, humidity, and wind speed from a formatted weather string."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
temp = conditions = humidity = wind = ""
for line in text.splitlines():
if "Temperature:" in line:
@@@ -150,6 -158,7 +187,10 @@@
# ── Main pipeline ─────────────────────────────────────────────────────────────
def analyze(image):
++<<<<<<< HEAD
++=======
+ """Run the full pipeline: identify the city from the uploaded map image, then fetch and return live weather data."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if image is None:
return "Please upload a map image.", "", "", "", ""
diff --cc multimodal/video_understanding_agent/.env.example
index 8b79f01,a037086..4a224e2
--- a/multimodal/video_understanding_agent/.env.example
+++ b/multimodal/video_understanding_agent/.env.example
@@@ -1,1 -1,2 +1,5 @@@
++<<<<<<< HEAD
++=======
+ # Your Gemini API key. Get one for free at https://aistudio.google.com
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
GEMINI_API_KEY=your_key_here
diff --cc multimodal/video_understanding_agent/README.md
index fc9633f,afb763d..9678c3b
--- a/multimodal/video_understanding_agent/README.md
+++ b/multimodal/video_understanding_agent/README.md
@@@ -1,16 -1,20 +1,33 @@@
# Video Understanding Agent
++<<<<<<< HEAD
+> Paste a YouTube URL and get an AI-powered chapter summary, key takeaways, and action items β€” powered by Gemini 3 Flash.
+
+## Overview
+
+Video Understanding Agent lets you drop any public YouTube URL into a Streamlit interface and receive a structured breakdown of the video in seconds. Gemini 3 Flash reads the video natively through the Gemini API β€” no downloading, no transcription, no third-party tools.
++=======
+ > Paste a YouTube URL and get an AI-powered chapter summary, key takeaways, and action items, powered by Gemini 3 Flash.
+
+ ## Demo
+
+ ![Demo](assets/demo.png)
+
+ ## Overview
+
+ Video Understanding Agent lets you drop any public YouTube URL into a Streamlit interface and receive a structured breakdown of the video in seconds. Gemini 3 Flash reads the video natively through the Gemini API. No downloading, no transcription, no third-party tools.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Features
- **Chapter-by-chapter summary** with timestamps for each major segment
++<<<<<<< HEAD
+- **Key takeaways** β€” 5–8 bullet points covering the most important insights
+- **Action items** β€” 4–6 concrete steps the viewer can act on immediately
++=======
+ - **Key takeaways**: 5–8 bullet points covering the most important insights
+ - **Action items**: 4–6 concrete steps the viewer can act on immediately
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
- Clean, expandable sections in a Streamlit UI
- Input validation rejects private, unavailable, or malformed URLs with clear error messages
@@@ -19,7 -23,7 +36,11 @@@
| Layer | Tool |
|---|---|
| AI Model | Gemini 3 Flash (`gemini-3-flash-preview`) |
++<<<<<<< HEAD
+| AI SDK | Google Generative AI (`google-generativeai`) |
++=======
+ | AI SDK | Google Gen AI SDK (`google-genai`) |
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
| UI | Streamlit |
| Environment | python-dotenv |
@@@ -83,8 -87,8 +104,13 @@@ https://www.youtube.com/watch?v=dQw4w9W
**Output:**
> **Chapter-by-Chapter Summary**
++<<<<<<< HEAD
+> - `0:00 - Introduction` β€” The video opens with an energetic hook establishing the central theme...
+> - `1:12 - Main Segment` β€” The speaker dives into the core content, covering...
++=======
+ > - `0:00 - Introduction`: The video opens with an energetic hook establishing the central theme...
+ > - `1:12 - Main Segment`: The speaker dives into the core content, covering...
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
> **Key Takeaways**
> - The most important insight from the video is...
@@@ -104,8 -108,12 +130,19 @@@
```text
video-understanding-agent/
++<<<<<<< HEAD
+β”œβ”€β”€ app.py # Streamlit app β€” UI, validation, Gemini API call, response parsing
++=======
+ β”œβ”€β”€ app.py # Streamlit app: UI, validation, Gemini API call, response parsing
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
β”œβ”€β”€ requirements.txt # Python dependencies
β”œβ”€β”€ .env.example # Template for environment variables
└── .env # Your local secrets (not committed)
```
++<<<<<<< HEAD
++=======
+
+ ---
+
+ [Back to top](#video-understanding-agent)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc multimodal/video_understanding_agent/app.py
index 2a9f7b3,5a79568..44ccf52
--- a/multimodal/video_understanding_agent/app.py
+++ b/multimodal/video_understanding_agent/app.py
@@@ -1,5 -1,6 +1,11 @@@
++<<<<<<< HEAD
+import streamlit as st
+import google.generativeai as genai
++=======
+ """Streamlit app that accepts a YouTube URL and returns a structured AI-powered summary using the Gemini API."""
+ import streamlit as st
+ from google import genai
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
from dotenv import load_dotenv
import os
import re
@@@ -24,9 -25,11 +30,17 @@@ YOUTUBE_PATTERN = re.compile
)
def is_valid_youtube_url(url: str) -> bool:
++<<<<<<< HEAD
+ return bool(YOUTUBE_PATTERN.search(url))
+
+def parse_sections(text: str) -> dict:
++=======
+ """Returns True if the given string matches a recognized YouTube URL pattern."""
+ return bool(YOUTUBE_PATTERN.search(url))
+
+ def parse_sections(text: str) -> dict:
+ """Splits a Gemini response into chapters, takeaways, and action items by matching section headings."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
sections = {"chapters": "", "takeaways": "", "actions": ""}
chapter_match = re.search(
@@@ -71,8 -74,8 +85,13 @@@ List 4–6 concrete, actionable steps t
Be concise, specific, and use the viewer's perspective. Do not include any preamble before the first heading."""
def analyze_video(youtube_url: str) -> dict:
++<<<<<<< HEAD
+ genai.configure(api_key=GEMINI_API_KEY)
+ model = genai.GenerativeModel("gemini-3-flash-preview")
++=======
+ """Sends the YouTube URL to Gemini and returns the parsed structured summary as a dict."""
+ client = genai.Client(api_key=GEMINI_API_KEY)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
video_part = {
"file_data": {
@@@ -81,7 -84,10 +100,14 @@@
}
}
++<<<<<<< HEAD
+ response = model.generate_content([video_part, PROMPT])
++=======
+ response = client.models.generate_content(
+ model="gemini-3-flash-preview",
+ contents=[video_part, PROMPT],
+ )
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return parse_sections(response.text)
diff --cc multimodal/video_understanding_agent/requirements.txt
index 0b0401b,1e80dee..703d504
--- a/multimodal/video_understanding_agent/requirements.txt
+++ b/multimodal/video_understanding_agent/requirements.txt
@@@ -1,3 -1,3 +1,7 @@@
streamlit>=1.35.0
++<<<<<<< HEAD
+google-generativeai>=0.7.0
++=======
+ google-genai>=1.0.0
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
python-dotenv>=1.0.0
diff --cc rag_apps/clinical_rag_with_ade/.env.example
index 35f53be,84dfe4f..99cd7df
--- a/rag_apps/clinical_rag_with_ade/.env.example
+++ b/rag_apps/clinical_rag_with_ade/.env.example
@@@ -1,2 -1,7 +1,11 @@@
++<<<<<<< HEAD
+VISION_AGENT_API_KEY=your_landingai_key_here
++=======
+ # LandingAI API key used for Agentic Document Extraction (ADE) parsing.
+ # Get one at https://va.landing.ai/my/settings/api-key
+ VISION_AGENT_API_KEY=your_landingai_key_here
+
+ # Mistral AI API key used for embeddings (mistral-embed) and reasoning (mistral-large-latest).
+ # Get one at https://console.mistral.ai/
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
MISTRAL_API_KEY=your_mistral_key_here
diff --cc rag_apps/clinical_rag_with_ade/README.md
index 10e4bd6,dc92881..ca4920a
--- a/rag_apps/clinical_rag_with_ade/README.md
+++ b/rag_apps/clinical_rag_with_ade/README.md
@@@ -1,4 -1,7 +1,10 @@@
# πŸ₯ Clinical RAG with ADE
++<<<<<<< HEAD
++=======
+
+ > Query dense clinical PDFs and get answers grounded in the document's exact visual layout.
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
![Clinical RAG Architecture](assets/clinical_rag.png)
## Overview
diff --cc rag_apps/clinical_rag_with_ade/app.py
index 919f4e2,7289f00..9c86b57
--- a/rag_apps/clinical_rag_with_ade/app.py
+++ b/rag_apps/clinical_rag_with_ade/app.py
@@@ -1,3 -1,4 +1,7 @@@
++<<<<<<< HEAD
++=======
+ """Streamlit dashboard for uploading clinical PDFs and querying them with visually grounded RAG."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import streamlit as st
import os
from processor import ClinicalRAGProcessor
diff --cc rag_apps/clinical_rag_with_ade/main.py
index 40fa6b3,07171fa..736a8a3
--- a/rag_apps/clinical_rag_with_ade/main.py
+++ b/rag_apps/clinical_rag_with_ade/main.py
@@@ -1,3 -1,6 +1,9 @@@
++<<<<<<< HEAD
++=======
+ """Placeholder entry point generated by the uv project scaffold; the app runs via app.py."""
+
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
def main():
print("Hello from clinical-rag-with-ade!")
diff --cc rag_apps/clinical_rag_with_ade/processor.py
index 8feac52,5a8ed07..539a43a
--- a/rag_apps/clinical_rag_with_ade/processor.py
+++ b/rag_apps/clinical_rag_with_ade/processor.py
@@@ -1,3 -1,4 +1,7 @@@
++<<<<<<< HEAD
++=======
+ import logging
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import os
import shutil
from pathlib import Path
@@@ -14,6 -15,8 +18,11 @@@ from langchain_core.documents import Do
load_dotenv()
++<<<<<<< HEAD
++=======
+ logger = logging.getLogger(__name__)
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
class ClinicalRAGProcessor:
def __init__(self, db_path="./chroma_db"):
"""
@@@ -33,7 -36,7 +42,11 @@@
Parses a PDF using ADE and indexes structured chunks into ChromaDB.
Returns the number of chunks indexed.
"""
++<<<<<<< HEAD
+ print(f"--- ADE Parsing Started: {file_path} ---")
++=======
+ logger.info("ADE parsing started: %s", file_path)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# ADE expects a pathlib.Path object for local file parsing
response = self.ade_client.parse(
@@@ -120,4 -123,4 +133,8 @@@
if os.path.exists(self.db_path):
shutil.rmtree(self.db_path)
self.vector_store = None
- print(f"Database at {self.db_path} has been wiped.")
- logger.info("Database at %s has been wiped.", self.db_path)
++<<<<<<< HEAD
++ print(f"Database at {self.db_path} has been wiped.")
++=======
++ logger.info("Database at %s has been wiped.", self.db_path)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc rag_apps/graphrag_knowledge_system/.env.example
index 192619e,54aa524..570cab1
--- a/rag_apps/graphrag_knowledge_system/.env.example
+++ b/rag_apps/graphrag_knowledge_system/.env.example
@@@ -1,4 -1,6 +1,12 @@@
++<<<<<<< HEAD
+MISTRAL_API_KEY=your_mistral_api_key_here
+
+# Optional β€” defaults to http://localhost:11434
++=======
+ # Mistral API key used for entity extraction and answer generation.
+ # Get one free at https://platform.mistral.ai
+ MISTRAL_API_KEY=your_mistral_api_key_here
+
+ # Optional, defaults to http://localhost:11434
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# OLLAMA_BASE_URL=http://localhost:11434
diff --cc rag_apps/graphrag_knowledge_system/README.md
index ad6e763,5c1f24f..bb4167b
--- a/rag_apps/graphrag_knowledge_system/README.md
+++ b/rag_apps/graphrag_knowledge_system/README.md
@@@ -4,7 -4,7 +4,11 @@@
## Overview
++<<<<<<< HEAD
+GraphRAG Knowledge System implements Microsoft's GraphRAG methodology as a fully local Streamlit application. Documents are chunked and processed through an entity-extraction pipeline powered by Mistral Small 4. Extracted entities and relationships are stored in a NetworkX graph persisted to disk, while text embeddings are stored in ChromaDB using Ollama's `nomic-embed-text` model. At query time the app supports two retrieval modes β€” **Local Search** for pinpointing specific entities and **Global Search** for synthesising broad themes across the entire graph β€” before generating a grounded answer with supporting knowledge graph context.
++=======
+ GraphRAG Knowledge System implements Microsoft's GraphRAG methodology as a fully local Streamlit application. Documents are chunked and processed through an entity-extraction pipeline powered by Mistral Small 4. Extracted entities and relationships are stored in a NetworkX graph persisted to disk, while text embeddings are stored in ChromaDB using Ollama's `nomic-embed-text` model. At query time the app supports two retrieval modes: **Local Search** for pinpointing specific entities and **Global Search** for synthesising broad themes across the entire graph, before generating a grounded answer with supporting knowledge graph context.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Demo
@@@ -12,14 -12,14 +16,25 @@@
## Features
++<<<<<<< HEAD
+- **Document ingestion** β€” upload PDF or TXT files; documents are chunked, entity-extracted, and indexed automatically
+- **GraphRAG entity extraction** β€” extracts typed entities (Person, Organization, Location, Technology, Concept, Event) and weighted relationships from every chunk using Mistral
+- **Local Knowledge Graph** β€” NetworkX `DiGraph` persisted as JSON; no external database required
+- **Local embeddings** β€” `nomic-embed-text` via Ollama runs entirely on your machine; no embedding API key needed
+- **Local vector store** β€” ChromaDB stores chunk embeddings with persistent local storage
+- **Dual search modes** β€” Local Search for entity-centric retrieval, Global Search for community-level thematic synthesis
+- **Document caching** β€” SHA-256 file hashing prevents re-indexing the same file on every run
+- **Community detection** β€” automatic Louvain community detection groups related entities and generates community summaries for Global Search
++=======
+ - **Document ingestion**: upload PDF or TXT files; documents are chunked, entity-extracted, and indexed automatically
+ - **GraphRAG entity extraction**: extracts typed entities (Person, Organization, Location, Technology, Concept, Event) and weighted relationships from every chunk using Mistral
+ - **Local Knowledge Graph**: NetworkX `DiGraph` persisted as JSON; no external database required
+ - **Local embeddings**: `nomic-embed-text` via Ollama runs entirely on your machine; no embedding API key needed
+ - **Local vector store**: ChromaDB stores chunk embeddings with persistent local storage
+ - **Dual search modes**: Local Search for entity-centric retrieval, Global Search for community-level thematic synthesis
+ - **Document caching**: SHA-256 file hashing prevents re-indexing the same file on every run
+ - **Community detection**: automatic Louvain community detection groups related entities and generates community summaries for Global Search
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Tech Stack
@@@ -29,7 -29,7 +44,11 @@@
| Document Ingestion | LangChain |
| LLM | Mistral Small 4 (`mistral-small-latest`) via Mistral AI API |
| Embeddings | `nomic-embed-text` via Ollama (local) |
++<<<<<<< HEAD
+| Graph Store | NetworkX DiGraph β€” persisted to `graph_store.json` |
++=======
+ | Graph Store | NetworkX DiGraph, persisted to `graph_store.json` |
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
| Vector Database | ChromaDB (local persistent storage in `chroma_db/`) |
| UI | Streamlit |
@@@ -101,11 -101,11 +120,19 @@@ Open [http://localhost:8501](http://loc
**Workflow**
1. Upload one or more PDF or TXT files using the sidebar file uploader
++<<<<<<< HEAD
+2. Click **βš™οΈ Process Documents** β€” the app chunks each file, extracts entities and relationships, builds the knowledge graph, and indexes embeddings
+3. Type a question in the main panel and choose a search mode:
+ - **πŸ” Local Search** β€” best for specific questions about named entities, events, or facts
+ - **🌐 Global Search** β€” best for broad thematic questions that span the whole document set
+4. Click **πŸš€ Ask** β€” the answer appears as a paragraph with supporting entities and relationships listed below
++=======
+ 2. Click **βš™οΈ Process Documents**: the app chunks each file, extracts entities and relationships, builds the knowledge graph, and indexes embeddings
+ 3. Type a question in the main panel and choose a search mode:
+ - **πŸ” Local Search**: best for specific questions about named entities, events, or facts
+ - **🌐 Global Search**: best for broad thematic questions that span the whole document set
+ 4. Click **πŸš€ Ask**: the answer appears as a paragraph with supporting entities and relationships listed below
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
**Example**
@@@ -139,7 -139,7 +166,11 @@@ Copy `.env.example` to `.env` and fill
| Variable | Required | Description |
|---|---|---|
++<<<<<<< HEAD
+| `MISTRAL_API_KEY` | Yes | Your Mistral AI API key β€” get one at [platform.mistral.ai](https://platform.mistral.ai) |
++=======
+ | `MISTRAL_API_KEY` | Yes | Your Mistral AI API key, get one at [platform.mistral.ai](https://platform.mistral.ai) |
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```env
MISTRAL_API_KEY=your_mistral_api_key_here
@@@ -150,7 -150,7 +181,11 @@@
## Project Structure
```text
++<<<<<<< HEAD
+graphrag-knowledge-system/
++=======
+ graphrag_knowledge_system/
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
β”œβ”€β”€ app.py # Streamlit UI, ingestion pipeline, community detection
β”œβ”€β”€ src/
β”‚ β”œβ”€β”€ cache_manager.py # SHA-256 file-hash cache (cache.json)
@@@ -160,10 -160,12 +195,21 @@@
β”‚ β”œβ”€β”€ llm_client.py # Mistral AI chat client with retry logic
β”‚ β”œβ”€β”€ search_engine.py # Local search and Global search implementations
β”‚ └── vector_store.py # ChromaDB collection with Ollama embedding function
++<<<<<<< HEAD
+β”œβ”€β”€ chroma_db/ # Auto-created β€” ChromaDB persistent storage
+β”œβ”€β”€ graph_store.json # Auto-created β€” serialised NetworkX graph
+β”œβ”€β”€ cache.json # Auto-created β€” processed file hashes
++=======
+ β”œβ”€β”€ chroma_db/ # Auto-created, ChromaDB persistent storage
+ β”œβ”€β”€ graph_store.json # Auto-created, serialised NetworkX graph
+ β”œβ”€β”€ cache.json # Auto-created, processed file hashes
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ .env.example
└── README.md
```
++<<<<<<< HEAD
++=======
+
+ [Back to top](#graphrag-knowledge-system)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc rag_apps/graphrag_knowledge_system/app.py
index bf67b21,12c8aba..3161982
--- a/rag_apps/graphrag_knowledge_system/app.py
+++ b/rag_apps/graphrag_knowledge_system/app.py
@@@ -1,3 -1,8 +1,11 @@@
++<<<<<<< HEAD
++=======
+ """
+ GraphRAG Knowledge System Streamlit app: document ingestion, knowledge graph
+ construction, community detection, and Local/Global search over the graph.
+ """
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import uuid
import json
import os
@@@ -69,6 -74,7 +77,10 @@@ st.markdown
@st.cache_resource(show_spinner=False)
def get_components():
++<<<<<<< HEAD
++=======
+ """Construct and cache the pipeline components shared across reruns."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
graph_store = GraphStore()
vector_store = VectorStore()
entity_extractor = EntityExtractor()
@@@ -105,6 -111,7 +117,10 @@@ Summary:""
def run_community_detection(
graph_store: GraphStore, llm_client: LLMClient, status_fn
) -> int:
++<<<<<<< HEAD
++=======
+ """Detect entity communities in the graph and summarise each one with the LLM."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
full_graph = graph_store.get_full_graph()
entities = full_graph["entities"]
relationships = full_graph["relationships"]
@@@ -179,12 -186,13 +195,20 @@@ def ingest_document
cache_manager: CacheManager,
llm_client: LLMClient,
) -> dict:
++<<<<<<< HEAD
++=======
+ """Chunk, extract entities from, and index a single uploaded document."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
file_hash = cache_manager.file_hash(file_content)
if cache_manager.is_processed(file_hash):
return {
"status": "cached",
++<<<<<<< HEAD
+ "message": f"'{filename}' was already processed β€” skipping.",
++=======
+ "message": f"'{filename}' was already processed, skipping.",
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
}
# ── Step 1: Load and chunk ────────────────────────────────────────────────
@@@ -214,7 -222,7 +238,11 @@@
chunk_id = f"{doc_id}_chunk_{idx}"
chunk_text = chunk.page_content
++<<<<<<< HEAD
+ # Store chunk in Neo4j
++=======
+ # Store chunk in the knowledge graph
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
graph_store.create_chunk(chunk_id, chunk_text, doc_id)
# Extract entities and relationships
@@@ -296,6 -304,7 +324,10 @@@ TYPE_COLORS =
def _type_badge(entity_type: str) -> str:
++<<<<<<< HEAD
++=======
+ """Render an entity type as a small colored HTML badge."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
color = TYPE_COLORS.get(entity_type, "#888")
return (
f'<span style="background:{color};color:#fff;padding:2px 10px;'
@@@ -305,6 -314,7 +337,10 @@@
def render_entity_list(entities: list):
++<<<<<<< HEAD
++=======
+ """Render up to 20 entities as name, description, and type badge rows."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if not entities:
st.caption("No entities retrieved.")
return
@@@ -323,6 -333,7 +359,10 @@@
def render_relationship_list(relationships: list):
++<<<<<<< HEAD
++=======
+ """Render up to 15 relationships as source-target-weight rows."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if not relationships:
st.caption("No relationships retrieved.")
return
@@@ -341,6 -352,7 +381,10 @@@
def main():
++<<<<<<< HEAD
++=======
+ """Render the Streamlit page: ingestion sidebar, search controls, and results."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# ── Header ────────────────────────────────────────────────────────────────
st.markdown(
'<div class="main-header">πŸ•ΈοΈ GraphRAG Knowledge System</div>', unsafe_allow_html=True
@@@ -364,8 -376,8 +408,13 @@@
except Exception as e:
st.error(f"Failed to initialise components: {e}")
st.info(
++<<<<<<< HEAD
+ "Check your `.env` file β€” make sure NEO4J_URI, NEO4J_PASSWORD, "
+ "MISTRAL_API_KEY are set and Ollama is running on http://localhost:11434"
++=======
+ "Check your `.env` file, make sure MISTRAL_API_KEY is set "
+ "and Ollama is running on http://localhost:11434"
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
)
get_components.clear()
return
@@@ -391,7 -403,7 +440,11 @@@
"Upload PDF or TXT files",
type=["pdf", "txt"],
accept_multiple_files=True,
++<<<<<<< HEAD
+ help="Documents are chunked, entity-extracted, and stored in Neo4j + ChromaDB.",
++=======
+ help="Documents are chunked, entity-extracted, and stored in the local knowledge graph and ChromaDB.",
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
)
if uploaded_files and st.button("βš™οΈ Process Documents", type="primary", use_container_width=True):
@@@ -433,13 -445,13 +486,21 @@@
try:
st.metric("Chunks", vector_store.count())
except Exception:
++<<<<<<< HEAD
+ st.metric("Chunks", "β€”")
++=======
+ st.metric("Chunks", "N/A")
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
with col2:
try:
communities = graph_store.get_all_communities()
st.metric("Communities", len(communities))
except Exception:
++<<<<<<< HEAD
+ st.metric("Communities", "β€”")
++=======
+ st.metric("Communities", "N/A")
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if st.button("πŸ”„ Refresh Stats", use_container_width=True):
st.rerun()
@@@ -485,7 -497,7 +546,11 @@@
# ── Answer ────────────────────────────────────────────────────────────
mode_label = "Local Search" if "Local" in search_mode else "Global Search"
++<<<<<<< HEAD
+ st.markdown(f"### Answer β€” {mode_label}")
++=======
+ st.markdown(f"### Answer: {mode_label}")
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
st.markdown(result["answer"])
# ── Supporting context ────────────────────────────────────────────────
@@@ -532,7 -544,7 +597,11 @@@
with info_col2:
st.info(
"**2. Knowledge Graph Built**\n\n"
++<<<<<<< HEAD
+ "Entities and relationships are stored in Neo4j. "
++=======
+ "Entities and relationships are stored in the local knowledge graph. "
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
"Text embeddings go into ChromaDB via Ollama."
)
with info_col3:
diff --cc rag_apps/graphrag_knowledge_system/src/cache_manager.py
index 247fcfe,289b4c0..f775fce
--- a/rag_apps/graphrag_knowledge_system/src/cache_manager.py
+++ b/rag_apps/graphrag_knowledge_system/src/cache_manager.py
@@@ -6,10 -6,12 +6,18 @@@ from pathlib import Pat
class CacheManager:
def __init__(self, cache_path: str = "./cache.json"):
++<<<<<<< HEAD
++=======
+ """Load the processed-file cache from disk."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
self.cache_path = Path(cache_path)
self._load()
def _load(self):
++<<<<<<< HEAD
++=======
+ """Read the cache JSON file from disk, or start empty if none exists."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if self.cache_path.exists():
with open(self.cache_path, "r") as f:
self.cache = json.load(f)
@@@ -17,18 -19,22 +25,34 @@@
self.cache = {}
def _save(self):
++<<<<<<< HEAD
++=======
+ """Write the current cache to disk as JSON."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
with open(self.cache_path, "w") as f:
json.dump(self.cache, f, indent=2)
def file_hash(self, content: bytes) -> str:
++<<<<<<< HEAD
+ return hashlib.sha256(content).hexdigest()
+
+ def is_processed(self, file_hash: str) -> bool:
++=======
+ """Compute a SHA-256 hash of the given file content."""
+ return hashlib.sha256(content).hexdigest()
+
+ def is_processed(self, file_hash: str) -> bool:
+ """Check whether a file with this hash has already been indexed."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return file_hash in self.cache
def mark_processed(
self, file_hash: str, filename: str, doc_id: str, chunk_count: int
):
++<<<<<<< HEAD
++=======
+ """Record a file as processed and persist the cache."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
self.cache[file_hash] = {
"filename": filename,
"document_id": doc_id,
@@@ -38,6 -44,7 +62,10 @@@
self._save()
def get_all(self) -> list:
++<<<<<<< HEAD
++=======
+ """Return summary info for every processed file in the cache."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return [
{
"filename": v["filename"],
@@@ -49,6 -56,7 +77,10 @@@
]
def remove(self, file_hash: str):
++<<<<<<< HEAD
++=======
+ """Remove a file's cache entry, if present, and persist the change."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if file_hash in self.cache:
del self.cache[file_hash]
self._save()
diff --cc rag_apps/graphrag_knowledge_system/src/document_processor.py
index 85267ae,c34b169..c40e429
--- a/rag_apps/graphrag_knowledge_system/src/document_processor.py
+++ b/rag_apps/graphrag_knowledge_system/src/document_processor.py
@@@ -8,6 -8,7 +8,10 @@@ from langchain_community.document_loade
class DocumentProcessor:
def __init__(self, chunk_size: int = 800, chunk_overlap: int = 150):
++<<<<<<< HEAD
++=======
+ """Configure the text splitter used to chunk loaded documents."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
self.splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
@@@ -15,6 -16,7 +19,10 @@@
)
def process(self, file_content: bytes, filename: str) -> list:
++<<<<<<< HEAD
++=======
+ """Load a PDF or TXT file from bytes and split it into text chunks."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
suffix = Path(filename).suffix.lower()
if suffix not in {".pdf", ".txt"}:
raise ValueError(f"Unsupported file type: {suffix}. Use PDF or TXT.")
diff --cc rag_apps/graphrag_knowledge_system/src/entity_extractor.py
index 8045e72,615876c..0cdebbd
--- a/rag_apps/graphrag_knowledge_system/src/entity_extractor.py
+++ b/rag_apps/graphrag_knowledge_system/src/entity_extractor.py
@@@ -28,7 -28,7 +28,11 @@@ Extraction rules
- Extract 3–12 meaningful, specific entities; skip generic words
- Every relationship source and target MUST be an entity you extracted
- weight is 0.0–1.0 reflecting relationship strength or importance
++<<<<<<< HEAD
+- Return only valid JSON β€” no markdown fences, no extra text
++=======
+ - Return only valid JSON, no markdown fences, no extra text
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
Text to analyze:
{text}"""
@@@ -36,9 -36,11 +40,17 @@@
class EntityExtractor:
def __init__(self):
++<<<<<<< HEAD
+ self.llm = LLMClient()
+
+ def extract(self, text: str, chunk_id: str) -> dict:
++=======
+ """Create the LLM client used for entity and relationship extraction."""
+ self.llm = LLMClient()
+
+ def extract(self, text: str, chunk_id: str) -> dict:
+ """Extract typed entities and weighted relationships from a text chunk via Mistral."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
prompt = EXTRACTION_PROMPT.format(text=text[:3000])
try:
diff --cc rag_apps/graphrag_knowledge_system/src/graph_store.py
index bb53cda,3012fc7..e1210c8
--- a/rag_apps/graphrag_knowledge_system/src/graph_store.py
+++ b/rag_apps/graphrag_knowledge_system/src/graph_store.py
@@@ -12,12 -12,14 +12,20 @@@ class GraphStore
"""
def __init__(self, persist_path: str = "./graph_store.json"):
++<<<<<<< HEAD
++=======
+ """Load the persisted graph from disk, or start a fresh one if none exists."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
self.persist_path = Path(persist_path)
self.G: nx.DiGraph = self._load()
# ── Persistence ───────────────────────────────────────────────────────────
def _load(self) -> nx.DiGraph:
++<<<<<<< HEAD
++=======
+ """Read the graph JSON file from disk and rebuild it as a DiGraph."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if self.persist_path.exists():
try:
with open(self.persist_path, "r", encoding="utf-8") as f:
@@@ -28,6 -30,7 +36,10 @@@
return nx.DiGraph()
def _save(self):
++<<<<<<< HEAD
++=======
+ """Serialise the current graph to disk as JSON."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
data = nx.node_link_data(self.G)
with open(self.persist_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False)
@@@ -35,12 -38,14 +47,20 @@@
# ── Document ─────────────────────────────────────────────────────────────
def create_document(self, doc_id: str, filename: str, file_hash: str):
++<<<<<<< HEAD
++=======
+ """Add a document node to the graph and persist the change."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
self.G.add_node(
doc_id, node_type="document", filename=filename, file_hash=file_hash
)
self._save()
def document_exists(self, file_hash: str) -> bool:
++<<<<<<< HEAD
++=======
+ """Check whether a document with the given file hash is already in the graph."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return any(
d.get("node_type") == "document" and d.get("file_hash") == file_hash
for _, d in self.G.nodes(data=True)
@@@ -49,6 -54,7 +69,10 @@@
# ── Chunks ────────────────────────────────────────────────────────────────
def create_chunk(self, chunk_id: str, content: str, doc_id: str):
++<<<<<<< HEAD
++=======
+ """Add a chunk node linked to its parent document and persist the change."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
self.G.add_node(chunk_id, node_type="chunk", content=content, doc_id=doc_id)
if self.G.has_node(doc_id):
self.G.add_edge(chunk_id, doc_id, rel_type="PART_OF")
@@@ -59,6 -65,7 +83,10 @@@
def upsert_entity(
self, name: str, entity_type: str, description: str, chunk_id: str
):
++<<<<<<< HEAD
++=======
+ """Create or update an entity node and link it to the chunk it appeared in."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if self.G.has_node(name) and self.G.nodes[name].get("node_type") == "entity":
existing = self.G.nodes[name]
if len(description) > len(existing.get("description", "")):
@@@ -81,6 -88,7 +109,10 @@@
def upsert_relationship(
self, source: str, target: str, description: str, weight: float
):
++<<<<<<< HEAD
++=======
+ """Create a relationship edge between two entities, or average the weight if it exists."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if not self.G.has_node(source) or not self.G.has_node(target):
return
if self.G.has_edge(source, target):
@@@ -102,13 -110,15 +134,22 @@@
# ── Community ─────────────────────────────────────────────────────────────
def set_entity_community(self, entity_name: str, community_id: str):
++<<<<<<< HEAD
+ # No _save() here β€” called in a tight loop; caller saves via create_community()
++=======
+ """Tag an entity node with the community it belongs to."""
+ # No _save() here since this runs in a tight loop; caller saves via create_community()
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if self.G.has_node(entity_name):
self.G.nodes[entity_name]["community_id"] = community_id
def create_community(
self, community_id: str, entity_names: List[str], summary: str, level: int = 0
):
++<<<<<<< HEAD
++=======
+ """Add a community node, link its member entities, and persist the change."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
self.G.add_node(
community_id,
node_type="community",
@@@ -122,6 -132,7 +163,10 @@@
self._save()
def get_all_communities(self) -> List[Dict]:
++<<<<<<< HEAD
++=======
+ """Return every community node along with its member entity names."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
result = []
for node_id, data in self.G.nodes(data=True):
if data.get("node_type") != "community":
@@@ -143,6 -154,7 +188,10 @@@
return result
def communities_exist(self) -> bool:
++<<<<<<< HEAD
++=======
+ """Check whether any community nodes have been created yet."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return any(
d.get("node_type") == "community" for _, d in self.G.nodes(data=True)
)
@@@ -150,6 -162,7 +199,10 @@@
# ── Graph export for community detection ─────────────────────────────────
def get_full_graph(self) -> Dict:
++<<<<<<< HEAD
++=======
+ """Return every entity and weighted relationship in the graph for community detection."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
entities = [
{"name": n, "type": d.get("type", "")}
for n, d in self.G.nodes(data=True)
@@@ -163,6 -176,7 +216,10 @@@
return {"entities": entities, "relationships": relationships}
def get_entity_descriptions(self, names: List[str]) -> List[Dict]:
++<<<<<<< HEAD
++=======
+ """Look up name, type, and description for each entity in the given list."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
result = []
for name in names:
if not self.G.has_node(name):
@@@ -181,6 -195,7 +238,10 @@@
# ── Search context ────────────────────────────────────────────────────────
def get_entity_neighborhood(self, entity_names: List[str]) -> Dict:
++<<<<<<< HEAD
++=======
+ """Collect the given entities plus everything directly related to them."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
seen_entities: set = set()
seen_rels: set = set()
entities: List[Dict] = []
@@@ -232,7 -247,9 +293,15 @@@
# ── Helpers ───────────────────────────────────────────────────────────────
def ping(self) -> Tuple[bool, str]:
++<<<<<<< HEAD
+ return True, "Connected (local NetworkX graph)"
+
+ def close(self):
++=======
+ """Report that the local graph store is always available."""
+ return True, "Connected (local NetworkX graph)"
+
+ def close(self):
+ """Persist the graph to disk before shutting down."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
self._save()
diff --cc rag_apps/graphrag_knowledge_system/src/llm_client.py
index 3a3c7b6,3c570ae..452bcc8
--- a/rag_apps/graphrag_knowledge_system/src/llm_client.py
+++ b/rag_apps/graphrag_knowledge_system/src/llm_client.py
@@@ -6,6 -6,7 +6,10 @@@ from langchain_core.messages import Hum
class LLMClient:
def __init__(self):
++<<<<<<< HEAD
++=======
+ """Create the plain-text and JSON-mode Mistral chat clients."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
api_key = os.getenv("MISTRAL_API_KEY")
if not api_key:
raise ValueError("MISTRAL_API_KEY not set in environment")
@@@ -22,6 -23,7 +26,10 @@@
)
def complete(self, prompt: str, json_mode: bool = False, max_retries: int = 3) -> str:
++<<<<<<< HEAD
++=======
+ """Send a single prompt to Mistral, retrying with backoff on failure."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
client = self.llm_json if json_mode else self.llm
messages = [HumanMessage(content=prompt)]
for attempt in range(max_retries):
@@@ -37,6 -39,7 +45,10 @@@
def complete_with_system(
self, system: str, user: str, json_mode: bool = False
) -> str:
++<<<<<<< HEAD
++=======
+ """Send a system and user message pair to Mistral and return the response text."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
client = self.llm_json if json_mode else self.llm
messages = [SystemMessage(content=system), HumanMessage(content=user)]
response = client.invoke(messages)
diff --cc rag_apps/graphrag_knowledge_system/src/search_engine.py
index fcb02c3,10cf18d..bb082db
--- a/rag_apps/graphrag_knowledge_system/src/search_engine.py
+++ b/rag_apps/graphrag_knowledge_system/src/search_engine.py
@@@ -59,6 -59,7 +59,10 @@@ Answer:""
class SearchEngine:
def __init__(self, graph_store: GraphStore, vector_store: VectorStore):
++<<<<<<< HEAD
++=======
+ """Wire up the graph store, vector store, and LLM client used for search."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
self.graph = graph_store
self.vector = vector_store
self.llm = LLMClient()
@@@ -66,6 -67,7 +70,10 @@@
# ── Local Search ──────────────────────────────────────────────────────────
def local_search(self, query: str, n_chunks: int = 5) -> Dict:
++<<<<<<< HEAD
++=======
+ """Retrieve matching chunks and their graph context, then answer the question."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if self.vector.count() == 0:
return self._no_docs_result()
@@@ -124,6 -126,7 +132,10 @@@
# ── Global Search ─────────────────────────────────────────────────────────
def global_search(self, query: str) -> Dict:
++<<<<<<< HEAD
++=======
+ """Rate each community's relevance to the question and synthesise an answer from the top ones."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
communities = self.graph.get_all_communities()
if not communities:
return self.local_search(query)
@@@ -196,6 -199,7 +208,10 @@@
@staticmethod
def _no_docs_result() -> Dict:
++<<<<<<< HEAD
++=======
+ """Build the placeholder result returned when no documents have been indexed."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return {
"answer": "No documents have been indexed yet. Please upload and process documents first.",
"entities": [],
diff --cc rag_apps/hybrid_rag_system/.env.example
index b263636,86490cc..160dace
--- a/rag_apps/hybrid_rag_system/.env.example
+++ b/rag_apps/hybrid_rag_system/.env.example
@@@ -1,1 -1,2 +1,5 @@@
++<<<<<<< HEAD
++=======
+ # Your Mistral AI API key. Get one for free at https://platform.mistral.ai
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
MISTRAL_API_KEY=your_mistral_api_key_here
diff --cc rag_apps/hybrid_rag_system/README.md
index 04fb207,549d157..14274fa
--- a/rag_apps/hybrid_rag_system/README.md
+++ b/rag_apps/hybrid_rag_system/README.md
@@@ -12,14 -12,14 +12,25 @@@ Hybrid RAG System dual-indexes every up
## Features
++<<<<<<< HEAD
+- **Dual indexing** β€” every document is indexed into both a knowledge graph and a vector store in a single ingestion pass
+- **Parallel retrieval** β€” graph and vector queries run concurrently via `ThreadPoolExecutor`, minimising latency
+- **Context fusion** β€” graph entities/relationships and ranked vector chunks are merged into one unified prompt
+- **Adjustable retrieval** β€” sliders to tune top-K vector chunks (1–20) and max graph entities (5–50) at query time
+- **Document cache** β€” SHA-256 hash check skips re-indexing files that are already processed
+- **Progress tracking** β€” two-phase progress bar shows entity extraction and embedding status during ingestion
+- **Source transparency** β€” answer panel shows graph sources and vector sources in separate labelled sections with similarity scores
+- **Performance metrics** β€” per-query timing for graph retrieval, vector retrieval, and generation
++=======
+ - **Dual indexing**: every document is indexed into both a knowledge graph and a vector store in a single ingestion pass
+ - **Parallel retrieval**: graph and vector queries run concurrently via `ThreadPoolExecutor`, minimising latency
+ - **Context fusion**: graph entities/relationships and ranked vector chunks are merged into one unified prompt
+ - **Adjustable retrieval**: sliders to tune top-K vector chunks (1–20) and max graph entities (5–50) at query time
+ - **Document cache**: SHA-256 hash check skips re-indexing files that are already processed
+ - **Progress tracking**: two-phase progress bar shows entity extraction and embedding status during ingestion
+ - **Source transparency**: answer panel shows graph sources and vector sources in separate labelled sections with similarity scores
+ - **Performance metrics**: per-query timing for graph retrieval, vector retrieval, and generation
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Tech Stack
@@@ -29,8 -29,8 +40,13 @@@
| Vector retrieval | LangChain + ChromaDB |
| LLM | Mistral Small 4 (`mistral-small-latest`) via Mistral AI API |
| Embeddings | `nomic-embed-text` via Ollama (local, no API key needed) |
++<<<<<<< HEAD
+| Graph store | NetworkX β€” persisted as JSON |
+| Vector database | ChromaDB β€” local persistent storage |
++=======
+ | Graph store | NetworkX, persisted as JSON |
+ | Vector database | ChromaDB, local persistent storage |
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
| UI | Streamlit |
| Configuration | python-dotenv |
@@@ -94,7 -94,7 +110,11 @@@ streamlit run app.p
The app opens at `http://localhost:8501`.
1. Upload a PDF or TXT file using the sidebar uploader
++<<<<<<< HEAD
+2. Click **Process Document** β€” the progress bar tracks entity extraction (Phase 1) then chunk embedding (Phase 2)
++=======
+ 2. Click **Process Document**. The progress bar tracks entity extraction (Phase 1) then chunk embedding (Phase 2)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
3. Type a question in the main panel and click **Ask**
4. Review the answer and expand **Graph Sources** and **Vector Sources** to inspect the retrieved evidence
@@@ -116,7 -116,7 +136,11 @@@ Ollama runs locally and requires no AP
```text
hybrid-rag-system/
++<<<<<<< HEAD
+β”œβ”€β”€ app.py # Streamlit application β€” UI, session state, parallel retrieval
++=======
+ β”œβ”€β”€ app.py # Streamlit application: UI, session state, parallel retrieval
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
β”œβ”€β”€ config.py # Constants and automatic data-directory creation
β”œβ”€β”€ src/
β”‚ β”œβ”€β”€ document_processor.py # PDF/TXT loading, text chunking, hash-based document cache
@@@ -136,3 -136,7 +160,10 @@@
β”œβ”€β”€ .env.example # Environment variable template
└── requirements.txt # Python dependencies
```
++<<<<<<< HEAD
++=======
+
+ ---
+
+ [Back to top](#hybrid-rag-system)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc rag_apps/hybrid_rag_system/app.py
index d48b13d,4f34d45..99eac49
--- a/rag_apps/hybrid_rag_system/app.py
+++ b/rag_apps/hybrid_rag_system/app.py
@@@ -1,3 -1,4 +1,7 @@@
++<<<<<<< HEAD
++=======
+ """Streamlit application combining knowledge graph retrieval and vector retrieval into a hybrid RAG pipeline for document question answering."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import os
import sys
import time
diff --cc rag_apps/hybrid_rag_system/src/context_fusion.py
index e17f28c,39b9ce5..e02db09
--- a/rag_apps/hybrid_rag_system/src/context_fusion.py
+++ b/rag_apps/hybrid_rag_system/src/context_fusion.py
@@@ -2,6 -2,7 +2,10 @@@ from typing import An
def format_graph_context(graph_results: dict[str, Any]) -> str:
++<<<<<<< HEAD
++=======
+ """Formats graph retrieval results into a plain-text block listing entities and relationships."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
entities = graph_results.get("entities", [])
relationships = graph_results.get("relationships", [])
@@@ -27,6 -28,7 +31,10 @@@
def format_vector_context(vector_results: list[dict[str, Any]]) -> str:
++<<<<<<< HEAD
++=======
+ """Formats vector retrieval results into a plain-text block of numbered chunks with similarity scores."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if not vector_results:
return "No vector context available."
lines = []
@@@ -42,6 -44,7 +50,10 @@@ def fuse_context
graph_results: dict[str, Any],
vector_results: list[dict[str, Any]],
) -> str:
++<<<<<<< HEAD
++=======
+ """Combines formatted graph and vector contexts into a single prompt-ready string."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
graph_ctx = format_graph_context(graph_results)
vector_ctx = format_vector_context(vector_results)
return (
diff --cc rag_apps/hybrid_rag_system/src/document_processor.py
index 40318be,23072b0..53da6c9
--- a/rag_apps/hybrid_rag_system/src/document_processor.py
+++ b/rag_apps/hybrid_rag_system/src/document_processor.py
@@@ -9,6 -9,7 +9,10 @@@ from config import CACHE_FILE, CHUNK_SI
def load_document(file_bytes: bytes, filename: str) -> str:
++<<<<<<< HEAD
++=======
+ """Reads a PDF or TXT file from bytes and returns its full text content."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
suffix = Path(filename).suffix.lower()
if suffix == ".pdf":
import io
@@@ -26,6 -27,7 +30,10 @@@
def chunk_text(text: str) -> list[str]:
++<<<<<<< HEAD
++=======
+ """Splits text into overlapping chunks using LangChain's RecursiveCharacterTextSplitter."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
splitter = RecursiveCharacterTextSplitter(
chunk_size=CHUNK_SIZE,
chunk_overlap=CHUNK_OVERLAP,
@@@ -35,10 -37,12 +43,18 @@@
def compute_hash(content: str) -> str:
++<<<<<<< HEAD
++=======
+ """Returns an MD5 hex digest of the given text string."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return hashlib.md5(content.encode()).hexdigest()
def load_cache() -> dict:
++<<<<<<< HEAD
++=======
+ """Loads the processed-documents registry from disk, returning an empty dict if absent or unreadable."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if CACHE_FILE.exists():
try:
return json.loads(CACHE_FILE.read_text(encoding="utf-8"))
@@@ -48,14 -52,17 +64,26 @@@
def save_cache(cache: dict) -> None:
++<<<<<<< HEAD
++=======
+ """Writes the processed-documents registry to disk as JSON."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
CACHE_FILE.write_text(json.dumps(cache, indent=2), encoding="utf-8")
def is_cached(content_hash: str) -> Optional[dict]:
++<<<<<<< HEAD
++=======
+ """Returns the cached metadata dict for a document hash, or None if it has not been indexed."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return load_cache().get(content_hash)
def add_to_cache(content_hash: str, filename: str, num_chunks: int, num_entities: int) -> None:
++<<<<<<< HEAD
++=======
+ """Adds a processed document's metadata to the on-disk cache."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
cache = load_cache()
cache[content_hash] = {
"filename": filename,
@@@ -67,4 -74,5 +95,8 @@@
def list_cached_docs() -> list[dict]:
++<<<<<<< HEAD
++=======
+ """Returns a list of all cached document metadata dicts."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
return list(load_cache().values())
diff --cc rag_apps/hybrid_rag_system/src/graph_indexer.py
index affd22b,b6458a4..2ab4e2f
--- a/rag_apps/hybrid_rag_system/src/graph_indexer.py
+++ b/rag_apps/hybrid_rag_system/src/graph_indexer.py
@@@ -31,6 -31,7 +31,10 @@@ JSON:""
def _parse_extraction(raw: str) -> dict:
++<<<<<<< HEAD
++=======
+ """Extracts the first JSON object from a raw string and returns it as a dict, or an empty scaffold on failure."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
match = re.search(r'\{.*\}', raw, re.DOTALL)
if match:
try:
@@@ -41,6 -42,7 +45,10 @@@
def _extract_from_chunk(client: Mistral, text: str) -> dict:
++<<<<<<< HEAD
++=======
+ """Sends a text chunk to Mistral and returns extracted entities and relationships, retrying up to three times."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
for attempt in range(3):
try:
resp = client.chat.complete(
@@@ -61,6 -63,7 +69,10 @@@ def build_doc_graph
client: Mistral,
progress_cb: Optional[Callable[[int, int], None]] = None,
) -> nx.Graph:
++<<<<<<< HEAD
++=======
+ """Builds a NetworkX graph from a list of text chunks by extracting entities and relationships via Mistral."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
G = nx.Graph()
for i, chunk in enumerate(chunks):
if progress_cb:
@@@ -106,6 -109,7 +118,10 @@@
def merge_into_combined(G_new: nx.Graph) -> nx.Graph:
++<<<<<<< HEAD
++=======
+ """Merges a new document graph into the persisted combined graph and saves it."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
G = load_combined_graph()
for node, data in G_new.nodes(data=True):
if G.has_node(node):
@@@ -127,12 -131,14 +143,20 @@@
def save_doc_graph(G: nx.Graph, doc_hash: str) -> None:
++<<<<<<< HEAD
++=======
+ """Serialises a document graph to a JSON file named by its hash."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
path = GRAPHS_DIR / f"{doc_hash}.json"
data = nx.node_link_data(G)
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
def load_combined_graph() -> nx.Graph:
++<<<<<<< HEAD
++=======
+ """Loads the combined graph from disk, returning an empty graph if not found."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if COMBINED_GRAPH_FILE.exists():
try:
data = json.loads(COMBINED_GRAPH_FILE.read_text(encoding="utf-8"))
@@@ -143,5 -149,6 +167,9 @@@
def save_combined_graph(G: nx.Graph) -> None:
++<<<<<<< HEAD
++=======
+ """Serialises the combined graph to its fixed JSON path."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
data = nx.node_link_data(G)
COMBINED_GRAPH_FILE.write_text(json.dumps(data, indent=2), encoding="utf-8")
diff --cc rag_apps/hybrid_rag_system/src/graph_retriever.py
index 139963c,cfac56a..ffa01c0
--- a/rag_apps/hybrid_rag_system/src/graph_retriever.py
+++ b/rag_apps/hybrid_rag_system/src/graph_retriever.py
@@@ -14,11 -14,13 +14,19 @@@ _STOP_WORDS =
def _query_terms(query: str) -> list[str]:
++<<<<<<< HEAD
++=======
+ """Tokenises a query string and returns non-stop-word terms longer than two characters."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
words = re.findall(r'\b\w+\b', query.lower())
return [w for w in words if w not in _STOP_WORDS and len(w) > 2]
def _score_node(node_name: str, terms: list[str]) -> float:
++<<<<<<< HEAD
++=======
+ """Returns a relevance score for a graph node based on how many query terms match its name."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
name_lower = node_name.lower()
score = 0.0
for term in terms:
@@@ -30,6 -32,7 +38,10 @@@
def retrieve_from_graph(G: nx.Graph, query: str, max_entities: int) -> dict[str, Any]:
++<<<<<<< HEAD
++=======
+ """Performs BFS from top-scoring seed nodes and returns matched entities and relationships up to max_entities."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if G.number_of_nodes() == 0:
return {"entities": [], "relationships": [], "seed_nodes": []}
diff --cc rag_apps/hybrid_rag_system/src/mistral_client.py
index 17a77a3,7e1d96d..f852646
--- a/rag_apps/hybrid_rag_system/src/mistral_client.py
+++ b/rag_apps/hybrid_rag_system/src/mistral_client.py
@@@ -18,6 -18,7 +18,10 @@@ Provide a clear, well-structured answe
def generate_answer(client: Mistral, question: str, fused_context: str) -> str:
++<<<<<<< HEAD
++=======
+ """Sends the fused context and question to Mistral Small 4 and returns the generated answer string."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
resp = client.chat.complete(
model="mistral-small-latest",
messages=[
diff --cc rag_apps/hybrid_rag_system/src/vector_indexer.py
index 7f0c053,b144fd7..b9f3805
--- a/rag_apps/hybrid_rag_system/src/vector_indexer.py
+++ b/rag_apps/hybrid_rag_system/src/vector_indexer.py
@@@ -21,6 -21,7 +21,10 @@@ class OllamaEmbeddingFunction(Embedding
def check_ollama() -> tuple[bool, str]:
++<<<<<<< HEAD
++=======
+ """Checks whether Ollama is reachable and whether the embedding model is installed, returning a status tuple."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
try:
resp = requests.get(f"{OLLAMA_URL}/api/tags", timeout=5)
if resp.status_code == 200:
@@@ -35,6 -36,7 +39,10 @@@
def get_chroma_collection() -> chromadb.Collection:
++<<<<<<< HEAD
++=======
+ """Creates or retrieves the persistent ChromaDB collection using the Ollama embedding function."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
client = chromadb.PersistentClient(path=str(CHROMA_DIR))
return client.get_or_create_collection(
name=CHROMA_COLLECTION,
@@@ -49,6 -51,7 +57,10 @@@ def index_chunks
doc_hash: str,
progress_cb: Optional[Callable[[int, int], None]] = None,
) -> None:
++<<<<<<< HEAD
++=======
+ """Embeds and stores text chunks in ChromaDB, calling progress_cb after each batch."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
batch_size = 5
total = len(chunks)
for i in range(0, total, batch_size):
@@@ -61,6 -64,7 +73,10 @@@
def collection_has_doc(collection: chromadb.Collection, doc_hash: str) -> bool:
++<<<<<<< HEAD
++=======
+ """Returns True if the ChromaDB collection already contains chunks for the given document hash."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
try:
results = collection.get(where={"doc_hash": doc_hash}, limit=1)
return len(results["ids"]) > 0
diff --cc rag_apps/hybrid_rag_system/src/vector_retriever.py
index b1cebf7,b3f7386..db44251
--- a/rag_apps/hybrid_rag_system/src/vector_retriever.py
+++ b/rag_apps/hybrid_rag_system/src/vector_retriever.py
@@@ -7,6 -7,7 +7,10 @@@ def retrieve_from_vector
query: str,
top_k: int,
) -> list[dict[str, Any]]:
++<<<<<<< HEAD
++=======
+ """Queries ChromaDB for the top-k most semantically similar chunks to the query string."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
count = collection.count()
if count == 0:
return []
diff --cc rag_apps/hyde_rag/.env.example
index 39bb49f,2348918..2401cea
--- a/rag_apps/hyde_rag/.env.example
+++ b/rag_apps/hyde_rag/.env.example
@@@ -1,1 -1,3 +1,6 @@@
++<<<<<<< HEAD
++=======
+ # Google API key used to authenticate Gemini 3 Flash and Gemini Embedding 2 requests.
+ # Get one free at https://aistudio.google.com
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
GOOGLE_API_KEY=your_google_api_key_here
diff --cc rag_apps/hyde_rag/README.md
index f51ad06,efda45f..2c44872
--- a/rag_apps/hyde_rag/README.md
+++ b/rag_apps/hyde_rag/README.md
@@@ -7,7 -7,7 +7,11 @@@
Standard RAG embeds the user's raw query and uses it to search the vector store. The problem: a short question and a long detailed answer live in very different regions of the embedding space, so the nearest-neighbour search often misses the most relevant chunks.
++<<<<<<< HEAD
+HyDE solves this by flipping the retrieval signal. Instead of embedding the query, the system prompts an LLM to generate N hypothetical answers β€” documents that *would* contain the answer. Each is embedded, the resulting vectors are averaged into a single HyDE embedding, and that richer signal is used to retrieve from the vector store. Hypothetical answers sit much closer to real answers in embedding space than the original query does.
++=======
+ HyDE solves this by flipping the retrieval signal. Instead of embedding the query, the system prompts an LLM to generate N hypothetical answers, documents that *would* contain the answer. Each is embedded, the resulting vectors are averaged into a single HyDE embedding, and that richer signal is used to retrieve from the vector store. Hypothetical answers sit much closer to real answers in embedding space than the original query does.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Demo
@@@ -15,9 -15,9 +19,15 @@@
## Features
++<<<<<<< HEAD
+- **Hypothetical Document Generation:** MiniMax M2.5 generates N configurable hypothetical answer documents per query
+- **HyDE Averaging:** Gemini Embedding 2 embeds each hypothetical doc; vectors are averaged with NumPy into a single retrieval signal
+- **ChromaDB Vector Store:** Lightweight, in-process vector store β€” no external service required
++=======
+ - **Hypothetical Document Generation:** Gemini 3 Flash generates N configurable hypothetical answer documents per query
+ - **HyDE Averaging:** Gemini Embedding 2 embeds each hypothetical doc; vectors are averaged with NumPy into a single retrieval signal
+ - **ChromaDB Vector Store:** Lightweight, in-process vector store that requires no external service
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
- **Transparent Intermediate Steps:** The UI surfaces the hypothetical documents and retrieved chunks so you can see exactly how retrieval worked
- **Configurable Retrieval:** Sliders for chunk size, chunk overlap, number of hypothetical docs, and number of retrieved chunks
- **PDF and TXT support:** LangChain document loaders handle both formats
@@@ -36,7 -36,7 +46,11 @@@
## Prerequisites
- Python 3.11 or later
++<<<<<<< HEAD
+- A Google API key β€” get one free at [aistudio.google.com](https://aistudio.google.com)
++=======
+ - A Google API key, get one free at [aistudio.google.com](https://aistudio.google.com)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Installation
@@@ -64,7 -64,7 +78,11 @@@ python -m venv .ven
**Install dependencies**
```bash
++<<<<<<< HEAD
+pip install -r pyproject.toml
++=======
+ pip install .
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```
Or with `uv`:
@@@ -109,7 -109,7 +127,11 @@@ Open `http://127.0.0.1:7860` in your br
User question
β”‚
β–Ό
++<<<<<<< HEAD
+MiniMax M2.5 generates N hypothetical answer documents
++=======
+ Gemini 3 Flash generates N hypothetical answer documents
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
β”‚
β–Ό
Gemini Embedding 2 embeds each hypothetical document
@@@ -124,7 -124,7 +146,11 @@@ ChromaDB similarity search with HyDE em
Top-K chunks retrieved
β”‚
β–Ό
++<<<<<<< HEAD
+MiniMax M2.5 synthesises final answer from retrieved context
++=======
+ Gemini 3 Flash synthesises final answer from retrieved context
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
```
## Project Structure
@@@ -132,11 -132,13 +158,23 @@@
```text
hyde_rag/
β”œβ”€β”€ app.py # Gradio UI
++<<<<<<< HEAD
+β”œβ”€β”€ rag.py # HyDERAG class β€” ingest and query pipeline
+β”œβ”€β”€ embedder.py # GeminiEmbedder β€” embedding + HyDE vector averaging
++=======
+ β”œβ”€β”€ rag.py # HyDERAG class, ingest and query pipeline
+ β”œβ”€β”€ embedder.py # GeminiEmbedder, embedding + HyDE vector averaging
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
β”œβ”€β”€ pyproject.toml # Project dependencies
β”œβ”€β”€ .env # Your API keys (git-ignored)
β”œβ”€β”€ .env.example # Template for .env
└── assets/
++<<<<<<< HEAD
+ └── demo.png
+```
++=======
+ └── demo.gif
+ ```
+
+ [Back to top](#hyde-rag)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc rag_apps/hyde_rag/app.py
index 84f5903,25e6cc5..36331b9
--- a/rag_apps/hyde_rag/app.py
+++ b/rag_apps/hyde_rag/app.py
@@@ -1,5 -1,5 +1,9 @@@
"""
++<<<<<<< HEAD
+HyDE RAG β€” Gradio UI
++=======
+ HyDE RAG, Gradio UI
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
"""
import os
@@@ -17,6 -17,7 +21,10 @@@ pipeline: HyDERAG | None = Non
def get_or_create_pipeline(google_key: str) -> HyDERAG:
++<<<<<<< HEAD
++=======
+ """Return the existing pipeline, creating one with the given key if none exists yet."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
global pipeline
if pipeline is None:
pipeline = HyDERAG(google_api_key=google_key)
@@@ -26,12 -27,14 +34,20 @@@
# ── Handlers ───────────────────────────────────────────────────────────────────
def validate_keys(google_key: str) -> tuple[bool, str]:
++<<<<<<< HEAD
++=======
+ """Check that a Google API key was provided, returning a success flag and error message."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if not google_key.strip():
return False, "Google API key is required."
return True, ""
def ingest_document(file, chunk_size, chunk_overlap, google_key):
++<<<<<<< HEAD
++=======
+ """Validate inputs and run the uploaded file through the ingest pipeline, updating the status panel."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if file is None:
return gr.update(value="No file uploaded.", visible=True), gr.update(value=None, visible=False)
@@@ -54,6 -57,7 +70,10 @@@
def run_query(question, n_hypothetical, n_results, google_key):
++<<<<<<< HEAD
++=======
+ """Validate inputs, run the HyDE query pipeline, and format the hypothetical docs, chunks, and answer for display."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
if not question.strip():
return "", "", ""
@@@ -99,6 -103,7 +119,10 @@@
def clear_all():
++<<<<<<< HEAD
++=======
+ """Reset the pipeline and clear all UI fields back to their initial state."""
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
global pipeline
if pipeline is not None:
pipeline.clear()
diff --cc rag_apps/hyde_rag/embedder.py
index a1d1e33,bd6abd5..704dba0
--- a/rag_apps/hyde_rag/embedder.py
+++ b/rag_apps/hyde_rag/embedder.py
@@@ -10,7 -10,7 +10,11 @@@ class GeminiEmbedder
"""Wraps the google-genai SDK to embed text using Gemini Embedding 2.
Also provides hyde_embed(), which embeds N hypothetical documents and
++<<<<<<< HEAD
+ returns their averaged vector β€” the core of the HyDE retrieval strategy.
++=======
+ returns their averaged vector, the core of the HyDE retrieval strategy.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
"""
MODEL = "gemini-embedding-2"
diff --cc rag_apps/hyde_rag/pyproject.toml
index 9d0990d,0daaafc..648a474
--- a/rag_apps/hyde_rag/pyproject.toml
+++ b/rag_apps/hyde_rag/pyproject.toml
@@@ -1,7 -1,7 +1,11 @@@
[project]
name = "hyde-rag"
version = "0.1.0"
++<<<<<<< HEAD
+description = "HyDE RAG pipeline β€” Hypothetical Document Embeddings with Gemini 3 Flash and Gemini Embedding 2"
++=======
+ description = "HyDE RAG pipeline using Hypothetical Document Embeddings with Gemini 3 Flash and Gemini Embedding 2"
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
requires-python = ">=3.11"
dependencies = [
diff --cc rag_apps/hyde_rag/rag.py
index 6223aea,d68c60e..768303a
--- a/rag_apps/hyde_rag/rag.py
+++ b/rag_apps/hyde_rag/rag.py
@@@ -18,7 -18,7 +18,11 @@@ from langchain_text_splitters import Re
from embedder import GeminiEmbedder
++<<<<<<< HEAD
+# ── Prompts ────────────────────────────────────────────────────────────────────
++=======
+ # Prompts
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
HYPOTHETICAL_PROMPT = """\
You are a knowledgeable assistant. A user has asked the following question:
@@@ -26,7 -26,7 +30,11 @@@
"{question}"
Write a detailed, factual hypothetical document excerpt that directly answers \
++<<<<<<< HEAD
+this question. Write it as if extracted from a real reference document β€” \
++=======
+ this question. Write it as if extracted from a real reference document, \
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
specific, informative, and self-contained. Do not explain that it is hypothetical.
"""
@@@ -44,7 -44,7 +52,11 @@@ Answer
"""
++<<<<<<< HEAD
+# ── Pipeline ───────────────────────────────────────────────────────────────────
++=======
+ # Pipeline
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
class HyDERAG:
"""End-to-end HyDE retrieval-augmented generation pipeline."""
@@@ -59,7 -59,7 +71,11 @@@
self._collection = self._chroma.get_or_create_collection(self.COLLECTION)
self.doc_info: dict | None = None
++<<<<<<< HEAD
+ # ── Ingest ──────────────────────────────────────────────────────────────
++=======
+ # Ingest
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
def ingest(
self,
@@@ -121,7 -121,7 +137,11 @@@
}
return self.doc_info
++<<<<<<< HEAD
+ # ── Query ───────────────────────────────────────────────────────────────
++=======
+ # Query
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
def _generate_hypothetical_docs(self, question: str, n: int) -> list[str]:
"""Use Gemini 3 Flash to generate N hypothetical answer documents."""
@@@ -154,13 -154,13 +174,23 @@@
n_results = min(n_results, self._collection.count())
++<<<<<<< HEAD
+ # Step 1 β€” generate hypothetical documents
+ hypo_docs = self._generate_hypothetical_docs(question, n_hypothetical)
+
+ # Step 2 β€” HyDE embedding (average of hypothetical doc embeddings)
+ hyde_vector = self.embedder.hyde_embed(hypo_docs)
+
+ # Step 3 β€” retrieve from ChromaDB using the HyDE vector
++=======
+ # Step 1: generate hypothetical documents
+ hypo_docs = self._generate_hypothetical_docs(question, n_hypothetical)
+
+ # Step 2: HyDE embedding (average of hypothetical doc embeddings)
+ hyde_vector = self.embedder.hyde_embed(hypo_docs)
+
+ # Step 3: retrieve from ChromaDB using the HyDE vector
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
results = self._collection.query(
query_embeddings=[hyde_vector],
n_results=n_results,
@@@ -168,7 -168,7 +198,11 @@@
retrieved_texts = results["documents"][0]
retrieved_meta = results["metadatas"][0]
++<<<<<<< HEAD
+ # Step 4 β€” generate final answer
++=======
+ # Step 4: generate final answer
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
context = "\n\n---\n\n".join(retrieved_texts)
response = self.client.models.generate_content(
model=self.MODEL_ID,
diff --cc rag_apps/rag_agent_with_database_routing/README.md
index 5273a82,b55dc93..d8fc614
--- a/rag_apps/rag_agent_with_database_routing/README.md
+++ b/rag_apps/rag_agent_with_database_routing/README.md
@@@ -1,3 -1,4 +1,7 @@@
++<<<<<<< HEAD
++=======
+ <a id="top"></a>
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# RAG Agent with Database Routing
> A RAG system that intelligently routes queries across three specialized databases covering product information, customer support, and financial data. When no relevant documents are found, a fallback agent performs live web research to still return a useful answer.
@@@ -43,7 -44,7 +47,11 @@@ cd Hands-On-AI-Engineering/rag_apps/rag
cp .env.example .env
```
++<<<<<<< HEAD
+Add your Google API key to `.env`.
++=======
+ Add your ORQ_API_KEY to `.env`.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
## Usage
@@@ -104,3 -105,5 +112,8 @@@ Qdrant retrieves top-k documents from t
β–Ό
Streamlit displays the answer with routing badge, source docs, and reasoning
```
++<<<<<<< HEAD
++=======
+
+ [Back to top](#top)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc rag_apps/rag_agent_with_database_routing/rag_agent/pipeline.py
index def554e,cf34993..1726521
--- a/rag_apps/rag_agent_with_database_routing/rag_agent/pipeline.py
+++ b/rag_apps/rag_agent_with_database_routing/rag_agent/pipeline.py
@@@ -27,6 -27,8 +27,11 @@@ RAG_SYSTEM =
@dataclass
class PipelineResult:
++<<<<<<< HEAD
++=======
+ """The final answer plus routing and retrieval metadata for a single query."""
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
answer: str
routing: RoutingDecision
docs: list[RetrievedDoc] = field(default_factory=list)
diff --cc rag_apps/rag_agent_with_database_routing/rag_agent/retriever.py
index 1a8a432,c40ac4e..29026b4
--- a/rag_apps/rag_agent_with_database_routing/rag_agent/retriever.py
+++ b/rag_apps/rag_agent_with_database_routing/rag_agent/retriever.py
@@@ -18,6 -18,8 +18,11 @@@ from .embeddings import OrqEmbedding
@dataclass
class RetrievedDoc:
++<<<<<<< HEAD
++=======
+ """A single document retrieved from a Qdrant collection, with its similarity score."""
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
text: str
score: float
source: str
diff --cc rag_apps/rag_agent_with_database_routing/rag_agent/router.py
index 8eae20c,5192e4a..e7de93e
--- a/rag_apps/rag_agent_with_database_routing/rag_agent/router.py
+++ b/rag_apps/rag_agent_with_database_routing/rag_agent/router.py
@@@ -34,6 -34,8 +34,11 @@@ _KEYWORDS: dict[str, list[str]] =
class RoutingDecision(BaseModel):
++<<<<<<< HEAD
++=======
+ """Holds which database a query was routed to and why."""
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
database: Literal["products", "support", "financial"]
reasoning: str
diff --cc rag_apps/vision_rag/.env.example
index ca327ce,9752a2a..1360c8a
--- a/rag_apps/vision_rag/.env.example
+++ b/rag_apps/vision_rag/.env.example
@@@ -1,2 -1,7 +1,11 @@@
++<<<<<<< HEAD
+OPENAI_API_KEY=your_openai_api_key_here
++=======
+ # Mistral API key used for Mistral Small (vision) question answering.
+ # Get one free at https://platform.mistral.ai
+ MISTRAL_API_KEY=your_mistral_api_key_here
+
+ # Cohere API key used for embed-v4.0 multimodal embeddings.
+ # Get one free at https://cohere.com
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
COHERE_API_KEY=your_cohere_api_key_here
diff --cc rag_apps/vision_rag/README.md
index bf5f693,e330e79..28771eb
--- a/rag_apps/vision_rag/README.md
+++ b/rag_apps/vision_rag/README.md
@@@ -3,28 -3,36 +3,60 @@@
A visual-first search engine that allows you to "talk" to your images and PDF documents. It combines visual similarity search with advanced Visual Question Answering (VQA).
## Principal Functionalities
++<<<<<<< HEAD
+- **Visual Retrieval Augmented Generation (VisionRAG)**: Unlike text-only RAG, this system breaks down PDFs and images into visual segments and uses **Cohere Embed-v3** to find the most relevant visual context for your question.
+- **Multimodal Question Answering**: Powered by **OpenAI Vision**, the system "looks" at the retrieved image or PDF page to answer specific questions about charts, diagrams, or photos.
++=======
+ - **Visual Retrieval Augmented Generation (VisionRAG)**: Unlike text-only RAG, this system breaks down PDFs and images into visual segments and uses **Cohere Embed-v4** to find the most relevant visual context for your question.
+ - **Multimodal Question Answering**: Powered by **Mistral Small (Vision)**, the system "looks" at the retrieved image or PDF page to answer specific questions about charts, diagrams, or photos.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
- **PDF-to-Visual Indexing**: High-fidelity conversion of PDF pages into searchable visual chunks using **PyMuPDF**.
- **Interactive Visual Chat**: A dashboard that shows you exactly which part of the document the AI is looking at when it gives its answer.
## Technical Context
++<<<<<<< HEAD
+- **Intelligence**: OpenAI `gpt-4o-mini` (Vision-enabled) for multimodal understanding.
+- **Embeddings**: Cohere `embed-english-v3.0` for high-accuracy visual search.
+- **Processing**: PyMuPDF and Pillow for document-to-image pipeline.
+
+## Setup & Execution
+
+### 1. Requirements
+This project runs within the shared repository environment. Ensure dependencies are installed:
+-This project runs within the shared repository environment. Ensure dependencies are installed:
+From the `vision_rag` directory, install dependencies:
+ ```bash
+cd vision_rag
+ pip install -r requirements.txt
+```
+### 2. Environment
+The application pulls your `OPENAI_API_KEY` and `COHERE_API_KEY` from the root `.env` file.
++=======
+ - **Intelligence**: Mistral `mistral-small-latest` (Vision-enabled) for multimodal understanding.
+ - **Embeddings**: Cohere `embed-v4.0` for high-accuracy visual search.
+ - **Processing**: PyMuPDF and Pillow for document-to-image pipeline.
+
+ ## Prerequisites
+
+ - Python 3.9 or later
+ - A Cohere API key, get one free at [cohere.com](https://cohere.com)
+ - A Mistral API key, get one free at [platform.mistral.ai](https://platform.mistral.ai)
+
+ ## Demo
+
+ ![Demo](assets/demo.gif)
+
+ ## Setup & Execution
+
+ ### 1. Requirements
+ From the `vision_rag` directory, install dependencies:
+ ```bash
+ cd vision_rag
+ pip install -r requirements.txt
+ ```
+ ### 2. Environment
+ The application pulls your `MISTRAL_API_KEY` and `COHERE_API_KEY` from the root `.env` file.
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
### 3. Launch
```bash
@@@ -35,3 -43,5 +67,8 @@@ streamlit run app.p
1. **Upload**: Load any image (PNG/JPG) or a multi-page PDF document.
2. **Interact**: Ask a question like "What does the growth chart on page 3 indicate?" or "Describe the logo in this image."
3. **Verify**: The system will display the most relevant visual segment side-by-side with its AI-generated answer.
++<<<<<<< HEAD
++=======
+
+ [Back to top](#visionrag-multimodal-search--vqa)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
diff --cc rag_apps/vision_rag/app.py
index 6ed301f,3179340..329097e
--- a/rag_apps/vision_rag/app.py
+++ b/rag_apps/vision_rag/app.py
@@@ -1,10 -1,14 +1,21 @@@
++<<<<<<< HEAD
++=======
+ """
+ VisionRAG: Multimodal Search & Visual Question Answering Streamlit app.
+ """
+
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
import streamlit as st
import os
import datetime
from PIL import Image
import numpy as np
from dotenv import load_dotenv, find_dotenv
++<<<<<<< HEAD
+from utils import get_cohere_embedding, openai_vqa, pdf_to_images, image_to_bytes, find_most_similar
++=======
+ from utils import get_cohere_embedding, mistral_vqa, pdf_to_images, image_to_bytes, find_most_similar
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# Load environment variables
load_dotenv(find_dotenv())
@@@ -14,7 -18,7 +25,11 @@@ st.set_page_config(page_title="VisionRA
st.title("VisionRAG: Multimodal Search & Visual Question Answering")
cohere_api = os.getenv("COHERE_API_KEY")
++<<<<<<< HEAD
+openai_api = os.getenv("OPENAI_API_KEY")
++=======
+ mistral_api = os.getenv("MISTRAL_API_KEY")
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# Initialize session state
if 'items' not in st.session_state:
@@@ -102,8 -106,8 +117,13 @@@ with st.form("question_form")
# Process question submission
if submit_button:
++<<<<<<< HEAD
+ if not cohere_api or not openai_api:
+ st.error("Please provide both Cohere and OpenAI API keys.")
++=======
+ if not cohere_api or not mistral_api:
+ st.error("Please provide both Cohere and Mistral API keys.")
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
elif not question:
st.error("Please enter a question.")
elif not st.session_state['items']:
@@@ -124,10 -128,10 +144,17 @@@
idx, sim = find_most_similar(q_emb, emb_list)
best_item = st.session_state['items'][idx]
++<<<<<<< HEAD
+ # Generate answer using OpenAI
+ st.info("Generating answer with OpenAI Vision...")
+ img_bytes = image_to_bytes(best_item['img'])
+ answer = openai_vqa(openai_api, img_bytes, question)
++=======
+ # Generate answer using Mistral
+ st.info("Generating answer with Mistral Vision...")
+ img_bytes = image_to_bytes(best_item['img'])
+ answer = mistral_vqa(mistral_api, img_bytes, question)
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
# Add to conversation history
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
diff --cc rag_apps/vision_rag/requirements.txt
index c3d06e6,c0d5a5d..98efa30
--- a/rag_apps/vision_rag/requirements.txt
+++ b/rag_apps/vision_rag/requirements.txt
@@@ -1,6 -1,6 +1,10 @@@
streamlit
cohere
++<<<<<<< HEAD
+openai==1.83.0
++=======
+ mistralai
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
python-dotenv
PyMuPDF
Pillow
diff --cc rag_apps/vision_rag/utils.py
index 718532d,a7bf04f..cdd7dc1
--- a/rag_apps/vision_rag/utils.py
+++ b/rag_apps/vision_rag/utils.py
@@@ -40,26 -40,26 +40,49 @@@ def get_cohere_embedding(api_key, input
else:
raise ValueError("input_type must be 'text' or 'image'")
++<<<<<<< HEAD
+# --- OpenAI GPT-4o-mini VQA ---
+def openai_vqa(api_key, image_bytes, question):
+ """
+ Send image and question to GPT-4o-mini for Visual Question Answering.
+
+ Args:
+ api_key (str): OpenAI API key
+ image_bytes (bytes): Image data
+ question (str): Question about the image
+
+ Returns:
+ str: Generated answer
+ """
+ from openai import OpenAI
+ client = OpenAI(api_key=api_key, timeout=30.0)
+
+ image_b64 = base64.b64encode(image_bytes).decode('utf-8')
+
+ response = client.chat.completions.create(
+ model="gpt-4o-mini",
++=======
+ # --- Mistral Small VQA ---
+ def mistral_vqa(api_key, image_bytes, question):
+ """
+ Send image and question to Mistral Small for Visual Question Answering.
+
+ Args:
+ api_key (str): Mistral API key
+ image_bytes (bytes): Image data
+ question (str): Question about the image
+
+ Returns:
+ str: Generated answer
+ """
+ from mistralai.client import Mistral
+ client = Mistral(api_key=api_key)
+
+ image_b64 = base64.b64encode(image_bytes).decode('utf-8')
+
+ response = client.chat.complete(
+ model="mistral-small-latest",
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
messages=[
{
"role": "user",
@@@ -67,7 -67,7 +90,11 @@@
{"type": "text", "text": question},
{
"type": "image_url",
++<<<<<<< HEAD
+ "image_url": {"url": f"data:image/png;base64,{image_b64}"},
++=======
+ "image_url": f"data:image/png;base64,{image_b64}",
++>>>>>>> 1d1e9f137cfd1123edbae5d8e955ce0b9c7fcf4a
},
],
}