On this tutorial, you’ll construct a sophisticated multi-agent incident response system utilizing: agent scope. We coordinate a number of ReAct brokers, every with clearly outlined roles comparable to routing, triage, evaluation, writing, and reviewing, and join them by means of structured routing and a shared message hub. By integrating OpenAI fashions, light-weight software calls, and easy inside runbooks, we present how complicated real-world agent workflows may be configured in pure Python with out heavy infrastructure or brittle glue code. Please examine Full code here.
!pip -q set up "agentscope>=0.1.5" pydantic nest_asyncio
import os, json, re
from getpass import getpass
from typing import Literal
from pydantic import BaseModel, Discipline
import nest_asyncio
nest_asyncio.apply()
from agentscope.agent import ReActAgent
from agentscope.message import Msg, TextBlock
from agentscope.mannequin import OpenAIChatModel
from agentscope.formatter import OpenAIChatFormatter
from agentscope.reminiscence import InMemoryMemory
from agentscope.software import Toolkit, ToolResponse, execute_python_code
from agentscope.pipeline import MsgHub, sequential_pipeline
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass("Enter OPENAI_API_KEY (hidden): ")
OPENAI_MODEL = os.environ.get("OPENAI_MODEL", "gpt-4o-mini")
Arrange the execution setting and set up all required dependencies to make sure the tutorial runs on Google Colab. Securely hundreds the OpenAI API key and initializes the core AgentScope part that’s shared between all brokers. Please examine Full code here.
RUNBOOK = [
{"id": "P0", "title": "Severity Policy", "text": "P0 critical outage, P1 major degradation, P2 minor issue"},
{"id": "IR1", "title": "Incident Triage Checklist", "text": "Assess blast radius, timeline, deployments, errors, mitigation"},
{"id": "SEC7", "title": "Phishing Escalation", "text": "Disable account, reset sessions, block sender, preserve evidence"},
]
def _score(q, d):
q = set(re.findall(r"[a-z0-9]+", q.decrease()))
d = re.findall(r"[a-z0-9]+", d.decrease())
return sum(1 for w in d if w in q) / max(1, len(d))
async def search_runbook(question: str, top_k: int = 2) -> ToolResponse:
ranked = sorted(RUNBOOK, key=lambda r: _score(question, r["title"] + r["text"]), reverse=True)[: max(1, int(top_k))]
textual content = "nn".be part of(f"[{r['id']}] {r['title']}n{r['text']}" for r in ranked)
return ToolResponse(content material=[TextBlock(type="text", text=text)])
toolkit = Toolkit()
toolkit.register_tool_function(search_runbook)
toolkit.register_tool_function(execute_python_code)
Outline a light-weight inside runbook and implement a easy relevance-based search software on prime of it. Registering this operate with a Python execution software permits the agent to acquire coverage data and dynamically compute outcomes. This exhibits how brokers may be enhanced with exterior capabilities past pure linguistic reasoning. Please examine Full code here.
def make_model():
return OpenAIChatModel(
model_name=OPENAI_MODEL,
api_key=os.environ["OPENAI_API_KEY"],
generate_kwargs={"temperature": 0.2},
)
class Route(BaseModel):
lane: Literal["triage", "analysis", "report", "unknown"] = Discipline(...)
aim: str = Discipline(...)
router = ReActAgent(
identify="Router",
sys_prompt="Route the request to triage, evaluation, or report and output structured JSON solely.",
mannequin=make_model(),
formatter=OpenAIChatFormatter(),
reminiscence=InMemoryMemory(),
)
triager = ReActAgent(
identify="Triager",
sys_prompt="Classify severity and instant actions utilizing runbook search when helpful.",
mannequin=make_model(),
formatter=OpenAIChatFormatter(),
reminiscence=InMemoryMemory(),
toolkit=toolkit,
)
analyst = ReActAgent(
identify="Analyst",
sys_prompt="Analyze logs and compute summaries utilizing python software when useful.",
mannequin=make_model(),
formatter=OpenAIChatFormatter(),
reminiscence=InMemoryMemory(),
toolkit=toolkit,
)
author = ReActAgent(
identify="Author",
sys_prompt="Write a concise incident report with clear construction.",
mannequin=make_model(),
formatter=OpenAIChatFormatter(),
reminiscence=InMemoryMemory(),
)
reviewer = ReActAgent(
identify="Reviewer",
sys_prompt="Critique and enhance the report with concrete fixes.",
mannequin=make_model(),
formatter=OpenAIChatFormatter(),
reminiscence=InMemoryMemory(),
)
Construct a number of specialised ReAct brokers and a structured router that decides the best way to deal with every person’s requests. We assign clear duties to triage, evaluation, writing, and reviewers to make sure separation of considerations. Please examine Full code here.
LOGS = """timestamp,service,standing,latency_ms,error
2025-12-18T12:00:00Z,checkout,200,180,false
2025-12-18T12:00:05Z,checkout,500,900,true
2025-12-18T12:00:10Z,auth,200,120,false
2025-12-18T12:00:12Z,checkout,502,1100,true
2025-12-18T12:00:20Z,search,200,140,false
2025-12-18T12:00:25Z,checkout,500,950,true
"""
def msg_text(m: Msg) -> str:
blocks = m.get_content_blocks("textual content")
if blocks is None:
return ""
if isinstance(blocks, str):
return blocks
if isinstance(blocks, checklist):
return "n".be part of(str(x) for x in blocks)
return str(blocks)
We current pattern log knowledge and a utility operate that normalizes agent output to scrub textual content. It ensures that downstream brokers can safely use and enhance on earlier responses with out introducing formatting points. It focuses on making communication between brokers sturdy and predictable. Please examine Full code here.
async def run_demo(user_request: str):
route_msg = await router(Msg("person", user_request, "person"), structured_model=Route)
lane = (route_msg.metadata or {}).get("lane", "unknown")
if lane == "triage":
first = await triager(Msg("person", user_request, "person"))
elif lane == "evaluation":
first = await analyst(Msg("person", user_request + "nnLogs:n" + LOGS, "person"))
elif lane == "report":
draft = await author(Msg("person", user_request, "person"))
first = await reviewer(Msg("person", "Evaluate and enhance:nn" + msg_text(draft), "person"))
else:
first = Msg("system", "Couldn't route request.", "system")
async with MsgHub(
members=[triager, analyst, writer, reviewer],
announcement=Msg("Host", "Refine the ultimate reply collaboratively.", "assistant"),
):
await sequential_pipeline([triager, analyst, writer, reviewer])
return {"route": route_msg.metadata, "initial_output": msg_text(first)}
end result = await run_demo(
"We see repeated 5xx errors in checkout. Classify severity, analyze logs, and produce an incident report."
)
print(json.dumps(end result, indent=2))
Coordinate the whole workflow by routing requests, working the suitable brokers, and utilizing message hubs to carry out collaborative coordination loops. Tune a number of brokers in sequence to enhance the ultimate output earlier than returning it to the person. This integrates all earlier parts right into a constant end-to-end agent pipeline.
In conclusion, we now have proven that AgentScope can be utilized to design sturdy, modular, and collaborative agent methods that transcend single-prompt interactions. Inside a clear and reproducible Colab setup, we dynamically routed duties, invoked instruments solely when mandatory, and refined outputs by means of multi-agent coordination. This sample exhibits the best way to scale from easy agent experiments to production-style inference pipelines whereas sustaining readability, management, and scalability for agent AI functions.
Please examine Full code here. Additionally, be at liberty to comply with us Twitter Do not forget to hitch us 100,000+ ML subreddits and subscribe our newsletter. grasp on! Are you on telegram? You can now also participate by telegram.
Asif Razzaq is the CEO of Marktechpost Media Inc. As a visionary entrepreneur and engineer, Asif is dedicated to harnessing the potential of synthetic intelligence for social good. His newest endeavor is the launch of Marktechpost, a synthetic intelligence media platform. It stands out for its thorough protection of machine studying and deep studying information, which is technically sound and simply understood by a large viewers. The platform boasts over 2 million views monthly, demonstrating its reputation amongst viewers.

