Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add-rainforest-product-integration #243

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions integrations/rainforest/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Rainforest API Integration

## Overview
Rainforest API integration enhances the capabilities of an AI agent by leveraging Rainforest Product Data API. This integration allows the AI agent to perform advanced searches, providing users with relevant data based on their search queries.


## Rainforest API
**Rainforest** is a real-time, high-scale API to request Amazon product data, customer reviews, seller offers, search results, category listing results and bestselling products.

## Usage
To use the Rainforest API integration, create an instance of the `SearchAmazonRequest` model with a specific query and send it to the agent. The agent will utilize the Rainforest Product Search API to perform the search and respond with formatted results.

# Getting Rainforest API Key

To access the Rainforest API, you need an API key. Follow these steps to obtain your API key:

1. Visit the Rainforest website at [https://www.rainforestapi.com/](https://www.rainforestapi.com/).
2. Sign up or log in to your account.
3. Navigate to the API section.
4. Create a new API key.
5. Copy the generated API key.
6. Replace the placeholder in the script with your actual API key.

Ensure that you keep your API key secure and do not share it publicly. It is a sensitive credential that grants access to Rainforest services.

# Agent Secrets on Agentverse

1. Go to the Agentverse platform.
2. Navigate to the Agent Secrets section.
3. Create an agent and copy the code in it
4. Add a new secret with the key `API_KEY` and the value as your API KEY.

# Steps to Enroll an Agent as a Service on Agentverse

You can integrate into DeltaV your Agents created on your local computer, IoT devices, in the VMs, or agents created on Agentverse. The steps are the same.

Once your agents are run, the agent protocol manifests are uploaded to the Almanac contract in the form of protocol digests. After uploading the manifests, we take the agent addresses and enroll the agents as a service under the "Services" tab in Agentverse.

## Agent Validation on Agentverse Explorer
*Note: You can validate the procedure by searching for your agent's address on Agent Explorer, checking if the protocols have been uploaded successfully. If not, you need to wait for some time (1-2 minutes) until the protocols are uploaded successfully.*

## Create a Service Group

1. Start by creating a new service group on Agentverse.
2. Set up the service group as PRIVATE (you will only be able to see your own agents).
- If you set up your service group as Public, anyone will be able to see your agents.

**Service group has been created.**

## Create a Service

1. To register the agents as a service, input a concise title and description for the agent service.
2. Choose the service group for the agent service that you've created previously.
3. Fill in the agent address in the Agent field.
4. Set the task type to Task.

Now, your agents are enrolled as a service in Agentverse. You can manage and monitor them under the "Services" tab. Ensure that you follow the agent validation steps on Agent Explorer to confirm successful enrollment.
103 changes: 103 additions & 0 deletions integrations/rainforest/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Here we demonstrate how we can create a DeltaV compatible agent responsible for getting Amazon Product from Rainforest
# API. After running this agent, it can be registered to DeltaV on Agentverse's Services tab. For registration,
# you will have to use the agent's address.
#
# third party modules used in this example
import requests
from pydantic import Field
from ai_engine import UAgentResponse, UAgentResponseType


# Define the updated Rainforest API protocol
class SearchAmazonRequest(Model):
search_term: str = Field(description="Describes the text field to query for a product to search in marketplace")


# Define the Rainforest API details
rainforest_base_url = "https://api.rainforestapi.com/request"

rainforest_protocol = Protocol("Rainforst Protocol")


# Function to extract top 5 products from the search results
def extract_top_5_products(data) -> list or None:
"""
Extracts all the Search Results from the API Response

Returns:
List of top 5 Products.
"""
products = data.get("search_results", []) # Extract top 5 results
enriched_products = []
index = 1
for product_info in products:
if len(enriched_products) <= 5:
if product_info.get('price'):
enriched_product = (
f"{index}. Title: {product_info.get('title')}\n"
f" ASIN: {product_info.get('asin')}\n"
f" Link: <a href={product_info.get('link')}>Product Link</a>\n"
f" Rating: {product_info.get('rating')}\n"
f" Price: {product_info.get('price').get('raw')}\n"
)
enriched_products.append(enriched_product)
index += 1
else:
continue
else:
break
return '\n\n'.join(enriched_products)


# Function to perform a search on Amazon using the Rainforest API
def search_amazon_products(search_term):
"""
Retrieves data from the Rainforest API for Amazon Products.
Args:
search_term: search term for product.

Returns:
list or None: A list of Amazon product data if successful, or None if the request fails.
"""
params = {
'api_key': API_KEY,
'type': 'search',
'amazon_domain': 'amazon.co.uk',
'search_term': search_term + ' above 100',
'output': 'json'
}

response = requests.get(rainforest_base_url, params=params)

if response.status_code == 200:
return response.json()
else:
return None

@rainforest_protocol.on_query(model=SearchAmazonRequest, replies=UAgentResponse)
async def search_amazon_q(ctx: Context, sender: str, msg: SearchAmazonRequest):
ctx.logger.info(f"Received message from {sender} to search Amazon for '{msg.search_term}'")
try:
data = search_amazon_products(msg.search_term)

if data is not None:
top_5_products = extract_top_5_products(data)
await ctx.send(sender, UAgentResponse(
message=top_5_products,
type=UAgentResponseType.FINAL,
))
else:
await ctx.send(sender, UAgentResponse(
message="Please try some other query, could not find any result for the given search query.",
type=UAgentResponseType.FINAL,
))
except Exception as exc:
ctx.logger.error(exc)
await ctx.send(sender, UAgentResponse(
message="Facing some trouble while finding the product from amazon, please try again after some time",
type=UAgentResponseType.FINAL,
))


# Include the updated Rainforest API protocol in the agent
agent.include(rainforest_protocol)
6 changes: 6 additions & 0 deletions integrations/rainforest/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"title": "Rainforest Product Finder",
"description": "Rainforest API integration enhances the capabilities of an AI agent by leveraging Rainforest Product Data API. ",
"categories": ["Product Finder"],
"deltav": true
}
Loading