• unwind ai
  • Posts
  • Build a Multi-agent AI News Assistant with OpenAI Swarm and Llama 3.2

Build a Multi-agent AI News Assistant with OpenAI Swarm and Llama 3.2

Multi-agent app with Llama 3.2 running locally on your computer (100% free) (step-by-step instructions)

We’re always looking for ways to automate complex workflows. Building tools that can search, synthesize, and summarize information is a key part of this, especially when dealing with ever-changing data like news.

For this tutorial, we’ll create a multi-agent AI news assistant using OpenAI’s Swarm framework along with Llama 3.2. You’ll be able to run everything locally, using multiple agents to break down the task into manageable, specialized roles—all without cost.

We will use Swarm to manage the interactions between agents, DuckDuckGo for real-time news search, and Llama 3.2 for processing and summarizing news. Each agent will handle a specific part of the workflow, resulting in a modular and flexible app that’s easy to adapt or expand.

What is OpenAI’s Swarm framework?

Swarm is a lightweight framework designed to coordinate multiple agents easily. It uses two main concepts: Agents and handoffs. Each Agent follows specific instructions and can pass control to another agent as needed, enabling you to build workflows that are scalable and customizable without complex setups.

🎁 $50 worth AI Bonus Content at the end!

What We’re Building

This Streamlit application implements a sophisticated news processing pipeline using multiple specialized AI agents to search, synthesize, and summarize news articles. It uses the Llama 3.2 model via Ollama and DuckDuckGo search to provide comprehensive news analysis.

Features

  • Multi-agent architecture with specialized roles:

    • News Searcher: Finds recent news articles

    • News Synthesizer: Analyzes and combines information

    • News Summarizer: Creates concise, professional summaries

  • Real-time news search using DuckDuckGo

  • AP/Reuters-style summary generation

  • User-friendly Streamlit interface

Prerequisites

Before we begin, make sure you have:

  1. Python installed on your machine (version 3.7 or higher is recommended)

  2. Ollama downloaded and installed. Follow the installation instructions provided on the website. Once installed, you can verify Ollama by running ollama --version

  3. Basic familiarity with Python programming

  4. A code editor of your choice (we recommend VS Code or PyCharm for their excellent Python support)

Step-by-Step Instructions

Setting Up the Environment

First, let's get our development environment ready:

  1. Clone the GitHub repository:

git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
cd local_news_agent_openai_swarm
pip install -r requirements.txt
  1. Pull and Run Llama 3.2 using Ollama:

# Pull the model
ollama pull llama3.2

# Verify installation
ollama list

# Run the model (optional test)
ollama run llama3.2
  1. Create a .env file with your configurations:

OPENAI_BASE_URL=http://localhost:11434/v1
OPENAI_API_KEY=fake-key 

How to confirm Ollama’s URL: After installing Ollama, you can check that it’s using this URL by starting the Ollama service. Simply run ollama serve in your Terminal. This command will start the API server on http://localhost:11434 by default. If you see any other port or URL, you may need to adjust OPENAI_BASE_URL in your .env file accordingly.

Code Walkthrough

Let’s create our app. Create a new file news_agent.py and add the following code:

  1. Import necessary libraries:
    • Load environment variables

    • Initialize Swarm client

    • Set up Llama 3.2 model using Ollama (Pull or Run Llama 3.2 using Ollama)

import streamlit as st
from duckduckgo_search import DDGS
from swarm import Swarm, Agent
from datetime import datetime
from dotenv import load_dotenv

load_dotenv()
MODEL = "llama3.2:latest"
client = Swarm()
  1. Set up the Streamlit App:

    Streamlit lets you create the user interface with just Python code, for this app we will add a title to the page and the app.

st.set_page_config(page_title="AI News Processor", page_icon="📰")
st.title("📰 News Inshorts Agent")
  1. Create News Search function:

    • Uses DuckDuckGo search API

    • Gets current month's news

    • Returns structured results

def search_news(topic):
    """Search for news articles using DuckDuckGo"""
    with DDGS() as ddg:
        results = ddg.text(f"{topic} news {datetime.now().strftime('%Y-%m')}", max_results=3)
        if results:
            news_results = "\n\n".join([
                f"Title: {result['title']}\nURL: {result['href']}\nSummary: {result['body']}" 
                for result in results
            ])
            return news_results
        return f"No news found for {topic}."
  1. Create News Search Agent:

    • Specialized for news searches

    • Focuses on reputable sources

    • Returns formatted results

search_agent = Agent(
    name="News Searcher",
    instructions="""
    You are a news search specialist. Your task is to:
    1. Search for the most relevant and recent news on the given topic
    2. Ensure the results are from reputable sources
    3. Return the raw search results in a structured format
    """,
    functions=[search_news],
    model=MODEL
)
  1. Create News Synthesis Agent:

    • Analyzes multiple sources

    • Identifies key themes

    • Creates coherent narrative

synthesis_agent = Agent(
    name="News Synthesizer",
    instructions="""
    You are a news synthesis expert. Your task is to:
    1. Analyze the raw news articles provided
    2. Identify the key themes and important information
    3. Combine information from multiple sources
    4. Create a comprehensive but concise synthesis
    5. Focus on facts and maintain journalistic objectivity
    6. Write in a clear, professional style
    Provide a 2-3 paragraph synthesis of the main points.
    """,
    model=MODEL
)
  1. Create News Summary Agent:

    • AP/Reuters style writing

    • Professional formatting

    • Concise summaries

summary_agent = Agent(
    name="News Summarizer",
    instructions="""
    You are an expert news summarizer combining AP and Reuters style clarity with digital-age brevity.

    Your task:
    1. Core Information:
       - Lead with the most newsworthy development
       - Include key stakeholders and their actions
       - Add critical numbers/data if relevant
       - Explain why this matters now
       - Mention immediate implications

    2. Style Guidelines:
       - Use strong, active verbs
       - Be specific, not general
       - Maintain journalistic objectivity
       - Make every word count
       - Explain technical terms if necessary

    Format: Create a single paragraph of 250-400 words that informs and engages.
    Pattern: [Major News] + [Key Details/Data] + [Why It Matters/What's Next]

    Focus on answering: What happened? Why is it significant? What's the impact?

    IMPORTANT: Provide ONLY the summary paragraph. Do not include any introductory phrases, 
    labels, or meta-text like "Here's a summary" or "In AP/Reuters style."
    Start directly with the news content.
    """,
    model=MODEL
)
  1. Implement news processing workflow:

    • Sequential processing

    • Progress indicators

    • Multi-stage workflow

def process_news(topic):
    """Run the news processing workflow"""
    with st.status("Processing news...", expanded=True) as status:
        # Search
        status.write("🔍 Searching for news...")
        search_response = client.run(
            agent=search_agent,
            messages=[...]
        
        # Synthesize
        status.write("🔄 Synthesizing information...")
        synthesis_response = client.run(
            agent=synthesis_agent,
            messages=[...]
        
        # Summarize
        status.write("📝 Creating summary...")
        summary_response = client.run(
            agent=summary_agent,
            messages=[...]
  1. Create Streamlit interface:

    • Clean interface

    • Primary action button

    • Clear output display

topic = st.text_input("Enter news topic:", value="artificial intelligence")
if st.button("Process News", type="primary"):
    if topic:
        try:
            raw_news, synthesized_news, final_summary = process_news(topic)
            st.header(f"📝 News Summary: {topic}")
            st.markdown(final_summary)
        except Exception as e:
            st.error(f"An error occurred: {str(e)}")
    else:
        st.error("Please enter a topic!")

Running the App

With our code in place, it's time to launch the app.

  • In your terminal, navigate to the project folder, and run the following command

streamlit run news_agent.py
  • Streamlit will provide a local URL (typically http://localhost:8501). Open this in your web browser, enter a topic, click "Process News," and view the results in seconds!

Working Application Demo

Conclusion

With this multi-agent setup, you’ve created a news assistant that finds, synthesizes, and summarizes news articles in real time within a user-friendly Streamlit interface.

For further enhancements, consider:

  • Incorporating Sentiment Analysis: Add a sentiment analysis layer to detect the tone of each news article (e.g., positive, neutral, negative).

  • Enabling Keyword Extraction: Highlight key phrases and terms in each summary to make the information more scannable and provide quick insights.

  • Integrating a User Feedback System: Allow users to rate or give feedback on the quality of summaries, helping to fine-tune the assistant.

  • Expanding Data Sources: Incorporate news from additional sources like RSS feeds or major publications, adding more variety to the content.

Keep experimenting and refining to build even smarter AI solutions!

We share hands-on tutorials like this 2-3 times a week, to help you stay ahead in the world of AI. If you're serious about levelling up your AI skills and staying ahead of the curve, subscribe now and be the first to access our latest tutorials.

Bonus worth $50 💵💰

Share this newsletter on your social channels and tag Unwind AI (X, LinkedIn, Threads, Facebook) to get AI resource pack worth $50 for FREE. Valid for limited time only!

Reply

or to participate.