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

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 GDELT Project's API 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 News Agent, built with Hive Agent Kit, 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 HiveNetwork.ai

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/hivenetwork-ai/example-agents/tree/main/news_agent 
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.

  • hive_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 HiveAgent.

import requests
from typing import Optional, Dict
from hive_agent import HiveAgent
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 HiveAgent

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

if __name__ == "__main__":
    my_agent = HiveAgent(
       name="news_agent",
       functions=[fetch_latest_news],
       config_path="./hive_config.toml",
       instruction="Use appropriate news sources to answer the questions.",
    )
    
    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

Access the Swagger UI at http://localhost:8000/docs to interact with the API.

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.

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

Wrap Up

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

Last updated