A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
feat: add Multi-Agent Coding Assistant using Mistral and LangChain
Tiioluwanid83ea4da7dd8
diff --git a/ai_agents/multi_agent_coding_assistant/.env.example b/ai_agents/multi_agent_coding_assistant/.env.examplenew file mode 100644index 0000000..08db593--- /dev/null+++ b/ai_agents/multi_agent_coding_assistant/.env.example@@ -0,0 +1,2 @@+# Mistral AI API key — obtain one at https://platform.mistral.ai+MISTRAL_API_KEY=your_mistral_api_key_herediff --git a/ai_agents/multi_agent_coding_assistant/README.md b/ai_agents/multi_agent_coding_assistant/README.mdnew file mode 100644index 0000000..8cffb99--- /dev/null+++ b/ai_agents/multi_agent_coding_assistant/README.md@@ -0,0 +1,107 @@+# Multi-Agent Coding Assistant++> A Streamlit app where three specialized AI agents collaborate to plan, write, review, and refine Python code from a single natural-language task description.++## Overview++Multi-Agent Coding Assistant orchestrates a four-stage pipeline powered by Mistral AI. You describe what you want built; a Planner Agent structures the approach, a Coder Agent writes the first draft, a Reviewer Agent critiques it for bugs and improvements, and the Coder Agent produces a polished final version. All four stages are surfaced in an expandable Streamlit UI so you can inspect every step of the process.++## Demo++++**Example task:** *"Build a Python function that reads a CSV file and returns a dictionary of summary statistics (mean, median, std dev, min, max) for each numeric column."*++**What you get:**+- A structured implementation plan with function signatures and edge cases+- A typed, documented first-draft implementation+- A line-by-line code review covering bugs, performance, and best practices+- A corrected final version with all reviewer feedback applied++## Features++- **Planner Agent** — breaks any coding task into a numbered, step-by-step implementation plan+- **Coder Agent (Draft)** — translates the plan into typed, documented Python code+- **Reviewer Agent** — audits the draft for bugs, edge cases, PEP 8 compliance, performance, and security issues+- **Coder Agent (Final)** — applies every piece of reviewer feedback to produce production-ready code+- Expandable result sections so you can compare draft vs. final side by side+- Inline API key input as a fallback when no `.env` file is present++## Tech Stack++| Layer | Technology |+|---|---|+| LLM | Mistral Small 4 (`mistral-small-latest`) via Mistral AI API |+| Agent Framework | LangChain (`langchain-mistralai`, `langchain-core`) |+| UI | Streamlit |+| Environment | python-dotenv |++## Prerequisites++- Python 3.9 or higher+- A [Mistral AI API key](https://platform.mistral.ai)++## Installation++**1. Clone the repository**++```bash+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/multi_agent_coding_assistant+```++**2. Create and activate a virtual environment**++*Windows*+```bash+python -m venv .venv+.venv\Scripts\activate+```++*macOS / Linux*+```bash+python -m venv .venv+source .venv/bin/activate+```++**3. Install dependencies**++```bash+pip install -r requirements.txt+```++**4. Configure environment variables**++```bash+cp .env.example .env+```++Open `.env` and add your Mistral API key (see [Environment Variables](#environment-variables)).++## Usage++```bash+streamlit run app.py+```++Open `http://localhost:8501` in your browser, describe a coding task, and click **Run Pipeline**.++## Environment Variables++| Variable | Description |+|---|---|+| `MISTRAL_API_KEY` | Your Mistral AI API key — obtain one at [platform.mistral.ai](https://platform.mistral.ai) |++If `MISTRAL_API_KEY` is not set, the app will prompt you to paste it directly in the UI.++## Project Structure++```text+multi-agent-coding-assistant/+├── app.py # Streamlit UI and pipeline orchestration+├── agents.py # LLM setup and agent prompt/invocation logic+├── requirements.txt # Python dependencies+├── .env.example # Environment variable template+└── assets/+ └── demo.png # App screenshot+```diff --git a/ai_agents/multi_agent_coding_assistant/agents.py b/ai_agents/multi_agent_coding_assistant/agents.pynew file mode 100644index 0000000..f3685df--- /dev/null+++ b/ai_agents/multi_agent_coding_assistant/agents.py@@ -0,0 +1,122 @@+from langchain_mistralai import ChatMistralAI+from langchain_core.messages import HumanMessage, SystemMessage+++PLANNER_SYSTEM_PROMPT = """You are a senior software architect and technical planner.++Your job is to take a natural language coding task and break it down into a clear, structured implementation plan.++Your plan must include:+1. A brief summary of what will be built and why+2. A numbered list of implementation steps in logical order+3. For each step: what it does, what inputs it expects, and what it outputs+4. Any edge cases or constraints to keep in mind+5. Suggested function/class names and their responsibilities++Be specific and actionable. The plan will be handed to a coder who will implement it exactly as described.+Do not write any code — only the plan."""+++CODER_SYSTEM_PROMPT = """You are an expert Python developer who writes clean, production-ready code.++Your job is to take an implementation plan and produce working Python code that fulfills it exactly.++Requirements for all code you write:+- Follow the plan step by step without skipping anything+- Write clear, descriptive docstrings for every function and class+- Add inline comments only where the logic is non-obvious+- Handle all edge cases mentioned in the plan+- Use type hints on all function signatures+- Structure the code logically with related functions grouped together+- Include example usage at the bottom inside an `if __name__ == "__main__":` block++Return ONLY the Python code. No explanations before or after — just the code."""+++REVIEWER_SYSTEM_PROMPT = """You are a meticulous senior code reviewer focused on quality, correctness, and best practices.++Your job is to review Python code and provide precise, actionable feedback.++Your review must cover:+1. **Bugs & Correctness** — logic errors, off-by-one errors, incorrect assumptions+2. **Edge Cases** — missing input validation, unhandled exceptions, empty/None inputs+3. **Best Practices** — PEP 8 compliance, naming conventions, code smells+4. **Performance** — inefficient algorithms, unnecessary operations, memory issues+5. **Security** — unsafe operations, injection risks, insecure defaults+6. **Improvements** — cleaner implementations, missing features, better stdlib usage++For each issue found, specify:+- The exact location (function name or line description)+- What the problem is+- How to fix it++Be direct and specific. The coder will use your feedback to rewrite the code."""+++FINAL_CODER_SYSTEM_PROMPT = """You are an expert Python developer who writes clean, production-ready code.++Your job is to take an original implementation plan, a first draft of code, and a reviewer's feedback, then produce an improved final version of the code.++Apply every piece of reviewer feedback. For each issue raised:+- Fix bugs and logic errors exactly as suggested+- Add missing edge case handling+- Refactor for clarity and best practices+- Improve performance where noted++Requirements for the final code:+- All reviewer concerns must be addressed+- Maintain clear docstrings and type hints+- Keep the `if __name__ == "__main__":` usage example, updated if needed+- The final code must be complete and runnable++Return ONLY the improved Python code. No explanations — just the final code."""+++def create_llm(api_key: str) -> ChatMistralAI:+ return ChatMistralAI(+ model="mistral-small-latest",+ api_key=api_key,+ temperature=0.1,+ )+++def run_planner(llm: ChatMistralAI, task: str) -> str:+ messages = [+ SystemMessage(content=PLANNER_SYSTEM_PROMPT),+ HumanMessage(content=f"Coding task: {task}"),+ ]+ response = llm.invoke(messages)+ return response.content+++def run_coder(llm: ChatMistralAI, plan: str) -> str:+ messages = [+ SystemMessage(content=CODER_SYSTEM_PROMPT),+ HumanMessage(content=f"Implementation plan:\n\n{plan}"),+ ]+ response = llm.invoke(messages)+ return response.content+++def run_reviewer(llm: ChatMistralAI, code: str) -> str:+ messages = [+ SystemMessage(content=REVIEWER_SYSTEM_PROMPT),+ HumanMessage(content=f"Review this Python code:\n\n```python\n{code}\n```"),+ ]+ response = llm.invoke(messages)+ return response.content+++def run_final_coder(llm: ChatMistralAI, plan: str, draft_code: str, review: str) -> str:+ messages = [+ SystemMessage(content=FINAL_CODER_SYSTEM_PROMPT),+ HumanMessage(+ content=(+ f"Original plan:\n\n{plan}\n\n"+ f"First draft code:\n\n```python\n{draft_code}\n```\n\n"+ f"Reviewer feedback:\n\n{review}"+ )+ ),+ ]+ response = llm.invoke(messages)+ return response.contentdiff --git a/ai_agents/multi_agent_coding_assistant/app.py b/ai_agents/multi_agent_coding_assistant/app.pynew file mode 100644index 0000000..94b689c--- /dev/null+++ b/ai_agents/multi_agent_coding_assistant/app.py@@ -0,0 +1,177 @@+import os+import streamlit as st+from dotenv import load_dotenv+from agents import create_llm, run_planner, run_coder, run_reviewer, run_final_coder++load_dotenv()++st.set_page_config(+ page_title="Multi-Agent Coding Assistant",+ page_icon="🤖",+ layout="wide",+)++# ── Styles ────────────────────────────────────────────────────────────────────+st.markdown(+ """+ <style>+ .agent-badge {+ display: inline-block;+ padding: 2px 10px;+ border-radius: 12px;+ font-size: 0.78rem;+ font-weight: 600;+ margin-bottom: 6px;+ }+ .badge-planner { background:#dbeafe; color:#1e40af; }+ .badge-coder { background:#dcfce7; color:#166534; }+ .badge-reviewer { background:#fef9c3; color:#854d0e; }+ .badge-final { background:#f3e8ff; color:#6b21a8; }+ .stExpander > div:first-child { font-weight: 600; }+ </style>+ """,+ unsafe_allow_html=True,+)+++def _strip_code_fences(text: str) -> str:+ """Remove markdown ```python ... ``` fences that the model may wrap around code."""+ lines = text.strip().splitlines()+ if lines and lines[0].startswith("```"):+ lines = lines[1:]+ if lines and lines[-1].strip() == "```":+ lines = lines[:-1]+ return "\n".join(lines)+++# ── Header ────────────────────────────────────────────────────────────────────+st.title("🤖 Multi-Agent Coding Assistant")+st.caption(+ "Describe a coding task and watch three specialized AI agents collaborate to produce "+ "high-quality, reviewed Python code."+)+st.divider()++# ── API key handling ──────────────────────────────────────────────────────────+api_key = os.getenv("MISTRAL_API_KEY", "")+if not api_key:+ st.warning(+ "No `MISTRAL_API_KEY` found in environment. "+ "Add it to a `.env` file or paste it below.",+ icon="⚠️",+ )+ api_key = st.text_input(+ "Mistral API Key",+ type="password",+ placeholder="Enter your Mistral API key…",+ )++# ── Task input ────────────────────────────────────────────────────────────────+task = st.text_area(+ "Describe your coding task",+ placeholder=(+ "e.g. Build a Python function that reads a CSV file and returns "+ "a dictionary of summary statistics (mean, median, std dev, min, max) "+ "for each numeric column."+ ),+ height=110,+)++run_button = st.button("🚀 Run Pipeline", type="primary", disabled=not (api_key and task))++# ── Pipeline ──────────────────────────────────────────────────────────────────+if run_button:+ if not api_key:+ st.error("Please provide your Mistral API key.")+ st.stop()+ if not task.strip():+ st.error("Please describe a coding task.")+ st.stop()++ llm = create_llm(api_key)++ # Step 1 — Planner+ st.markdown(+ '<span class="agent-badge badge-planner">🗺️ Planner Agent</span>',+ unsafe_allow_html=True,+ )+ with st.spinner("Planner is breaking down the task…"):+ plan = run_planner(llm, task)+ st.session_state["plan"] = plan++ # Step 2 — Coder (first draft)+ st.markdown(+ '<span class="agent-badge badge-coder">💻 Coder Agent — First Draft</span>',+ unsafe_allow_html=True,+ )+ with st.spinner("Coder is writing the first draft…"):+ draft_code = run_coder(llm, plan)+ st.session_state["draft_code"] = draft_code++ # Step 3 — Reviewer+ st.markdown(+ '<span class="agent-badge badge-reviewer">🔍 Reviewer Agent</span>',+ unsafe_allow_html=True,+ )+ with st.spinner("Reviewer is auditing the code…"):+ review = run_reviewer(llm, draft_code)+ st.session_state["review"] = review++ # Step 4 — Coder (final version)+ st.markdown(+ '<span class="agent-badge badge-final">✨ Coder Agent — Final Version</span>',+ unsafe_allow_html=True,+ )+ with st.spinner("Coder is applying feedback and producing the final version…"):+ final_code = run_final_coder(llm, plan, draft_code, review)+ st.session_state["final_code"] = final_code++ st.success("Pipeline complete!", icon="✅")+ st.divider()++# ── Results ───────────────────────────────────────────────────────────────────+if all(k in st.session_state for k in ("plan", "draft_code", "review", "final_code")):++ with st.expander("🗺️ Plan", expanded=True):+ st.markdown(+ '<span class="agent-badge badge-planner">Planner Agent</span>',+ unsafe_allow_html=True,+ )+ st.markdown(st.session_state["plan"])++ with st.expander("💻 First Draft Code", expanded=False):+ st.markdown(+ '<span class="agent-badge badge-coder">Coder Agent</span>',+ unsafe_allow_html=True,+ )+ clean_draft = _strip_code_fences(st.session_state["draft_code"])+ st.code(clean_draft, language="python")++ with st.expander("🔍 Review Feedback", expanded=False):+ st.markdown(+ '<span class="agent-badge badge-reviewer">Reviewer Agent</span>',+ unsafe_allow_html=True,+ )+ st.markdown(st.session_state["review"])++ with st.expander("✨ Final Code", expanded=True):+ st.markdown(+ '<span class="agent-badge badge-final">Coder Agent — Improved</span>',+ unsafe_allow_html=True,+ )+ clean_final = _strip_code_fences(st.session_state["final_code"])+ st.code(clean_final, language="python")++ # Streamlit's st.code already renders a copy icon in the top-right corner of+ # the code block. The button below provides an explicit fallback with feedback.+ col1, col2 = st.columns([1, 5])+ with col1:+ if st.button("📋 Copy Final Code"):+ st.session_state["copy_triggered"] = True++ if st.session_state.get("copy_triggered"):+ st.toast("Use the copy icon on the code block above — browser security "+ "prevents clipboard access from a button outside the code widget.",+ icon="📋")+ # Reset flag so toast only fires once per click+ st.session_state["copy_triggered"] = Falsediff --git a/ai_agents/multi_agent_coding_assistant/assets/demo.png b/ai_agents/multi_agent_coding_assistant/assets/demo.pngnew file mode 100644index 0000000..a2c8858Binary files /dev/null and b/ai_agents/multi_agent_coding_assistant/assets/demo.png differdiff --git a/ai_agents/multi_agent_coding_assistant/requirements.txt b/ai_agents/multi_agent_coding_assistant/requirements.txtnew file mode 100644index 0000000..6e0a954--- /dev/null+++ b/ai_agents/multi_agent_coding_assistant/requirements.txt@@ -0,0 +1,5 @@+streamlit>=1.32.0+langchain>=0.2.0+langchain-mistralai>=0.1.0+langchain-core>=0.2.0+python-dotenv>=1.0.0