AI Agents and Multi-Agent Systems: Building Intelligent Workflows
Alvin
Approx. read time: 7 mins
In today’s rapidly evolving artificial intelligence landscape, AI agents have become powerful tools for automating complex tasks and decision-making processes. This blog explores the fascinating world of AI agents, particularly focusing on multi-agent systems and how they can be implemented using Python and LangGraph.
What is an AI Agent?
An AI agent is a software entity that can perceive its environment, make decisions, and take actions to achieve specific goals. Unlike traditional software that follows predetermined rules, AI agents can adapt their behavior based on their experiences and the changing environment.
Key characteristics of AI agents include:
Autonomy: They can operate without direct human intervention
Reactivity: They respond to changes in their environment
Proactivity: They can take the initiative to achieve their goals
Social ability: They can interact with other agents or humans
AI agents typically follow a perception-action cycle:
Perceive the environment
Process information using their knowledge and reasoning capabilities
Plan and decide on appropriate actions
Execute those actions
Learn from the outcomes
Why Multi-Agent Systems Matter
While a single AI agent can be powerful, multiple agents working together can handle more complex scenarios through:
Division of labor: Different agents can specialize in different tasks
Parallel processing: Multiple agents can work simultaneously
Redundancy: If one agent fails, others can continue
Diverse perspectives: Different agents can approach problems differently
Let’s explore how to build a multi-agent system using Python and LangGraph, with a practical example from the financial domain.
Building a Financial Advisory Multi-Agent System
For our example, we’ll create a simplified financial advisory system with multiple specialized agents:
Market Analyzer: Analyzes market trends
Risk Assessor: Evaluates investment risks
Client Communicator: Translates technical findings into client-friendly language
Each agent will have specific responsibilities yet work together to provide comprehensive financial advice.
import os from typing import Dict, List, Any from enum import Enum
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage from langchain_openai import ChatOpenAI from langgraph.graph import StateGraph, END
Defining a Simple Tool
We’ll start with a simple tool that our agents can use:
from langchain_core.tools import tool
@tool def get_stock_price(ticker: str) -> str: """ Get the current price of a stock (simulated data).
Args: ticker: The stock ticker symbol to look up.
Returns: The current stock price. """ # In a real implementation, this would call an API stocks = { "AAPL": 178.72, "MSFT": 413.64, "GOOGL": 177.48, "AMZN": 185.07, "TSLA": 177.58 }
if ticker in stocks: return f"{ticker} is currently trading at ${stocks[ticker]}" else: return f"No data available for {ticker}."
Defining the Agent State
Let’s define a simple structure for our multi-agent system’s state:
class AgentState(dict): """State for our multi-agent system.""" messages: List[BaseMessage] next_agent: str
class AgentType(str, Enum): """Types of agents in our system.""" MARKET_ANALYZER = "market_analyzer" RISK_ASSESSOR = "risk_assessor" CLIENT_COMMUNICATOR = "client_communicator"
Creating the Market Analyzer Agent
Our first agent will analyze market data:
def create_market_analyzer(): """Create the market analyzer agent.""" system_prompt = """You are a Market Analyzer agent in a financial advisory system.
Your job is to analyze stocks and provide insights based on their current prices. Focus on facts and clear analysis.
After your analysis, the Risk Assessor agent will evaluate the investment risks. """
# Generate response using the LLM with tools response = llm_with_tools.invoke(messages)
# Return updated state, passing to risk assessor next return { "messages": messages + [response], "next_agent": AgentType.RISK_ASSESSOR }
return agent_function
Creating the Risk Assessor Agent
Our second agent will assess investment risks:
def create_risk_assessor(): """Create the risk assessor agent.""" system_prompt = """You are a Risk Assessor agent in a financial advisory system.
Your job is to evaluate the risk of investments based on the Market Analyzer's insights. Assign a risk level (Low, Medium, High) to each investment option.
After your assessment, the Client Communicator will translate the findings for the client. """
# Return updated state, passing to client communicator next return { "messages": messages + [response], "next_agent": AgentType.CLIENT_COMMUNICATOR }
return agent_function
Creating the Client Communicator Agent
Our final agent will communicate with the client:
def create_client_communicator(): """Create the client communicator agent.""" system_prompt = """You are a Client Communicator agent in a financial advisory system.
Your job is to translate technical financial information into clear, client-friendly language. Explain the market analysis and risk assessment in terms the client can understand. Provide a concise, actionable summary of the investment advice.
You can implement dynamic routing based on message content:
def determine_next_agent(message_content): """Determine which agent should act next based on the content.""" if "risk" in message_content.lower(): return AgentType.RISK_ASSESSOR elif "explanation" in message_content.lower(): return AgentType.CLIENT_COMMUNICATOR else: return AgentType.MARKET_ANALYZER
# Then use this in your agent functions def dynamic_routing_agent(state): # ... process input ...
# Determine next agent dynamically next_agent = determine_next_agent(response.content)
Multi-agent systems have numerous applications in finance:
Investment Advisory: Specialized agents for different asset classes
Fraud Detection: Multiple agents monitor different aspects of transactions
Customer Service: Routing questions to specialized financial experts
Risk Management: Different agents monitor various risk factors
Conclusion
AI agents and multi-agent systems represent a significant advancement in how we can leverage artificial intelligence to solve complex problems. By breaking down tasks into specialized domains and allowing agents to collaborate, we can create more robust and flexible AI systems.
Our financial advisory example demonstrates how different specialized agents can work together to provide comprehensive advice that no single agent could deliver alone. Each agent contributes its unique expertise while being part of a coherent workflow.
As you build your own multi-agent systems, remember to:
Define clear responsibilities for each agent
Design efficient communication between agents
Implement appropriate routing to ensure the right agent handles each task
Test the system thoroughly with various inputs
Whether you’re looking to optimize business processes, enhance decision-making, or create more engaging user experiences, multi-agent systems provide a robust framework for building the next generation of intelligent applications.