«`html
A Code Implementation to Build a Multi-Agent Research System with OpenAI Agents, Function Tools, Handoffs, and Session Memory
In this tutorial, we explore the capabilities of OpenAI Agents in constructing a multi-agent research system. We begin by setting up our Colab environment with the OpenAI API key and installing the OpenAI Agents SDK. We define custom function tools: web_search
, analyze_data
, and save_research
, to leverage the agents’ functionalities. Three specialized OpenAI Agents are instantiated: Research Specialist, Data Analyst, and Research Coordinator, each with specific instructions and tool access. This system enables asynchronous and synchronous collaboration among agents, maintains session memory for continuity, and facilitates rapid experimentation through helper functions.
Setting Up the Environment
To get started, install the necessary packages and set your OpenAI API key:
!pip install openai-agents python-dotenv
import asyncio
import json
from datetime import datetime
from agents import Agent, Runner, function_tool, SQLiteSession
import os
os.environ['OPENAI_API_KEY'] = 'Use Your Own API Key'
Defining Function Tools
We define three function tools for our agents:
@function_tool
def web_search(query: str, max_results: int = 3) -> str:
results = [
f"Result 1 for '{query}': Latest findings show significant developments...",
f"Result 2 for '{query}': Research indicates new approaches in this field...",
f"Result 3 for '{query}': Expert analysis suggests important implications..."
]
return f"Search results for '{query}':\n" + "\n".join(results[:max_results])
@function_tool
def analyze_data(data: str, analysis_type: str = "summary") -> str:
analyses = {
"summary": f"Summary: The data contains {len(data.split())} key points with main themes around innovation and efficiency.",
"detailed": f"Detailed Analysis: Breaking down the {len(data)} characters of data reveals patterns in methodology and conclusions.",
"trends": f"Trend Analysis: Current data suggests upward trajectory with 3 major inflection points identified."
}
return analyses.get(analysis_type, "Analysis complete: Standard evaluation performed.")
@function_tool
def save_research(title: str, content: str, category: str = "general") -> str:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
research_entry = {
"title": title,
"content": content,
"category": category,
"timestamp": timestamp,
"id": f"research_{len(content) % 1000}"
}
return f" Research saved: '{title}' in category '{category}' at {timestamp}"
Creating Specialized Agents
We define three OpenAI Agents with clear roles:
research_agent = Agent(
name="Research Specialist",
instructions="""You are an expert researcher who:
- Conducts thorough web searches on any topic
- Analyzes information critically and objectively
- Identifies key insights and patterns
- Always uses tools to gather and analyze data before responding""",
tools=[web_search, analyze_data]
)
analyst_agent = Agent(
name="Data Analyst",
instructions="""You are a senior data analyst who:
- Takes research findings and performs deep analysis
- Identifies trends, patterns, and actionable insights
- Creates structured summaries and recommendations
- Uses analysis tools to enhance understanding""",
tools=[analyze_data, save_research]
)
coordinator_agent = Agent(
name="Research Coordinator",
instructions="""You are a research coordinator who:
- Manages multi-step research projects
- Delegates tasks to appropriate specialists
- Synthesizes findings from multiple sources
- Makes final decisions on research direction
- Handoff to research_agent for initial data gathering
- Handoff to analyst_agent for detailed analysis""",
handoffs=[research_agent, analyst_agent],
tools=[save_research]
)
Running the Advanced Research Workflow
We demonstrate a complete multi-agent research workflow:
async def run_advanced_research_workflow():
session = SQLiteSession("research_session_001")
research_topic = "artificial intelligence in healthcare 2024"
result1 = await Runner.run(
coordinator_agent,
f"I need comprehensive research on '{research_topic}'. Please coordinate a full research workflow including data gathering, analysis, and final report generation.",
session=session
)
result2 = await Runner.run(
coordinator_agent,
"Based on the previous research, I need a detailed trend analysis focusing on emerging opportunities and potential challenges. Save the final analysis for future reference.",
session=session
)
result3 = await Runner.run(
analyst_agent,
"Perform a detailed analysis of the healthcare AI market, focusing on regulatory challenges and market opportunities. Categorize this as 'market_analysis'.",
session=session
)
return result1, result2, result3
Focused Analysis and Quick Research
We also illustrate focused single-agent capabilities and synchronous research:
async def run_focused_analysis():
result = await Runner.run(
research_agent,
"Research in quantum computing and analyze the key breakthroughs from 2024.",
max_turns=5
)
return result
def quick_research_sync(topic: str):
result = Runner.run_sync(
research_agent,
f"Quickly research {topic} and provide 3 key insights."
)
return result
Main Function to Demonstrate Capabilities
The main function orchestrates the entire demo:
async def main():
await run_advanced_research_workflow()
await run_focused_analysis()
quick_research_sync("blockchain adoption in enterprise")
if __name__ == "__main__":
import nest_asyncio
nest_asyncio.apply()
asyncio.run(main())
Conclusion
In conclusion, this tutorial highlights the strengths of the OpenAI Agents framework: coordinated multi-agent collaboration, extensible custom tools, persistent session memory, and flexible execution modes. Users are encouraged to expand upon these foundations by adding new tools and experimenting with different agent roles and handoff strategies.
Check out the Full Codes and feel free to explore further resources.
«`