Saturday, December 27, 2025

Construct AI Brokers with RapidAPI for Actual-Time Knowledge


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 lately considered one potential approach – what if they’d 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 can provide entry to AI brokers to realtime data 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 the complete course of for a similar, so you possibly can simply comply with it and replicate the outcomes to your personal use. Allow us to begin with some fundamental data –

What’s RapidAPI?

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

The way to Use the APIs from RapidAPI?

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

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

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

Check your API

4. You’ll see a web page like this, additionally the API secret’s already current within the check code. Simply be sure that the goal is ready 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 need to use the test-endpoint button on the right-top and check code will probably be executed and you will get the response.

test-endpoint button | AI Agents Realtime APIs

Observe: 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 will probably 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 device 
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

@device
def search_news(question: str, restrict: int = 10) -> str:
    """Seek for real-time information articles based mostly 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()
    consequence = json.masses(information.decode("utf-8"))

    return json.dumps(consequence, indent=2)

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

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

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

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

End result

News Agent Review

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

Observe: Our agent works totally on when requested one thing utilizing just one phrase (instance: “Sports activities”,”Forest”..and so on). It’s because the device accepts solely a single string and never a sentence, to repair this we will 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

@device
def get_stock_history(image: str, interval: str = "1m", restrict: int = 640) -> str:
    """Get historic inventory value information for a logo."""
    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()
    consequence = json.masses(information.decode("utf-8"))

    return json.dumps(consequence, indent=2)


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

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

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

End result

Stock Agent Output

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

Properties Agent

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

Code

@device
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()
    consequence = json.masses(information.decode("utf-8"))

    return json.dumps(consequence, 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, often 'metropolis' or "
        "'postal_code'. Don't ask the person for technical identifiers; "
        "name the device instantly."
    ),
)

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

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

End result

Property Dealer Agent

We obtained the actual properties as output, however they’ve been blurred due to apparent causes.

Film Recommender Agent

This agent can have entry to each IMDB’s high rated and worst rated API’s as instruments and we’ll configure the system immediate to choose which device to make use of based mostly on the immediate.

@device
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")


@device
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 aim is to assist customers discover films "
        "based mostly on high quality. If a person asks for one thing 'good', 'advisable', "
        "or 'basic', 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
consequence = movie_agent.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": "I'm in the mood for a really terrible movie, what's the worst out there?",
            }
        ]
    }
)

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

End result

If you would like actually terrible, IMDb’s lowest-rated picks embrace 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’ve efficiently created an agent which might entry a number of instruments and might counsel each extremely rated or worst rated films.

Conclusion

By integrating actual time APIs with brokers, we will transfer past static responses and construct programs that really feel actually clever. RapidAPI makes this integration easy and scalable throughout domains. Additionally it’s essential that we choose the precise instruments and in addition tune the agent to work in concord with the device. As an example, many APIs can provide an error whereas single quotes or areas are current within the argument. Additionally RapidAPI affords MCP help throughout its APIs, which might be explored within the ongoing efforts of creating higher brokers.

Regularly Requested Questions

Q1. What’s an API?

A. An API permits totally different software program programs 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 hundreds of actual time APIs.

Q3. Why combine APIs with AI brokers?

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

This fall. 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.

Obsessed with know-how and innovation, a graduate of Vellore Institute of Expertise. At present working as a Knowledge Science Trainee, specializing in Knowledge Science. Deeply considering Deep Studying and Generative AI, desirous to discover cutting-edge methods to resolve complicated issues and create impactful options.

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

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles