pip install openai
export OPENAI_API_KEY=sk-...
Create agents with distinct roles: triage, researcher, writer, and reviewer.
1 from openai import OpenAI 2 from dataclasses import dataclass, field 3 import json 4 5 client = OpenAI() 6 7 @dataclass 8 class Agent: 9 name: str 10 instructions: str 11 tools: list[dict] = field(default_factory=list) 12 handoffs: list[str] = field(default_factory=list) 13 14 AGENTS = { 15 "triage": Agent( 16 name="triage", 17 instructions="You are a routing agent. For research questions handoff to 'researcher'. For writing tasks handoff to 'writer'. Say DONE when complete.", 18 handoffs=["researcher", "writer"], 19 ), 20 "researcher": Agent( 21 name="researcher", 22 instructions="You are a research expert. Find relevant information and provide detailed findings. Handoff to 'writer' when you have enough data.", 23 handoffs=["writer"], 24 ), 25 "writer": Agent( 26 name="writer", 27 instructions="You write clear, structured content based on research. Handoff to 'reviewer' for final check.", 28 handoffs=["reviewer"], 29 ), 30 "reviewer": Agent( 31 name="reviewer", 32 instructions="Review the content for accuracy, clarity, and completeness. If good, say DONE. Otherwise handoff back to 'writer'.", 33 handoffs=["writer"], 34 ), 35 } 36 37 def build_handoff_tool(target: str) -> dict: 38 return { 39 "type": "function", 40 "function": { 41 "name": f"handoff_to_{target}", 42 "description": f"Transfer the task to the {target} agent.", 43 "parameters": {"type": "object", "properties": {}, "required": []} 44 } 45 } 46 47 def run_pipeline(task: str) -> str: 48 current = "triage" 49 messages = [{"role": "user", "content": task}] 50 for _ in range(20): 51 agent = AGENTS[current] 52 all_tools = agent.tools + [build_handoff_tool(h) for h in agent.handoffs] 53 response = client.chat.completions.create( 54 model="gpt-4o", 55 tools=all_tools or None, 56 messages=[{"role": "system", "content": agent.instructions}] + messages, 57 ) 58 msg = response.choices[0].message 59 messages.append(msg) 60 if not msg.tool_calls: 61 if "DONE" in (msg.content or ""): 62 return msg.content 63 continue 64 for tc in msg.tool_calls: 65 if tc.function.name.startswith("handoff_to_"): 66 next_agent = tc.function.name.replace("handoff_to_", "") 67 print(f"Handoff: {current} → {next_agent}") 68 current = next_agent 69 messages.append({"role": "tool", "tool_call_id": tc.id, "content": "Handoff accepted"}) 70 break 71 return messages[-1].content or "No result" 72
Four agents running a research-to-report pipeline
Sign in to share your feedback and join the discussion.