Add custom tools (#2259)

Co-authored-by: luowei <glpat-EjySCyNjWiLqAED-YmwM>
Co-authored-by: crazywoola <427733928@qq.com>
Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com>
This commit is contained in:
Charlie.Wei 2024-01-30 11:03:20 +08:00 • committed by GitHub
commit 76cc19f525
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 320 additions and 1 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

View file

@ -0,0 +1,24 @@
import requests
import urllib.parse
from core.tools.provider.builtin_tool_provider import BuiltinToolProviderController
from core.tools.errors import ToolProviderCredentialValidationError
class GaodeProvider(BuiltinToolProviderController):
def _validate_credentials(self, credentials: dict) -> None:
try:
if 'api_key' not in credentials or not credentials.get('api_key'):
raise ToolProviderCredentialValidationError("Gaode API key is required.")
try:
response = requests.get(url="https://restapi.amap.com/v3/geocode/geo?address={address}&key={apikey}"
"".format(address=urllib.parse.quote('广东省广州市天河区广州塔'),
apikey=credentials.get('api_key')))
if response.status_code == 200 and (response.json()).get('info') == 'OK':
pass
else:
raise ToolProviderCredentialValidationError((response.json()).get('info'))
except Exception as e:
raise ToolProviderCredentialValidationError("Gaode API Key is invalid. {}".format(e))
except Exception as e:
raise ToolProviderCredentialValidationError(str(e))

View file

@ -0,0 +1,29 @@
identity:
author: CharlirWei
name: gaode
label:
en_US: GaoDe
zh_Hans: 高德
pt_BR: GaoDe
description:
en_US: Autonavi Open Platform service toolkit.
zh_Hans: 高德开放平台服务工具包。
pt_BR: Kit de ferramentas de serviço Autonavi Open Platform.
icon: icon.png
credentials_for_provider:
api_key:
type: secret-input
required: true
label:
en_US: API Key
zh_Hans: API Key
pt_BR: Fogo a chave
placeholder:
en_US: Please enter your GaoDe API Key
zh_Hans: 请输入你的高德开放平台 API Key
pt_BR: Insira sua chave de API GaoDe
help:
en_US: Get your API Key from GaoDe
zh_Hans: 从高德获取您的 API Key
pt_BR: Obtenha sua chave de API do GaoDe
url: https://console.amap.com/dev/key/app

View file

@ -0,0 +1,55 @@
import json
import requests
from core.tools.tool.builtin_tool import BuiltinTool
from core.tools.entities.tool_entities import ToolInvokeMessage
from typing import Any, Dict, List, Union
class GaodeRepositoriesTool(BuiltinTool):
def _invoke(self, user_id: str, tool_paramters: Dict[str, Any]) -> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
"""
invoke tools
"""
city = tool_paramters.get('city', '')
if not city:
return self.create_text_message('Please tell me your city')
if 'api_key' not in self.runtime.credentials or not self.runtime.credentials.get('api_key'):
return self.create_text_message("Gaode API key is required.")
try:
s = requests.session()
api_domain = 'https://restapi.amap.com/v3'
city_response = s.request(method='GET', headers={"Content-Type": "application/json; charset=utf-8"},
url="{url}/config/district?keywords={keywords}"
"&subdistrict=0&extensions=base&key={apikey}"
"".format(url=api_domain, keywords=city,
apikey=self.runtime.credentials.get('api_key')))
City_data = city_response.json()
if city_response.status_code == 200 and City_data.get('info') == 'OK':
if len(City_data.get('districts')) > 0:
CityCode = City_data['districts'][0]['adcode']
weatherInfo_response = s.request(method='GET',
url="{url}/weather/weatherInfo?city={citycode}&extensions=all&key={apikey}&output=json"
"".format(url=api_domain, citycode=CityCode,
apikey=self.runtime.credentials.get('api_key')))
weatherInfo_data = weatherInfo_response.json()
if weatherInfo_response.status_code == 200 and weatherInfo_data.get('info') == 'OK':
contents = list()
if len(weatherInfo_data.get('forecasts')) > 0:
for item in weatherInfo_data['forecasts'][0]['casts']:
content = dict()
content['date'] = item.get('date')
content['week'] = item.get('week')
content['dayweather'] = item.get('dayweather')
content['daytemp_float'] = item.get('daytemp_float')
content['daywind'] = item.get('daywind')
content['nightweather'] = item.get('nightweather')
content['nighttemp_float'] = item.get('nighttemp_float')
contents.append(content)
s.close()
return self.create_text_message(self.summary(user_id=user_id, content=json.dumps(contents, ensure_ascii=False)))
s.close()
return self.create_text_message(f'No weather information for {city} was found.')
except Exception as e:
return self.create_text_message("Github API Key and Api Version is invalid. {}".format(e))

View file

@ -0,0 +1,28 @@
identity:
name: gaode_weather
author: CharlieWei
label:
en_US: Weather Forecast
zh_Hans: 天气预报
pt_BR: Previsão do tempo
icon: icon.svg
description:
human:
en_US: Weather forecast inquiry
zh_Hans: 天气预报查询。
pt_BR: Inquérito sobre previsão meteorológica.
llm: A tool when you want to ask about the weather or weather-related question.
parameters:
- name: city
type: string
required: true
label:
en_US: city
zh_Hans: 城市
pt_BR: cidade
human_description:
en_US: Target city for weather forecast query.
zh_Hans: 天气预报查询的目标城市。
pt_BR: Cidade de destino para consulta de previsão do tempo.
llm_description: If you don't know you can extract the city name from the question or you can reply:Please tell me your city. You have to extract the Chinese city name from the question.
form: llm