Building a Multi‑Agent Finance Chatbot with AG2

 


Building a Multi‑Agent Finance Chatbot with AG2

Financial conversations often touch on complex markets, risk preferences and compliance constraints. A single large‑language model may struggle to handle every nuance, so AG2 (formerly AutoGen) offers a multi‑agent architecture where each agent specializes in part of the workflow. This article demonstrates how to create a finance chatbot using AG2 and Python. We will define specialised agents, orchestrate them via a group chat and show a sample interaction. The approach is inspired by multi‑agent healthcare chatbots but adapted to investment discussions.

Why multi‑agent chatbots?

Recent tutorials explain that multi‑agent chatbots divide complex interactions into specialised roles. Each agent focuses on one task—answering questions, providing recommendations or analysing data—so the overall system can handle nuanced conversations more accurately (analyticsvidhya.com). The AG2 documentation notes that multi‑agent architectures are easier to maintain and extend; they allow developers to add or remove functionality without redesigning the entire system (docs.ag2.ai).  Multi‑agent designs also support different conversation patterns (sequential, group or nested chat) and enable tool use and code execution (docs.ag2.ai). In regulated industries such as healthcare or finance, this modularity improves accuracy and reduces risk (docs.ag2.ai).

Another advantage is practicality. Building a chatbot for stock‑market questions is complex, but packages like Chainlit and AG2 simplify the process by handling chat orchestration and tool calls (tinztwinshub.com). These frameworks allow you to run large‑language models locally or through an API and to register Python functions as tools (tinztwinshub.com). As open‑source models like Meta’s Llama 3.1 gain popularity, developers can deploy multi‑agent systems on local machines (tinztwinshub.com).

Pros and cons

AspectProsCons & Considerations
ModularityEach agent has a focused role, making the system easier to extend or modify (docs.ag2.ai).More agents increase the number of interactions to manage and may introduce coordination overhead.
SpecialisationDomain‑specific agents can outperform a monolithic model on their task (analyticsvidhya.com).Requires careful prompt design to keep agents within their remit and avoid conflicting advice.
Resource usageMulti‑agent architectures can run cheaper models for some roles while leveraging larger models only where needed (docs.ag2.ai).Running multiple models in parallel increases latency and can be costly for high‑volume workloads.
TransparencyBy exposing distinct agent responses, users can understand how conclusions are derived (e.g., one agent summarises market data, another suggests allocations).In some contexts users may prefer a single, unified answer; too much detail may confuse non‑experts.

Defining the finance chatbot agents

Our finance chatbot will engage the user to understand their goals, analyse market conditions and provide general asset‑allocation suggestions. It is not a licensed financial adviser; recommendations are for educational purposes. We adapt the roles from a mental‑health chatbot example into finance:

  1. Client Agent – Captures the user’s financial situation, risk tolerance and investment goals.

  2. Market Analysis Agent – Analyses the market based on user input. It summarises macro‑economic trends, asset‑class performance and volatility without giving personalised advice.

  3. Portfolio Recommendation Agent – Suggests a high‑level asset allocation based on the analysis and user profile. It does not trade or recommend specific securities.

The roles can be summarized as follows:

AgentPurposeKey instructions
Client AgentCollects information about the user’s financial goals, investment horizon and risk tolerance.Ask the user about their objectives, constraints and any particular interests or concerns.
Market Analysis AgentSummarises market conditions, including recent trends in equities, bonds, commodities and macro‑economic indicators.Do not provide personal investment advice; instead, report high‑level insights such as whether markets are volatile or stable.
Portfolio Recommendation AgentProvides general asset‑allocation suggestions based on the user’s profile and the market summary.Recommend broad categories (e.g., 60 % equities, 30 % bonds, 10 % alternatives); include a disclaimer that this is not financial advice.

Setting up the environment

To follow along you need Python 3.11+ and the ag2 library. You can install AG2 via pip (pip install ag2[openai]). If you plan to run local models, install an API wrapper like ollama and download a model such as Llama 3.1 (tinztwinshub.com). You will also need API keys if using cloud models. In this example we configure the LLM via llm_config without specifying an API key; supply your own key as needed.

Implementing the agents

The following Python code illustrates how to create the finance chatbot. It borrows the group‑chat structure from the mental‑health example and uses AG2’s ConversableAgent, GroupChat and GroupChatManager classes:

from autogen import ConversableAgent, GroupChat, GroupChatManager # Replace None with your OpenAI or local model API key if required llm_config = {"config_list": [{"model": "gpt-4o", "api_key": None}]} # 1. Client Agent: collects user goals and risk tolerance client_agent = ConversableAgent( name="client", system_message=( "You are the client interface.\n" "Your job is to describe your financial goals, risk tolerance, investment horizon, " "and any budget constraints or ethical considerations." ), llm_config=llm_config ) # 2. Market Analysis Agent: summarises current market conditions market_analysis_agent = ConversableAgent( name="market_analysis", system_message=( "You analyse the current market based on the client's input." "Summarise macroeconomic factors (interest rates, inflation), sector trends and recent market volatility. " "Do not provide personalised investment advice; simply report high-level observations." ), llm_config=llm_config ) # 3. Portfolio Recommendation Agent: proposes a high-level allocation portfolio_recommendation_agent = ConversableAgent( name="portfolio_recommendation", system_message=( "You suggest a general asset allocation based on the analysis from the Market Analysis Agent." "Consider the client's risk tolerance and goals." "Recommend proportions across asset classes such as equities, bonds, and alternatives." "Include a disclaimer that the suggestions are educational and not financial advice." ), llm_config=llm_config ) # Configure a group chat where the analysis and recommendation agents converse # The manager orchestrates turn-taking in round‑robin fashion finance_groupchat = GroupChat( agents=[market_analysis_agent, portfolio_recommendation_agent], messages=[], max_round=3, speaker_selection_method="round_robin" ) manager = GroupChatManager(name="manager", groupchat=finance_groupchat) # Function to start the finance chatbot def start_finance_chat(): print("\nWelcome to the AI Finance Chatbot!") user_input = input("Please describe your financial goals and risk tolerance: ") # The client agent initiates the conversation with the manager print("\nAnalysing your profile and market conditions...") response = client_agent.initiate_chat( manager, message=( f"My financial goals and risk tolerance are: {user_input}. " "Based on this, what insights and recommendations can you provide?" ) ) # Fallback in case the first response is empty if not response: response = portfolio_recommendation_agent.initiate_chat( manager, message="Based on the client's goals, please provide portfolio recommendations." ) # Run the chatbot start_finance_chat()

How it works

  1. User input – The client_agent collects the investor’s goals and risk tolerance. In a real deployment you might ask follow‑up questions to ensure clarity.

  2. Market analysis – The market_analysis_agent reviews the input and provides a concise summary of current market conditions. It does not provide personalised advice, reflecting a common compliance requirement for general market commentary.

  3. Portfolio suggestion – The portfolio_recommendation_agent uses the market summary and client profile to recommend an asset allocation. It emphasises diversification and includes a disclaimer.

  4. Group chat management – The GroupChatManager coordinates the exchange. We use a round‑robin method to ensure both agents contribute (analyticsvidhya.com). The max_round parameter prevents infinite loops.

Sample interaction

Suppose a user says: “I’m saving for retirement in 20 years, have moderate risk tolerance and want to invest ethically.” The agents might respond as follows:

Market Analysis Agent: “Based on the current environment, central banks are signalling that interest rates may remain high to curb inflation, equities have been volatile with technology and renewable‑energy sectors outperforming, and bond yields offer moderate returns. Commodities like gold have appreciated due to geopolitical tension.”

Portfolio Recommendation Agent: “Given your 20‑year horizon and moderate risk tolerance, a diversified allocation could be 60 % equities (with a tilt towards ESG‑focused funds), 30 % bonds (combining government and investment‑grade corporate bonds), and 10 % alternatives such as real‑estate investment trusts or commodities. This is general information and not personalised financial advice.”

In a real‑world application you could register functions that fetch real‑time market data or compute portfolio statistics using AG2’s register_function API (tinztwinshub.com), but our simple example relies on the language model.

Pros and cons of this approach

  • Pros:

    • Modularity and specialisation – Each agent has a clear purpose, which can improve the relevance and quality of responses (docs.ag2.ai). For example, one agent summarises macro data while another focuses on portfolio construction.

    • Ease of extension – You can add agents to handle regulatory checks, tax considerations or portfolio rebalancing without rewriting existing components (docs.ag2.ai).

    • Transparency – Users can see how the system arrives at recommendations because each agent’s contribution is visible (docs.ag2.ai).

  • Cons:

    • Coordination overhead – More agents mean more messages and potential latency. Tuning max_round and speaker selection helps avoid long conversations.

    • Prompt management – Agents must be carefully prompted to avoid stepping outside their roles. If the market‑analysis agent gives advice, it could cause compliance issues.

    • Resource usage – Running multiple models or using powerful models for each agent can be costly. Techniques like mixing cheap and expensive models or limiting context length can help (docs.ag2.ai).

Future enhancements

  • Real‑time data integration: Register functions to call APIs (e.g., yfinance, Bloomberg, or custom data feeds) so the analysis agent can deliver up‑to‑the‑minute market summaries. The Tinz Twins example shows how to plot year‑to‑date gains using a registered function (tinztwinshub.com).

  • Regulatory compliance: Add an agent that checks whether recommendations adhere to regional regulations (e.g., MIFID II or SEC guidelines). It could flag issues before suggestions reach the user.

  • Advanced conversation patterns: Use nested or constrained group chats to handle multi‑step workflows, such as gathering risk questionnaires, performing Monte‑Carlo simulations and then generating a report. AG2 supports these patterns (docs.ag2.ai).

  • Multi‑modal output: Integrate charting tools to visualise asset allocations or risk/return trade‑offs. For instance, register a function that plots allocation pie charts and returns an image.

Conclusion

AG2’s multi‑agent architecture makes it straightforward to build tailored chatbots for complex domains such as finance. By dividing the conversation into specialised roles, developers can achieve greater accuracy, transparency and extensibility compared with monolithic chatbots (analyticsvidhya.com). The simple example above illustrates how you can adapt a mental‑health chatbot pattern to a personal‑finance advisor. Although multi‑agent systems introduce coordination challenges and resource overhead, careful design and modern frameworks like AG2 or Chainlit can mitigate these issues (docs.ag2.ai). As open‑source models and tooling evolve, we can expect multi‑agent finance chatbots to become more capable—potentially integrating real‑time data, compliance checks and sophisticated analytics.

Comments

Popular Posts