Build AI Agents with RapidAPI for Real-Time Data

Build AI Agents with RapidAPI for Real-Time Data

Agent creation has change into simpler than ever however have you ever ever thought – how can we make them extra highly effective than they already are? I just lately considered one potential approach – what if that they had realtime details about particular classes like finance and films. That might be actually cool, proper? Whereas exploring this selection, I discovered RapidAPI a hub of APIs that may give entry to AI brokers to realtime info with a easy API name. I then determined to make a number of brokers that may make use of those APIs to make higher role-playing brokers.

On this article, I share all the course of for a similar, so you’ll be able to simply comply with it and replicate the outcomes to your personal use. Allow us to begin with some primary info –

What’s RapidAPI?

RapidAPI is definitely the older identify and has just lately change into Nokia API Hub after acquisition. It has a catalog of APIs the place we are able to use or publish APIs. It covers different classes from Cybersecurity, Films, Communication and extra. You’ll be able to explore more about RapidAPI here.

Learn how to Use the APIs from RapidAPI?

1. First sign-in/sign-up to RapidAPI here

2. Go to a developer authorisation page and create an authorization of sort ‘RapidAPI’ by click on on the ‘Add Authorization’ on the right-top.

Add Authorization | RapidAPI

3. Return to the house web page to find APIs and click on on any API you want. For example, I clicked on a cryptocurrency information API right here.

Check your API

4. You’d see a web page like this, additionally the API secret is already current within the check code. Simply be sure that the goal is about to ‘python’:

5. Now click on on ‘Subscribe to check’ on the right-top and choose the free-tier for now. After which click on on subscribe after clicking ‘Begin Free Plan’.

Subscribe to test

6. Now you should use the test-endpoint button on the right-top and check code might be executed and you will get the response.

test-endpoint button | AI Agents Realtime APIs

Be aware: Many of the APIs have a beneficiant free-tier and can be utilized up-to the talked about month-to-month limits.

Making Brokers built-in with RapidAPI

On this part we’ll be making brokers utilizing the ‘create_agent’ operate from langchain.brokers and the brokers might be powered by OpenAI, particularly the ‘gpt-5-mini’. Be at liberty to experiment with totally different fashions, model-providers or agent frameworks.

Prerequisite

To keep away from repetition, we’ll use the identical set of imports and initialize the APIs to make use of it for a number of brokers. And ensure to subscribe to the APIs within the hyperlinks if you wish to check together with me. Additionally I’ll be utilizing Google Colab for the demo.

Subscribe to those APIs

Configure your Google Colab Pocket book

Add your OpenAI API and RapidAPI as ‘OPENAI_API_KEY’ and ‘RAPIDAPI_KEY’ within the secrets and techniques part on the left, and don’t overlook to activate the pocket book entry.

Installations

!pip set up langchain langchain_core langchain_openai -q 

Imports

from google.colab import userdata 
import os 
import http.consumer 
import json 
from langchain_core.instruments import instrument 
from langchain_openai import ChatOpenAI 
from langchain.brokers import create_agent

API Keys

os.environ['OPENAI_API_KEY'] = userdata.get('OPENAI_API_KEY') 
RAPIDAPI_KEY = userdata.get('RAPIDAPI_KEY') 

Constructing a Information Agent

@instrument
def search_news(question: str, restrict: int = 10) -> str:
    """Seek for real-time information articles primarily based on a question. Returns newest information articles."""
    conn = http.consumer.HTTPSConnection("real-time-news-data.p.rapidapi.com")

    headers = {
        "x-rapidapi-key": RAPIDAPI_KEY,
        "x-rapidapi-host": "real-time-news-data.p.rapidapi.com",
    }

    conn.request(
        "GET",
        f"/search?question={question}&restrict={restrict}&time_published=anytime&nation=US&lang=en",
        headers=headers,
    )

    res = conn.getresponse()
    information = res.learn()
    end result = json.masses(information.decode("utf-8"))

    return json.dumps(end result, indent=2)

news_agent = create_agent(
    ChatOpenAI(temperature=0, mannequin="gpt-5-mini"),
    instruments=[search_news],
)

Be aware that we’re utilizing the API supplied by RapidAPI as a instrument and passing the instrument to the agent. The Agent will take assist from the instrument every time it feels a instrument name is critical.

# Take a look at the agent 
end result = news_agent.invoke({ 
 "messages": [{"role": "user", "content": "Search for latest news about Messi"}] 

}) 
print(end result["messages"][-1].content material)

Outcome

News Agent Review

Nice! We have now made our first agent and it’s wanting good. You’ll be able to experiment with new prompts in the event you like.

Be aware: Our agent works totally on when requested one thing utilizing just one phrase (instance: “Sports activities”,”Forest”..and many others). It’s because the instrument accepts solely a single string and never a sentence, to repair this we are able to configure our agent’s system immediate.

Inventory Agent

Let’s create a Inventory Agent that makes use of Yahoo’s API to fetch the inventory particulars utilizing a inventory ticker image of any explicit inventory.

Code

@instrument
def get_stock_history(image: str, interval: str = "1m", restrict: int = 640) -> str:
    """Get historic inventory worth information for an emblem."""
    conn = http.consumer.HTTPSConnection("yahoo-finance15.p.rapidapi.com")

    headers = {
        "x-rapidapi-key": RAPIDAPI_KEY,
        "x-rapidapi-host": "yahoo-finance15.p.rapidapi.com",
    }

    path = (
        f"/api/v2/markets/inventory/historical past?"
        f"image={image}&interval={interval}&restrict={restrict}"
    )

    conn.request("GET", path, headers=headers)
    res = conn.getresponse()
    information = res.learn()
    end result = json.masses(information.decode("utf-8"))

    return json.dumps(end result, indent=2)


stock_agent = create_agent(
    ChatOpenAI(temperature=0, mannequin="gpt-5-mini"),
    instruments=[get_stock_history],
)

# Instance name
end result = stock_agent.invoke(
    {"messages": [{"role": "user", "content": "Get the last intraday price history for AAPL"}]}
)

print(end result["messages"][-1].content material)

Outcome

Stock Agent Output

Nice, we efficiently retrieved the output for AAPL (Apple Inc.), and the knowledge is totally actual time.

Properties Agent

The purpose right here is to create an agent utilizing an API that searches properties on the market/hire, the one we’re utilizing from Zoopla searches the properties particularly within the UK.

Code

@instrument
def search_properties(
    location_value: str,
    location_identifier: str = "metropolis",
    web page: int = 1,
) -> str:
    """
    Seek for residential properties.

    Args:
        location_value: The identify of the situation
            (e.g., 'London', 'Manchester', 'E1 6AN').
        location_identifier: The class of the situation.
            - Use 'metropolis' for main cities (default).
            - Use 'postal_code' if the person offers a postcode (e.g., 'W1').
            - Use 'space' for smaller neighborhoods.
    """
    # URL encoding to stop InvalidURL errors
    safe_val = location_value.change(" ", "%20").change(",", "%2C")
    safe_id = location_identifier.change(" ", "%20")

    conn = http.consumer.HTTPSConnection("zoopla.p.rapidapi.com")

    headers = {
        "x-rapidapi-key": RAPIDAPI_KEY,
        "x-rapidapi-host": "zoopla.p.rapidapi.com",
    }

    path = (
        f"/properties/v2/record?locationValue={safe_val}"
        f"&locationIdentifier={safe_id}"
        f"&class=residential&furnishedState=Any"
        f"&sortOrder=newest_listings&web page={web page}"
    )

    conn.request("GET", path, headers=headers)
    res = conn.getresponse()
    information = res.learn()
    end result = json.masses(information.decode("utf-8"))

    return json.dumps(end result, indent=2)


property_agent = create_agent(
    ChatOpenAI(temperature=0, mannequin="gpt-5-mini"),
    instruments=[search_properties],
    system_prompt=(
        "You're a real-estate professional. When a person asks for a location, "
        "infer the 'location_identifier' your self, normally 'metropolis' or "
        "'postal_code'. Don't ask the person for technical identifiers; "
        "name the instrument instantly."
    ),
)

end result = property_agent.invoke(
    {"messages": [{"role": "user", "content": "Search for properties in London, England"}]}
)

print(end result["messages"][-1].content material)

Outcome

Property Dealer Agent

Film Recommender Agent

This agent may have entry to each IMDB’s high rated and worst rated API’s as instruments and we’ll configure the system immediate to select which instrument to make use of primarily based on the immediate.

@instrument
def get_top_rated_movies() -> str:
    """
    Fetch the record of top-rated English films on IMDb.

    Use this when the person desires a suggestion or a "good" film.
    """
    conn = http.consumer.HTTPSConnection("imdb236.p.rapidapi.com")

    headers = {
        "x-rapidapi-key": RAPIDAPI_KEY,
        "x-rapidapi-host": "imdb236.p.rapidapi.com",
    }

    conn.request("GET", "/api/imdb/top-rated-english-movies", headers=headers)
    res = conn.getresponse()

    # Decode and return uncooked JSON for the agent to course of
    return res.learn().decode("utf-8")


@instrument
def get_lowest_rated_movies() -> str:
    """
    Fetch the record of lowest-rated films on IMDb.

    Use this when the person asks for "unhealthy" films or films to keep away from.
    """
    conn = http.consumer.HTTPSConnection("imdb236.p.rapidapi.com")

    headers = {
        "x-rapidapi-key": RAPIDAPI_KEY,
        "x-rapidapi-host": "imdb236.p.rapidapi.com",
    }

    conn.request("GET", "/api/imdb/lowest-rated-movies", headers=headers)
    res = conn.getresponse()

    return res.learn().decode("utf-8")


movie_agent = create_agent(
    ChatOpenAI(temperature=0, mannequin="gpt-5-mini"),
    instruments=[get_top_rated_movies, get_lowest_rated_movies],
    system_prompt=(
        "You're an professional film critic. Your purpose is to assist customers discover films "
        "primarily based on high quality. If a person asks for one thing 'good', 'really helpful', "
        "or 'traditional', name get_top_rated_movies. If a person asks for one thing "
        "'unhealthy', 'horrible', or 'lowest rated', name get_lowest_rated_movies. "
        "Each instruments require no parameters. Summarize the leads to a pleasant "
        "approach in a single sentence."
    ),
)

# Instance utilization
end result = movie_agent.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": "I'm in the mood for a really terrible movie, what's the worst out there?",
            }
        ]
    }
)

print(end result["messages"][-1].content material)

Outcome

If you need actually terrible, IMDb’s lowest-rated picks embody Daniel der
 Zauberer (Daniel the Wizard) and Smolensk — each hovering round a 1.2
 common ranking and ideal in the event you’re after a 
“so-bad-it’s-fascinating” watch. 

Nice! We have now efficiently created an agent which may entry a number of instruments and may counsel each extremely rated or worst rated films.

Conclusion

By integrating actual time APIs with brokers, we are able to transfer past static responses and construct methods that really feel actually clever. RapidAPI makes this integration easy and scalable throughout domains. Additionally it’s vital that we decide the correct instruments and likewise tune the agent to work in concord with the instrument. For example, many APIs may give an error whereas single quotes or areas are current within the argument. Additionally RapidAPI provides MCP assist throughout its APIs, which might be explored within the ongoing efforts of constructing higher brokers.

Steadily Requested Questions

Q1. What’s an API?

A. An API permits totally different software program methods to speak by exchanging structured requests and responses over outlined endpoints.

Q2. What’s RapidAPI used for?

A. RapidAPI offers a unified platform to find, check, subscribe to, and combine 1000’s of actual time APIs.

Q3. Why combine APIs with AI brokers?

A. APIs give brokers entry to actual time information, enabling dynamic responses as a substitute of relying solely on static mannequin data.

This autumn. What makes an agent efficient when utilizing APIs?

A. An efficient agent makes use of clear prompts, nicely outlined instruments, correct enter formatting, and error A. dealing with for dependable execution.

Mounish V

Captivated with expertise and innovation, a graduate of Vellore Institute of Know-how. At the moment working as a Information Science Trainee, specializing in Information Science. Deeply inquisitive about Deep Studying and Generative AI, desirous to discover cutting-edge strategies to resolve advanced issues and create impactful options.

Login to proceed studying and luxuriate in expert-curated content material.