api_tools_manage_service.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. import json
  2. import logging
  3. from typing import Optional
  4. from httpx import get
  5. from core.model_runtime.utils.encoders import jsonable_encoder
  6. from core.tools.entities.api_entities import UserTool, UserToolProvider
  7. from core.tools.entities.common_entities import I18nObject
  8. from core.tools.entities.tool_bundle import ApiToolBundle
  9. from core.tools.entities.tool_entities import (
  10. ApiProviderAuthType,
  11. ApiProviderSchemaType,
  12. ToolCredentialsOption,
  13. ToolProviderCredentials,
  14. )
  15. from core.tools.provider.api_tool_provider import ApiToolProviderController
  16. from core.tools.tool_label_manager import ToolLabelManager
  17. from core.tools.tool_manager import ToolManager
  18. from core.tools.utils.configuration import ToolConfigurationManager
  19. from core.tools.utils.parser import ApiBasedToolSchemaParser
  20. from extensions.ext_database import db
  21. from models.tools import ApiToolProvider
  22. from services.tools.tools_transform_service import ToolTransformService
  23. logger = logging.getLogger(__name__)
  24. class ApiToolManageService:
  25. @staticmethod
  26. def parser_api_schema(schema: str) -> list[ApiToolBundle]:
  27. """
  28. parse api schema to tool bundle
  29. """
  30. try:
  31. warnings = {}
  32. try:
  33. tool_bundles, schema_type = ApiBasedToolSchemaParser.auto_parse_to_tool_bundle(schema, warning=warnings)
  34. except Exception as e:
  35. raise ValueError(f"invalid schema: {str(e)}")
  36. credentials_schema = [
  37. ToolProviderCredentials(
  38. name="auth_type",
  39. type=ToolProviderCredentials.CredentialsType.SELECT,
  40. required=True,
  41. default="none",
  42. options=[
  43. ToolCredentialsOption(value="none", label=I18nObject(en_US="None", zh_Hans="无")),
  44. ToolCredentialsOption(value="api_key", label=I18nObject(en_US="Api Key", zh_Hans="Api Key")),
  45. ],
  46. placeholder=I18nObject(en_US="Select auth type", zh_Hans="选择认证方式"),
  47. ),
  48. ToolProviderCredentials(
  49. name="api_key_header",
  50. type=ToolProviderCredentials.CredentialsType.TEXT_INPUT,
  51. required=False,
  52. placeholder=I18nObject(en_US="Enter api key header", zh_Hans="输入 api key header,如:X-API-KEY"),
  53. default="api_key",
  54. help=I18nObject(en_US="HTTP header name for api key", zh_Hans="HTTP 头部字段名,用于传递 api key"),
  55. ),
  56. ToolProviderCredentials(
  57. name="api_key_value",
  58. type=ToolProviderCredentials.CredentialsType.TEXT_INPUT,
  59. required=False,
  60. placeholder=I18nObject(en_US="Enter api key", zh_Hans="输入 api key"),
  61. default="",
  62. ),
  63. ]
  64. return jsonable_encoder(
  65. {
  66. "schema_type": schema_type,
  67. "parameters_schema": tool_bundles,
  68. "credentials_schema": credentials_schema,
  69. "warning": warnings,
  70. }
  71. )
  72. except Exception as e:
  73. raise ValueError(f"invalid schema: {str(e)}")
  74. @staticmethod
  75. def convert_schema_to_tool_bundles(
  76. schema: str, extra_info: Optional[dict] = None
  77. ) -> tuple[list[ApiToolBundle], str]:
  78. """
  79. convert schema to tool bundles
  80. :return: the list of tool bundles, description
  81. """
  82. try:
  83. tool_bundles = ApiBasedToolSchemaParser.auto_parse_to_tool_bundle(schema, extra_info=extra_info)
  84. return tool_bundles
  85. except Exception as e:
  86. raise ValueError(f"invalid schema: {str(e)}")
  87. @staticmethod
  88. def create_api_tool_provider(
  89. user_id: str,
  90. tenant_id: str,
  91. provider_name: str,
  92. icon: dict,
  93. credentials: dict,
  94. schema_type: str,
  95. schema: str,
  96. privacy_policy: str,
  97. custom_disclaimer: str,
  98. labels: list[str],
  99. ):
  100. """
  101. create api tool provider
  102. """
  103. if schema_type not in [member.value for member in ApiProviderSchemaType]:
  104. raise ValueError(f"invalid schema type {schema}")
  105. provider_name = provider_name.strip()
  106. # check if the provider exists
  107. provider: ApiToolProvider = (
  108. db.session.query(ApiToolProvider)
  109. .filter(
  110. ApiToolProvider.tenant_id == tenant_id,
  111. ApiToolProvider.name == provider_name,
  112. )
  113. .first()
  114. )
  115. if provider is not None:
  116. raise ValueError(f"provider {provider_name} already exists")
  117. # parse openapi to tool bundle
  118. extra_info = {}
  119. # extra info like description will be set here
  120. tool_bundles, schema_type = ApiToolManageService.convert_schema_to_tool_bundles(schema, extra_info)
  121. if len(tool_bundles) > 100:
  122. raise ValueError("the number of apis should be less than 100")
  123. # create db provider
  124. db_provider = ApiToolProvider(
  125. tenant_id=tenant_id,
  126. user_id=user_id,
  127. name=provider_name,
  128. icon=json.dumps(icon),
  129. schema=schema,
  130. description=extra_info.get("description", ""),
  131. schema_type_str=schema_type,
  132. tools_str=json.dumps(jsonable_encoder(tool_bundles)),
  133. credentials_str={},
  134. privacy_policy=privacy_policy,
  135. custom_disclaimer=custom_disclaimer,
  136. )
  137. if "auth_type" not in credentials:
  138. raise ValueError("auth_type is required")
  139. # get auth type, none or api key
  140. auth_type = ApiProviderAuthType.value_of(credentials["auth_type"])
  141. # create provider entity
  142. provider_controller = ApiToolProviderController.from_db(db_provider, auth_type)
  143. # load tools into provider entity
  144. provider_controller.load_bundled_tools(tool_bundles)
  145. # encrypt credentials
  146. tool_configuration = ToolConfigurationManager(tenant_id=tenant_id, provider_controller=provider_controller)
  147. encrypted_credentials = tool_configuration.encrypt_tool_credentials(credentials)
  148. db_provider.credentials_str = json.dumps(encrypted_credentials)
  149. db.session.add(db_provider)
  150. db.session.commit()
  151. # update labels
  152. ToolLabelManager.update_tool_labels(provider_controller, labels)
  153. return {"result": "success"}
  154. @staticmethod
  155. def get_api_tool_provider_remote_schema(user_id: str, tenant_id: str, url: str):
  156. """
  157. get api tool provider remote schema
  158. """
  159. headers = {
  160. "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko)"
  161. " Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
  162. "Accept": "*/*",
  163. }
  164. try:
  165. response = get(url, headers=headers, timeout=10)
  166. if response.status_code != 200:
  167. raise ValueError(f"Got status code {response.status_code}")
  168. schema = response.text
  169. # try to parse schema, avoid SSRF attack
  170. ApiToolManageService.parser_api_schema(schema)
  171. except Exception as e:
  172. logger.exception(f"parse api schema error: {str(e)}")
  173. raise ValueError("invalid schema, please check the url you provided")
  174. return {"schema": schema}
  175. @staticmethod
  176. def list_api_tool_provider_tools(user_id: str, tenant_id: str, provider: str) -> list[UserTool]:
  177. """
  178. list api tool provider tools
  179. """
  180. provider_name = provider
  181. provider: ApiToolProvider = (
  182. db.session.query(ApiToolProvider)
  183. .filter(
  184. ApiToolProvider.tenant_id == tenant_id,
  185. ApiToolProvider.name == provider,
  186. )
  187. .first()
  188. )
  189. if provider is None:
  190. raise ValueError(f"you have not added provider {provider_name}")
  191. controller = ToolTransformService.api_provider_to_controller(db_provider=provider)
  192. labels = ToolLabelManager.get_tool_labels(controller)
  193. return [
  194. ToolTransformService.tool_to_user_tool(
  195. tool_bundle,
  196. labels=labels,
  197. )
  198. for tool_bundle in provider.tools
  199. ]
  200. @staticmethod
  201. def update_api_tool_provider(
  202. user_id: str,
  203. tenant_id: str,
  204. provider_name: str,
  205. original_provider: str,
  206. icon: dict,
  207. credentials: dict,
  208. schema_type: str,
  209. schema: str,
  210. privacy_policy: str,
  211. custom_disclaimer: str,
  212. labels: list[str],
  213. ):
  214. """
  215. update api tool provider
  216. """
  217. if schema_type not in [member.value for member in ApiProviderSchemaType]:
  218. raise ValueError(f"invalid schema type {schema}")
  219. provider_name = provider_name.strip()
  220. # check if the provider exists
  221. provider: ApiToolProvider = (
  222. db.session.query(ApiToolProvider)
  223. .filter(
  224. ApiToolProvider.tenant_id == tenant_id,
  225. ApiToolProvider.name == original_provider,
  226. )
  227. .first()
  228. )
  229. if provider is None:
  230. raise ValueError(f"api provider {provider_name} does not exists")
  231. # parse openapi to tool bundle
  232. extra_info = {}
  233. # extra info like description will be set here
  234. tool_bundles, schema_type = ApiToolManageService.convert_schema_to_tool_bundles(schema, extra_info)
  235. # update db provider
  236. provider.name = provider_name
  237. provider.icon = json.dumps(icon)
  238. provider.schema = schema
  239. provider.description = extra_info.get("description", "")
  240. provider.schema_type_str = ApiProviderSchemaType.OPENAPI.value
  241. provider.tools_str = json.dumps(jsonable_encoder(tool_bundles))
  242. provider.privacy_policy = privacy_policy
  243. provider.custom_disclaimer = custom_disclaimer
  244. if "auth_type" not in credentials:
  245. raise ValueError("auth_type is required")
  246. # get auth type, none or api key
  247. auth_type = ApiProviderAuthType.value_of(credentials["auth_type"])
  248. # create provider entity
  249. provider_controller = ApiToolProviderController.from_db(provider, auth_type)
  250. # load tools into provider entity
  251. provider_controller.load_bundled_tools(tool_bundles)
  252. # get original credentials if exists
  253. tool_configuration = ToolConfigurationManager(tenant_id=tenant_id, provider_controller=provider_controller)
  254. original_credentials = tool_configuration.decrypt_tool_credentials(provider.credentials)
  255. masked_credentials = tool_configuration.mask_tool_credentials(original_credentials)
  256. # check if the credential has changed, save the original credential
  257. for name, value in credentials.items():
  258. if name in masked_credentials and value == masked_credentials[name]:
  259. credentials[name] = original_credentials[name]
  260. credentials = tool_configuration.encrypt_tool_credentials(credentials)
  261. provider.credentials_str = json.dumps(credentials)
  262. db.session.add(provider)
  263. db.session.commit()
  264. # delete cache
  265. tool_configuration.delete_tool_credentials_cache()
  266. # update labels
  267. ToolLabelManager.update_tool_labels(provider_controller, labels)
  268. return {"result": "success"}
  269. @staticmethod
  270. def delete_api_tool_provider(user_id: str, tenant_id: str, provider_name: str):
  271. """
  272. delete tool provider
  273. """
  274. provider: ApiToolProvider = (
  275. db.session.query(ApiToolProvider)
  276. .filter(
  277. ApiToolProvider.tenant_id == tenant_id,
  278. ApiToolProvider.name == provider_name,
  279. )
  280. .first()
  281. )
  282. if provider is None:
  283. raise ValueError(f"you have not added provider {provider_name}")
  284. db.session.delete(provider)
  285. db.session.commit()
  286. return {"result": "success"}
  287. @staticmethod
  288. def get_api_tool_provider(user_id: str, tenant_id: str, provider: str):
  289. """
  290. get api tool provider
  291. """
  292. return ToolManager.user_get_api_provider(provider=provider, tenant_id=tenant_id)
  293. @staticmethod
  294. def test_api_tool_preview(
  295. tenant_id: str,
  296. provider_name: str,
  297. tool_name: str,
  298. credentials: dict,
  299. parameters: dict,
  300. schema_type: str,
  301. schema: str,
  302. ):
  303. """
  304. test api tool before adding api tool provider
  305. """
  306. if schema_type not in [member.value for member in ApiProviderSchemaType]:
  307. raise ValueError(f"invalid schema type {schema_type}")
  308. try:
  309. tool_bundles, _ = ApiBasedToolSchemaParser.auto_parse_to_tool_bundle(schema)
  310. except Exception as e:
  311. raise ValueError("invalid schema")
  312. # get tool bundle
  313. tool_bundle = next(filter(lambda tb: tb.operation_id == tool_name, tool_bundles), None)
  314. if tool_bundle is None:
  315. raise ValueError(f"invalid tool name {tool_name}")
  316. db_provider: ApiToolProvider = (
  317. db.session.query(ApiToolProvider)
  318. .filter(
  319. ApiToolProvider.tenant_id == tenant_id,
  320. ApiToolProvider.name == provider_name,
  321. )
  322. .first()
  323. )
  324. if not db_provider:
  325. # create a fake db provider
  326. db_provider = ApiToolProvider(
  327. tenant_id="",
  328. user_id="",
  329. name="",
  330. icon="",
  331. schema=schema,
  332. description="",
  333. schema_type_str=ApiProviderSchemaType.OPENAPI.value,
  334. tools_str=json.dumps(jsonable_encoder(tool_bundles)),
  335. credentials_str=json.dumps(credentials),
  336. )
  337. if "auth_type" not in credentials:
  338. raise ValueError("auth_type is required")
  339. # get auth type, none or api key
  340. auth_type = ApiProviderAuthType.value_of(credentials["auth_type"])
  341. # create provider entity
  342. provider_controller = ApiToolProviderController.from_db(db_provider, auth_type)
  343. # load tools into provider entity
  344. provider_controller.load_bundled_tools(tool_bundles)
  345. # decrypt credentials
  346. if db_provider.id:
  347. tool_configuration = ToolConfigurationManager(tenant_id=tenant_id, provider_controller=provider_controller)
  348. decrypted_credentials = tool_configuration.decrypt_tool_credentials(credentials)
  349. # check if the credential has changed, save the original credential
  350. masked_credentials = tool_configuration.mask_tool_credentials(decrypted_credentials)
  351. for name, value in credentials.items():
  352. if name in masked_credentials and value == masked_credentials[name]:
  353. credentials[name] = decrypted_credentials[name]
  354. try:
  355. provider_controller.validate_credentials_format(credentials)
  356. # get tool
  357. tool = provider_controller.get_tool(tool_name)
  358. tool = tool.fork_tool_runtime(
  359. runtime={
  360. "credentials": credentials,
  361. "tenant_id": tenant_id,
  362. }
  363. )
  364. result = tool.validate_credentials(credentials, parameters)
  365. except Exception as e:
  366. return {"error": str(e)}
  367. return {"result": result or "empty response"}
  368. @staticmethod
  369. def list_api_tools(user_id: str, tenant_id: str) -> list[UserToolProvider]:
  370. """
  371. list api tools
  372. """
  373. # get all api providers
  374. db_providers: list[ApiToolProvider] = (
  375. db.session.query(ApiToolProvider).filter(ApiToolProvider.tenant_id == tenant_id).all() or []
  376. )
  377. result: list[UserToolProvider] = []
  378. for provider in db_providers:
  379. # convert provider controller to user provider
  380. provider_controller = ToolTransformService.api_provider_to_controller(db_provider=provider)
  381. labels = ToolLabelManager.get_tool_labels(provider_controller)
  382. user_provider = ToolTransformService.api_provider_to_user_provider(
  383. provider_controller, db_provider=provider, decrypt_credentials=True
  384. )
  385. user_provider.labels = labels
  386. # add icon
  387. ToolTransformService.repack_provider(user_provider)
  388. tools = provider_controller.get_tools(user_id=user_id, tenant_id=tenant_id)
  389. for tool in tools:
  390. user_provider.tools.append(
  391. ToolTransformService.tool_to_user_tool(
  392. tenant_id=tenant_id, tool=tool, credentials=user_provider.original_credentials, labels=labels
  393. )
  394. )
  395. result.append(user_provider)
  396. return result