Skip to content

Commit

Permalink
Merge branch 'fetchai:main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
steeevin88 authored Sep 18, 2024
2 parents a951c3c + 458c4b4 commit b66ce2e
Show file tree
Hide file tree
Showing 404 changed files with 1,958 additions and 1,445 deletions.
2 changes: 2 additions & 0 deletions integrations/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ When opening a PR please adhere to the following naming scheme where the type wo
<type>(integration): <title>
```

Please add your integrations to the community folder `integrations/community/`

### types

- **chore**: Commits that don't directly add features, fix bugs, or refactor code, but rather maintain the project or its surrounding processes.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@

# Get the HUGGING_FACE_ACCESS_TOKEN from environment variable or default to a placeholder string if not found.
HUGGING_FACE_ACCESS_TOKEN = os.getenv(
"HUGGING_FACE_ACCESS_TOKEN", "HUGGING FACE secret phrase :)")
"HUGGING_FACE_ACCESS_TOKEN", "HUGGING FACE secret phrase :)"
)

BLIP_URL = "https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-large"
BLIP_URL = (
"https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-large"
)

# Define headers for HTTP request, including content type and authorization details
HEADERS = {
"Authorization": f"Bearer {HUGGING_FACE_ACCESS_TOKEN}"
}
HEADERS = {"Authorization": f"Bearer {HUGGING_FACE_ACCESS_TOKEN}"}

# Create an agent with predefined properties
agent = Agent(
Expand Down Expand Up @@ -44,7 +45,9 @@ async def get_image_caption(ctx: Context, sender: str, imagedata: str):

# If the request response is not successful (non-200 code), send error message
if response.status_code != 200:
await ctx.send(sender, Error(error=f"Error: {response.json().get('error')}"))
await ctx.send(
sender, Error(error=f"Error: {response.json().get('error')}")
)
return

# Parse the first message (image caption) from the response
Expand All @@ -55,9 +58,15 @@ async def get_image_caption(ctx: Context, sender: str, imagedata: str):

# If an unknown exception occurs, send a generic error message to the sender/user
except Exception as ex:
await ctx.send(sender, Error(error=f"Sorry, I wasn't able to complete your request this time. Error detail: {ex}"))
await ctx.send(
sender,
Error(
error=f"Sorry, I wasn't able to complete your request this time. Error detail: {ex}"
),
)
return


# Create an instance of Protocol with a label "BlipImageCaptioning"
blip_agent = Protocol(name="BlipImageCaptioning", version="0.1.0")

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from uagents import Agent, Context, Protocol # Import necessary modules

# Import Basic messages
from messages.basic import CaptionRequest, CaptionResponse, Error

Expand All @@ -10,7 +11,9 @@
IMAGE_FILE = "sample-images/gandhi.jpg"

# AI model agent address
AI_MODEL_AGENT_ADDRESS = "agent1qvklft2qr2kgwm5h24pq74wywxvsuwgqfm2gwyh5gys9rjmzpz5asx8zke0"
AI_MODEL_AGENT_ADDRESS = (
"agent1qvklft2qr2kgwm5h24pq74wywxvsuwgqfm2gwyh5gys9rjmzpz5asx8zke0"
)

# Define user agent with specified parameters
user = Agent(
Expand Down Expand Up @@ -43,7 +46,7 @@ async def image_caption(ctx: Context):
# Opening the file in read binary mode
with open(IMAGE_FILE, "rb") as f:
# Encoding the image data to base64
data = base64.b64encode(f.read()).decode('ascii')
data = base64.b64encode(f.read()).decode("ascii")
# Using the context to send the request to the desired address with the image data
await ctx.send(AI_MODEL_AGENT_ADDRESS, CaptionRequest(image_data=data))

Expand All @@ -55,13 +58,15 @@ async def handle_data(ctx: Context, sender: str, caption: CaptionResponse):
ctx.logger.info(f"image caption => {caption.generated_text}")
ctx.storage.set("captionCreated", True)


# Define a function to handle and log errors occurred during process


@blip_user.on_message(model=Error)
async def handle_error(ctx: Context, sender: str, error: Error):
ctx.logger.info(f"Got error from uagent: {error}")


# Include the protocol with the agent, publish_manifest will make the protocol details available on Agentverse.
user.include(blip_user, publish_manifest=True)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,28 @@

Advisor_API_KEY = os.getenv("Advisor_API_KEY")


def advisor(query):
url = "https://maps-data.p.rapidapi.com/searchmaps.php"

headers = {
"X-RapidAPI-Key": Advisor_API_KEY,
"X-RapidAPI-Host": "maps-data.p.rapidapi.com"
}
querystring = {"query":"places to visit in "+query,
"limit":"20",
"country":"in",
"lang":"en"}

"X-RapidAPI-Key": Advisor_API_KEY,
"X-RapidAPI-Host": "maps-data.p.rapidapi.com",
}
querystring = {
"query": "places to visit in " + query,
"limit": "20",
"country": "in",
"lang": "en",
}

response = requests.get(url, headers=headers, params=querystring)
return(response.json())
return response.json()



travel_advisor_protocol = Protocol(name="TravelAdvisor")



class Request(Model):
message: str = Field(description="name of destination user wants to visit.")

Expand All @@ -33,9 +37,12 @@ class Request(Model):
async def handle_message(ctx: Context, sender: str, msg: Request):
i = 0
response = advisor(msg.message)
result = [item['name'] for item in response['data']]
result = [item["name"] for item in response["data"]]
refactored_data = [f"""● {name}\n""" for name in result]
await ctx.send(sender, UAgentResponse(message=str(refactored_data), type=UAgentResponseType.FINAL))
await ctx.send(
sender,
UAgentResponse(message=str(refactored_data), type=UAgentResponseType.FINAL),
)



agent.include(travel_advisor_protocol)
agent.include(travel_advisor_protocol)
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import requests
from ai_engine import UAgentResponse, UAgentResponseType
from pydantic import Field
from pydantic import Field
import os
from dotenv import load_dotenv

Expand All @@ -11,22 +11,21 @@
flights_protocol = Protocol(name="flights_protocol")
book_flight_protocol = Protocol(name="BookFlight")


class Flights(Model):
source: str = Field(
description="name of source location of the user."
)
source: str = Field(description="name of source location of the user.")
destination: str = Field(
description="name of destination location. location where the user wants to go."
)
date: str = Field(
description="date of flight departure."
)
person: int = Field(
description="number of passengers the user wants to book for."
)
date: str = Field(description="date of flight departure.")
person: int = Field(description="number of passengers the user wants to book for.")


class BookFlight(Model):
bookquery : str = Field(description="takes the response from flight booking details system.")
bookquery: str = Field(
description="takes the response from flight booking details system."
)


def fetch_airport_info(location):
url = "https://sky-scrapper.p.rapidapi.com/api/v1/flights/searchAirport"
Expand All @@ -35,7 +34,7 @@ def fetch_airport_info(location):

headers = {
"X-RapidAPI-Key": "Flight_API_KEY",
"X-RapidAPI-Host": "sky-scrapper.p.rapidapi.com"
"X-RapidAPI-Host": "sky-scrapper.p.rapidapi.com",
}

response = requests.get(url, headers=headers, params=querystring)
Expand All @@ -44,6 +43,7 @@ def fetch_airport_info(location):
print(data["data"][0]["skyId"], data["data"][0]["navigation"]["entityId"])
return data["data"][0]["skyId"], data["data"][0]["navigation"]["entityId"]


def fetch_flight(src, dest, date, person):
src_skyId, src_entityId = fetch_airport_info(src)
dest_skyId, dest_entityId = fetch_airport_info(dest)
Expand All @@ -62,32 +62,35 @@ def fetch_flight(src, dest, date, person):
"adults": person,
"currency": "USD",
"market": "en-US",
"countryCode": "US"
"countryCode": "US",
}

headers = {
"X-RapidAPI-Key": "Flight_API_KEY",
"X-RapidAPI-Host": "sky-scrapper.p.rapidapi.com"
"X-RapidAPI-Host": "sky-scrapper.p.rapidapi.com",
}

response = requests.get(url, headers=headers, params=querystring)
print('response', response)
print("response", response)
return response.json()


def format_data(data):
airports_data = data['filterStats']
src_airports = airports_data['airports'][0]["city"]
des_airports = airports_data['airports'][1]["city"]
airports_data = data["filterStats"]
src_airports = airports_data["airports"][0]["city"]
des_airports = airports_data["airports"][1]["city"]
print(src_airports, des_airports)

stopprices = airports_data['stopPrices']['direct']['formattedPrice']
stopprices = airports_data["stopPrices"]["direct"]["formattedPrice"]
carriers = []

for items in airports_data['carriers']:
carriers.append(items['name'])
for items in airports_data["carriers"]:
carriers.append(items["name"])

return [f"{carrier} - {src_airports} to {des_airports} cost {stopprices}\n" for carrier in carriers]
return [
f"{carrier} - {src_airports} to {des_airports} cost {stopprices}\n"
for carrier in carriers
]


@flights_protocol.on_message(model=Flights, replies={UAgentResponse})
Expand All @@ -97,16 +100,18 @@ async def flight_offers(ctx: Context, sender: str, msg: Flights):
response = fetch_flight(msg.source, msg.destination, datenew, msg.person)
ctx.logger.info(f"data response {response}")
ctx.logger.info(f"{response['data']}")
data = format_data(response['data'])
await ctx.send(sender, UAgentResponse(message=str(data), type=UAgentResponseType.FINAL))
data = format_data(response["data"])
await ctx.send(
sender, UAgentResponse(message=str(data), type=UAgentResponseType.FINAL)
)


@book_flight_protocol.on_message(model=BookFlight, replies=UAgentResponse)
async def book_hotel(ctx: Context, sender: str, msg: BookFlight):
ctx.logger.info(f"Received booking message from {sender}")
name = msg.bookquery
ctx.logger.info(f"{name}")

# url = 'https://twilio-vercel.vercel.app/sendsms'
# myobj = {'phone': '+919860245752', message:f"{name} hotel booked successfully"}

Expand All @@ -115,13 +120,13 @@ async def book_hotel(ctx: Context, sender: str, msg: BookFlight):
# print(x.text)

await ctx.send(
sender,
UAgentResponse(
message=f"{name} booked successfully",
type=UAgentResponseType.FINAL,
public_manifest=True
)
)
sender,
UAgentResponse(
message=f"{name} booked successfully",
type=UAgentResponseType.FINAL,
public_manifest=True,
),
)


agent.include(flights_protocol)
Expand Down
Loading

0 comments on commit b66ce2e

Please sign in to comment.