Skip to content

Commit

Permalink
add a lot of apis
Browse files Browse the repository at this point in the history
  • Loading branch information
caizhuoyue77 committed May 17, 2024
1 parent 4032d0f commit 4dec8ee
Show file tree
Hide file tree
Showing 35 changed files with 3,353 additions and 20 deletions.
43 changes: 23 additions & 20 deletions rewoo.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
from config import TOOL_LIST, TASK, PROMPT_TEMPLATE, SOLVE_PROMPT
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.tools.tavily_search import TavilySearchResults
from tools import weather_forcast_24h
from langgraph.graph import StateGraph, END
from config_api_keys import TAVILY_API_KEY, OPENAI_API_KEY
import colorlog
Expand Down Expand Up @@ -48,10 +46,6 @@ class ReWOO(TypedDict):
# TODO:后续要替换为自己的本地模型
model = ChatOpenAI(temperature=0.1, model="gpt-3.5-turbo")

# 把对应的工具import进来
search = TavilySearchResults()
weather_search = weather_forcast_24h

# 正则表达式
regex_pattern = r"Plan:\s*(.+)\s*(#E\d+)\s*=\s*(\w+)\s*\[([^\]]+)\]"

Expand Down Expand Up @@ -79,6 +73,28 @@ def _get_current_task(state: ReWOO):
else:
return len(state["results"]) + 1

# TODO: 修改得更加智能一点,能够读取文件夹里的所有工具,然后
def use_actual_tool(tool: str, tool_input: dict):
# 把对应的工具import进来
from langchain_community.tools.tavily_search import TavilySearchResults
from tools import weather_forcast_24h
search = TavilySearchResults()
weather_search = weather_forcast_24h


if tool == "Google":
result = search.invoke(tool_input)
elif tool == "LLM":
result = model.invoke(tool_input)
elif tool == "WeatherSearch":
result = weather_search(tool_input)
elif tool == "HotelSearch":
result = "长沙的酒店有:1.桔子水晶 2.如家 3.锦江之星"
elif tool == "GetTime":
result = "2024-05-20"
else:
raise ValueError(f"Unknown tool: {tool}")
return result

def tool_execution(state: ReWOO):
"""执行计划中的工具。"""
Expand All @@ -94,20 +110,7 @@ def tool_execution(state: ReWOO):
# 写一个函数专门来选择并执行工具
# execute_tool(tool, tool_input)

if tool == "Google":
result = search.invoke(tool_input)
elif tool == "LLM":
result = model.invoke(tool_input)
logger.error(f"Executing LLM tool with input {tool_input}")
elif tool == "WeatherSearch":
result = weather_search(tool_input)
logger.error(f"Executing WeatherSearch tool with input {tool_input}")
elif tool == "HotelSearch":
result = "长沙的酒店有:1.桔子水晶 2.如家 3.锦江之星"
elif tool == "GetTime":
return "2024-05-20"
else:
raise ValueError(f"Unknown tool: {tool}")
result = use_actual_tool(tool, tool_input)

_results[step_name] = str(result)
return {"results": _results}
Expand Down
20 changes: 20 additions & 0 deletions tools/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
## 导入所有的工具类
from .water_level import waterlevelcheck, WaterLevelSchema
from tools.search_weather import search_weather, WeatherInput
from tools.search_location import search_location, LocationInput
from tools.sunrise_sunset import sunrise_sunset, WeatherInput
from tools.weather_forcast_24h import weather_forcast_24h
from tools.weather_rain_minute import weather_rain_minute
from tools.weather_forcast_3d import weather_forcast_3d
from tools.weather_forcast_7d import weather_forcast_7d
from tools.weather_index_1d import weather_index_1d
from tools.get_current_time import get_current_time, TimeInput
from tools.bookings_get_currency import get_currency
from tools.bookings_get_exchange_rates import get_exchange_rates
from tools.bookings_get_languages import get_languages
from tools.bookings_location_to_lat_lon import get_location_to_lat_lon
from tools.bookings_search_attractions import search_attractions
from tools.bookings_search_flights import search_flights
from tools.bookings_search_hotels import search_hotels


25 changes: 25 additions & 0 deletions tools/bookings_get_currency.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import json
import asyncio
from pydantic import BaseModel, Field
import aiohttp

async def get_currency_iter():
url = "https://booking-com15.p.rapidapi.com/api/v1/meta/getCurrency"
headers = {
"X-RapidAPI-Key": "e873f2422cmsh92c1c839d99aee8p1dfd77jsne5cf72c01848",
"X-RapidAPI-Host": "booking-com15.p.rapidapi.com"
}

async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:
if response.status == 200:
return await response.json() # Return the parsed JSON data
else:
return {"error": f"Failed to fetch currency data, status code: {response.status}"}

def get_currency(query:str):
return asyncio.run(get_currency_iter())

if __name__ == "__main__":
result = fetch_currency("")
print("Answer:", result)
29 changes: 29 additions & 0 deletions tools/bookings_get_exchange_rates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import json
import asyncio
from pydantic import BaseModel, Field
import aiohttp


async def get_exchange_rates_iter(base_currency:str):
url = "https://booking-com15.p.rapidapi.com/api/v1/meta/getExchangeRates"
headers = {
"X-RapidAPI-Key": "e873f2422cmsh92c1c839d99aee8p1dfd77jsne5cf72c01848",
"X-RapidAPI-Host": "booking-com15.p.rapidapi.com"
}
params = {"base_currency": base_currency}

async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=params) as response:
if response.status == 200:
return await response.json() # Return the parsed JSON data
else:
return {"error": f"Failed to fetch exchange rates, status code: {response.status}"}

def get_exchange_rates(base_currency: str):
base_currency = "CNY"
return asyncio.run(get_exchange_rates_iter(base_currency))

# if __name__ == "__main__":
# base_currency = "CNY"
# result = fetch_exchange_rates(base_currency)
# print("Answer:", result)
31 changes: 31 additions & 0 deletions tools/bookings_get_languages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import json
import asyncio
from pydantic import BaseModel, Field
import requests

async def get_languages_iter():

return "中文是zh-cn 英文是us-en 没了"

url = "https://booking-com15.p.rapidapi.com/api/v1/meta/getLanguages"
headers = {
"X-RapidAPI-Key": "e873f2422cmsh92c1c839d99aee8p1dfd77jsne5cf72c01848",
"X-RapidAPI-Host": "booking-com15.p.rapidapi.com"
}

try:
response = requests.get(url, headers=headers)

if response.status_code == 200:
return response.json() # 返回解析后的JSON数据
else:
return {"error": f"Failed to fetch languages, status code: {response.status_code}"}
except requests.RequestException as e:
return {"error": f"Request failed: {str(e)}"}

def get_languages(query: str):
return asyncio.run(get_languages_iter())

if __name__ == "__main__":
result = get_languages("")
print("答案:", result)
31 changes: 31 additions & 0 deletions tools/bookings_location_to_lat_lon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import json
import asyncio
from pydantic import BaseModel, Field
import aiohttp

async def location_to_lat_lon_iter(query: str):
url = "https://booking-com15.p.rapidapi.com/api/v1/meta/locationToLatLong"
headers = {
"X-RapidAPI-Key": "e873f2422cmsh92c1c839d99aee8p1dfd77jsne5cf72c01848",
"X-RapidAPI-Host": "booking-com15.p.rapidapi.com"
}
params = {"query": query}

async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=params) as response:
if response.status == 200:
return await response.json() # Return the parsed JSON data
else:
return {"error": f"Failed to convert location to latitude and longitude, status code: {response.status}"}

def location_to_lat_lon(query: str):
query="shanghai"
return asyncio.run(location_to_lat_lon_iter(query))

class LocationToLatLonInput(BaseModel):
query: str = Field(description="Location query to be converted to latitude and longitude coordinates")

if __name__ == "__main__":
query = "man"
result = location_to_lat_lon(query)
print("Answer:", result)
37 changes: 37 additions & 0 deletions tools/bookings_search_attraction_locations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import json
import asyncio
from pydantic import BaseModel, Field
import aiohttp

async def search_attraction_locations(query: str, language_code: str):
url = "https://booking-com15.p.rapidapi.com/api/v1/attraction/searchLocation"
headers = {
"X-RapidAPI-Key": "e873f2422cmsh92c1c839d99aee8p1dfd77jsne5cf72c01848",
"X-RapidAPI-Host": "booking-com15.p.rapidapi.com"
}
params = {
"query": query,
"languagecode": language_code
}

async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=params) as response:
if response.status == 200:
return await response.json() # Return the parsed JSON data
else:
return {"error": f"Failed to fetch attractions, status code: {response.status}"}

def search_attraction_locations(query: str):
query = "shanghai"
language_code = "zh-cn"
return asyncio.run(search_attraction_locations(query, language_code))

class AttractionLocationSearchInput(BaseModel):
query: str = Field(description="Search query for attractions")
language_code: str = Field(description="Language code for the response")

if __name__ == "__main__":
query = "shanghai"
language_code = "zh-cn"
result = search_attraction_locations(query, language_code)
print("Answer:", result)
45 changes: 45 additions & 0 deletions tools/bookings_search_attractions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import json
import asyncio
from pydantic import BaseModel, Field
import aiohttp

async def search_attractions_iter(id: str, page: int, currency_code: str, language_code: str):
url = "https://booking-com15.p.rapidapi.com/api/v1/attraction/searchAttractions"
headers = {
"X-RapidAPI-Key": "e873f2422cmsh92c1c839d99aee8p1dfd77jsne5cf72c01848",
"X-RapidAPI-Host": "booking-com15.p.rapidapi.com"
}
params = {
"id": id,
"page": str(page),
"currency_code": currency_code,
"languagecode": language_code
}

async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=params) as response:
if response.status == 200:
return await response.json() # Return the parsed JSON data
else:
return {"error": f"Failed to fetch attractions, status code: {response.status}"}

def search_attractions(query: str):
id = "eyJwaW5uZWRQcm9kdWN0IjoiUFJ2cFpHVWxKWkN6IiwidWZpIjotMTkyNDQ2NX0="
page = 1
currency_code = "CNY"
language_code = "zh-cn"
return asyncio.run(search_attractions_iter(id, page, currency_code, language_code))

class AttractionSearchInput(BaseModel):
id: str = Field(description="Unique identifier for the attraction")
page: int = Field(default=1, description="Page number for pagination")
currency_code: str = Field(description="Currency code for pricing information")
language_code: str = Field(description="Language code for the response")

if __name__ == "__main__":
id = "eyJwaW5uZWRQcm9kdWN0IjoiUFJ2cFpHVWxKWkN6IiwidWZpIjotMTkyNDQ2NX0="
page = 1
currency_code = "CNY"
language_code = "zh-cn"
result = search_attractions(id, page, currency_code, language_code)
print("Answer:", result)
31 changes: 31 additions & 0 deletions tools/bookings_search_flight_location.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import json
import asyncio
from pydantic import BaseModel, Field
import aiohttp

async def search_flight_location_iter(query: str):
url = "https://booking-com15.p.rapidapi.com/api/v1/flights/searchDestination"
headers = {
"X-RapidAPI-Key": "e873f2422cmsh92c1c839d99aee8p1dfd77jsne5cf72c01848",
"X-RapidAPI-Host": "booking-com15.p.rapidapi.com"
}
params = {"query": query}

async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=params) as response:
if response.status == 200:
return await response.json() # Return the parsed JSON data
else:
return {"error": f"Failed to fetch flight locations, status code: {response.status}"}

def search_flight_location(query: str):
query = "shanghai"
return asyncio.run(search_flight_location_iter(query))

class FlightLocationSearchInput(BaseModel):
query: str = Field(default_factory=str, description="The search query string")

if __name__ == "__main__":
query_string = "new"
result = search_flight_location(query_string)
print("Answer:", result)
59 changes: 59 additions & 0 deletions tools/bookings_search_flights.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import json
import asyncio
from pydantic import BaseModel, Field
import aiohttp

async def search_flights_iter(from_id: str, to_id: str, depart_date: str, page_no: int, adults: int, children: str, currency_code: str):
return "有1班飞机从上海飞往新加坡,航班号为1012466,票价为200元"

url = "https://booking-com15.p.rapidapi.com/api/v1/flights/searchFlights"
headers = {
"X-RapidAPI-Key": "e873f2422cmsh92c1c839d99aee8p1dfd77jsne5cf72c01848",
"X-RapidAPI-Host": "booking-com15.p.rapidapi.com"
}
querystring = {
"fromId": from_id,
"toId": to_id,
"departDate": depart_date,
"pageNo": str(page_no),
"adults": str(adults),
"children": children,
"currency_code": currency_code
}

async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=querystring) as response:
if response.status == 200:
return await response.json() # Return the parsed JSON data
else:
return {"error": f"Failed to fetch flight data, status code: {response.status}"}

def search_flights(quert: str):
from_id = "BOM.AIRPORT"
to_id = "DEL.AIRPORT"
depart_date = "2024-10-01" # Replace <REQUIRED> with actual date
page_no = 1
adults = 1
children = "0,17"
currency_code = "CNY"
return asyncio.run(get_flights_iter(from_id, to_id, depart_date, page_no, adults, children, currency_code))

class FlightSearchInput(BaseModel):
from_id: str = Field(description="Airport code for the departure location")
to_id: str = Field(description="Airport code for the destination location")
depart_date: str = Field(description="Departure date")
page_no: int = Field(default=1, description="Page number for pagination")
adults: int = Field(default=1, description="Number of adults")
children: str = Field(default="0", description="Comma-separated ages of children")
currency_code: str = Field(description="Currency code")

if __name__ == "__main__":
from_id = "BOM.AIRPORT"
to_id = "DEL.AIRPORT"
depart_date = "2024-10-01" # Replace <REQUIRED> with actual date
page_no = 1
adults = 1
children = "0,17"
currency_code = "CNY"
result = search_flights(from_id, to_id, depart_date, page_no, adults, children, currency_code)
print("Answer:", result)
Loading

0 comments on commit 4dec8ee

Please sign in to comment.