SwarmZero Docs
Main WebsitePricingGitHubDiscordX
  • GETTING STARTED
    • Welcome
    • Developing on SwarmZero
    • Quickstart
    • Key Concepts
      • AI
      • ML
      • LLM
      • AI Agents
      • Swarms
    • Contributing to SwarmZero
  • SDK
    • Agent Kit
    • Agent API Schema
    • Observability
      • Langtrace
      • OpenLIT
      • AgentOps
  • EXAMPLES
    • AI Agents
      • Build a Dune Agent with SwarmZero.ai
      • Build a News Agent with SwarmZero.ai using the GDELT API
      • Build a Uniswap Docs Retrieval Agent with SwarmZero.ai
      • Build an AAVE AI Agent to Lend and Borrow Crypto
      • Build & Monitor a Web Search Agent
      • Build a Multi-Chain Crypto Trading Telegram Bot with SwarmZero, Bitquery and DEXRabbit
    • Swarms
      • AI Researcher Swarm
      • Build a Web3 dApp with a Swarm of AI Agents
      • Livepeer Youtube Video Generator Swarm
    • Tools
      • Tools for Building Agents with Livepeer
      • Tools for Building Agents with Dune
      • YouTube Video Editor & Upload Tools
      • File Operations Tools
Powered by GitBook
LogoLogo

Quick Links

  • Main Website
  • Pricing
  • GitHub
  • Discord

© 2025 SwarmZero Technology Solutions Inc. All rights reserved.

On this page
  • Prerequisites
  • Step-By-Step Tutorial for Building a News Agent with SwarmZero
  • Wrap Up

Was this helpful?

  1. EXAMPLES
  2. AI Agents

Build a News Agent with SwarmZero.ai using the GDELT API

PreviousBuild a Dune Agent with SwarmZero.aiNextBuild a Uniswap Docs Retrieval Agent with SwarmZero.ai

Last updated 6 months ago

Was this helpful?

Imagine having a powerful agent that fetches the latest news, processes it, and delivers personalized responses to your queries. In this tutorial, you will learn how to create a News Agent that uses the to fetch and process news from various sources.

The GDELT Project monitors the world's news media, providing real-time translation, indexing, and analysis of global news coverage. Whether seeking the latest headlines, in-depth analyses, or specific topic updates, this agent ensures you receive accurate and timely information.

Whether you need the latest headlines, in-depth analyses, or updates on specific topics, this , built with SwarmzeroSDK, ensures you receive accurate and timely information.

Prerequisites

Before starting, ensure you have the following:

  • Python 3.11 or higher installed

  • Git installed

  • An IDE or text editor (VS Code, PyCharm, etc.)

  • Basic understanding of Python programming

  • API keys from OpenAI, Anthropic, and Mistral if you plan to use these services

Step-By-Step Tutorial for Building a News Agent with SwarmZero

Here is a detailed guide to building the News Agent:

Cloning the Repository

To begin, we need to clone the news_agent repository to our local machine.

Step 1: Open your terminal or command prompt. Ensure you have Git installed on your system.

Step 2: Run the following commands:

git clone https://github.com/swarmzero/examples/tree/main/agents/ 
cd news_agent

These commands will download the repository and navigate into its directory, setting up the base environment to start working on the agent.

Setting Up the Environment

Now that you have the repository cloned, the next step is to set up the environment to run the agent. This involves creating a virtual environment, installing dependencies, and configuring environment variables.

Step 1: Creating a Virtual Environment

python -m venv ./venv

Step 2: Activate the virtual environment

  • Command Prompt:

    venv\Scripts\activate.bat
  • PowerShell:

    venv\Scripts\Activate.ps1
  • On Unix/Mac:

    source venv/bin/activate

Installing Dependencies

With the virtual environment activated, install the required dependencies:

pip install -r requirements.txt

Setting Up Environment Variables

Step 1: Create a new file called .env in the root directory:

touch .env

Step 2: Copy the contents of .env.example into your new .env file.

Step 3: Add your API keys to the .env file:

OPENAI_API_KEY=your_openai_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key
MISTRAL_API_KEY=your_mistral_api_key

These steps will ensure your environment is properly configured to run the Dune Agent.

Understanding the Code Structure

Before running and customizing the agent, it's essential to understand the structure of the news_agent repository. This will help you navigate through the code and make necessary modifications efficiently.

Overview of Key Files and Directories

  • .env.example: This file provides an example of the environment variables required for the project. You should copy this file to create your .env file and add the necessary API keys.

  • swarmzero_config.toml: Contains configuration settings for the agent, such as API keys, query parameters, and other adjustable settings. This file is essential for configuring the agent's behavior.

  • news_agent.py: This is the main script that runs the agent. It contains the core logic for fetching and processing news data.

  • requirements.txt: Lists all the dependencies required to run the agent. These are the libraries and tools the agent relies on.

  • requirements-dev.txt: Lists the development dependencies needed for testing and development purposes. This file is useful for setting up a development environment.

In this section, you will understand the logic and process of building a News agent with SwarmZero.ai.

Step 1: Import Necessary Libraries

Start by importing all the required libraries. These include libraries for handling environment variables, making HTTP requests, and interacting with the Agent.

from datetime import datetime, timedelta
from swarmzero import Agent
from newsapi import NewsApiClient
from typing import Optional, Dict, List, Literal
import requests
from dotenv import load_dotenv

Step 2: Load Environment Variables

Load your environment variables from a .env file. This file should contain any necessary configuration, such as API keys, used by your application.

load_dotenv()

Step 3: Define the Function to Fetch the Latest News

Create a function that fetches the latest news articles based on a user query. This function will make an HTTP request to the GDELT Project API and return a summary of the latest news articles.

def fetch_latest_news(query: str) -> Optional[str]:
    """
    Fetches the latest news articles based on the user query.

    :param query: The query to search for in the news articles.
    :return: A summary of the latest news articles, or None if an error occurs or the articles cannot be found.
    """
    url = f"https://api.gdeltproject.org/api/v2/doc/doc?query={query}&mode=artlist&format=json"

    try:
        response = requests.get(url)
        response.raise_for_status()
        data = response.json()
        
        articles = data.get("articles", [])
        if articles:
            summary = "\n\n".join([f"Title: {article.get('title')}\nLink: {article.get('url')}" for article in articles[:5]])
            return summary.strip()
        else:
            return "No articles found."
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")
        return None

Step 4: Create and Run the Agent

Finally, create an instance of Agent, passing in the functions and configuration path. Then, run the agent.

if __name__ == "__main__":
    my_agent = Agent(
       name="news_agent",
       functions=[fetch_all_articles],
       config_path="./swarmzero_config.toml",
       instruction="Use appropriate tools to answer the questions related to the news.",
    )
    
    my_agent.run()

Running the Agent

With the environment set up and a basic understanding of the code structure, you are now ready to run the agent and see it in action.

Step 1: Run the API Server

Ensure your virtual environment is activated. You can test your agent by running the following command:

(venv) python news_agent.py

Step 2: Open the Swagger Docs

Step 3: Test the POST /api/v1/chat Endpoint

You can test the agent with a curl command as follows:

curl --location 'localhost:8000/api/v1/chat' \
--header 'Content-Type: application/json' \
--data '{
    "user_id": "user123",
    "session_id": "session123",
    "chat_data": {
        "messages": [
            { "role": "user", "content": "Can I get the latest news on AI?" }
        ]
    }
}'

This will send a request to the API and provide you with a response, allowing you to verify the agent’s functionality.

Output

You can also interact with the News Agent using SwarmZero’s UI, following the instructions provided in this repository.

Wrap Up

Building the News Agent ()

Access the Swagger UI at to interact with the API.

As the next steps, you can proceed with further and customization if required.

Congratulations! You've successfully set up, configured, and customized your News Agent using the from .

news_agent.py
http://localhost:8000/docs
testing
news_agent repository
SwarmZero.ai
GDELT Project's API
News Agent