api_tools_manage_service.py 17 KB

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