Skip to content

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

audit: fix multi_agent_research_assistant_ag2 - swap to Mistral via native AG2 integration, fix UI layout, add docstrings, rewrite em dashes

Tiioluwani4db05f3a413a
diff --git a/ai_agents/multi_agent_research_assistant_ag2/.env.example b/ai_agents/multi_agent_research_assistant_ag2/.env.example
index 1650210..48e13ce 100644
--- a/ai_agents/multi_agent_research_assistant_ag2/.env.example
+++ b/ai_agents/multi_agent_research_assistant_ag2/.env.example
@@ -1,3 +1,4 @@
-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
diff --git a/ai_agents/multi_agent_research_assistant_ag2/README.md b/ai_agents/multi_agent_research_assistant_ag2/README.md
index e34805b..198e5c0 100644
--- a/ai_agents/multi_agent_research_assistant_ag2/README.md
+++ b/ai_agents/multi_agent_research_assistant_ag2/README.md
@@ -1,25 +1,31 @@
+<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 with LLM-driven speaker
-selection to research any topic and produce a structured Markdown report.
+(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
-- 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)
+- Native Mistral support via AG2's `api_type: "mistral"` config entry
- Download report as Markdown
+## Demo
+
+![Demo](assets/demo.gif)
+
## Prerequisites
- Python 3.10+
-- OpenAI API key (or compatible endpoint)
+- Mistral API key from [console.mistral.ai](https://console.mistral.ai/api-keys)
## Installation
```bash
cd multi_agent_research_assistant_ag2
pip install -r requirements.txt
-cp .env.example .env # add your API key
+cp .env.example .env # add your Mistral API key
```
## Usage
@@ -32,12 +38,13 @@ streamlit run research_assistant.py
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
-4. **GroupChatManager** uses LLM-based speaker selection to orchestrate the conversation
+4. **GroupChatManager** orchestrates the analyst and writer in round-robin order
## 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
+- `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
> **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 @@ streamlit run research_assistant.py
## Running Tests
-Tests are fully mocked — no API keys or network access required.
+Tests are fully mocked and require no API keys or network access.
```bash
pip install pytest
@@ -66,3 +73,7 @@ multi_agent_research_assistant_ag2/
├── requirements.txt
└── .env.example
```
+
+---
+
+[Back to top](#top)
diff --git a/ai_agents/multi_agent_research_assistant_ag2/assets/demo.gif b/ai_agents/multi_agent_research_assistant_ag2/assets/demo.gif
new file mode 100644
index 0000000..85e32ce
Binary files /dev/null and b/ai_agents/multi_agent_research_assistant_ag2/assets/demo.gif differ
diff --git a/ai_agents/multi_agent_research_assistant_ag2/requirements.txt b/ai_agents/multi_agent_research_assistant_ag2/requirements.txt
index 340ceea..4cf915d 100644
--- a/ai_agents/multi_agent_research_assistant_ag2/requirements.txt
+++ b/ai_agents/multi_agent_research_assistant_ag2/requirements.txt
@@ -1,3 +1,4 @@
ag2>=0.11.0
+mistralai>=2.0.0
streamlit>=1.31.0
python-dotenv>=1.0.0
diff --git a/ai_agents/multi_agent_research_assistant_ag2/research_assistant.py b/ai_agents/multi_agent_research_assistant_ag2/research_assistant.py
index abbf300..f8d9354 100644
--- 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 @@
-# 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."""
import os
import streamlit as st
from datetime import datetime
@@ -9,32 +10,69 @@ from tools.research_tools import web_search, fetch_page_content
load_dotenv()
-# ── AG2 (formerly AutoGen) requires ag2>=0.11 ──────────────────────────────────
+# ── 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:
- api_key = os.getenv("OPENAI_API_KEY", "")
+ """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("OPENAI_API_KEY is not set. Add it to .env or the sidebar.")
+ raise ValueError("MISTRAL_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")},
+ {"api_type": "mistral",
+ "model": os.getenv("LLM_MODEL", "mistral-small-latest"),
+ "api_key": api_key},
temperature=0.3,
cache_seed=None, # always fetch fresh data
)
def run_research(topic: str) -> str:
+ """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.
+ """
llm_config = build_llm_config()
# ── Agents ─────────────────────────────────────────────────────────────────
researcher = AssistantAgent(
name="researcher",
- 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.""",
llm_config=llm_config,
)
@@ -63,7 +101,9 @@ End with: REPORT COMPLETE""",
name="executor",
human_input_mode="NEVER",
code_execution_config={"work_dir": "workspace", "use_docker": False},
- 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")
+ ),
default_auto_reply="",
)
@@ -81,18 +121,37 @@ End with: REPORT COMPLETE""",
description=(fn.__doc__ or "").strip().split("\n")[0],
)
- # ── GroupChat orchestration ────────────────────────────────────────────────
+ # ── 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, researcher, analyst, writer],
+ agents=[executor, analyst, writer],
messages=[],
- max_round=20,
- speaker_selection_method="auto", # LLM selects the next speaker
+ max_round=6,
+ speaker_selection_method="round_robin", # analyst then writer, no extra LLM call per round
)
manager = GroupChatManager(groupchat=groupchat, llm_config=llm_config)
executor.initiate_chat(
manager,
- 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}",
clear_history=True,
)
@@ -109,19 +168,10 @@ End with: REPORT COMPLETE""",
st.set_page_config(page_title="Multi-Agent Research Assistant (AG2)", layout="wide")
st.title("Multi-Agent Research Assistant")
-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")
if "report" not in st.session_state:
st.session_state.report = None
diff --git 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
index 5749132..a3a2c52 100644
--- 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 @@
import os
import pytest
-os.environ.setdefault("OPENAI_API_KEY", "test-key-no-llm-calls")
+os.environ.setdefault("MISTRAL_API_KEY", "test-key-no-llm-calls")
def test_agents_instantiate():
"""Verify agent setup does not raise — no LLM calls made."""
@@ -34,7 +34,7 @@ def test_tool_registration():
from tools.research_tools import web_search, fetch_page_content
from autogen import AssistantAgent, UserProxyAgent, LLMConfig, register_function
- llm = LLMConfig({"model": "gpt-4o-mini", "api_key": "test"})
+ llm = LLMConfig({"api_type": "mistral", "model": "mistral-small-latest", "api_key": "test"})
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):