Skip to content

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

feat: add multi-agent research assistant (AG2) to ai_agents dir

cyberholicsdab4c8076637
diff --git a/ai_agents/multi_agent_research_assistant_ag2/.env.example b/ai_agents/multi_agent_research_assistant_ag2/.env.example
new file mode 100644
index 0000000..1650210
--- /dev/null
+++ b/ai_agents/multi_agent_research_assistant_ag2/.env.example
@@ -0,0 +1,3 @@
+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
diff --git a/ai_agents/multi_agent_research_assistant_ag2/.gitignore b/ai_agents/multi_agent_research_assistant_ag2/.gitignore
new file mode 100644
index 0000000..7a7990c
--- /dev/null
+++ b/ai_agents/multi_agent_research_assistant_ag2/.gitignore
@@ -0,0 +1,4 @@
+__pycache__/
+*.pyc
+.env
+workspace/
diff --git a/ai_agents/multi_agent_research_assistant_ag2/README.md b/ai_agents/multi_agent_research_assistant_ag2/README.md
new file mode 100644
index 0000000..e34805b
--- /dev/null
+++ b/ai_agents/multi_agent_research_assistant_ag2/README.md
@@ -0,0 +1,68 @@
+# 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)
+
+## Installation
+```bash
+cd multi_agent_research_assistant_ag2
+pip install -r requirements.txt
+cp .env.example .env # add your API key
+```
+
+## Usage
+```bash
+streamlit run research_assistant.py
+```
+
+## How It Works
+
+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
+
+## 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
+
+> **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
+> an isolated environment.
+
+## Running Tests
+
+Tests are fully mocked — no API keys or network access required.
+
+```bash
+pip install pytest
+python -m pytest tests/ -v
+```
+
+## Project Structure
+
+```
+multi_agent_research_assistant_ag2/
+├── research_assistant.py # Agents, GroupChat orchestration, Streamlit UI
+├── tools/
+│ └── research_tools.py # web_search (DuckDuckGo API), fetch_page_content
+├── tests/
+│ ├── conftest.py # sys.path setup, Streamlit stub
+│ ├── test_agent_setup.py # Agent instantiation, tool registration
+│ └── test_research_tools.py # Mocked tool tests, SSRF validation
+├── requirements.txt
+└── .env.example
+```
diff --git a/ai_agents/multi_agent_research_assistant_ag2/requirements.txt b/ai_agents/multi_agent_research_assistant_ag2/requirements.txt
new file mode 100644
index 0000000..340ceea
--- /dev/null
+++ b/ai_agents/multi_agent_research_assistant_ag2/requirements.txt
@@ -0,0 +1,3 @@
+ag2>=0.11.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
new file mode 100644
index 0000000..abbf300
--- /dev/null
+++ b/ai_agents/multi_agent_research_assistant_ag2/research_assistant.py
@@ -0,0 +1,149 @@
+# research_assistant.py
+import os
+import streamlit as st
+from datetime import datetime
+from dotenv import load_dotenv
+
+from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager, LLMConfig, register_function
+from tools.research_tools import web_search, fetch_page_content
+
+load_dotenv()
+
+# ── 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")},
+ temperature=0.3,
+ cache_seed=None, # always fetch fresh data
+ )
+
+
+def run_research(topic: str) -> str:
+ 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.""",
+ llm_config=llm_config,
+ )
+
+ analyst = AssistantAgent(
+ name="analyst",
+ system_message="""You are a senior analyst. Once RESEARCH COMPLETE is signalled,
+critically evaluate the research: identify key themes, contradictions, and knowledge gaps.
+Produce a structured analysis with bullet points. End with: ANALYSIS COMPLETE.""",
+ llm_config=llm_config,
+ )
+
+ writer = AssistantAgent(
+ name="writer",
+ system_message="""You are a professional technical writer. Once ANALYSIS COMPLETE
+is signalled, produce a polished markdown report with:
+## Executive Summary
+## Key Findings
+## Detailed Analysis
+## Conclusions & Next Steps
+End with: REPORT COMPLETE""",
+ llm_config=llm_config,
+ )
+
+ # Executes tool calls; no LLM of its own
+ executor = UserProxyAgent(
+ 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 ""),
+ default_auto_reply="",
+ )
+
+ # ── Tool registration: caller=LLM agent, executor=UserProxyAgent ──────────
+ # This AG2 pattern separates tool description (for the LLM) from execution
+ # (sandboxed in the UserProxyAgent). The executor can be swapped for a
+ # Docker container without changing any agent reasoning code.
+
+ for fn in (web_search, fetch_page_content):
+ register_function(
+ fn,
+ caller=researcher,
+ executor=executor,
+ name=fn.__name__,
+ description=(fn.__doc__ or "").strip().split("\n")[0],
+ )
+
+ # ── GroupChat orchestration ────────────────────────────────────────────────
+ groupchat = GroupChat(
+ agents=[executor, researcher, analyst, writer],
+ messages=[],
+ max_round=20,
+ speaker_selection_method="auto", # LLM selects the next speaker
+ )
+ manager = GroupChatManager(groupchat=groupchat, llm_config=llm_config)
+
+ executor.initiate_chat(
+ manager,
+ message=f"Research the following topic thoroughly: {topic}",
+ clear_history=True,
+ )
+
+ # Extract the final report from writer messages
+ report_msgs = [
+ m["content"]
+ for m in groupchat.messages
+ if m.get("name") == "writer" and m.get("content")
+ ]
+ return report_msgs[-1] if report_msgs else "Report generation did not complete."
+
+
+# ── Streamlit UI ──────────────────────────────────────────────────────────────
+
+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")
+
+if "report" not in st.session_state:
+ st.session_state.report = None
+
+if run_btn:
+ if not topic.strip():
+ st.error("Please enter a research topic.")
+ else:
+ with st.spinner("AG2 agents are researching..."):
+ try:
+ st.session_state.report = run_research(topic)
+ except Exception as exc:
+ st.error(f"Error: {exc}")
+
+if st.session_state.report:
+ st.markdown(st.session_state.report)
+ st.download_button(
+ "Download Report",
+ data=st.session_state.report,
+ file_name=f"research_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md",
+ mime="text/markdown",
+ )
+
+st.markdown("---")
+st.caption("For educational purposes only")
diff --git a/ai_agents/multi_agent_research_assistant_ag2/tests/__init__.py b/ai_agents/multi_agent_research_assistant_ag2/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/ai_agents/multi_agent_research_assistant_ag2/tests/conftest.py b/ai_agents/multi_agent_research_assistant_ag2/tests/conftest.py
new file mode 100644
index 0000000..310f3c5
--- /dev/null
+++ b/ai_agents/multi_agent_research_assistant_ag2/tests/conftest.py
@@ -0,0 +1,42 @@
+"""
+Stub out UI and optional dependencies so tests run without a Streamlit install.
+research_assistant.py calls st.* at module level, so we must intercept before import.
+"""
+import sys
+import os
+from types import ModuleType
+from unittest.mock import MagicMock
+
+
+def _stub_module(name: str, **attrs) -> ModuleType:
+ m = ModuleType(name)
+ for k, v in attrs.items():
+ setattr(m, k, v)
+ sys.modules[name] = m
+ return m
+
+
+# Streamlit: stub the entire module — research_assistant.py runs st.* at module level
+_st = _stub_module(
+ "streamlit",
+ set_page_config=MagicMock(),
+ title=MagicMock(),
+ caption=MagicMock(),
+ header=MagicMock(),
+ text_input=MagicMock(return_value=""),
+ text_area=MagicMock(return_value=""),
+ button=MagicMock(return_value=False),
+ spinner=MagicMock(),
+ error=MagicMock(),
+ markdown=MagicMock(),
+ download_button=MagicMock(),
+ sidebar=MagicMock(),
+ session_state=MagicMock(report=None),
+)
+_st.sidebar.__enter__ = MagicMock(return_value=_st.sidebar)
+_st.sidebar.__exit__ = MagicMock(return_value=False)
+
+# Ensure parent dir (multi_agent_research_assistant_ag2/) is on sys.path
+parent = os.path.dirname(os.path.dirname(__file__))
+if parent not in sys.path:
+ sys.path.insert(0, parent)
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
new file mode 100644
index 0000000..5749132
--- /dev/null
+++ b/ai_agents/multi_agent_research_assistant_ag2/tests/test_agent_setup.py
@@ -0,0 +1,42 @@
+import os
+import pytest
+os.environ.setdefault("OPENAI_API_KEY", "test-key-no-llm-calls")
+
+def test_agents_instantiate():
+ """Verify agent setup does not raise — no LLM calls made."""
+ from research_assistant import build_llm_config
+ from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager
+
+ llm_config = build_llm_config()
+ researcher = AssistantAgent(name="researcher", system_message="Test", llm_config=llm_config)
+ analyst = AssistantAgent(name="analyst", system_message="Test", llm_config=llm_config)
+ writer = AssistantAgent(name="writer", system_message="Test", llm_config=llm_config)
+ executor = UserProxyAgent(name="executor", human_input_mode="NEVER", code_execution_config=False)
+
+ gc = GroupChat(agents=[executor, researcher, analyst, writer], messages=[], max_round=12)
+ manager = GroupChatManager(groupchat=gc, llm_config=llm_config)
+ assert len(gc.agents) == 4
+ assert manager.groupchat is gc
+
+def test_llm_config_structure():
+ """Validate build_llm_config returns a proper LLMConfig."""
+ from research_assistant import build_llm_config
+ from autogen import LLMConfig
+ cfg = build_llm_config()
+ assert isinstance(cfg, LLMConfig)
+ assert len(cfg.config_list) >= 1
+ entry = cfg.config_list[0]
+ assert entry.model
+ assert entry.api_key
+
+def test_tool_registration():
+ """Register both tools on researcher/executor pair."""
+ 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"})
+ 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):
+ register_function(fn, caller=researcher, executor=executor,
+ name=fn.__name__, description=(fn.__doc__ or "").strip().split("\n")[0])
diff --git a/ai_agents/multi_agent_research_assistant_ag2/tests/test_research_tools.py b/ai_agents/multi_agent_research_assistant_ag2/tests/test_research_tools.py
new file mode 100644
index 0000000..7016fce
--- /dev/null
+++ b/ai_agents/multi_agent_research_assistant_ag2/tests/test_research_tools.py
@@ -0,0 +1,58 @@
+import json
+from unittest.mock import patch, MagicMock
+import pytest
+from tools.research_tools import web_search, fetch_page_content
+
+
+def _mock_urlopen(response_body: bytes):
+ """Create a mock for urllib.request.urlopen."""
+ mock_resp = MagicMock()
+ mock_resp.read.return_value = response_body
+ mock_resp.__enter__ = lambda s: s
+ mock_resp.__exit__ = MagicMock(return_value=False)
+ return mock_resp
+
+
+def test_web_search_returns_valid_json():
+ body = json.dumps({"RelatedTopics": [{"Text": "Python info", "FirstURL": "https://python.org"}],
+ "AbstractText": "Python is a language", "Heading": "Python",
+ "AbstractURL": "https://python.org"}).encode()
+ with patch("tools.research_tools.urllib.request.urlopen", return_value=_mock_urlopen(body)):
+ result = web_search("Python programming language", num_results=3)
+ data = json.loads(result)
+ assert "query" in data
+ assert "results" in data
+ assert isinstance(data["results"], list)
+ assert len(data["results"]) >= 1
+
+
+def test_web_search_handles_empty_query():
+ body = json.dumps({"RelatedTopics": []}).encode()
+ with patch("tools.research_tools.urllib.request.urlopen", return_value=_mock_urlopen(body)):
+ result = web_search("")
+ data = json.loads(result)
+ assert isinstance(data, dict)
+
+
+def test_fetch_page_content_rejects_file_url():
+ result = fetch_page_content("file:///etc/passwd")
+ data = json.loads(result)
+ assert "error" in data
+ assert "Unsupported URL scheme" in data["error"]
+
+
+def test_fetch_page_content_strips_html():
+ body = b"<html><body><h1>Title</h1><p>Content here</p></body></html>"
+ with patch("tools.research_tools.urllib.request.urlopen", return_value=_mock_urlopen(body)):
+ result = fetch_page_content("https://example.com", max_chars=100)
+ data = json.loads(result)
+ assert "content" in data
+ assert "<" not in data["content"]
+ assert len(data["content"]) <= 100
+
+
+def test_fetch_page_content_handles_error():
+ with patch("tools.research_tools.urllib.request.urlopen", side_effect=ConnectionError("timeout")):
+ result = fetch_page_content("https://unreachable.test")
+ data = json.loads(result)
+ assert "error" in data
diff --git a/ai_agents/multi_agent_research_assistant_ag2/tools/__init__.py b/ai_agents/multi_agent_research_assistant_ag2/tools/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/ai_agents/multi_agent_research_assistant_ag2/tools/research_tools.py b/ai_agents/multi_agent_research_assistant_ag2/tools/research_tools.py
new file mode 100644
index 0000000..32cf68e
--- /dev/null
+++ b/ai_agents/multi_agent_research_assistant_ag2/tools/research_tools.py
@@ -0,0 +1,61 @@
+# tools/research_tools.py
+import json
+import re
+import urllib.request
+import urllib.parse
+from datetime import datetime, timezone
+
+
+def web_search(query: str, num_results: int = 5) -> str:
+ """Search the web using DuckDuckGo Instant Answer API.
+
+ Returns a JSON string with top results including titles, URLs, and snippets.
+
+ Args:
+ query: Search query string.
+ num_results: Number of results to return (default 5).
+ """
+ try:
+ encoded = urllib.parse.quote(query)
+ url = f"https://api.duckduckgo.com/?q={encoded}&format=json&no_html=1"
+ with urllib.request.urlopen(url, timeout=10) as resp:
+ data = json.loads(resp.read().decode())
+
+ results = []
+ for item in data.get("RelatedTopics", [])[:num_results]:
+ if isinstance(item, dict) and "Text" in item:
+ results.append({
+ "title": item.get("Text", "")[:100],
+ "url": item.get("FirstURL", ""),
+ "snippet": item.get("Text", ""),
+ })
+ if data.get("AbstractText"):
+ results.insert(0, {
+ "title": data.get("Heading", query),
+ "url": data.get("AbstractURL", ""),
+ "snippet": data["AbstractText"],
+ })
+ return json.dumps({"query": query, "results": results, "timestamp": datetime.now(timezone.utc).isoformat()})
+ except Exception as exc:
+ return json.dumps({"error": str(exc), "query": query})
+
+
+def fetch_page_content(url: str, max_chars: int = 3000) -> str:
+ """Fetch and return the text content of a web page.
+
+ Args:
+ url: URL of the page to fetch.
+ max_chars: Maximum characters to return (default 3000).
+ """
+ parsed = urllib.parse.urlparse(url)
+ if parsed.scheme not in ("http", "https"):
+ return json.dumps({"error": f"Unsupported URL scheme: {parsed.scheme}", "url": url})
+ try:
+ req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
+ with urllib.request.urlopen(req, timeout=10) as resp:
+ content = resp.read().decode("utf-8", errors="ignore")
+ text = re.sub(r"<[^>]+>", " ", content)
+ text = re.sub(r"\s+", " ", text).strip()
+ return json.dumps({"url": url, "content": text[:max_chars]})
+ except Exception as exc:
+ return json.dumps({"error": str(exc), "url": url})
diff --git a/multi_agent_research_assistant_ag2/.env.example b/multi_agent_research_assistant_ag2/.env.example
new file mode 100644
index 0000000..1650210
--- /dev/null
+++ b/multi_agent_research_assistant_ag2/.env.example
@@ -0,0 +1,3 @@
+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
diff --git a/multi_agent_research_assistant_ag2/.gitignore b/multi_agent_research_assistant_ag2/.gitignore
new file mode 100644
index 0000000..7a7990c
--- /dev/null
+++ b/multi_agent_research_assistant_ag2/.gitignore
@@ -0,0 +1,4 @@
+__pycache__/
+*.pyc
+.env
+workspace/
diff --git a/multi_agent_research_assistant_ag2/README.md b/multi_agent_research_assistant_ag2/README.md
new file mode 100644
index 0000000..e34805b
--- /dev/null
+++ b/multi_agent_research_assistant_ag2/README.md
@@ -0,0 +1,68 @@
+# 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)
+
+## Installation
+```bash
+cd multi_agent_research_assistant_ag2
+pip install -r requirements.txt
+cp .env.example .env # add your API key
+```
+
+## Usage
+```bash
+streamlit run research_assistant.py
+```
+
+## How It Works
+
+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
+
+## 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
+
+> **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
+> an isolated environment.
+
+## Running Tests
+
+Tests are fully mocked — no API keys or network access required.
+
+```bash
+pip install pytest
+python -m pytest tests/ -v
+```
+
+## Project Structure
+
+```
+multi_agent_research_assistant_ag2/
+├── research_assistant.py # Agents, GroupChat orchestration, Streamlit UI
+├── tools/
+│ └── research_tools.py # web_search (DuckDuckGo API), fetch_page_content
+├── tests/
+│ ├── conftest.py # sys.path setup, Streamlit stub
+│ ├── test_agent_setup.py # Agent instantiation, tool registration
+│ └── test_research_tools.py # Mocked tool tests, SSRF validation
+├── requirements.txt
+└── .env.example
+```
diff --git a/multi_agent_research_assistant_ag2/requirements.txt b/multi_agent_research_assistant_ag2/requirements.txt
new file mode 100644
index 0000000..340ceea
--- /dev/null
+++ b/multi_agent_research_assistant_ag2/requirements.txt
@@ -0,0 +1,3 @@
+ag2>=0.11.0
+streamlit>=1.31.0
+python-dotenv>=1.0.0
diff --git a/multi_agent_research_assistant_ag2/research_assistant.py b/multi_agent_research_assistant_ag2/research_assistant.py
new file mode 100644
index 0000000..abbf300
--- /dev/null
+++ b/multi_agent_research_assistant_ag2/research_assistant.py
@@ -0,0 +1,149 @@
+# research_assistant.py
+import os
+import streamlit as st
+from datetime import datetime
+from dotenv import load_dotenv
+
+from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager, LLMConfig, register_function
+from tools.research_tools import web_search, fetch_page_content
+
+load_dotenv()
+
+# ── 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")},
+ temperature=0.3,
+ cache_seed=None, # always fetch fresh data
+ )
+
+
+def run_research(topic: str) -> str:
+ 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.""",
+ llm_config=llm_config,
+ )
+
+ analyst = AssistantAgent(
+ name="analyst",
+ system_message="""You are a senior analyst. Once RESEARCH COMPLETE is signalled,
+critically evaluate the research: identify key themes, contradictions, and knowledge gaps.
+Produce a structured analysis with bullet points. End with: ANALYSIS COMPLETE.""",
+ llm_config=llm_config,
+ )
+
+ writer = AssistantAgent(
+ name="writer",
+ system_message="""You are a professional technical writer. Once ANALYSIS COMPLETE
+is signalled, produce a polished markdown report with:
+## Executive Summary
+## Key Findings
+## Detailed Analysis
+## Conclusions & Next Steps
+End with: REPORT COMPLETE""",
+ llm_config=llm_config,
+ )
+
+ # Executes tool calls; no LLM of its own
+ executor = UserProxyAgent(
+ 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 ""),
+ default_auto_reply="",
+ )
+
+ # ── Tool registration: caller=LLM agent, executor=UserProxyAgent ──────────
+ # This AG2 pattern separates tool description (for the LLM) from execution
+ # (sandboxed in the UserProxyAgent). The executor can be swapped for a
+ # Docker container without changing any agent reasoning code.
+
+ for fn in (web_search, fetch_page_content):
+ register_function(
+ fn,
+ caller=researcher,
+ executor=executor,
+ name=fn.__name__,
+ description=(fn.__doc__ or "").strip().split("\n")[0],
+ )
+
+ # ── GroupChat orchestration ────────────────────────────────────────────────
+ groupchat = GroupChat(
+ agents=[executor, researcher, analyst, writer],
+ messages=[],
+ max_round=20,
+ speaker_selection_method="auto", # LLM selects the next speaker
+ )
+ manager = GroupChatManager(groupchat=groupchat, llm_config=llm_config)
+
+ executor.initiate_chat(
+ manager,
+ message=f"Research the following topic thoroughly: {topic}",
+ clear_history=True,
+ )
+
+ # Extract the final report from writer messages
+ report_msgs = [
+ m["content"]
+ for m in groupchat.messages
+ if m.get("name") == "writer" and m.get("content")
+ ]
+ return report_msgs[-1] if report_msgs else "Report generation did not complete."
+
+
+# ── Streamlit UI ──────────────────────────────────────────────────────────────
+
+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")
+
+if "report" not in st.session_state:
+ st.session_state.report = None
+
+if run_btn:
+ if not topic.strip():
+ st.error("Please enter a research topic.")
+ else:
+ with st.spinner("AG2 agents are researching..."):
+ try:
+ st.session_state.report = run_research(topic)
+ except Exception as exc:
+ st.error(f"Error: {exc}")
+
+if st.session_state.report:
+ st.markdown(st.session_state.report)
+ st.download_button(
+ "Download Report",
+ data=st.session_state.report,
+ file_name=f"research_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md",
+ mime="text/markdown",
+ )
+
+st.markdown("---")
+st.caption("For educational purposes only")
diff --git a/multi_agent_research_assistant_ag2/tests/__init__.py b/multi_agent_research_assistant_ag2/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/multi_agent_research_assistant_ag2/tests/conftest.py b/multi_agent_research_assistant_ag2/tests/conftest.py
new file mode 100644
index 0000000..310f3c5
--- /dev/null
+++ b/multi_agent_research_assistant_ag2/tests/conftest.py
@@ -0,0 +1,42 @@
+"""
+Stub out UI and optional dependencies so tests run without a Streamlit install.
+research_assistant.py calls st.* at module level, so we must intercept before import.
+"""
+import sys
+import os
+from types import ModuleType
+from unittest.mock import MagicMock
+
+
+def _stub_module(name: str, **attrs) -> ModuleType:
+ m = ModuleType(name)
+ for k, v in attrs.items():
+ setattr(m, k, v)
+ sys.modules[name] = m
+ return m
+
+
+# Streamlit: stub the entire module — research_assistant.py runs st.* at module level
+_st = _stub_module(
+ "streamlit",
+ set_page_config=MagicMock(),
+ title=MagicMock(),
+ caption=MagicMock(),
+ header=MagicMock(),
+ text_input=MagicMock(return_value=""),
+ text_area=MagicMock(return_value=""),
+ button=MagicMock(return_value=False),
+ spinner=MagicMock(),
+ error=MagicMock(),
+ markdown=MagicMock(),
+ download_button=MagicMock(),
+ sidebar=MagicMock(),
+ session_state=MagicMock(report=None),
+)
+_st.sidebar.__enter__ = MagicMock(return_value=_st.sidebar)
+_st.sidebar.__exit__ = MagicMock(return_value=False)
+
+# Ensure parent dir (multi_agent_research_assistant_ag2/) is on sys.path
+parent = os.path.dirname(os.path.dirname(__file__))
+if parent not in sys.path:
+ sys.path.insert(0, parent)
diff --git a/multi_agent_research_assistant_ag2/tests/test_agent_setup.py b/multi_agent_research_assistant_ag2/tests/test_agent_setup.py
new file mode 100644
index 0000000..5749132
--- /dev/null
+++ b/multi_agent_research_assistant_ag2/tests/test_agent_setup.py
@@ -0,0 +1,42 @@
+import os
+import pytest
+os.environ.setdefault("OPENAI_API_KEY", "test-key-no-llm-calls")
+
+def test_agents_instantiate():
+ """Verify agent setup does not raise — no LLM calls made."""
+ from research_assistant import build_llm_config
+ from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager
+
+ llm_config = build_llm_config()
+ researcher = AssistantAgent(name="researcher", system_message="Test", llm_config=llm_config)
+ analyst = AssistantAgent(name="analyst", system_message="Test", llm_config=llm_config)
+ writer = AssistantAgent(name="writer", system_message="Test", llm_config=llm_config)
+ executor = UserProxyAgent(name="executor", human_input_mode="NEVER", code_execution_config=False)
+
+ gc = GroupChat(agents=[executor, researcher, analyst, writer], messages=[], max_round=12)
+ manager = GroupChatManager(groupchat=gc, llm_config=llm_config)
+ assert len(gc.agents) == 4
+ assert manager.groupchat is gc
+
+def test_llm_config_structure():
+ """Validate build_llm_config returns a proper LLMConfig."""
+ from research_assistant import build_llm_config
+ from autogen import LLMConfig
+ cfg = build_llm_config()
+ assert isinstance(cfg, LLMConfig)
+ assert len(cfg.config_list) >= 1
+ entry = cfg.config_list[0]
+ assert entry.model
+ assert entry.api_key
+
+def test_tool_registration():
+ """Register both tools on researcher/executor pair."""
+ 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"})
+ 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):
+ register_function(fn, caller=researcher, executor=executor,
+ name=fn.__name__, description=(fn.__doc__ or "").strip().split("\n")[0])
diff --git a/multi_agent_research_assistant_ag2/tests/test_research_tools.py b/multi_agent_research_assistant_ag2/tests/test_research_tools.py
new file mode 100644
index 0000000..7016fce
--- /dev/null
+++ b/multi_agent_research_assistant_ag2/tests/test_research_tools.py
@@ -0,0 +1,58 @@
+import json
+from unittest.mock import patch, MagicMock
+import pytest
+from tools.research_tools import web_search, fetch_page_content
+
+
+def _mock_urlopen(response_body: bytes):
+ """Create a mock for urllib.request.urlopen."""
+ mock_resp = MagicMock()
+ mock_resp.read.return_value = response_body
+ mock_resp.__enter__ = lambda s: s
+ mock_resp.__exit__ = MagicMock(return_value=False)
+ return mock_resp
+
+
+def test_web_search_returns_valid_json():
+ body = json.dumps({"RelatedTopics": [{"Text": "Python info", "FirstURL": "https://python.org"}],
+ "AbstractText": "Python is a language", "Heading": "Python",
+ "AbstractURL": "https://python.org"}).encode()
+ with patch("tools.research_tools.urllib.request.urlopen", return_value=_mock_urlopen(body)):
+ result = web_search("Python programming language", num_results=3)
+ data = json.loads(result)
+ assert "query" in data
+ assert "results" in data
+ assert isinstance(data["results"], list)
+ assert len(data["results"]) >= 1
+
+
+def test_web_search_handles_empty_query():
+ body = json.dumps({"RelatedTopics": []}).encode()
+ with patch("tools.research_tools.urllib.request.urlopen", return_value=_mock_urlopen(body)):
+ result = web_search("")
+ data = json.loads(result)
+ assert isinstance(data, dict)
+
+
+def test_fetch_page_content_rejects_file_url():
+ result = fetch_page_content("file:///etc/passwd")
+ data = json.loads(result)
+ assert "error" in data
+ assert "Unsupported URL scheme" in data["error"]
+
+
+def test_fetch_page_content_strips_html():
+ body = b"<html><body><h1>Title</h1><p>Content here</p></body></html>"
+ with patch("tools.research_tools.urllib.request.urlopen", return_value=_mock_urlopen(body)):
+ result = fetch_page_content("https://example.com", max_chars=100)
+ data = json.loads(result)
+ assert "content" in data
+ assert "<" not in data["content"]
+ assert len(data["content"]) <= 100
+
+
+def test_fetch_page_content_handles_error():
+ with patch("tools.research_tools.urllib.request.urlopen", side_effect=ConnectionError("timeout")):
+ result = fetch_page_content("https://unreachable.test")
+ data = json.loads(result)
+ assert "error" in data
diff --git a/multi_agent_research_assistant_ag2/tools/__init__.py b/multi_agent_research_assistant_ag2/tools/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/multi_agent_research_assistant_ag2/tools/research_tools.py b/multi_agent_research_assistant_ag2/tools/research_tools.py
new file mode 100644
index 0000000..32cf68e
--- /dev/null
+++ b/multi_agent_research_assistant_ag2/tools/research_tools.py
@@ -0,0 +1,61 @@
+# tools/research_tools.py
+import json
+import re
+import urllib.request
+import urllib.parse
+from datetime import datetime, timezone
+
+
+def web_search(query: str, num_results: int = 5) -> str:
+ """Search the web using DuckDuckGo Instant Answer API.
+
+ Returns a JSON string with top results including titles, URLs, and snippets.
+
+ Args:
+ query: Search query string.
+ num_results: Number of results to return (default 5).
+ """
+ try:
+ encoded = urllib.parse.quote(query)
+ url = f"https://api.duckduckgo.com/?q={encoded}&format=json&no_html=1"
+ with urllib.request.urlopen(url, timeout=10) as resp:
+ data = json.loads(resp.read().decode())
+
+ results = []
+ for item in data.get("RelatedTopics", [])[:num_results]:
+ if isinstance(item, dict) and "Text" in item:
+ results.append({
+ "title": item.get("Text", "")[:100],
+ "url": item.get("FirstURL", ""),
+ "snippet": item.get("Text", ""),
+ })
+ if data.get("AbstractText"):
+ results.insert(0, {
+ "title": data.get("Heading", query),
+ "url": data.get("AbstractURL", ""),
+ "snippet": data["AbstractText"],
+ })
+ return json.dumps({"query": query, "results": results, "timestamp": datetime.now(timezone.utc).isoformat()})
+ except Exception as exc:
+ return json.dumps({"error": str(exc), "query": query})
+
+
+def fetch_page_content(url: str, max_chars: int = 3000) -> str:
+ """Fetch and return the text content of a web page.
+
+ Args:
+ url: URL of the page to fetch.
+ max_chars: Maximum characters to return (default 3000).
+ """
+ parsed = urllib.parse.urlparse(url)
+ if parsed.scheme not in ("http", "https"):
+ return json.dumps({"error": f"Unsupported URL scheme: {parsed.scheme}", "url": url})
+ try:
+ req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
+ with urllib.request.urlopen(req, timeout=10) as resp:
+ content = resp.read().decode("utf-8", errors="ignore")
+ text = re.sub(r"<[^>]+>", " ", content)
+ text = re.sub(r"\s+", " ", text).strip()
+ return json.dumps({"url": url, "content": text[:max_chars]})
+ except Exception as exc:
+ return json.dumps({"error": str(exc), "url": url})