apibank add lv3 apis

This commit is contained in:
黎星 2023-11-17 12:53:38 +08:00
parent 0105af14fa
commit 79e1fe82a1
22 changed files with 1759 additions and 0 deletions

View File

@ -0,0 +1,54 @@
from apis.api import API
class AccountInfo(API):
description = "API for retrieving and updating user account information."
input_parameters = {
'username': {'type': 'str', 'description': 'Name of the user.'},
'password': {'type': 'str', 'description': 'Password of the user.'},
}
output_parameters = {
'status': {'type': 'str', 'description': 'success or failed'},
'account_info': {'type': 'dict', 'description': 'User account information'}
}
def __init__(self):
self.database = [
(('John', '123456'), {'email': 'john@example.com', 'phone': '1234567890'}),
(('Mary', 'abcdef'), {'email': 'mary@example.com', 'phone': '0987654321'}),
(('Peter', 'qwerty'), {'email': 'peter@example.com', 'phone': '1231231234'}),
(('Tom', 'asdfgh'), {'email': 'tom@example.com', 'phone': '4564564567'}),
(('Jerry', 'zxcvbn'), {'email': 'jerry@example.com', 'phone': '7897897890'}),
]
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']
def call(self, username: str, password: str) -> dict:
input_parameters = {
'username': username,
'password': password
}
try:
account_info = self.retrieve_account_info(username, password)
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None,
'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': account_info, 'exception': None}
def retrieve_account_info(self, username, password):
for (user, pwd), account_info in self.database:
if user == username and pwd == password:
return account_info
raise Exception('User not found.')

View File

@ -0,0 +1,94 @@
from apis.api import API
import json
import os
import datetime
class AddMeeting(API):
description = "This API allows users to make a reservation for a meeting and store the meeting information in the database." \
"Function" \
"Allow users to make a reservation for a meeting." \
"Exception Handling" \
"1. If the reservation is successful, return a success message." \
"2. If the reservation fails, return a corresponding error message."
input_parameters = {
'meeting_topic': {'type': 'str', 'description': 'The title of the meeting, no more than 50 characters.'},
'start_time': {'type': 'str',
'description': 'The start time of the meeting, in the pattern of %Y-%m-%d %H:%M:%S'},
'end_time': {'type': 'str',
'description': 'The end time of the meeting, in the pattern of %Y-%m-%d %H:%M:%S'},
'location': {'type': 'str',
'description': 'The location where the meeting to be held, no more than 100 characters.'},
'attendees': {'type': 'list(str)',
'description': 'The attendees of the meeting, including names, positions and other information.'}
}
output_parameters = {
'status': {'type': 'str', 'description': 'success or failed'}
}
def __init__(self):
self.database = []
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
response_content, groundtruth_content = response['input']['meeting_topic'].split(" "), groundtruth['input'][
'meeting_topic'].split(" ")
content_satisfied = False
if len(set(response_content).intersection(set(groundtruth_content))) / len(set(response_content).union(
set(groundtruth_content))) > 0.5:
content_satisfied = True
response['input'].pop('meeting_topic')
groundtruth['input'].pop('meeting_topic')
if content_satisfied and response['input'] == groundtruth['input'] and response['output'] == \
groundtruth['output'] and response['exception'] == groundtruth['exception']:
return True
else:
return False
def call(self, meeting_topic: str, start_time: str, end_time: str, location: str,
attendees: list) -> dict:
input_parameters = {
'meeting_topic': meeting_topic,
'start_time': start_time,
'end_time': end_time,
'location': location,
'attendees': attendees
}
try:
status = self.add_meeting(meeting_topic, start_time, end_time, location, attendees)
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None,
'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': status,
'exception': None}
def add_meeting(self, meeting_topic: str, start_time: str, end_time: str, location: str,
attendees: list) -> str:
# Check the format of the input parameters.
datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
datetime.datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
if meeting_topic.strip() == "":
raise Exception('Meeting Topic should not be null')
self.database.append({
'meeting_topic': meeting_topic,
'start_time': start_time,
'end_time': end_time,
'location': location,
'attendees': attendees
})
return "success"

View File

@ -0,0 +1,207 @@
from apis.api import API
class Calculator(API):
description = 'This API provides basic arithmetic operations: addition, subtraction, multiplication, and division.'
input_parameters = {
'formula': {'type': 'str', 'description': 'The formula that needs to be calculated. Only integers are supported. Valid operators are +, -, *, /, and (, ). For example, \'(1 + 2) * 3\'.'},
}
output_parameters = {
'result': {'type': 'float', 'description': 'The result of the formula.'},
}
def __init__(self) -> None:
pass
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
re_formula = response['input']['formula'].replace(' ', '')
gt_formula = groundtruth['input']['formula'].replace(' ', '')
if re_formula == gt_formula and response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception']:
return True
else:
return False
def call(self, formula: str) -> float:
"""
Calculates the result of the formula.
Parameters:
- formula (str): the formula that needs to be calculated. Valid operators are +, -, *, /, and (, ). For example, '(1 + 2) * 3'.
Returns:
- result (float): the result of the formula.
- formula (str): the formula that was calculated.
"""
input_parameters = {
'formula': formula,
}
try:
result = self.calculate(formula)
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None, 'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': result, 'exception': None}
def calculate(self, formula: str) -> float:
"""
Calculates the result of the formula.
Parameters:
- formula (str): the formula that needs to be calculated. Valid operators are +, -, *, /, and (, ). For example, '(1 + 2) * 3'.
Returns:
- result (float): the result of the formula.
"""
# Remove all spaces from the formula
formula = formula.replace(' ', '')
# Check if the formula is valid
if not self.is_valid_formula(formula):
raise Exception('invalid formula')
# Convert the formula to a list
formula = self.convert_formula_to_list(formula)
# Calculate the result
result = self.calculate_formula(formula)
return result
def is_valid_formula(self, formula: str) -> bool:
"""
Checks if the formula is valid.
Parameters:
- formula (str): the formula that needs to be checked.
Returns:
- is_valid (bool): True if the formula is valid, False otherwise.
"""
# Check if the formula is empty
if len(formula) == 0:
return False
# Check if the formula contains invalid characters
for c in formula:
if c not in '0123456789+-*/()':
return False
# Check if the formula contains an invalid number of parentheses
if formula.count('(') != formula.count(')'):
return False
# Check if the formula contains an invalid number of operators
if formula.count('+') + formula.count('-') + formula.count('*') + formula.count('/') == 0:
return False
# Check if the formula contains an invalid number of operands
if formula.count('+') + formula.count('-') + formula.count('*') + formula.count('/') + 1 == len(formula):
return False
return True
def convert_formula_to_list(self, formula: str) -> list:
"""
Converts the formula to a list.
Parameters:
- formula (str): the formula that needs to be converted.
Returns:
- formula_list (list): the formula converted to a list.
"""
formula_list = []
number = ''
for c in formula:
if c in '0123456789':
number += c
else:
if number != '':
formula_list.append(float(number))
number = ''
formula_list.append(c)
if number != '':
formula_list.append(float(number))
return formula_list
def calculate_formula(self, formula: list) -> float:
"""
Calculates the result of the formula.
Parameters:
- formula (list): the formula that needs to be calculated.
Returns:
- result (float): the result of the formula.
"""
# Calculate the result of the parentheses
while '(' in formula:
left_parenthesis_index = formula.index('(')
right_parenthesis_index = formula.index(')')
formula[left_parenthesis_index:right_parenthesis_index + 1] = [self.calculate_formula(formula[left_parenthesis_index + 1:right_parenthesis_index])]
# Calculate the result of the multiplication and division
while '*' in formula or '/' in formula:
if '*' in formula and '/' in formula:
if formula.index('*') < formula.index('/'):
index = formula.index('*')
else:
index = formula.index('/')
elif '*' in formula:
index = formula.index('*')
else:
index = formula.index('/')
formula[index - 1:index + 2] = [self.calculate_operation(formula[index - 1], formula[index], formula[index + 1])]
# Calculate the result of the addition and subtraction
while '+' in formula or '-' in formula:
if '+' in formula and '-' in formula:
if formula.index('+') < formula.index('-'):
index = formula.index('+')
else:
index = formula.index('-')
elif '+' in formula:
index = formula.index('+')
else:
index = formula.index('-')
formula[index - 1:index + 2] = [self.calculate_operation(formula[index - 1], formula[index], formula[index + 1])]
return formula[0]
def calculate_operation(self, operand1: float, operator: str, operand2: float) -> float:
"""
Calculates the result of the operation.
Parameters:
- operand1 (float): the first operand.
- operator (str): the operator.
- operand2 (float): the second operand.
Returns:
- result (float): the result of the operation.
"""
if operator == '+':
return operand1 + operand2
elif operator == '-':
return operand1 - operand2
elif operator == '*':
return operand1 * operand2
elif operator == '/':
return operand1 / operand2
if __name__ == '__main__':
# Create the API
api = Calculator()
response = api.call('(1 + 2) * 3')
print(response)

View File

@ -0,0 +1,81 @@
from apis.api import API
class ClothingRecommendation(API):
description = "API for providing clothing recommendations based on weather conditions."
input_parameters = {
'temperature': {'type': 'float', 'description': 'Temperature in Celsius.'},
'humidity': {'type': 'float', 'description': 'Relative humidity in percentage.'},
'weather_conditions': {'type': 'str', 'description': 'Description of weather conditions.'},
}
output_parameters = {
'clothing_options': {'type': 'list', 'description': 'List of recommended clothing options.'},
}
def call(self, temperature: float, humidity: float, weather_conditions: str) -> dict:
input_parameters = {
'temperature': temperature,
'humidity': humidity,
'weather_conditions': weather_conditions,
}
try:
clothing_options = self.get_clothing_recommendation(temperature, humidity, weather_conditions)
return {
'api_name': self.__class__.__name__,
'input': input_parameters,
'output': {'clothing_options': clothing_options},
'exception': None
}
except Exception as e:
exception = str(e)
return {
'api_name': self.__class__.__name__,
'input': input_parameters,
'output': None,
'exception': exception
}
def get_clothing_recommendation(self, temperature: float, humidity: float,
weather_conditions: str) -> list:
# Clothing recommendation logic based on weather conditions
clothing_options = []
if temperature < 10:
clothing_options.append('Warm coat')
clothing_options.append('Hat')
clothing_options.append('Gloves')
if temperature >= 10 and temperature < 20:
clothing_options.append('Light jacket')
clothing_options.append('Long-sleeved shirt')
if temperature >= 20 and temperature < 30:
clothing_options.append('T-shirt')
clothing_options.append('Shorts')
if temperature >= 30:
clothing_options.append('Sun hat')
clothing_options.append('Sunglasses')
clothing_options.append('Loose-fitting clothes')
if humidity > 70:
clothing_options.append('Umbrella')
clothing_options.append('Waterproof shoes')
if 'rain' in weather_conditions.lower():
clothing_options.append('Raincoat')
return clothing_options
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']

View File

@ -0,0 +1,63 @@
import datetime
from apis.api import API
class EmailReminder(API):
description = "This API sends an email reminder to the user with the meeting details."
input_parameters = {
'content': {'type': 'str', 'description': 'The content of the email.'},
'time': {'type': 'str', 'description': 'The time for the meeting. Format: %Y-%m-%d %H:%M:%S'},
'location': {'type': 'str', 'description': 'The location of the meeting.'},
'recipient': {'type': 'str', 'description': 'The email address of the recipient.'},
}
output_parameters = {
'status': {'type': 'str', 'description': 'success or failed'}
}
def __init__(self):
pass
def call(self, content: str, time: str, location: str, recipient: str) -> dict:
input_parameters = {
'content': content,
'time': time,
'location': location,
'recipient': recipient
}
try:
self.send_email(content, time, location, recipient)
status = 'success'
except Exception as e:
status = 'failed'
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None, 'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': status, 'exception': None}
def send_email(self, content: str, time: str, location: str, recipient: str):
# Validate the input parameters
datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
if content.strip() == "":
raise Exception('Content should not be empty')
# Send the email to the recipient
# email_subject = f"Meeting Reminder: {content}"
# email_body = f"Meeting Details:\n\nContent: {content}\nTime: {time}\nLocation: {location}"
# self.email_sender.send_email(token, recipient, email_subject, email_body)
return 'success'
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
response['input'].pop('content')
groundtruth['input'].pop('content')
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']

View File

@ -0,0 +1,87 @@
import datetime
from apis.api import API
class FlightSearch(API):
description = "API to retrieve flight options based on the destination and travel dates."
input_parameters = {
'source': {'type': 'str', 'description': "Source for the flight."},
'destination': {'type': 'str', 'description': "Destination for the flight."},
'travel_dates': {'type': 'str', 'description': 'Travel dates. Format: %Y-%m-%d'}
}
output_parameters = {
'flights': {'type': 'list', 'description': 'List of available flight options.'}
}
def __init__(self):
self.flight_data = [{
'source': 'New York',
'destination': 'San Francisco',
'departure_date': datetime.datetime(2022, 1, 1, 12, 0, 0),
'arrival_date': datetime.datetime(2022, 1, 1, 15, 0, 0),
},
{
'source': 'Los Angeles',
'destination': 'San Francisco',
'departure_date': datetime.datetime(2022, 1, 2, 12, 0, 0),
'arrival_date': datetime.datetime(2022, 1, 2, 15, 0, 0),
},
{
'source': 'London',
'destination': 'San Francisco',
'departure_date': datetime.datetime(2022, 1, 3, 12, 0, 0),
'arrival_date': datetime.datetime(2022, 1, 3, 15, 0, 0),
},
{
'source': 'New York',
'destination': 'London',
'departure_date': datetime.datetime(2022, 1, 4, 12, 0, 0),
'arrival_date': datetime.datetime(2022, 1, 4, 15, 0, 0),
},
{
'source': 'New York',
'destination': 'Los Angeles',
'departure_date': datetime.datetime(2022, 1, 5, 12, 0, 0),
'arrival_date': datetime.datetime(2022, 1, 5, 15, 0, 0),
}]
def get_flights(self, source, destination, travel_dates):
travel_dates = datetime.datetime.strptime(travel_dates, '%Y-%m-%d')
flights = []
for flight in self.flight_data:
if flight['source'] == source and flight['destination'] == destination and flight['departure_date'].date() == travel_dates.date():
flight['departure_date'] = flight['departure_date'].strftime('%Y-%m-%d %H:%M:%S')
flight['arrival_date'] = flight['arrival_date'].strftime('%Y-%m-%d %H:%M:%S')
flights.append(flight)
return flights
def call(self, source, destination, travel_dates):
input_parameters = {
'source': source,
'destination': destination,
'travel_dates': travel_dates
}
try:
flights = self.get_flights(source, destination, travel_dates)
output_parameters = {'flights': flights}
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': output_parameters,
'exception': None}
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None,
'exception': exception}
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']

View File

@ -0,0 +1,53 @@
from apis.api import API
class Geocoding(API):
description = "The API for converting an address or place name to geographical coordinates."
input_parameters = {
'address': {'type': 'str', 'description': 'The address or place name to be converted.'},
}
output_parameters = {
'latitude': {'type': 'float', 'description': 'The latitude of the location.'},
'longitude': {'type': 'float', 'description': 'The longitude of the location.'},
}
def __init__(self):
self.address_to_coordinates = {
'New York City': (40.7128, 74.0060),
'San Francisco': (37.7749, 122.4194),
'London': (51.5074, 0.1278),
'Paris': (48.8566, 2.3522),
'Tokyo': (35.6762, 139.6503),
}
def call(self, address: str) -> dict:
input_parameters = {
'address': address,
}
try:
latitude, longitude = self.convert_address_to_coordinates(address)
output_parameters = {
'latitude': latitude,
'longitude': longitude,
}
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None, 'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': output_parameters, 'exception': None}
def convert_address_to_coordinates(self, address: str) -> tuple:
return self.address_to_coordinates[address]
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']

View File

@ -0,0 +1,65 @@
from apis.api import API
class GetOccupationSalary(API):
description = "API for querying the salary of a given occupation."
input_parameters = {
'occupation': {'type': 'str', 'description': 'The occupation to query.'},
}
output_parameters = {
'salary': {'type': 'float', 'description': 'The salary of the given occupation.'}
}
def __init__(self):
self.salary_info = {
'Financial Analyst': 100000,
'Software Engineer': 120000,
'Data Scientist': 150000,
'Product Manager': 130000,
'Doctor': 200000,
}
def check_api_call_correctness(self, response, groundtruth):
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']
def call(self, occupation: str) -> dict:
input_parameters = {
'occupation': occupation,
}
try:
salary = self.query_salary(occupation)
output_parameters = {
'salary': salary,
}
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None,
'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': output_parameters,
'exception': None}
def query_salary(self, occupation: str) -> float:
"""
Queries the salary of the given occupation.
Parameters:
- occupation (str): the occupation to query.
Returns:
- salary (float): the salary of the given occupation.
"""
if occupation not in self.salary_info:
raise Exception("The occupation is not in the database.")
return self.salary_info[occupation]

View File

@ -0,0 +1,79 @@
import requests
from apis.api import API
class GetWeatherForCoordinates(API):
description = "Retrieves current weather information based on the provided coordinates."
input_parameters = {
'latitude': {'type': 'float', 'description': 'Latitude of the location.'},
'longitude': {'type': 'float', 'description': 'Longitude of the location.'}
}
output_parameters = {
'temperature': {'type': 'float', 'description': 'Current temperature in Celsius.'},
'humidity': {'type': 'float', 'description': 'Current humidity level.'},
'description': {'type': 'str', 'description': 'Weather description.'}
}
def __init__(self):
self.coordinates_to_weather = [
((40.7128, 74.0060), {
'temperature': 10,
'humidity': 0.5,
'description': 'Clear'
}),
((37.7749, 122.4194), {
'temperature': 20,
'humidity': 0.8,
'description': 'Cloudy'
}),
((51.5074, 0.1278), {
'temperature': 5,
'humidity': 0.9,
'description': 'Rainy'
}),
((48.8566, 2.3522), {
'temperature': 15,
'humidity': 0.7,
'description': 'Sunny'
}),
((35.6762, 139.6503), {
'temperature': 25,
'humidity': 0.6,
'description': 'Rainy'
}),
]
def check_api_call_correctness(self, response, groundtruth):
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']
def call(self, latitude: float, longitude: float) -> dict:
input_parameters = {
'latitude': latitude,
'longitude': longitude
}
try:
response = self.fetch_weather(latitude, longitude)
output_parameters = {
'temperature': response['temperature'],
'humidity': response['humidity'],
'description': response['description']
}
except requests.exceptions.RequestException as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None, 'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': output_parameters, 'exception': None}
def fetch_weather(self, latitude, longitude):
for coordinates, weather in self.coordinates_to_weather:
if coordinates == (latitude, longitude):
return weather

View File

@ -0,0 +1,103 @@
import datetime
from apis.api import API
class HotelAvailability(API):
description = "API for checking hotel availability based on the destination and travel dates."
input_parameters = {
'destination': {'type': 'str', 'description': "Destination for hotel search."},
'check_in_date': {'type': 'str', 'description': 'Check-in date. Format: %Y-%m-%d'},
'check_out_date': {'type': 'str', 'description': 'Check-out date. Format: %Y-%m-%d'},
}
output_parameters = {
'hotels': {'type': 'list', 'description': 'List of available hotels.'},
}
def __init__(self):
self.hotel_database = {
'hotel_1': {
'destination': 'San Francisco',
'check_in_date': datetime.datetime(2022, 1, 1),
'check_out_date': datetime.datetime(2022, 1, 2),
},
'hotel_2': {
'destination': 'San Francisco',
'check_in_date': datetime.datetime(2022, 1, 2),
'check_out_date': datetime.datetime(2022, 1, 3),
},
'hotel_3': {
'destination': 'San Francisco',
'check_in_date': datetime.datetime(2022, 1, 3),
'check_out_date': datetime.datetime(2022, 1, 4),
},
'hotel_4': {
'destination': 'San Francisco',
'check_in_date': datetime.datetime(2022, 1, 4),
'check_out_date': datetime.datetime(2022, 1, 5),
},
'hotel_5': {
'destination': 'San Francisco',
'check_in_date': datetime.datetime(2022, 1, 5),
'check_out_date': datetime.datetime(2022, 1, 6),
},
}
def check_api_call_correctness(self, response, groundtruth):
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
if response['input']['destination'] == groundtruth['input']['destination'] \
and response['input']['check_in_date'] == groundtruth['input']['check_in_date'] \
and response['input']['check_out_date'] == groundtruth['input']['check_out_date'] \
and response['output']['hotels'] == groundtruth['output']['hotels']:
return True
else:
return False
def call(self, destination: str, check_in_date: str, check_out_date: str) -> dict:
input_parameters = {
'destination': destination,
'check_in_date': check_in_date,
'check_out_date': check_out_date
}
try:
hotels = self.get_available_hotels(destination, check_in_date, check_out_date)
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None,
'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': {'hotels': hotels},
'exception': None}
def get_available_hotels(self, destination: str, check_in_date: str, check_out_date: str) -> list:
# Check the format of the input parameters.
datetime.datetime.strptime(check_in_date, '%Y-%m-%d')
datetime.datetime.strptime(check_out_date, '%Y-%m-%d')
available_hotels = []
for hotel_id, hotel in self.hotel_database.items():
if hotel['destination'] == destination and self.is_hotel_available(hotel, check_in_date, check_out_date):
hotel['check_in_date'] = hotel['check_in_date'].strftime('%Y-%m-%d')
hotel['check_out_date'] = hotel['check_out_date'].strftime('%Y-%m-%d')
available_hotels.append(hotel)
return available_hotels
def is_hotel_available(self, hotel, check_in_date, check_out_date) -> bool:
hotel_check_in_date = hotel['check_in_date'] if isinstance(hotel['check_in_date'], datetime.datetime) \
else datetime.datetime.strptime(hotel['check_in_date'], '%Y-%m-%d')
hotel_check_out_date = hotel['check_out_date'] if isinstance(hotel['check_out_date'], datetime.datetime) \
else datetime.datetime.strptime(hotel['check_out_date'], '%Y-%m-%d')
user_check_in_date = datetime.datetime.strptime(check_in_date, '%Y-%m-%d')
user_check_out_date = datetime.datetime.strptime(check_out_date, '%Y-%m-%d')
if user_check_in_date >= hotel_check_in_date and user_check_out_date <= hotel_check_out_date:
return True

View File

@ -0,0 +1,64 @@
from apis.api import API
class LikeCount(API):
description = "API to retrieve the number of likes for a given post ID."
input_parameters = {
'post_id': {'type': 'int', 'description': "Post ID."},
}
output_parameters = {
'like_count': {'type': 'int', 'description': 'Number of likes for the post.'},
}
def __init__(self):
self.database = {
1: 10,
2: 20,
3: 30,
4: 40,
5: 50,
6: 60,
7: 70,
8: 80,
9: 90,
10: 100,
11: 110,
12: 120,
13: 130,
14: 140,
15: 150,
}
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']
def call(self, post_id: int) -> dict:
input_parameters = {
'post_id': post_id,
}
try:
like_count = self.retrieve_like_count(post_id)
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None,
'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters,
'output': {'like_count': like_count}, 'exception': None}
def retrieve_like_count(self, post_id: int) -> int:
if post_id not in self.database:
raise Exception(f"Post with ID {post_id} does not exist.")
return self.database[post_id]

View File

@ -0,0 +1,58 @@
from apis.api import API
class MovieRecommendations(API):
description = "The API for retrieving recommended movies based on user preferences and filtering watched movies."
input_parameters = {
'preferences': {'type': 'list', 'description': "User's movie preferences."},
}
output_parameters = {
'recommended_movies': {'type': 'list', 'description': 'List of recommended movies.'}
}
def __init__(self):
self.database = {
'Action': ['The Dark Knight', 'The Matrix', 'The Lord of the Rings'],
'Comedy': ['The Hangover', 'Knives Out', 'Deadpool'],
'Drama': ['The Shawshank Redemption', 'Forrest Gump', 'Joker'],
'Romance': ['Titanic', 'La La Land', 'The Notebook'],
'Thriller': ['Inception', 'Parasite', 'Get Out'],
}
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']
def call(self, preferences: list) -> dict:
input_parameters = {
'preferences': preferences,
}
try:
recommended_movies = self.get_recommendations(preferences)
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None,
'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': {'recommended_movies': recommended_movies},
'exception': None}
def get_recommendations(self, preferences: list) -> list:
recommended_movies = []
for preference in preferences:
movies = self.database[preference]
recommended_movies.extend(movies)
return recommended_movies

View File

@ -0,0 +1,65 @@
from apis.api import API
class NearbyRestaurants(API):
description = "Retrieves nearby restaurants based on the provided coordinates and search parameters."
input_parameters = {
'latitude': {'type': 'float', 'description': 'Latitude of the location.'},
'longitude': {'type': 'float', 'description': 'Longitude of the location.'},
'distance': {'type': 'int', 'description': 'The distance in meters from the location to search for restaurants.'},
}
output_parameters = {
'restaurants': {'type': 'list', 'description': 'A list of nearby restaurants.'},
}
def __init__(self):
self.restaurants = [
{'coordinates': (40.7128, 74.0060), 'name': 'Restaurant A'},
{'coordinates': (37.7749, 122.4194), 'name': 'Restaurant B'},
{'coordinates': (40.7128, 74.0060), 'name': 'Restaurant C'},
{'coordinates': (37.7749, 122.4194), 'name': 'Restaurant D'},
]
def get_nearby_restaurants(self, latitude: float, longitude: float, distance: int) -> list:
"""
Retrieves nearby restaurants based on the provided coordinates and search parameters.
Parameters:
- latitude (float): latitude of the location.
- longitude (float): longitude of the location.
- distance (int): the distance in meters from the location to search for restaurants.
Returns:
- restaurants (list): a list of nearby restaurants.
"""
return self.restaurants
def check_api_call_correctness(self, response, groundtruth):
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['input'] == groundtruth['input']
def call(self, latitude: float, longitude: float, distance: int) -> dict:
input_parameters = {
'latitude': latitude,
'longitude': longitude,
'distance': distance
}
try:
restaurants = self.get_nearby_restaurants(latitude, longitude, distance)
output_parameters = {
'restaurants': restaurants
}
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None, 'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': output_parameters, 'exception': None}

View File

@ -0,0 +1,77 @@
from apis.api import API
class OrganizationMembers(API):
description = "API to retrieve the list of members in the organization."
input_parameters = {
'organization': {'type': 'str', 'description': "Name of the organization."},
}
output_parameters = {
'members': {'type': 'list', 'description': 'List of organization members.'}
}
def __init__(self):
self.database = {
'Alibaba': [
'John',
'Mary',
'Peter',
],
'Tencent': [
'Tom',
'Jerry',
],
'Baidu': [
'Jack',
'Rose',
],
'ByteDance': [
'Bob',
'Alice',
],
'JD': [
'Mike',
'Jane',
],
}
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
if response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']:
return True
else:
return False
def call(self, organization: str) -> dict:
input_parameters = {
'organization': organization
}
try:
members = self.get_organization_members(organization)
output_parameters = {
'members': members
}
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None,
'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': output_parameters,
'exception': None}
def get_organization_members(self, organization):
return self.database[organization]

View File

@ -0,0 +1,111 @@
import datetime
from apis.api import API
class QueryMeeting(API):
description = "The API for retrieving the meeting details from the user's calendar."
input_parameters = {
'user_name': {'type': 'str', 'description': 'Name of the user.'},
}
output_parameters = {
'meetings': {'type': 'list', 'description': 'List of meetings.'},
}
def __init__(self):
self.database = {
'John': [
{
'meeting_id': 1,
'meeting_name': 'Meeting with the client',
'meeting_time': datetime.datetime(2021, 1, 1, 10, 0, 0).strftime('%Y-%m-%d %H:%M:%S'),
'meeting_location': 'Room 1',
'meeting_attendees': ['John', 'Mary', 'Peter'],
},
{
'meeting_id': 2,
'meeting_name': 'Meeting about the new project',
'meeting_time': datetime.datetime(2021, 1, 2, 10, 0, 0).strftime('%Y-%m-%d %H:%M:%S'),
'meeting_location': 'Room 2',
'meeting_attendees': ['John', 'Mary', 'Peter'],
},
],
'Mary': [
{
'meeting_id': 1,
'meeting_name': 'Meeting with the client',
'meeting_time': datetime.datetime(2021, 1, 1, 10, 0, 0).strftime('%Y-%m-%d %H:%M:%S'),
'meeting_location': 'Room 1',
'meeting_attendees': ['John', 'Mary', 'Peter'],
},
{
'meeting_id': 2,
'meeting_name': 'Meeting about the new project',
'meeting_time': datetime.datetime(2021, 1, 2, 10, 0, 0).strftime('%Y-%m-%d %H:%M:%S'),
'meeting_location': 'Room 2',
'meeting_attendees': ['John', 'Mary', 'Peter'],
},
],
'Peter': [
{
'meeting_id': 1,
'meeting_name': 'Meeting with the client',
'meeting_time': datetime.datetime(2021, 1, 1, 10, 0, 0).strftime('%Y-%m-%d %H:%M:%S'),
'meeting_location': 'Room 1',
'meeting_attendees': ['John', 'Mary', 'Peter'],
},
{
'meeting_id': 2,
'meeting_name': 'Meeting about the new project',
'meeting_time': datetime.datetime(2021, 1, 2, 10, 0, 0).strftime('%Y-%m-%d %H:%M:%S'),
'meeting_location': 'Room 2',
'meeting_attendees': ['John', 'Mary', 'Peter'],
},
],
'Tom': [
{
'meeting_id': 1,
'meeting_name': 'Meeting',
'meeting_time': datetime.datetime(2021, 1, 1, 10, 0, 0).strftime('%Y-%m-%d %H:%M:%S'),
'meeting_location': 'Room 1',
'meeting_attendees': ['Tom', 'Jerry'],
},
],
'Jerry': [
{
'meeting_id': 1,
'meeting_name': 'Meeting',
'meeting_time': datetime.datetime(2021, 1, 1, 10, 0, 0).strftime('%Y-%m-%d %H:%M:%S'),
'meeting_location': 'Room 1',
'meeting_attendees': ['Tom', 'Jerry'],
},
],
}
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']
def call(self, user_name):
input_parameters = {
'user_name': user_name,
}
try:
meetings = self.retrieve_user_meetings(user_name)
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None, 'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': {'meetings': meetings}, 'exception': None}
def retrieve_user_meetings(self, user_name):
return self.database[user_name]

View File

@ -0,0 +1,64 @@
from apis.api import API
class TaxCalculator(API):
description = "API for calculating tax deductions based on the given salary."
input_parameters = {
'salary': {'type': 'float', 'description': 'The salary to calculate tax deductions for.'},
}
output_parameters = {
'salary_after_tax': {'type': 'float', 'description': 'The salary after tax deductions.'}
}
def __init__(self, tax_rates=None):
if tax_rates is not None:
self.tax_rates = tax_rates
else:
self.tax_rates = {
0: 0.0, # 0% tax rate
1000: 0.1, # 10% tax rate for income up to 1000
3000: 0.2, # 20% tax rate for income up to 3000
5000: 0.3, # 30% tax rate for income up to 5000
float('inf'): 0.4 # 40% tax rate for income above 5000
}
def calculate_tax_deductions(self, salary):
tax_rate = next(rate for threshold, rate in sorted(self.tax_rates.items(), reverse=True) if salary >= threshold)
tax_deduction = salary * tax_rate
salary_after_tax = salary - tax_deduction
return salary_after_tax
def check_api_call_correctness(self, response, groundtruth):
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
if response['input']['salary'] == groundtruth['input']['salary'] and \
response['output']['salary_after_tax'] == groundtruth['output']['salary_after_tax'] and \
response['exception'] == groundtruth['exception']:
return True
else:
return False
def call(self, salary):
input_parameters = {'salary': salary}
try:
salary_after_tax = self.calculate_tax_deductions(salary)
output_parameters = {'salary_after_tax': salary_after_tax}
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None,
'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters,
'output': output_parameters, 'exception': None}
if __name__ == '__main__':
tax_calculator = TaxCalculator()
response = tax_calculator.call(100000)
print(response)

View File

@ -0,0 +1,149 @@
from sentence_transformers import SentenceTransformer, util
import logging
logging.getLogger('sentence_transformers').setLevel(logging.WARNING)
import json
from apis.api import API
import os
class ToolSearcher(API):
description = 'Searches for relevant tools in library based on the keyword.'
input_parameters = {
'keywords': {'type': 'str', 'description': 'The keyword to search for.'}
}
output_parameters = {
'best_matchs': {'type': 'Union[List[dict], dict]', 'description': 'The best match tool(s).'},
}
def __init__(self, apis_dir = './lv3_apis'):
import importlib.util
all_apis = []
# import all the file in the apis folder, and load all the classes
except_files = ['__init__.py', 'api.py', 'tool_search.py']
for file in os.listdir(apis_dir):
if file.endswith('.py') and file not in except_files:
api_file = file.split('.')[0]
basename = os.path.basename(apis_dir)
module = importlib.import_module(basename + "." + api_file)
classes = [getattr(module, x) for x in dir(module) if isinstance(getattr(module, x), type)]
for cls in classes:
if issubclass(cls, API) and cls is not API:
all_apis.append(cls)
classes = all_apis
# # Import the module containing the API classes
# spec = importlib.util.spec_from_file_location('apis', './apis.py')
# module = importlib.util.module_from_spec(spec)
# spec.loader.exec_module(module)
# # Get a list of all classes in the module
# classes = inspect.getmembers(module, inspect.isclass)
def api_summery(cls):
cls_name = cls.__name__
# split cls_name by capital letters
cls_name = ''.join([' ' + i.lower() if i.isupper() else i for i in cls_name]).strip()
return cls_name + cls.description
# Get the description parameter for each class
apis = []
for cls in classes:
if issubclass(cls, object) and cls is not object:
desc_for_search = api_summery(cls)
apis.append({
'name': cls.__name__,
'description': cls.description,
'input_parameters': cls.input_parameters,
'output_parameters': cls.output_parameters,
'desc_for_search': desc_for_search
})
self.apis = apis
def check_api_call_correctness(self, response, groundtruth) -> bool:
if response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception']:
return True
else:
return False
def call(self, keywords):
"""
Searches for relevant tools in various libraries based on the keyword.
Parameters:
- keywords (str): the keywords to search for.
Returns:
- best_match (dict): the best match for the keywords.
"""
input_parameters = {
'keywords': keywords
}
try:
best_match = self.best_match_api(keywords)
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None, 'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': best_match, 'exception': None}
def best_match_api(self, keywords):
model = SentenceTransformer('sentence-transformers/paraphrase-MiniLM-L3-v2')
kw_emb = model.encode(keywords)
best_match = None
best_match_score = 0
for api in self.apis:
re_emb = model.encode(api['desc_for_search'])
cos_sim = util.cos_sim(kw_emb, re_emb).item()
if cos_sim > best_match_score:
best_match = api.copy()
best_match_score = cos_sim
best_match.pop('desc_for_search')
if 'token' in best_match['input_parameters']:
return [self.get_user_token_api, best_match]
else:
return best_match
# best_match = None
# for api in self.apis:
# if api['name'] == keywords:
# best_match = api
# break
# best_match = best_match.copy()
# best_match.pop('desc_for_search')
# return best_match
# model = SentenceTransformer('sentence-transformers/paraphrase-MiniLM-L3-v2')
# kw_emb = model.encode(keywords)
# scores = []
# for api in self.apis:
# re_emb = model.encode(api['desc_for_search'])
# cos_sim = util.cos_sim(kw_emb, re_emb).item()
# scores.append((api, cos_sim))
# scores.sort(key=lambda x: x[1], reverse=True)
# api_id = input('Please select the best match from {}:\n'.format([x[0]['name'] for x in scores[:3]]))
# try:
# api_id = int(api_id) - 1
# except:
# best_match = scores[0][0]
# for api in self.apis:
# if api['name'] == api_id:
# best_match = api
# break
# else:
# best_match = scores[int(api_id)][0]
# best_match = best_match.copy()
# best_match.pop('desc_for_search')
# return best_match
if __name__ == '__main__':
tool_searcher = ToolSearcher(apis_dir='./lv3_apis')
print(tool_searcher.call('add alarm'))

View File

@ -0,0 +1,56 @@
from apis.api import API
class TravelStatus(API):
description = "API for retrieving the current travel status of each member."
input_parameters = {
'member_name': {'type': 'str', 'description': 'Name of the member.'},
}
output_parameters = {
'status': {'type': 'str', 'description': 'Travel status'},
}
def __init__(self):
self.database = {
'John': 'Traveling',
'Mary': 'Working from home',
'Peter': 'Working from office',
'Tom': 'Traveling',
'Jerry': 'Working from home',
'Jack': 'Working from office',
'Rose': 'Working from office',
'Bob': 'Traveling',
'Alice': 'Working from home',
'Mike': 'Working from office',
'Jane': 'Working from office',
}
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): The response from the API call.
- groundtruth (dict): The groundtruth response.
Returns:
- is_correct (bool): Whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']
def call(self, member_name: str) -> dict:
input_parameters = {'member_name': member_name}
try:
status = self.get_travel_status(member_name)
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None,
'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': status,
'exception': None}
def get_travel_status(self, member_name):
return self.database[member_name]

View File

@ -0,0 +1,74 @@
from apis.api import API
class PersonalInfoUpdate(API):
description = "The API for updating a user's personal information and address."
input_parameters = {
'username': {'type': 'str', 'description': 'Name of the user.'},
'password': {'type': 'str', 'description': 'Password of the user.'},
'address': {'type': 'str', 'description': 'Updated address information.'},
}
output_parameters = {
'status': {'type': 'str', 'description': 'Success or failure'},
}
def __init__(self):
self.database = [
(('John', '123456'), {'email': 'john@example.com', 'phone': '1234567890'}),
(('Mary', 'abcdef'), {'email': 'mary@example.com', 'phone': '0987654321'}),
(('Peter', 'qwerty'), {'email': 'peter@example.com', 'phone': '1231231234'}),
(('Tom', 'asdfgh'), {'email': 'tom@example.com', 'phone': '4564564567'}),
(('Jerry', 'zxcvbn'), {'email': 'jerry@example.com', 'phone': '7897897890'}),
]
def check_api_call_correctness(self, response, groundtruth):
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['input'] == groundtruth['input'] and response['output'] == groundtruth['output']
def call(self, username: str, password: str, address: dict) -> dict:
input_parameters = {
'username': username,
'password': password,
'address': address
}
try:
status = self.update_personal_info(username, password, address)
output_parameters = {
'status': status
}
except Exception as e:
exception = str(e)
return {
'api_name': self.__class__.__name__,
'input': input_parameters,
'output': None,
'exception': exception
}
else:
return {
'api_name': self.__class__.__name__,
'input': input_parameters,
'output': output_parameters,
'exception': None
}
def update_personal_info(self, username, password, address):
for (user, pwd), user_account in self.database:
if user == username and pwd == password:
user_account['address'] = address
return 'success'
raise Exception('User not found.')

View File

@ -0,0 +1,53 @@
from apis.api import API
class UserPosts(API):
description = "API to retrieve the post IDs for a specific user."
input_parameters = {
'user_id': {'type': 'int', 'description': "User's ID."},
}
output_parameters = {
'post_ids': {'type': 'list', 'description': 'List of post IDs.'},
}
def __init__(self):
self.database = {
1: [1, 2, 3],
2: [4, 5, 6],
3: [7, 8, 9],
4: [10, 11, 12],
5: [13, 14, 15],
}
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']
def call(self, user_id: int) -> dict:
input_parameters = {
'user_id': user_id,
}
try:
post_ids = self.retrieve_user_post_ids(user_id)
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None, 'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': {'post_ids': post_ids}, 'exception': None}
def retrieve_user_post_ids(self, user_id: int) -> list:
return self.database[user_id]

View File

@ -0,0 +1,54 @@
from apis.api import API
class UserWatchedMovies(API):
description = "API for retrieving a user's watched movie list."
input_parameters = {
'user_name': {'type': 'str', 'description': 'Name of the user.'},
}
output_parameters = {
'watched_movies': {'type': 'list', 'description': 'List of watched movies.'},
}
def __init__(self):
self.database = {
'John': ['The Matrix', 'The Lord of the Rings', 'The Dark Knight'],
'Mary': ['The Lord of the Rings', 'The Dark Knight', 'The Matrix'],
'Peter': ['The Matrix', 'The Lord of the Rings', 'The Dark Knight'],
'Tom': ['The Lord of the Rings', 'The Dark Knight', 'The Matrix'],
'Jerry': ['The Matrix', 'The Lord of the Rings', 'The Dark Knight'],
}
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']
def call(self, user_name: str) -> dict:
input_parameters = {
'user_name': user_name
}
try:
watched_movies = self.retrieve_watched_movies(user_name)
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None,
'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': watched_movies,
'exception': None}
def retrieve_watched_movies(self, user_name):
if user_name not in self.database:
raise Exception('User not found.')
return self.database[user_name]

View File

@ -0,0 +1,48 @@
from apis.api import API
class UserMoviePreferences(API):
description = "API for retrieving user preferences for movie recommendations."
input_parameters = {
'user_name': {'type': 'str', 'description': 'Name of the user.'},
}
output_parameters = {
'preferences': {'type': 'list', 'description': 'List of movie preferences.'},
}
def __init__(self):
self.database = {
'John': ['Action', 'Comedy', 'Drama'],
'Mary': ['Comedy', 'Drama', 'Romance'],
'Peter': ['Action', 'Drama', 'Thriller'],
'Tom': ['Action', 'Comedy', 'Drama'],
'Jerry': ['Comedy', 'Drama', 'Romance'],
}
def check_api_call_correctness(self, response, groundtruth) -> bool:
"""
Checks if the response from the API call is correct.
Parameters:
- response (dict): the response from the API call.
- groundtruth (dict): the groundtruth response.
Returns:
- is_correct (bool): whether the response is correct.
"""
assert response['api_name'] == groundtruth['api_name'], "The API name is not correct."
return response['output'] == groundtruth['output'] and response['exception'] == groundtruth['exception'] and response['input'] == groundtruth['input']
def call(self, user_name: str) -> dict:
input_parameters = {
'user_name': user_name
}
try:
preferences = self.retrieve_preferences(user_name)
except Exception as e:
exception = str(e)
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': None, 'exception': exception}
else:
return {'api_name': self.__class__.__name__, 'input': input_parameters, 'output': {'preferences': preferences}, 'exception': None}
def retrieve_preferences(self, user_name):
return self.database[user_name]