In this tutorial, we begin by showcasing the power of OpenAI Agents as the driving force behind our multi-agent research system. We set up our Colab environment with the OpenAI API key, installed the OpenAI Agents SDK, and then defined custom function tools, web_search, analyze_data, and save_research, to harness the agents’ capabilities. We instantiate three specialized OpenAI Agents (Research Specialist, Data Analyst, and Research Coordinator), each with clear, role-specific instructions and tool access. We demonstrate how these agents collaborate asynchronously and synchronously, maintain session memory for continuity, and allow rapid experimentation through helper functions. Check out the Full Codes here.
!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'
We install openai-agents and python-dotenv, then import asyncio, json, datetime, and the core SDK primitives (Agent, Runner, function_tool, SQLiteSession). We set OPENAI_API_KEY in the environment so we can immediately run our agents in this runtime. Check out the Full Codes here.
@function_tool
def web_search(query: str, max_results: int = 3) -> str:
"""Simulate web search results for demonstration"""
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:
"""Analyze provided data with different analysis types"""
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:
"""Save research findings to a structured format"""
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}"
We define three function tools for our agents: web_search simulates quick results, analyze_data returns summary/detailed/trend insights, and save_research stores findings with a timestamped ID. We use them to gather signals, turn text into insights, and persist outputs for later steps. Check out the Full Codes here.
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]
)
We define three OpenAI Agents with clear roles: the Research Specialist gathers and synthesizes information, the Data Analyst deep-dives and saves structured outputs, and the Research Coordinator orchestrates handoffs and final decisions. Together, we delegate, analyze with tools, and produce actionable summaries end-to-end. Check out the Full Codes here.
async def run_advanced_research_workflow():
"""Demonstrates a complete multi-agent research workflow"""
session = SQLiteSession("research_session_001")
print(" Starting Advanced Multi-Agent Research System")
print("=" * 60)
research_topic = "artificial intelligence in healthcare 2024"
print(f"\n PHASE 1: Initiating research on '{research_topic}'")
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
)
print(f"Coordinator Response: {result1.final_output}")
print(f"\n PHASE 2: Requesting detailed trend analysis")
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
)
print(f"Analysis Response: {result2.final_output}")
print(f"\n PHASE 3: Direct specialist analysis")
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
)
print(f"Specialist Response: {result3.final_output}")
print("\n Research workflow completed successfully!")
return result1, result2, result3
async def run_focused_analysis():
"""Shows focused single-agent capabilities"""
print("\n FOCUSED ANALYSIS DEMO")
print("-" * 40)
result = await Runner.run(
research_agent,
"Research in quantum computing and analyze the key breakthroughs from 2024.",
max_turns=5
)
print(f"Focused Analysis Result: {result.final_output}")
return result
def quick_research_sync(topic: str):
"""Synchronous research for quick queries"""
print(f"\n QUICK SYNC RESEARCH: {topic}")
print("-" * 40)
result = Runner.run_sync(
research_agent,
f"Quickly research {topic} and provide 3 key insights."
)
print(f"Quick Result: {result.final_output}")
return result
We run a full multi-agent workflow with session memory (three phases coordinated by the coordinator and analyst). We perform a focused single-agent analysis with a turn cap, and finally, we trigger a quick synchronous research helper for fast, three-insight summaries. Check out the Full Codes here.
async def main():
"""Main function demonstrating all capabilities"""
print(" OpenAI Agents SDK - Advanced Tutorial")
print("Building a Multi-Agent Research System")
print("=" * 60)
try:
await run_advanced_research_workflow()
await run_focused_analysis()
quick_research_sync("blockchain adoption in enterprise")
print("\n Tutorial completed successfully!")
print("\nKey Features Demonstrated:")
print(" Multi-agent coordination with handoffs")
print(" Custom function tools")
print(" Session memory for conversation continuity")
print(" Async and sync execution patterns")
print(" Structured workflows with max_turns control")
print(" Specialized agent roles and capabilities")
except Exception as e:
print(f" Error: {e}")
print("\nTroubleshooting tips:")
print("- Ensure OPENAI_API_KEY is set correctly")
print("- Check internet connection")
print("- Verify openai-agents package is installed")
if __name__ == "__main__":
import nest_asyncio
nest_asyncio.apply()
asyncio.run(main())
def create_custom_agent(name: str, role: str, tools_list: list = None):
"""Helper function to create custom agents quickly"""
return Agent(
name=name,
instructions=f"You are a {role} who provides expert assistance.",
tools=tools_list or []
)
custom_agent = create_custom_agent("Code Reviewer", "senior software engineer", [analyze_data])
result = Runner.run_sync(custom_agent, "Review this Python code for best practices")
print("\n Tutorial Notes:")
print("- Modify research topics and agent instructions to explore different use cases")
print("- Add your own custom tools using the @function_tool decorator")
print("- Experiment with different agent handoff patterns")
print("- Use sessions for multi-turn conversations")
print("- Perfect for Colab - just add your OpenAI API key and run!")
We orchestrate the end-to-end demo with main(), running the multi-agent workflow, a focused analysis, and a quick sync task, while handling errors and logging key features. We also provide a helper to spin up custom agents and show a synchronous “Code Reviewer” example for immediate feedback.
In conclusion, we wrap up the Advanced OpenAI Agents tutorial by highlighting the core strengths of this framework: coordinated multi-agent collaboration, extensible custom tools, persistent session memory, and flexible execution modes. We encourage you to expand on these foundations by adding new tools, crafting custom agent roles, and experimenting with different handoff strategies. We emphasize that this modular architecture empowers you to build sophisticated AI-driven research pipelines with minimal boilerplate.
Check out the Full Codes here. Feel free to check out our GitHub Page for Tutorials, Codes and Notebooks. Also, feel free to follow us on Twitter and don’t forget to join our 100k+ ML SubReddit and Subscribe to our Newsletter.

Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is committed to harnessing the potential of Artificial Intelligence for social good. His most recent endeavor is the launch of an Artificial Intelligence Media Platform, Marktechpost, which stands out for its in-depth coverage of machine learning and deep learning news that is both technically sound and easily understandable by a wide audience. The platform boasts of over 2 million monthly views, illustrating its popularity among audiences.