181 linhas
7.1KB

  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[
  74. "context"
  75. ].content = "请你随机用一种聊天风格,提醒用户:如果想重置tool插件,reset之后不要加任何字符"
  76. e_context.action = EventAction.BREAK
  77. return
  78. query = content_list[1].strip()
  79. # Don't modify bot name
  80. all_sessions = Bridge().get_bot("chat").sessions
  81. user_session = all_sessions.session_query(
  82. query, e_context["context"]["session_id"]
  83. ).messages
  84. # chatgpt-tool-hub will reply you with many tools
  85. logger.debug("[tool]: just-go")
  86. try:
  87. _reply = self.app.ask(query, user_session)
  88. e_context.action = EventAction.BREAK_PASS
  89. all_sessions.session_reply(
  90. _reply, e_context["context"]["session_id"]
  91. )
  92. except Exception as e:
  93. logger.exception(e)
  94. logger.error(str(e))
  95. e_context["context"].content = "请你随机用一种聊天风格,提醒用户:这个问题tool插件暂时无法处理"
  96. reply.type = ReplyType.ERROR
  97. e_context.action = EventAction.BREAK
  98. return
  99. reply.content = _reply
  100. e_context["reply"] = reply
  101. return
  102. def _read_json(self) -> dict:
  103. curdir = os.path.dirname(__file__)
  104. config_path = os.path.join(curdir, "config.json")
  105. tool_config = {"tools": [], "kwargs": {}}
  106. if not os.path.exists(config_path):
  107. return tool_config
  108. else:
  109. with open(config_path, "r") as f:
  110. tool_config = json.load(f)
  111. return tool_config
  112. def _build_tool_kwargs(self, kwargs: dict):
  113. tool_model_name = kwargs.get("model_name")
  114. request_timeout = kwargs.get("request_timeout")
  115. return {
  116. "debug": kwargs.get("debug", False),
  117. "openai_api_key": conf().get("open_ai_api_key", ""),
  118. "proxy": conf().get("proxy", ""),
  119. "request_timeout": request_timeout if request_timeout else conf().get("request_timeout", 120),
  120. # note: 目前tool暂未对其他模型测试,但这里仍对配置来源做了优先级区分,一般插件配置可覆盖全局配置
  121. "model_name": tool_model_name if tool_model_name else conf().get("model", "gpt-3.5-turbo"),
  122. "no_default": kwargs.get("no_default", False),
  123. "top_k_results": kwargs.get("top_k_results", 3),
  124. # for news tool
  125. "news_api_key": kwargs.get("news_api_key", ""),
  126. # for bing-search tool
  127. "bing_subscription_key": kwargs.get("bing_subscription_key", ""),
  128. # for google-search tool
  129. "google_api_key": kwargs.get("google_api_key", ""),
  130. "google_cse_id": kwargs.get("google_cse_id", ""),
  131. # for searxng-search tool
  132. "searx_host": kwargs.get("searx_host", ""),
  133. # for wolfram-alpha tool
  134. "wolfram_alpha_appid": kwargs.get("wolfram_alpha_appid", ""),
  135. # for morning-news tool
  136. "zaobao_api_key": kwargs.get("zaobao_api_key", ""),
  137. # for visual_dl tool
  138. "cuda_device": kwargs.get("cuda_device", "cpu"),
  139. }
  140. def _filter_tool_list(self, tool_list: list):
  141. valid_list = []
  142. for tool in tool_list:
  143. if tool in get_all_tool_names():
  144. valid_list.append(tool)
  145. else:
  146. logger.warning("[tool] filter invalid tool: " + repr(tool))
  147. return valid_list
  148. def _reset_app(self) -> App:
  149. tool_config = self._read_json()
  150. app_kwargs = self._build_tool_kwargs(tool_config.get("kwargs", {}))
  151. app = AppFactory()
  152. app.init_env(**app_kwargs)
  153. # filter not support tool
  154. tool_list = self._filter_tool_list(tool_config.get("tools", []))
  155. return app.create_app(tools_list=tool_list, **app_kwargs)