openapi_function_tool.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from app.models.action import Action
  2. from app.core.tools.base_tool import BaseTool
  3. from app.exceptions.exception import ResourceNotFoundError
  4. from app.services.tool.openapi_call import call_action_api
  5. from app.schemas.tool.action import ActionMethod, ActionBodyType
  6. from app.services.tool.openapi_utils import action_param_dict_to_schema
  7. from app.schemas.tool.authentication import Authentication
  8. class OpenapiFunctionTool(BaseTool):
  9. """
  10. openapi tool, definition as follows:
  11. {'id': '65d6c295a09d481250cc8ed1', 'type': 'action'}
  12. """
  13. name = ""
  14. description = ""
  15. args_schema = None
  16. action: Action = None
  17. def __init__(self, definition: dict, extra_body: dict, action: Action) -> None:
  18. if definition["type"] != "action" or "id" not in definition:
  19. raise ValueError(f"definition format error: {definition}")
  20. # an exception is thrown if no action is found
  21. if action is None:
  22. raise ResourceNotFoundError(message="action not found")
  23. if not action.use_for_everyone:
  24. action_authentications = extra_body.get("action_authentications")
  25. if action_authentications:
  26. authentication = action_authentications.get(action.id)
  27. if authentication:
  28. action.authentication = authentication
  29. else:
  30. action.authentication = {"type": "none"}
  31. self.action = action
  32. self.openai_function = {"type": "function", "function": action.function_def}
  33. self.name = action.function_def["name"]
  34. def run(self, **arguments: dict) -> dict:
  35. action = self.action
  36. response = call_action_api(
  37. url=action.url,
  38. method=ActionMethod(action.method),
  39. path_param_schema=action_param_dict_to_schema(action.path_param_schema),
  40. query_param_schema=action_param_dict_to_schema(action.query_param_schema),
  41. body_param_schema=action_param_dict_to_schema(action.body_param_schema),
  42. body_type=ActionBodyType(action.body_type),
  43. parameters=arguments,
  44. headers={},
  45. authentication=Authentication(**action.authentication),
  46. )
  47. return response