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: Live scores integration and Gemini AI integration #228

Merged
merged 8 commits into from
Feb 16, 2024
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
38 changes: 38 additions & 0 deletions integrations/gemini_AI_integration/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Google Gemini Generative AI Integration 🤑

This repository contains examples of Google Gemini chat conversation integrations using two agents: `Gemini_agent` and `user_agent`.

1. `user_agent` : This agent takes request from user (message) and queries google gemini agent.

2. `Gemini_agent`: This agent takes query from user, and asks google gemini generative AI for response. [Google Gemini ](https://makersuite.google.com/app/prompts/new_freeform). Once it gets response from generative AI. It sends back to user.

## Getting Started 🚀

To use these agents, follow the steps below:

### Step 1: Obtain API Keys 🔑

Before running the agents, you need to obtain the required API keys:

#### Google Gemini API Key

1. Visit the Google AI Studio website: [Google AI Studio](https://makersuite.google.com/app/prompts/new_freeform)
2. Login using google credentials.
3. Click on Get API Key and store this key at safe place.
4. For more information on how to use Gemini API refer [Gemini API Quickstart](https://ai.google.dev/tutorials/python_quickstart#chat_conversations)

### Step 2: Set API Keys and address in agent scripts

1. Fill in the API Keys in the `gemini_agent` scripts.
2. Check for all gemini_agent address and replace it into the google agent.

### Step 3: Run Project

To run the project and its agents:

```bash
cd src
python main.py
```

Now you have the agents up and running to perform gemini integrations using the provided APIs. Happy integrating! 🎉
5 changes: 5 additions & 0 deletions integrations/gemini_AI_integration/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"title": "Google Gemini Integration",
"description": "This integration helps to have chat conversation with Google Gemini Generative AI",
"categories": ["Generative AI", "Google Gemini"]
}
74 changes: 74 additions & 0 deletions integrations/gemini_AI_integration/src/agents/gemini_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Importing necessary libraries
from uagents import Agent, Context
from uagents.setup import fund_agent_if_low
from uagents import Model
import google.generativeai as genai

# Defining a model for messages
class Message(Model):
message: str

# Defining the user agent
Gemini_agent = Agent(
name="Gemini Agent",
port=8001,
seed="Gemini Agent secret phrase",
endpoint=["http://localhost:8001/submit"],
)

# Funding the user agent if its wallet balance is low
fund_agent_if_low(Gemini_agent.wallet.address())

# Configuring the API key for Google's generative AI service
genai.configure(api_key='GEMINI_API_KEY') #replace your gemini API key here

# Initializing the generative model with a specific model name
model = genai.GenerativeModel('gemini-pro')

# Starting a new chat session
chat = model.start_chat(history=[])

print("Chat session has started. Type 'quit' to exit.")

# Function to handle incoming messages
async def handle_message(message):

while True:
# Get user input
user_message = message

# Check if the user wants to quit the conversation
if user_message.lower() == 'quit':
return "Exiting chat session."

# Send the message to the chat session and receive a streamed response
response = chat.send_message(user_message, stream=True)

# Initialize an empty string to accumulate the response text
full_response_text = ""

# Accumulate the chunks of text
for chunk in response:
full_response_text += chunk.text

# Print the accumulated response as a single paragraph
message = "Gemini: " + full_response_text
return message

# Event handler for agent startup
@Gemini_agent.on_event('startup')
async def address(ctx: Context):
# Logging the agent's address
ctx.logger.info(Gemini_agent.address)

# Handler for query given by user
@Gemini_agent.on_message(model=Message)
async def handle_query_response(ctx: Context, sender: str, msg: Message):
# Handling the incoming message
message = await handle_message(msg.message)

# Logging the response
ctx.logger.info(message)

# Sending the response back to the sender
await ctx.send(sender, Message(message=message))
39 changes: 39 additions & 0 deletions integrations/gemini_AI_integration/src/agents/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Importing necessary libraries from uagents package
from uagents import Agent, Context
from uagents.setup import fund_agent_if_low
from uagents import Model

# Defining a model for messages
class Message(Model):
message: str

# Specifying the address of the gemini ai agent
Gemini_Address = "agent1qwg20ukwk97t989h6kc8a3sev0lvaltxakmvvn3sqz9jdjw4wsuxqa45e8l" # replace your Gemini API key here

# Defining the user agent with specific configuration details
user = Agent(
name="user",
port=8000,
seed="user secret phrase",
endpoint=["http://localhost:8000/submit"],
)

# Checking and funding the user agent's wallet if its balance is low
fund_agent_if_low(user.wallet.address())

# Event handler for the user agent's startup event
@user.on_event('startup')
async def agent_address(ctx: Context):
# Logging the user agent's address
ctx.logger.info(user.address)
# Prompting for user input and sending it as a message to the gemini agent
message = str(input('You:'))
await ctx.send(Gemini_Address, Message(message=message))

# Handler for receiving messages from gemini agent and sending new request
@user.on_message(model=Message)
async def handle_query_response(ctx: Context, sender: str, msg: Message):
# Prompting for the next user input upon receiving a message
message = str(input('You:'))
# Sending the user's message back to the sender (restaurant agent)
await ctx.send(sender, Message(message=message))
21 changes: 21 additions & 0 deletions integrations/gemini_AI_integration/src/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Importing agent configurations from user-defined modules
from agents.user import user # Imports the user agent configuration
from agents.gemini_agent import Gemini_agent # Imports the Gemini agent configuration

# Importing the Bureau class from the uagents package
from uagents import Bureau

# The main entry point of the script
if __name__ == "__main__":
# Creating a Bureau instance with a specified endpoint and port
# This acts as a central manager for all agents
bureau = Bureau(endpoint="http://127.0.0.1:5000/submit", port=8000)

# Adding the Gemini_agent to the Bureau's list of managed agents
bureau.add(Gemini_agent)

# Adding the user agent to the Bureau's list of managed agents
bureau.add(user)

# Starting the Bureau, which in turn starts and manages the added agents
bureau.run()
45 changes: 45 additions & 0 deletions integrations/live_sports_integration/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# uAgent Live Sports Integration

This repository contains examples of live sports integrations using three agents: `sports_agent` and `user_agent`.

1. `user_agent` : This agent takes from and to location request as details from user, and responds with all possible routes with detailed plan.

2. `sports_agent`: This agent takes sports name from user, for all sports other than cricket [Sport Score API](https://rapidapi.com/tipsters/api/sportscore1/) is used to fetch live scores. For cricket [LiveScore Sports API](https://rapidapi.com/tipsters/api/livescore-sports) is used to get live scores.

## Getting Started 🚀

To use these agents, follow the steps below:

### Step 1: Obtain API Keys 🔑

Before running the agents, you need to obtain the required API keys:

#### Sport Score API

1. Visit the RapidAPI website:https://rapidapi.com/tipsters/api/sportscore1/
2. If you don't have an account, create one by signing up.
3. Once you are logged in, click on test endpoint and register for API on free-tier.
4. Once done you will see X-RapidAPI-Key in header parameter.

#### LiveScore Sports API

1. Visit the RapidAPI website: https://rapidapi.com/tipsters/api/livescore-sports
2. If you don't have an account, create one by signing up.
3. Once you are logged in, click on test endpoint and register for API on free-tier.
4. Once done you will see X-RapidAPI-Key in header parameter.

### Step 2: Set API Keys and address in agent scripts

1. Fill in the API Keys in the `sports_agent` scripts.
2. Replace the sports agent address in user agent's script.

### Step 3: Run Project

To run the project and its agents:

```bash
cd src
python main.py
```

Now you have the agents up and running to perform live sports score integrations using the provided APIs. Happy integrating! 🎉
5 changes: 5 additions & 0 deletions integrations/live_sports_integration/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"title": "Live Sports Score",
"description": "This integration helps user to get live scores for top sports",
"categories": ["Sports", "Live Sports"]
}
95 changes: 95 additions & 0 deletions integrations/live_sports_integration/src/agents/sports_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Importing libraries
import requests
from uagents import Agent, Model, Context, Protocol
from uagents.setup import fund_agent_if_low

# Assuming Message and Response models are defined elsewhere
from message.model import Response, Message

# Setting up the Live Sports Agent
sport_agent = Agent(
name='Live Sports Agent',
port=1123,
seed='Sports Agent secret seed phrase',
endpoint='http://localhost:1123/submit'
)

# Checking and funding the agent's wallet if the balance is low
fund_agent_if_low(sport_agent.wallet.address())

@sport_agent.on_event('startup')
async def address(ctx: Context):
# Logging the agent's address upon startup
ctx.logger.info(sport_agent.address)

def format_sport_name(sport_name):
"""
Format the sport name input by the user to capitalize the first letter.
"""
return sport_name.capitalize()

def fetch_events_for_sport(sport_name):
"""
Fetch live event details for the specified sport and return as a formatted string.
"""
# Choosing the API endpoint based on the sport
url = "https://livescore-sports.p.rapidapi.com/v1/events/live" if sport_name == "Cricket" else "https://sportscore1.p.rapidapi.com/events/live"
# Setting the query parameters based on the sport
querystring = {"locale":"EN", "timezone":"0", "sport":"cricket"} if sport_name == "Cricket" else {"page":"1"}
headers = {
"X-RapidAPI-Key": "Your-RapidAPI-Key",
"X-RapidAPI-Host": url.split("/")[2]
}
# Making the API request
response = requests.get(url, headers=headers, params=querystring)
data = response.json()

# Processing the API response
events_data = []
if sport_name == "Cricket":
# Specific processing for cricket data
data = data['DATA'][0] if 'DATA' in data and len(data['DATA']) > 0 else None
if data and 'EVENTS' in data:
for match in data['EVENTS']:
events_data.append(process_match_details(match))
else:
# Processing for other sports
data = data['data'] if 'data' in data else []
for event in data:
if event['sport']['name'].lower() == sport_name.lower():
events_data.append(process_match_details(event, is_cricket=False))

# Returning formatted event details
return "\n\n".join(events_data)

def process_match_details(match, is_cricket=True):
"""
Process and format match details for display.
"""
# Formatting details based on whether it's cricket or another sport
if is_cricket:
details = [
f"Match: {match['HOME_TEAM'][0]['NAME']} vs {match['AWAY_TEAM'][0]['NAME']}",
f"Status: {match.get('LONG_VERSION_OF_MATCH_STATUS', 'Status not provided')}",
f"Description: {match.get('DESCRIBE_CURRENT_STATUS_OF_MATCH', 'No description')}"
]
else:
details = [
f"Match: {match['home_team']['name']} vs {match['away_team']['name']}",
f"Sport: {match['sport']['name']}",
f"Score: {match['home_team']['name']} {match['home_score']['current']} - {match['away_team']['name']} {match['away_score']['current']}",
f"League: {match['league']['name']}",
f"Status: {match['status']}",
f"Start Time: {match['start_at']}",
f"Round: {match.get('round_info', {}).get('round', 'N/A') if match.get('round_info') else 'N/A'}"
]
return "\n".join(details)

@sport_agent.on_message(model=Message, replies=Response)
async def handle_query(ctx: Context, sender: str, msg: Message):
# Handling user queries for live sports events
sport = msg.message
formatted_sport_name = format_sport_name(sport)
events_response = fetch_events_for_sport(formatted_sport_name)
# Sending the fetched events response back to the user
await ctx.send(sender, Response(response=events_response))
33 changes: 33 additions & 0 deletions integrations/live_sports_integration/src/agents/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Importing necessary libraries from uagents package
from uagents import Agent, Context
from uagents.setup import fund_agent_if_low
from uagents import Model
from message.model import Message, Response


# Specifying the address of the sports agent
Sports_agent = "agent1q034g5mjap6zsex7rvfamuymd2xzggd4xemjrar6jzfy3mknp9sh5qdnvtp" # replace with your sports agent address

# Defining the user agent with specific configuration details
user = Agent(
name="user",
port=8000,
seed="user secret phrase",
endpoint=["http://localhost:8000/submit"],
)

# Checking and funding the user agent's wallet if its balance is low
fund_agent_if_low(user.wallet.address())

# Event handler for the user agent's startup event
@user.on_interval(period = 30.0)
async def agent_address(ctx: Context):
# Logging the user agent's address
ctx.logger.info(user.address)
# Prompting for user input and sending it as a message to the restaurant agent
sport = str(input("Enter the sport name (Football, Tennis, Hockey, Basketball, Volleyball, Handball, Cricket): "))
await ctx.send(Sports_agent, Message(message=sport))

@user.on_message(model = Response)
async def handle_response(ctx: Context, sender: str, msg: Response):
ctx.logger.info(msg.response)
14 changes: 14 additions & 0 deletions integrations/live_sports_integration/src/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# import required libraries
from agents.sports_agent import sport_agent
from agents.user import user

from uagents import Bureau

#adding all users to bureau and running it
if __name__ == "__main__":
bureau = Bureau(endpoint="http://127.0.0.1:8000/submit", port=8000)
bureau.add(sport_agent)
bureau.add(user)
bureau.run()


10 changes: 10 additions & 0 deletions integrations/live_sports_integration/src/message/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# import required libraries
from uagents import Model

# taking request as sports name
class Message(Model):
message : str

# getting response as live scores
class Response(Model):
response : str
Loading