HomeBig DataConstruct AI Brokers with RapidAPI for Actual-Time Knowledge

Construct AI Brokers with RapidAPI for Actual-Time Knowledge


Agent creation has turn 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 means – what if that they had realtime details about particular classes like finance and films. That may be actually cool, proper? Whereas exploring this selection, I discovered RapidAPI a hub of APIs that may give entry to AI brokers to realtime data with a easy API name. I then determined to make just a few brokers that may make use of those APIs to make higher role-playing brokers.

On this article, I share your complete course of for a similar, so you possibly can simply comply with it and replicate the outcomes in your personal use. Allow us to begin with some fundamental data –

What’s RapidAPI?

RapidAPI is definitely the older identify and has lately turn into Nokia API Hub after acquisition. It has a catalog of APIs the place we will use or publish APIs. It covers different classes from Cybersecurity, Motion pictures, Communication and extra. You possibly can discover extra about RapidAPI right here.

How one can 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 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. As an 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 key’s already current within the take a look at 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 should utilize the test-endpoint button on the right-top and take a look at code might be executed and you may get the response.

test-endpoint button | AI Agents Realtime APIs

Notice: A lot 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 are going to 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 take a look at 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 neglect 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 software 
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

@software
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()
    knowledge = res.learn()
    end result = json.masses(knowledge.decode("utf-8"))

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

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

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

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

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

End result

News Agent Review

Nice! We have now made our first agent and it’s trying good. You possibly can experiment with new prompts if you happen to like.

Notice: Our agent works totally on when requested one thing utilizing just one phrase (instance: “Sports activities”,”Forest”..and many others). It’s because the software 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

@software
def get_stock_history(image: str, interval: str = "1m", restrict: int = 640) -> str:
    """Get historic inventory worth knowledge 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()
    knowledge = res.learn()
    end result = json.masses(knowledge.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)

End result

Stock Agent Output

Nice, we efficiently retrieved the output for AAPL (Apple Inc.), and the data 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

@software
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 placement
            (e.g., 'London', 'Manchester', 'E1 6AN').
        location_identifier: The class of the placement.
            - Use 'metropolis' for main cities (default).
            - Use 'postal_code' if the consumer gives a postcode (e.g., 'W1').
            - Use 'space' for smaller neighborhoods.
    """
    # URL encoding to stop InvalidURL errors
    safe_val = location_value.exchange(" ", "%20").exchange(",", "%2C")
    safe_id = location_identifier.exchange(" ", "%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()
    knowledge = res.learn()
    end result = json.masses(knowledge.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 skilled. When a consumer asks for a location, "
        "infer the 'location_identifier' your self, normally 'metropolis' or "
        "'postal_code'. Don't ask the consumer for technical identifiers; "
        "name the software instantly."
    ),
)

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

print(end result["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 prime rated and worst rated API’s as instruments and we are going to configure the system immediate to choose which software to make use of primarily based on the immediate.

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

    Use this when the consumer needs a advice 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")


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

    Use this when the consumer 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 skilled film critic. Your purpose is to assist customers discover films "
        "primarily based on high quality. If a consumer asks for one thing 'good', 'really helpful', "
        "or 'basic', name get_top_rated_movies. If a consumer asks for one thing "
        "'unhealthy', 'horrible', or 'lowest rated', name get_lowest_rated_movies. "
        "Each instruments require no parameters. Summarize the ends in a pleasant "
        "means 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)

End result

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 score and ideal if you happen to’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 might recommend each extremely rated or worst rated films.

Conclusion

By integrating actual time APIs with brokers, we will transfer past static responses and construct methods that really feel actually clever. RapidAPI makes this integration easy and scalable throughout domains. Additionally it’s necessary that we decide the precise instruments and in addition tune the agent to work in concord with the software. As an example, many APIs may give an error whereas single quotes or areas are current within the argument. Additionally RapidAPI gives MCP help 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 gives a unified platform to find, take a look at, subscribe to, and combine hundreds of actual time APIs.

Q3. Why combine APIs with AI brokers?

A. APIs give brokers entry to actual time knowledge, 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, effectively outlined instruments, correct enter formatting, and error A. dealing with for dependable execution.

Captivated with expertise and innovation, a graduate of Vellore Institute of Expertise. At the moment working as a Knowledge Science Trainee, specializing in Knowledge Science. Deeply focused on Deep Studying and Generative AI, wanting to discover cutting-edge methods to resolve advanced 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

- Advertisment -
Google search engine

Most Popular

Recent Comments