1. Learning Objectives
By the end of this lesson, you will be able to:
-
Understand the principles of multi-agent systems (MAS) and the benefits of agent collaboration in finance.
-
Design and implement multi-agent systems using orchestration frameworks (AutoGen, CrewAI, LangGraph).
-
Apply multi-agent collaboration patterns: debate, consensus, voting, and hierarchical delegation.
-
Implement agent communication protocols and shared memory systems.
-
Build a multi-agent investment committee with specialized roles (bull, bear, neutral, risk, decision).
-
Evaluate multi-agent system performance and robustness.
2. Foundations of Multi-Agent Systems
2.1 Why Multi-Agent Systems in Finance?
| Benefit | Description | Example |
|---|---|---|
| Specialization | Each agent can have a specific role and expertise. | Bull agent vs. Bear agent. |
| Parallelization | Agents can work concurrently, reducing latency. | Data collection + Sentiment analysis + Technical analysis in parallel. |
| Robustness | If one agent fails, others can compensate. | If the data agent fails, the research agent may have cached data. |
| Transparency | The division of labor makes the system more explainable. | Each agent documents its reasoning. |
| Consensus | Multiple agents can vote to reduce bias. | Investment committee vote. |
2.2 Multi-Agent System Architecture
┌─────────────────────────────────────────────────────────────────────────────┐ │ MULTI-AGENT SYSTEM │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ ORCHESTRATOR │ │ │ │ (Manages agents, coordinates tasks, aggregates results) │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ │ ▼ ▼ ▼ │ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ │ │ DATA AGENT │ │ RESEARCH AGENT │ │ SENTIMENT AGENT│ │ │ │ (Collects data)│ │ (Analyzes data)│ │ (News/ Social) │ │ │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ │ │ │ │ │ │ ▼ ▼ ▼ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ SHARED MEMORY │ │ │ │ (Vector database, knowledge graph, message bus) │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ EXECUTION AGENT │ │ │ │ (Executes trades, generates reports) │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────┘
3. Multi-Agent Frameworks
3.1 AutoGen
AutoGen (Microsoft) is a framework for multi-agent conversations. It supports:
-
Agent roles: AssistantAgent, UserProxyAgent, and custom agents.
-
Conversation patterns: GroupChat, Sequential, and custom.
-
Tool integration: Agents can call tools and execute code.
-
Human-in-the-loop: Humans can approve actions.
Key concepts:
-
AssistantAgent: An LLM-based agent that can reason and respond. -
UserProxyAgent: Executes code and interacts with the environment. -
GroupChat: Manages a conversation among multiple agents. -
GroupChatManager: Orchestrates the group chat.
Example: Multi-agent investment research
from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager # Define agents research_agent = AssistantAgent( name="ResearchAgent", system_message="You are a financial research analyst. Provide insights on companies." ) sentiment_agent = AssistantAgent( name="SentimentAgent", system_message="You are a sentiment analyst. Analyze market sentiment." ) technical_agent = AssistantAgent( name="TechnicalAgent", system_message="You are a technical analyst. Analyze technical indicators." ) portfolio_agent = AssistantAgent( name="PortfolioAgent", system_message="You are a portfolio manager. Make allocation decisions." ) # Define group chat group_chat = GroupChat( agents=[research_agent, sentiment_agent, technical_agent, portfolio_agent], messages=[], max_round=20, speaker_selection_method="round_robin" ) manager = GroupChatManager(groupchat=group_chat) # Start the conversation user_proxy = UserProxyAgent(name="UserProxy", human_input_mode="NEVER") user_proxy.initiate_chat( manager, message="Analyze the tech sector and suggest a portfolio allocation." )
3.2 CrewAI
CrewAI is a role-playing framework for agents. It is designed for task decomposition and delegation.
Key concepts:
-
Agent: A role with a goal and backstory. -
Task: A specific task to be completed. -
Crew: A group of agents that work together on tasks.
Example:
from crewai import Agent, Task, Crew research_agent = Agent( role="Research Analyst", goal="Conduct thorough research on companies", backstory="You are a highly experienced financial analyst." ) sentiment_agent = Agent( role="Sentiment Analyst", goal="Analyze market sentiment from news and social media", backstory="You are an expert in NLP and sentiment analysis." ) task1 = Task( description="Research Company X and provide a summary.", agent=research_agent ) task2 = Task( description="Analyze sentiment around Company X.", agent=sentiment_agent ) crew = Crew( agents=[research_agent, sentiment_agent], tasks=[task1, task2] ) result = crew.kickoff()
3.3 LangGraph
LangGraph is a graph-based framework for agent workflows. It supports:
-
Stateful workflows: Agents can maintain state across steps.
-
Cyclic workflows: Agents can loop (e.g., for reflection).
-
Conditional branching: The workflow can branch based on conditions.
Key concepts:
-
State: The shared state across agents. -
Node: An agent or a function. -
Edge: Defines the transition between nodes.
Example:
from langgraph.graph import StateGraph # Define state class AgentState: def __init__(self): self.messages = [] self.data = {} # Define agent functions def research_agent(state): # Analyze and update state state.messages.append("Research conducted.") return state def decision_agent(state): # Decide based on state if state.data.get("risk") < 0.5: state.messages.append("Decision: Buy") else: state.messages.append("Decision: Hold") return state # Build graph graph = StateGraph(AgentState) graph.add_node("research", research_agent) graph.add_node("decision", decision_agent) graph.set_entry_point("research") graph.add_edge("research", "decision") graph.add_edge("decision", END)
4. Multi-Agent Collaboration Patterns
4.1 Sequential Collaboration
Agents work in a sequence, each building on the previous agent’s output.
Data Agent → Research Agent → Portfolio Agent → Execution Agent
Example:
-
Data Agent collects market data.
-
Research Agent analyzes the data.
-
Portfolio Agent determines the allocation.
-
Execution Agent executes the trades.
4.2 Parallel Collaboration
Agents work concurrently and their results are aggregated.
┌─────────────────┐
│ Data Agent │
└────────┬────────┘
│
┌────────┼────────┐
│ │ │
▼ ▼ ▼
┌─────────┐┌─────────┐┌─────────┐
│Research ││Sentiment││Technical│
│ Agent ││ Agent ││ Agent │
└─────────┘└─────────┘└─────────┘
│ │ │
└────────┼────────┘
▼
┌─────────────────┐
│ Aggregator │
└─────────────────┘
Example:
-
Data Agent collects data and broadcasts it.
-
Research Agent, Sentiment Agent, and Technical Agent analyze in parallel.
-
Aggregator combines their outputs.
4.3 Debate and Consensus
Agents with different perspectives debate and reach a consensus.
┌─────────────────────────────────────┐
│ MODERATOR │
└─────────────────────────────────────┘
│
┌────────┼────────┐
│ │ │
▼ ▼ ▼
┌─────────┐┌─────────┐┌─────────┐
│ Bull ││ Bear ││ Neutral │
│ Agent ││ Agent ││ Agent │
└─────────┘└─────────┘└─────────┘
│ │ │
└────────┼────────┘
▼
┌─────────────────┐
│ Decision Agent │
└─────────────────┘
Debate pattern:
-
Bull Agent presents the bullish case.
-
Bear Agent presents the bearish case.
-
Neutral Agent evaluates both arguments.
-
Decision Agent makes the final decision (by vote or by synthesis).
4.4 Hierarchical Delegation
A manager agent delegates tasks to specialist agents.
┌─────────────────────────────────────┐
│ MANAGER AGENT │
└─────────────────────────────────────┘
│
┌────────┼────────┐
│ │ │
▼ ▼ ▼
┌─────────┐┌─────────┐┌─────────┐
│Sub-agent││Sub-agent││Sub-agent│
│ 1 ││ 2 ││ 3 │
└─────────┘└─────────┘└─────────┘
Example:
-
Manager Agent: “We need to rebalance the portfolio.”
-
Manager delegates:
-
Sub-agent 1: Collect data.
-
Sub-agent 2: Analyze.
-
Sub-agent 3: Execute.
-
-
Manager synthesizes results and makes the final decision.
4.5 Voting Patterns
| Voting Method | Description | Example |
|---|---|---|
| Simple majority | Each agent votes, majority wins. | 3 agents vote Buy, 2 vote Sell → Buy. |
| Unanimous | All agents must agree. | All 5 agents must agree on Buy. |
| Weighted voting | Agents have different voting weights. | Portfolio Manager has 3 votes, others have 1. |
| Consensus | Agents reach consensus through discussion. | Agents debate until they agree. |
5. Agent Communication and Shared Memory
5.1 Communication Protocols
| Protocol | Description | Use Case |
|---|---|---|
| Direct message | One agent sends a message to another. | Immediate task delegation. |
| Broadcast | One agent sends a message to all agents. | Data update. |
| Publish-Subscribe | Agents subscribe to topics. | News feed. |
| Shared memory | Agents read/write to shared memory. | Database, vector store, knowledge graph. |
5.2 Shared Memory Design
Shared memory is a central repository that agents can read from and write to.
Types of shared memory:
-
Vector database: For storing embeddings of documents, memories, and observations.
-
Knowledge graph: For storing structured relationships (see Lesson 6.7).
-
Message queue: For asynchronous communication.
-
Key-value store: For simple data storage (e.g., Redis).
Example: Shared memory for an investment committee
| Entity | Attributes |
|---|---|
| Company | ticker, name, sector, market cap, financials, price |
| News | date, headline, content, sentiment |
| Analysis | analyst, date, recommendation, target price |
| Position | ticker, quantity, entry price, current price |
5.3 Message Bus Architecture
A message bus (e.g., Redis Pub/Sub, RabbitMQ) enables asynchronous communication between agents.
┌────────────┐ ┌────────────┐ ┌────────────┐
│ Data │───▶│ Message │───▶│ Research │
│ Agent │ │ Bus │ │ Agent │
└────────────┘ └────────────┘ └────────────┘
│
▼
┌────────────┐
│ Portfolio │
│ Agent │
└────────────┘
6. Multi-Agent Investment Committee
6.1 Committee Composition
| Agent | Role | Prompt |
|---|---|---|
| Bull | Optimistic, growth-focused | “You are optimistic about the market. Focus on growth opportunities.” |
| Bear | Pessimistic, risk-focused | “You are cautious. Focus on risks and downside protection.” |
| Value | Value-focused | “You are a value investor. Focus on fundamentals and intrinsic value.” |
| Technical | Technical analysis | “You focus on technical indicators and market trends.” |
| Risk | Risk management | “You ensure that all decisions are within risk limits.” |
| Moderator | Facilitates discussion | “You moderate the discussion and ensure all voices are heard.” |
| Decision | Makes final decision | “You synthesize all arguments and make the final decision.” |
6.2 Committee Workflow
1. Data Agent: Collects market data, news, and financials. 2. Bull Agent: Presents the bullish case. 3. Bear Agent: Presents the bearish case. 4. Value Agent: Presents the value case. 5. Technical Agent: Presents the technical analysis. 6. Risk Agent: Evaluates the risk of each case. 7. Moderator: Summarizes the discussion. 8. Decision Agent: Makes the final decision.
6.3 Committee Prompt Example
Bull Agent prompt:
You are an optimistic investment analyst. Your role is to present the bullish case for the proposed investment. Key points to highlight: 1. Growth potential 2. Competitive advantages 3. Positive catalysts 4. Favorable market trends Be persuasive but evidence-based.
Bear Agent prompt:
You are a cautious investment analyst. Your role is to present the bearish case for the proposed investment. Key points to highlight: 1. Risks and challenges 2. Competitive threats 3. Negative catalysts 4. Unfavorable market trends Be thorough but fair.
Decision Agent prompt:
You are the decision-maker for the investment committee. Based on the arguments presented: 1. What is your decision? (Buy/Hold/Sell) 2. What is the conviction level? (High/Medium/Low) 3. What are the key reasons for your decision? 4. What is the recommended position size? Synthesize all the arguments and make a reasoned decision.
7. Evaluation of Multi-Agent Systems
7.1 Metrics
| Metric | Description |
|---|---|
| Task completion rate | Percentage of tasks completed successfully. |
| Decision accuracy | Accuracy compared to a baseline (e.g., human experts). |
| Consensus time | Time to reach consensus. |
| Diversity of perspectives | Are agents offering distinct viewpoints? |
| Robustness | System performance when one agent fails. |
| Explainability | Can the system explain its decisions? |
7.2 Testing Multi-Agent Systems
| Test Type | Description |
|---|---|
| Unit testing | Test each agent individually. |
| Integration testing | Test the interaction between agents. |
| Scenario testing | Test the system on specific scenarios (e.g., market crash, earnings surprise). |
| Adversarial testing | Test with adversarial inputs (e.g., false news, biased data). |
| Stress testing | Test with high workload and system failures. |
7.3 Continuous Improvement
-
Feedback loop: Collect human feedback and use it to improve agent prompts and tools.
-
Model updates: Regularly update the LLMs used by agents.
-
Data refresh: Continuously update the data and knowledge base.
-
Performance monitoring: Track metrics over time and trigger retraining or reconfiguration if performance degrades.
8. Challenges and Mitigations
| Challenge | Mitigation |
|---|---|
| Communication overhead | Efficient message design, publish-subscribe patterns. |
| Agent conflicts | Clear roles, moderator, and decision protocols. |
| Scale | Hierarchical organization, parallelization. |
| Security | Authentication, encryption, audit trails. |
| Cost | Smaller models, caching, efficient prompting. |
| Bias | Diverse agent perspectives, bias detection, fairness constraints. |
9. Summary for the AI Practitioner
-
Multi-agent systems enable specialization, parallelization, and robust decision-making in finance.
-
Frameworks like AutoGen, CrewAI, and LangGraph provide building blocks for multi-agent orchestration.
-
Collaboration patterns include sequential, parallel, debate, and hierarchical delegation.
-
Shared memory and message buses enable agent communication.
-
A multi-agent investment committee with specialized roles (bull, bear, risk, etc.) can provide more balanced and robust decisions.
-
Evaluation must include task completion, decision accuracy, and robustness metrics.
This completes Lessons 9.7 and 9.8, finishing Module 9. Would you like to proceed to Module 10 (AI Strategy, Ethics, Governance, and Deployment) or need any revisions?