You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

176 line
7.0KB

  1. import json
  2. import os
  3. from chatgpt_tool_hub.apps import AppFactory
  4. from chatgpt_tool_hub.apps.app import App
  5. from chatgpt_tool_hub.tools.all_tool_list import get_all_tool_names
  6. import plugins
  7. from bridge.bridge import Bridge
  8. from bridge.context import ContextType
  9. from bridge.reply import Reply, ReplyType
  10. from common import const
  11. from common.log import logger
  12. from config import conf
  13. from plugins import *
  14. @plugins.register(
  15. name="tool",
  16. desc="Arming your ChatGPT bot with various tools",
  17. version="0.4",
  18. author="goldfishh",
  19. desire_priority=0,
  20. )
  21. class Tool(Plugin):
  22. def __init__(self):
  23. super().__init__()
  24. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  25. self.app = self._reset_app()
  26. logger.info("[tool] inited")
  27. def get_help_text(self, verbose=False, **kwargs):
  28. help_text = "这是一个能让chatgpt联网,搜索,数字运算的插件,将赋予强大且丰富的扩展能力。"
  29. if not verbose:
  30. return help_text
  31. trigger_prefix = conf().get("plugin_trigger_prefix", "$")
  32. help_text += "使用说明:\n"
  33. help_text += f"{trigger_prefix}tool " + "命令: 根据给出的{命令}使用一些可用工具尽力为你得到结果。\n"
  34. help_text += f"{trigger_prefix}tool reset: 重置工具。\n"
  35. return help_text
  36. def on_handle_context(self, e_context: EventContext):
  37. if e_context["context"].type != ContextType.TEXT:
  38. return
  39. # 暂时不支持未来扩展的bot
  40. if Bridge().get_bot_type("chat") not in (
  41. const.CHATGPT,
  42. const.OPEN_AI,
  43. const.CHATGPTONAZURE,
  44. ):
  45. return
  46. content = e_context["context"].content
  47. content_list = e_context["context"].content.split(maxsplit=1)
  48. if not content or len(content_list) < 1:
  49. e_context.action = EventAction.CONTINUE
  50. return
  51. logger.debug("[tool] on_handle_context. content: %s" % content)
  52. reply = Reply()
  53. reply.type = ReplyType.TEXT
  54. trigger_prefix = conf().get("plugin_trigger_prefix", "$")
  55. # todo: 有些工具必须要api-key,需要修改config文件,所以这里没有实现query增删tool的功能
  56. if content.startswith(f"{trigger_prefix}tool"):
  57. if len(content_list) == 1:
  58. logger.debug("[tool]: get help")
  59. reply.content = self.get_help_text()
  60. e_context["reply"] = reply
  61. e_context.action = EventAction.BREAK_PASS
  62. return
  63. elif len(content_list) > 1:
  64. if content_list[1].strip() == "reset":
  65. logger.debug("[tool]: reset config")
  66. self.app = self._reset_app()
  67. reply.content = "重置工具成功"
  68. e_context["reply"] = reply
  69. e_context.action = EventAction.BREAK_PASS
  70. return
  71. elif content_list[1].startswith("reset"):
  72. logger.debug("[tool]: remind")
  73. e_context["context"].content = "请你随机用一种聊天风格,提醒用户:如果想重置tool插件,reset之后不要加任何字符"
  74. e_context.action = EventAction.BREAK
  75. return
  76. query = content_list[1].strip()
  77. # Don't modify bot name
  78. all_sessions = Bridge().get_bot("chat").sessions
  79. user_session = all_sessions.session_query(query, e_context["context"]["session_id"]).messages
  80. # chatgpt-tool-hub will reply you with many tools
  81. logger.debug("[tool]: just-go")
  82. try:
  83. _reply = self.app.ask(query, user_session)
  84. e_context.action = EventAction.BREAK_PASS
  85. all_sessions.session_reply(_reply, e_context["context"]["session_id"])
  86. except Exception as e:
  87. logger.exception(e)
  88. logger.error(str(e))
  89. e_context["context"].content = "请你随机用一种聊天风格,提醒用户:这个问题tool插件暂时无法处理"
  90. reply.type = ReplyType.ERROR
  91. e_context.action = EventAction.BREAK
  92. return
  93. reply.content = _reply
  94. e_context["reply"] = reply
  95. return
  96. def _read_json(self) -> dict:
  97. curdir = os.path.dirname(__file__)
  98. config_path = os.path.join(curdir, "config.json")
  99. tool_config = {"tools": [], "kwargs": {}}
  100. if not os.path.exists(config_path):
  101. return tool_config
  102. else:
  103. with open(config_path, "r") as f:
  104. tool_config = json.load(f)
  105. return tool_config
  106. def _build_tool_kwargs(self, kwargs: dict):
  107. tool_model_name = kwargs.get("model_name")
  108. request_timeout = kwargs.get("request_timeout")
  109. return {
  110. "debug": kwargs.get("debug", False),
  111. "openai_api_key": conf().get("open_ai_api_key", ""),
  112. "proxy": conf().get("proxy", ""),
  113. "request_timeout": request_timeout if request_timeout else conf().get("request_timeout", 120),
  114. # note: 目前tool暂未对其他模型测试,但这里仍对配置来源做了优先级区分,一般插件配置可覆盖全局配置
  115. "model_name": tool_model_name if tool_model_name else conf().get("model", "gpt-3.5-turbo"),
  116. "no_default": kwargs.get("no_default", False),
  117. "top_k_results": kwargs.get("top_k_results", 3),
  118. # for news tool
  119. "news_api_key": kwargs.get("news_api_key", ""),
  120. # for bing-search tool
  121. "bing_subscription_key": kwargs.get("bing_subscription_key", ""),
  122. # for google-search tool
  123. "google_api_key": kwargs.get("google_api_key", ""),
  124. "google_cse_id": kwargs.get("google_cse_id", ""),
  125. # for searxng-search tool
  126. "searx_host": kwargs.get("searx_host", ""),
  127. # for wolfram-alpha tool
  128. "wolfram_alpha_appid": kwargs.get("wolfram_alpha_appid", ""),
  129. # for morning-news tool
  130. "zaobao_api_key": kwargs.get("zaobao_api_key", ""),
  131. # for visual_dl tool
  132. "cuda_device": kwargs.get("cuda_device", "cpu"),
  133. }
  134. def _filter_tool_list(self, tool_list: list):
  135. valid_list = []
  136. for tool in tool_list:
  137. if tool in get_all_tool_names():
  138. valid_list.append(tool)
  139. else:
  140. logger.warning("[tool] filter invalid tool: " + repr(tool))
  141. return valid_list
  142. def _reset_app(self) -> App:
  143. tool_config = self._read_json()
  144. app_kwargs = self._build_tool_kwargs(tool_config.get("kwargs", {}))
  145. app = AppFactory()
  146. app.init_env(**app_kwargs)
  147. # filter not support tool
  148. tool_list = self._filter_tool_list(tool_config.get("tools", []))
  149. return app.create_app(tools_list=tool_list, **app_kwargs)