Multi-Agent Applications
local graph
Chapter 7 — Multi-Agent Applications
Section titled “Chapter 7 — Multi-Agent Applications”Until now, we’ve explored how to build powerful single-agent systems—intelligent entities that leverage tools, knowledge, memory, and orchestration layers to solve complex tasks. These agents can be highly capable when properly configured, drawing on vast knowledge and integrations to act independently. However, the true potential of agentic systems begins to unfold when we move beyond the solitary agent.
Just as humans rely on teams with diverse roles and expertise, AI systems can benefit immensely from having multiple agents working in tandem, each with its own specialization, perspective, or function.
This chapter explores how agents can communicate, coordinate, and cooperate to complete tasks that would be difficult—or even impossible—for a single agent to handle alone. In this chapter, we will cover the following topics:
- Introduction to multi-agent systems
- Understanding and designing different workflows for your multi-agent system
- Overview of multi-agent orchestrators
- Building your first multi-agent application with LangGraph
By the end of this chapter, you’ll have a clear understanding of what it takes to architect and launch multi-agent AI applications to tackle your unique use cases.
Technical requirements
Section titled “Technical requirements”All the code and necessary dependencies for this chapter are listed in the requirements.txt file available in the official GitHub repository of the book at https://github.com/PacktPublishing/AI-Agents-in-Practice.
To set up your environment, simply clone the repository and install the requirements by running the following:
pip install -r requirements.txtThis will ensure that you have all the libraries and tools needed to follow along with the hands-on examples.
Introduction to multi-agent systems
Section titled “Introduction to multi-agent systems”As we’ve seen in earlier chapters, a single AI agent will typically be provided with tools such as web APIs, databases, web services, and more. These tools extend the agent’s functionality beyond text generation, enabling it to interact with the world and perform goal-driven tasks. For example, in the previous chapter, we explored how an AI agent for an Italian restaurant can be integrated with the backend database containing in-stock products, retrieve relevant insight from a vector database, and even perform actions such as adding an item to the user’s cart.
But what if we took this one step further?
Just as a single agent can call a tool, an agent can also call another agent. In fact, from the perspective of a higher-level agent, another agent is a tool, as long as it is provided with a natural language description of its capabilities. This gives rise to multi-agent systems, where intelligent entities communicate and collaborate, each contributing a specialized capability to the larger system.
For example, imagine a simple AI system where a Python function is used to fetch a user’s calendar events from an online service such as Google Calendar. This function takes specific parameters—such as a date or event ID—and returns exactly what it was asked for, nothing more.
Now, in a multi-agent system, that same calendar functionality could be handled by a specialized “Calendar Agent.” This agent would go beyond basic data retrieval. It could do the following:
- Understand vague queries such as “What’s my next free afternoon?”
- Detect and resolve scheduling conflicts (e.g., two meetings overlapping)
- Negotiate changes with other agents—for instance, proposing new meeting times that work for everyone involved
This transformation from a simple function to an intelligent agent illustrates how multi-agent systems bring richer reasoning, flexibility, and autonomy into otherwise basic tasks.
Why should we do that? Can’t we rely on a simple tool to do that? The short answer—and considering the simple example—might be yes, we can rely on a single tool. However, there might be scenarios where you want to have a very specialized agent instead of a tool, so that you can provide it with a clear system message and extend its capabilities a bit more. Plus, this very same Calendar Agent might be used across different processes and applications, making it a repeatable component across your organization.
Let’s consider another example—this time, a bit more complex. Let’s say that we want to enable an AI application that will help you with your shopping online, across multiple stores. This is a typical query you might want to execute: “Purchase the new shoes from XYW, size 39 EU.”

Figure 7.1: Example of a hierarchical multi-agent system
Figure 7.1: Example of a hierarchical multi-agent system
In a single-agent setup, that agent would sequentially search for the shoes, manage scheduling, fill in address details, and process the payment. But in a modular, multi-agent design, this task is broken into specialized components:
- A Planner Agent interprets the instruction and coordinates the following execution.
- A Web Agent browses e-commerce platforms, using low-level Web Controller Agents (e.g., Selenium-driven bots) to interact with the interface—clicking, scrolling, and searching visually.
- A Scheduling Agent checks the calendar for delivery availability, calling a Calendar Agent to get or create events.
- An Order Placement Agent finalizes the purchase by coordinating with the following:
- A Payment Agent, responsible for securely handling transactions 2. An Address Agent, which validates and formats the shipping address
Each agent operates independently but contributes to the larger mission. The Planner agent acts as the conductor, orchestrating a team of intelligent performers: Web agent, Scheduling agent, Order Placement agent, Web Controllers, Calendar Agent, Address Agent, and Payment Agent.
This approach, which is very much in line with the two key concepts of modularity and abstraction that we covered in previous chapters, offers several advantages:
- Scalability: Multi-agent systems naturally scale by design. Since each agent encapsulates a specific function or responsibility, agents can be deployed independently across different servers, containers, or even geographic regions. If a certain agent becomes a bottleneck (e.g., a web-scraping agent during peak traffic), it can be scaled horizontally—replicated and load-balanced—without affecting the rest of the system. This distributed nature makes it easier to build AI applications that grow with user demand.
- Maintainability: Modularity promotes maintainability. Because each agent is self-contained and communicates via defined protocols or interfaces, it can be updated, refactored, or replaced without rewriting the entire system. For example, swapping a summarization agent for a more advanced model (or even a different model provider) doesn’t affect the logic of agents handling retrieval, filtering, or user interaction. This clean separation of concerns makes long-term evolution and experimentation easier and safer.
- Specialization: Each agent can be finely tuned or built using the best tools for its job. Some agents may use a code-generation LLM such as GPT-4o, while others may be based on retrieval-augmented architectures or even rule-based logic. Similarly, agents can be developed in different languages (Python, JavaScript, etc.) or frameworks as long as they comply with a shared protocol. This flexibility allows teams to optimize performance and cost, choosing the right approach for each component of the system.
Finally, to build and understand multi-agent systems, we must also turn to the world of microservices from two main perspectives: a foundational design and an infrastructure pattern that enables multi-agent intelligence to actually function.
Definition
Microservices are a software architecture pattern where applications are broken down into small, independent services, each responsible for a single function and communicating over lightweight protocols such as HTTP or messaging queues. This modular approach enables scalability, flexibility, and easier maintenance, forming the foundation for modern distributed systems—and, increasingly, for multi-agent AI systems.
From a design perspective, microservices are built on the principle of modularity—breaking down a large application into independent, specialized services that do one thing well. This is precisely how agent systems should be designed:
- Each agent has a single responsibility: browsing, scheduling, ordering, validating, or paying
- Each agent encapsulates its logic and tools just like a microservice encapsulates its APIs and database access
- Agents communicate via structured protocols (messages, events, and APIs), allowing asynchronous, flexible coordination
You can swap out an agent for a smarter one or redeploy a failing agent without disrupting the rest of the system.
In other words, multi-agent design is microservice design applied to artificial intelligence. It emphasizes decoupling, specialization, and composability—core tenets of modern software engineering.
From an infrastructure perspective, microservices provide the backbone for deploying and managing agent-based systems in the real world.
Each agent can be the following:
- Containerized (e.g., with Docker) and deployed as a standalone application that can be exposed as an API
- Hosted in a cloud-native environment (e.g., Kubernetes), scaling independently
- Connected via service meshes or message brokers, enabling secure and efficient communication
- Developed in polyglot environments (e.g., one agent can run on Python, another on JavaScript—whatever suits the task best)

Figure 7.2: Microservices backend for multi-agent systems
Figure 7.2: Microservices backend for multi-agent systems
Let’s revisit the example from Figure 7.1. A Planner Agent breaks down a task (“Buy shoes, size 39 EU”) into subtasks, handled by modular agents—Web Agent, Scheduling Agent, Order Placement Agent—each with their own downstream helpers (e.g., Payment Agent and Address Agent).
These agents could be running as the following:
- Independent microservices, each deployed in a Kubernetes cluster
- Isolated serverless functions, spun up only when needed
- Background services with persistent memory and state, orchestrated through an event-driven architecture
Without the microservices infrastructure, building, deploying, and managing such distributed agentic systems would be brittle and inefficient. It’s the combination of modular design and scalable hosting that makes a real-world multi-agent AI system possible.
At the same time, we also need to define the way we want these agents to communicate with each other, which brings us to the topic of multi-agent design workflows.
Understanding and designing different workflows for your multi-agent system
Section titled “Understanding and designing different workflows for your multi-agent system”When we transition from single-agent systems to multi-agent architectures, the way agents interact becomes crucial. Different workflows (or, in other words, communication patterns) shape how agents collaborate, share information, and make decisions. Selecting the right workflow depends on the nature of the task, the roles of each agent, and the desired outcomes.
Let’s explore five core multi-agent workflows (see Figure 7.3):

Figure 7.3: Different types of agentic workflows
Figure 7.3: Different types of agentic workflows
Here are the five core multi-agent workflows in detail:
- Network: All agents are peers in a fully connected graph, where each agent can directly communicate with any other. This allows for highly interactive, dynamic collaboration.
Let’s consider the following example. In a fast-moving start-up, a team of AI agents collaborates to conceptualize, validate, and plan a new mobile app launch. Each agent has a clear domain, but they work together in a dynamic, iterative fashion, just like a real product team:
- Agent A—Market Research Agent: This agent continuously monitors consumer trends, app store data, and competitor activity. It identifies a growing interest in AI-driven wellness apps and shares a report highlighting unmet user needs.
- Agent B—Product Designer Agent: This agent uses insights from the Market Research Agent to sketch out initial concepts for a wellness app, including user flows and feature mockups. It consults the UX style guide and adapts previous successful patterns. It then shares these with the team for feedback.
- Agent C—Regulatory Compliance Agent: As soon as new feature ideas are proposed, this agent reviews them for potential legal or privacy concerns—such as the handling of health data—and suggests modifications to keep the app compliant with GDPR and HIPAA.
- Agent D—Project Manager Agent: This agent tracks progress and dependencies between tasks. It proposes a timeline and flags risks, such as design features that may need extra compliance approval. It also nudges the team when decisions are pending or tasks are blocking others.

Figure 7.4: Network workflow
Figure 7.4: Network workflow
This setup, as shown in Figure 7.4, mimics cross-functional agile teams, thriving on continuous coordination and rapid feedback.
- Reflection: A self-evaluating loop where an agent reflects on or critiques its own outputs (or has another agent do so), allowing iterative improvement through feedback. For example, consider a university research group that wants to use a writing assistant to generate scientific paper drafts. The primary agent produces the content, while a “reviewer” agent evaluates clarity, logic, and citation accuracy. It flags weak arguments or missing references.
The first agent then revises the text accordingly and resubmits it for review. This cycle repeats until the output reaches publication quality.

Figure 7.5: Reflection workflow
Figure 7.5: Reflection workflow
Reflection workflows are powerful for quality control and tasks where refinement is as important as generation.
- Sequential: Agents are organized in a linear pipeline. Each one performs a specific task and passes its output to the next agent in the chain. For example, consider a media organization that automates the process of creating and publishing breaking news articles using a sequential chain of specialized agents:
- Agent A—News Aggregator: Monitors live feeds from news wires, social media, and press releases to identify emerging stories. It selects a breaking news event and extracts relevant facts.
- Agent B—Fact-Checker: Validates the gathered information against trusted sources such as government databases, prior news reports, and knowledge graphs. It flags any discrepancies and ensures accuracy before the story progresses.
- Agent C—Writer Agent: Takes the verified data and crafts a compelling news article, adhering to journalistic tone and publication standards.
- Agent D—SEO and Social Optimization Agent: Refines the article headline, adds meta descriptions, tags, and adjusts formatting for maximum reach on search engines and social platforms.
- Agent E—Publishing Agent: Schedules and publishes the article across web, mobile, and newsletter platforms.

- Agent A—News Aggregator: Monitors live feeds from news wires, social media, and press releases to identify emerging stories. It selects a breaking news event and extracts relevant facts.
Figure 7.6: Sequential workflow
Figure 7.6: Sequential workflow
With this workflow, you will definitely have more control over your agents, as you are giving a clear order of execution to them.
- Hierarchical:A manager agent oversees and delegates tasks to subordinate agents and aggregates their outputs. Communication typically flows top-down and bottom-up. For example, consider a SaaS company that deploys a hierarchical AI system for customer service. When a customer submits a query such as “Why was I charged twice this month?”, the Manager Agent parses the request and delegates subtasks:
- The Billing Agent checks the transaction history.
- The Technical Agent inspects system logs for double charges.
- The FAQ Agent checks whether it’s a known issue. Once each subordinate responds, the manager compiles and delivers a coherent, unified answer. This setup mirrors real-world management, promoting modularity and specialized handling.

- The Billing Agent checks the transaction history.
Figure 7.7: Hierarchical workflow
Figure 7.7: Hierarchical workflow
This pattern is particularly suitable if the order of execution is not clear in advance (differently from the sequential pattern), yet you still want to preserve a level of monitoring at the top (differently from the network pattern).
- Hybrid: Combines multiple patterns (e.g., a hierarchical backbone with reflection loops or sequential steps with embedded networks), allowing for flexible, layered collaboration.Let’s revisit the media publication pipeline, discussed in the sequential architecture, and add a hierarchical twist inside one of the steps:
- Agent A—News Aggregator: Monitors live feeds from news wires, social media, and press releases to identify emerging stories. It selects a breaking news event and extracts relevant facts.
- Agent B—Editorial Manager: Takes the identified story and acts as a sub-editor-in-chief. Rather than writing the article directly, it manages a team of agents:
- Writer Agent: Generates a first draft based on available facts - Style Agent: Ensures tone, grammar, and formatting align with the publication’s editorial guidelines - Fact-Checking Agent: Cross-verifies the claims using reliable databases and reports The Editorial Manager Agent oversees these agents, reviews their work, and compiles the final version of the article before passing it on.
- Agent C—Publishing Agent: Prepares the final article for online distribution, adds tags and SEO metadata, and publishes it to the news site and social media platforms.

- Agent A—News Aggregator: Monitors live feeds from news wires, social media, and press releases to identify emerging stories. It selects a breaking news event and extracts relevant facts.
Figure 7.8: Hybrid pattern
Figure 7.8: Hybrid pattern
This hybrid structure adds flexibility and quality control to an otherwise linear pipeline. The hierarchical substructure managed by the Editorial Manager allows for specialization and robustness without breaking the overall sequential task flow.
In previous chapters, we explored the importance of having an AI orchestrator when dealing with single AI agents, so that we can properly design the way they interact with tools. When it comes to multi-agent systems, AI orchestrators become even more important, as they will be needed for managing not only the single agent’s interaction with tools but also the interaction of multiple agents with each other.
In the next section, we are going to explore some of the most popular multi-agent orchestrators.
Overview of multi-agent orchestrators
Section titled “Overview of multi-agent orchestrators”As we’ve explored the evolution from single-agent systems to collaborative multi-agent architectures, it’s evident that coordinating multiple intelligent agents requires robust orchestration. So, the need for an AI orchestrator is more than ever.
When it comes to multi-agent applications, there are some additional orchestrators it is worth exploring for your scenarios.
AutoGen
Section titled “AutoGen”AutoGen, developed by Microsoft, is an open source framework that facilitates the creation of multi-agent systems through conversational interactions. It emphasizes the design of agents that can communicate, collaborate, and adapt to achieve complex tasks.
The framework is built with a layered, modular architecture, where each layer has a distinct responsibility and builds upon the functionality of the layers beneath it. This structure allows developers to interact with the system at different levels of complexity, from high-level abstractions ideal for rapid development to lower-level components that offer fine-grained control:
- Core API: At the foundation, the Core API manages message-passing between agents, event-driven behaviors, and offers runtime support for both local and distributed deployments. It is designed for maximum flexibility and even supports cross-language interoperability between Python and.NET environments.
- AgentChat API: Sitting on top of the Core layer, the AgentChat API provides a higher-level, opinionated interface focused on ease of use and rapid prototyping. It simplifies common patterns such as two-agent conversations and group interactions, making it familiar to users transitioning from earlier versions of the framework.
- Extensions API: The topmost layer enables continuous enhancement of the framework through official and third-party extensions. This includes integrations with popular LLM providers (such as OpenAI and Azure OpenAI) and advanced capabilities such as external code execution and tool use.
Beyond the framework itself, AutoGen also offers development tools, including a no-code GUI called AutoGen Studio and a benchmarking suite called AutoGen Bench.
AutoGen is well suited for applications such as automated customer support, collaborative content creation, and complex problem-solving scenarios where agents need to negotiate, plan, and execute tasks collectively.
TaskWeaver
Section titled “TaskWeaver”TaskWeaver is a code-first agent framework developed by Microsoft, designed for planning and executing complex data analytics workflows. The main differentiator of this framework is its code-driven execution: TaskWeaver interprets user requests into actionable code snippets and executes them, coordinating multiple functions or plugins seamlessly. Plus, unlike traditional agent systems that focus mainly on text-based conversation histories, TaskWeaver combines chat history with code execution history and in-memory data states, making it ideal for working with structured, high-dimensional data such as tables and databases.
Key features of TaskWeaver include the following:
- Complex task planning and reflective execution: TaskWeaver enables intelligent task decomposition, progress tracking, and reflective execution, allowing agents to adjust their strategy dynamically based on execution feedback.
- Rich data handling and stateful execution: The framework supports working with rich Python data structures such as DataFrames, maintains computational state across tasks, and ensures consistent user experiences by verifying generated code before execution.
- Customizable, extensible, and secure: Developers can easily extend TaskWeaver with domain-specific plugins, encapsulate custom algorithms, and safely manage multi-agent workflows with session isolation and secure code execution.
- Developer-friendly and transparent: TaskWeaver offers a simple setup experience with ready-to-use plugins, detailed logging for easy debugging, and an open, transparent architecture that helps users understand and control the entire execution process.
Given its code-driven approach and strong support for structured data, TaskWeaver is particularly well suited for data-intensive applications, analytics workflows, scientific research, financial modeling, and any environment where precision, reproducibility, and execution transparency are critical.
OpenAI Agents SDK
Section titled “OpenAI Agents SDK”The OpenAI Agents SDK is a lightweight but powerful framework designed to simplify building and orchestrating multi-agent workflows. Developed by OpenAI, it offers a modular approach to connecting agents, assigning them tools, applying guardrails, and seamlessly transferring control between them.
It’s provider-agnostic, meaning it can work with OpenAI’s APIs but is also compatible with 100+ different LLMs, making it extremely flexible for different AI backends.
Key features of Agents SDK include the following:
- Hand-offs for agent collaboration: OpenAI Agents introduces hand-offs—a clean, first-class mechanism for passing control between agents based on task context, making multi-agent collaboration intuitive and natural.
- Built-in guardrails: Safety is a core concern; you can define guardrails for input validation, output checking, and custom constraints, improving the reliability and ethical behavior of your workflows.
- Native tracing and debugging tools: The SDK includes built-in tracing support that allows you to visualize agent interactions, monitor execution paths, and easily debug multi-agent workflows, critical for transparency and optimization.
- Simple, fast API: Agents are easy to define (name, instructions, and tools) and can be composed into complex workflows with minimal boilerplate. It’s designed for rapid prototyping without sacrificing depth.
- Multi-provider support: While it integrates tightly with OpenAI’s models, it’s not locked in—you can connect to other model providers effortlessly, supporting diverse deployment needs.
Overall, the OpenAI Agent SDK empowers developers to build intelligent, multi-agent systems that can reason, delegate tasks, and interact with tools autonomously.
LangGraph
Section titled “LangGraph”LangGraph is an extension of the LangChain ecosystem, designed to orchestrate multi-agent systems through a graph-based architecture.
Definition
In mathematics, a graph is a structure made up of nodes (also called vertices) connected by edges used to model relationships or connections between pairs of objects. Graphs are fundamental in fields such as network theory, computer science, and combinatorics.
In the context of LangGraph, graphs are used to model AI workflows through the following elements:
- Nodes: In LangGraph, each node represents a specific task or operation within the workflow. Nodes can be LLM agents, tools, or custom functions, performing actions such as document retrieval, data processing, text generation, or decision-making based on inputs.
- Edges: Edges define how control and data move between nodes, dictating the sequence of execution. They can also include conditional logic, allowing the workflow to dynamically route based on the state or outputs of previous nodes.
- State: The state is a shared data structure that travels across nodes during execution. It carries the necessary context—such as messages, intermediate results, or relevant metadata—that nodes use to perform their tasks and coordinate actions.
- Conditional logic: LangGraph enables dynamic decision-making through conditional edges. These edges evaluate the current state to determine the next step, supporting branching, looping, and real-time adjustments in the workflow.
- Workflow compilation: Once defined, LangGraph compiles the nodes, edges, and conditional logic into an executable graph. This compiled workflow manages the order of execution, state transitions, and coordination between nodes, ensuring tasks are performed efficiently and reliably.
For example, in Figure 7.9, you can see a LangGraph workflow where we have a first conditional edge that decides whether the web agent is needed or not; then, based on the output, it decides whether the query has to be rewritten or it can be directly displayed to the end user as the final result.

Figure 7.9: Example of LangGraph workflow
Figure 7.9: Example of LangGraph workflow
By combining these elements, LangGraph allows developers to build modular, reusable, and dynamic workflows capable of powering complex multi-agent interactions and sophisticated decision-making with LLMs and external tools.
There is no absolute “best” orchestrator among AutoGen, TaskWeaver, the Agents SDK, or LangGraph. Each has been designed with different philosophies and strengths, and the right choice largely depends on your specific use case, your technical preferences, and the complexity of the workflows you aim to build. Some favor lightweight, rapid prototyping; others excel in orchestrating intricate, stateful interactions across multiple agents.
In the next section, we are going to leverage LangGraph for our hands-on use case, exploring how to build a multi-agent system step by step using graph-based orchestration.
Building your first multi-agent application with LangGraph
Section titled “Building your first multi-agent application with LangGraph”Time to get hands-on! In this section, we are going to build a multi-agent application leveraging LangGraph. Note that I will not include the entire code here, but rather, the relevant sections to understand the agents’ building blocks. You can find the whole code at the book’s GitHub repository here: https://github.com/PacktPublishing/AI-Agents-in-Practice.
Let’s introduce the challenge we want to solve with our multi-agent app.
Managing an investment portfolio is a complex task that requires constant attention to market trends, asset performance, and risk exposure. Many individual investors and financial advisors struggle to manually analyze vast amounts of financial data to make informed decisions. This application is designed to alleviate that challenge by using a team of intelligent agents to analyze a user’s portfolio, extract relevant market insights, and provide actionable recommendations.
The goal is to deliver a comprehensive report—automatically generated—that helps users optimize their investments for better returns or lower risk. For the purposes of this demonstration, we’ll assume the portfolio is represented as a JSON file, structured as follows:
[ { "symbol": "AAPL", "sector": "Technology", "quantity": 13, "purchase_price": 1202.57, "total_invested": 15633.41, "purchase_date": "2022-03-12" },……](1) to quickly copy code into your coding environment, or click the Explain button
(2) to get the AI assistant to explain a block of code to you.

To accomplish this task, we develop a multi-agent application with the following structure:

Figure 7.10: Hierarchical multi-agent portfolio analyzer
Figure 7.10: Hierarchical multi-agent portfolio analyzer
Let’s examine each component as illustrated in Figure 7.10:
- search_agent: Specialized in retrieving relevant websites to answer users’ questions and provided with the following tools:
- tavily_tool: A pre-built tool available in LangChain, specifically designed to retrieve search results from the Tavily API Definition Tavily is an AI-powered search API designed to enhance retrieval-augmented generation (RAG) and agent-based applications by providing real-time, high-quality web search results. It enables developers to integrate external knowledge into LLM workflows through simple, fast, and cost-effective API calls. Tavily is often used to improve the accuracy and relevance of AI-generated responses by grounding them in up-to-date web content.
Let’s initialize this agent, starting with the tools’ initialization:
# Load environment variables from .env fileload_dotenv()# Initialize the Azure OpenAI modelllm = AzureChatOpenAI( openai_api_version=openai_api_version, azure_deployment=azure_chat_deployment,)tavily_tool = TavilySearchResults(max_results=5, tavily_api_key=tavily_api_key)Now, we can create the agent and initialize it as nodes in a LangGraph graph:
search_agent = create_react_agent(llm, tools=[tavily_tool])def search_node(state: State) -> Command[Literal["supervisor"]]: result = search_agent.invoke(state) return Command( update={ "messages": [ HumanMessage( content=result["messages"][-1].content, name="search") ] },# We want our workers to ALWAYS "report back" to the supervisor when done goto="supervisor", )- read_portfolio_agent: Specialized in reading portfolios from provided paths and provided with the following tools:
- read_portfolio: Hardcoded function to read financial portfolios saved as
JSONfiles
- read_portfolio: Hardcoded function to read financial portfolios saved as
Let’s initialize the tool and agent:
@tooldef read_sample_portfolio( json_path: str = "sample_portfolio.json") -> str: """ Reads the sample_portfolio.json file and returns its content as a string. Each entry includes the stock symbol, sector, quantity, purchase price, and purchase date. """ if not os.path.exists(json_path): return f"File not found: {json_path}" with open(json_path, "r") as f: portfolio = json.load(f) if not isinstance(portfolio, list): return "Unexpected portfolio format." response = "Sample Portfolio:\n" for stock in portfolio: response += ( f"- {stock['symbol']} ({stock['sector']}): " f"{stock['quantity']}shares @${stock['purchase_price']}" f"(Bought on {stock['purchase_date']})\n" ) return responseread_portfolio_agent = create_react_agent( llm, tools=[read_sample_portfolio])def read_portfolio_node( state: State) -> Command[Literal["supervisor"]]: result = read_portfolio_agent.invoke(state) return Command( update={ "messages": [ HumanMessage(content=result["messages"][-1].content, name="read_portfolio") ] }, # We want our workers to ALWAYS "report back" to the supervisor when done goto="supervisor", )- doc_writer_agent: Specialized in writing detailed reports with a structured outline and provided with the following tools:
- write_document: Hardcoded function to write the agent’s outcome in a predefined directory
Let’s initialize the tool and agent:
from pathlib import Pathfrom tempfile import TemporaryDirectoryfrom typing import Dict, Optionalfrom typing_extensions import TypedDict# Define a real directory pathREAL_DIRECTORY = Path(r"your_path")#_TEMP_DIRECTORY = TemporaryDirectory()WORKING_DIRECTORY = Path(REAL_DIRECTORY)@tooldef write_document( content: Annotated[ str, "Text content to be written into the document."], file_name: Annotated[str, "File path to save the document."],) -> Annotated[str, "Path of the saved document file."]: """Create and save a text document.""" with (WORKING_DIRECTORY / file_name).open("w") as file: file.write(content) return f"Document saved to {file_name}"report_prompt = """You are an expert report generator. Given the input from other agents, you generate a detailed report on how to optimize the provided portfolio.The report will have the following outline:-------------------------------**Introduction on market landscape****Portfolio Overview****Investment Strategy****Performance Analysis****Recommendations****Conclusion****References**--------------------------------Once the report is generated, save it using your write_document tool."""doc_writer_agent = create_react_agent( llm, tools=[write_document], prompt=report_prompt,)def doc_writing_node(state: State) -> Command[Literal["supervisor"]]: result = doc_writer_agent.invoke(state) return Command( update={ "messages": [ HumanMessage(content=result["messages"][-1].content, name="doc_writer") ] }, # We want our workers to ALWAYS "report back" to the supervisor when done goto="supervisor", )Now that we’ve initialized all three agents, it’s time to add another level of abstraction at a higher hierarchy. To do so, we will create a team supervisor role that will call the teams depending on the user’s query:
class State(MessagesState): next: strdef make_supervisor_node(llm: BaseChatModel, members: list[str]) -> str: options = ["FINISH"] + members system_prompt = ( "You are a supervisor tasked with managing a conversation between the" f" following workers: {members}. Given the following user request," " respond with the worker to act next. Each worker will perform a" " task and respond with their results and status. When finished," " respond with FINISH." ) class Router(TypedDict): """Worker to route to next. If no workers needed, route to FINISH.""" next: Literal[*options] def supervisor_node(state: State) -> Command[ Literal[*members, "__end__"] ]: """An LLM-based router.""" messages = [ {"role": "system", "content": system_prompt}, ] + state["messages"] response = llm.with_structured_output(Router).invoke(messages) goto = response["next"] if goto == "FINISH": goto = END return Command(goto=goto, update={"next": goto}) return supervisor_nodesupervisor_node = make_supervisor_node(llm, ["search","read_portfolio", "doc_writer"])Now, we can compile the graph:
# Define the graph.builder = StateGraph(State)builder.add_node("supervisor", supervisor_node)builder.add_node("read_portfolio", read_portfolio_node)builder.add_node("search", search_node)builder.add_node("doc_writer", doc_writing_node)builder.add_edge(START, "supervisor")super_graph = builder.compile()Let’s test it:
for s in super_graph.stream( { "messages": [ ("user", "Generate a well structured report on how to improve my portfolio given the market landscape in Q4 2025.") ], }, {"recursion_limit": 150},): print(s) print("---")Here is the truncated output:
{'supervisor': {'next': 'search'}}---{'search': {'messages': [HumanMessage(content='**Portfolio Improvement Report Based on Market Landscape Q4 2025**\n\n---\n\n### 1. **Market Landscape Highlights for Q4 2025:**\nThe market trends observed for Q4 2025 suggest:\n- **Elevated Interest Rates:** Policy rates in developed markets, particularly in the US, are expected to remain high. This "higher-for-longer" rate narrative creates opportunities for varied asset positioning.\n- **Equity Market Dispersion:[...]]}}---{'supervisor': {'next': 'read_portfolio'}}---{'read_portfolio': {'messages': [HumanMessage(content='### Portfolio Improvement Report: Alignment with Market Landscape Q4 2025 \n\n---\n\n#### Portfolio Overview\nYour existing portfolio demonstrates strong exposure to technology (AAPL, GOOGL, MSFT, NVDA), consumer discretionary (AMZN, TSLA, BABA), and financials (V, JPM). [...]]}}---{'supervisor': {'next': 'doc_writer'}}---{'doc_writer': {'messages': [HumanMessage(content='The report on optimizing your portfolio for Q4 2025 has been successfully generated and saved. You can find it in the file named **Portfolio_Optimization_Q4_2025.txt**. Let me know if you need further assistance or any modifications!', additional_kwargs={}, response_metadata={}, name='doc_writer', id='8fa9e6a9-fafc-466c-8bbc-19514654c3be')]}}---{'supervisor': {'next': '__end__'}}You will find your file under the specified folder (in my case, outputs).

Figure 7.11: Example of the.txt file created in my local folder
Figure 7.11: Example of the.txt file created in my local folder
Here is the output:

Figure 7.12: Example of the final report generated by the agents
Figure 7.12: Example of the final report generated by the agents
As you can see, the output adheres to the outline we specified as a system message in the report generator agent.
Summary
Section titled “Summary”In this chapter, we moved beyond the world of single, tool-augmented agents and explored the exciting landscape of multi-agent systems. We saw how agents can collaborate much like human teams, each specializing in their own tasks yet working together to solve problems that would be too complex for any one agent alone.
We also established that designing multi-agent systems is as much an architectural challenge as it is an AI challenge, requiring careful thought around modularity, communication, coordination, and reliability. Drawing parallels with microservices architecture, we recognized that agents can (and should) be modular, independent, and orchestrated intelligently to form scalable, resilient systems.
We introduced multi-agent orchestrators such as AutoGen, TaskWeaver, and LangGraph, and, with the latter, experimented with a hands-on demonstration building our first multi-agent application.
This chapter also concludes Part 2 of the book. In the next chapter, we will shift gears and explore a critical topic—building responsible AI systems. As we create increasingly autonomous agents and multi-agent ecosystems, it becomes essential to design for safety, transparency, security, and ethical alignment.
References
Section titled “References”- LangGraph: https://www.langchain.com/langgraph
- Multi-agent systems with LangGraph: https://langchain-ai.github.io/langgraph/concepts/multi_agent/
- LangGraph Agentic concepts: https://langchain-ai.github.io/langgraph/concepts/agentic_concepts/
- OpenAI Agents SDK: https://github.com/openai/openai-agents-python
- AutoGen: https://github.com/microsoft/autogen
- TaskWeaver: https://github.com/microsoft/TaskWeaver