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.

179 lines
7.3KB

  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 config import conf
  12. from plugins import *
  13. @plugins.register(
  14. name="tool",
  15. desc="Arming your ChatGPT bot with various tools",
  16. version="0.4",
  17. author="goldfishh",
  18. desire_priority=0,
  19. )
  20. class Tool(Plugin):
  21. def __init__(self):
  22. super().__init__()
  23. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  24. self.app = self._reset_app()
  25. logger.info("[tool] inited")
  26. def get_help_text(self, verbose=False, **kwargs):
  27. help_text = "这是一个能让chatgpt联网,搜索,数字运算的插件,将赋予强大且丰富的扩展能力。"
  28. trigger_prefix = conf().get("plugin_trigger_prefix", "$")
  29. if not verbose:
  30. return help_text
  31. help_text += "\n使用说明:\n"
  32. help_text += f"{trigger_prefix}tool " + "命令: 根据给出的{命令}使用一些可用工具尽力为你得到结果。\n"
  33. help_text += f"{trigger_prefix}tool reset: 重置工具。\n\n"
  34. help_text += f"已加载工具列表: \n"
  35. for idx, tool in enumerate(self.app.get_tool_list()):
  36. if idx != 0:
  37. help_text += ", "
  38. help_text += f"{tool}"
  39. return help_text
  40. def on_handle_context(self, e_context: EventContext):
  41. if e_context["context"].type != ContextType.TEXT:
  42. return
  43. # 暂时不支持未来扩展的bot
  44. if Bridge().get_bot_type("chat") not in (
  45. const.CHATGPT,
  46. const.OPEN_AI,
  47. const.CHATGPTONAZURE,
  48. const.LINKAI,
  49. ):
  50. return
  51. content = e_context["context"].content
  52. content_list = e_context["context"].content.split(maxsplit=1)
  53. if not content or len(content_list) < 1:
  54. e_context.action = EventAction.CONTINUE
  55. return
  56. logger.debug("[tool] on_handle_context. content: %s" % content)
  57. reply = Reply()
  58. reply.type = ReplyType.TEXT
  59. trigger_prefix = conf().get("plugin_trigger_prefix", "$")
  60. # todo: 有些工具必须要api-key,需要修改config文件,所以这里没有实现query增删tool的功能
  61. if content.startswith(f"{trigger_prefix}tool"):
  62. if len(content_list) == 1:
  63. logger.debug("[tool]: get help")
  64. reply.content = self.get_help_text()
  65. e_context["reply"] = reply
  66. e_context.action = EventAction.BREAK_PASS
  67. return
  68. elif len(content_list) > 1:
  69. if content_list[1].strip() == "reset":
  70. logger.debug("[tool]: reset config")
  71. self.app = self._reset_app()
  72. reply.content = "重置工具成功"
  73. e_context["reply"] = reply
  74. e_context.action = EventAction.BREAK_PASS
  75. return
  76. elif content_list[1].startswith("reset"):
  77. logger.debug("[tool]: remind")
  78. e_context["context"].content = "请你随机用一种聊天风格,提醒用户:如果想重置tool插件,reset之后不要加任何字符"
  79. e_context.action = EventAction.BREAK
  80. return
  81. query = content_list[1].strip()
  82. # Don't modify bot name
  83. all_sessions = Bridge().get_bot("chat").sessions
  84. user_session = all_sessions.session_query(query, e_context["context"]["session_id"]).messages
  85. # chatgpt-tool-hub will reply you with many tools
  86. logger.debug("[tool]: just-go")
  87. try:
  88. _reply = self.app.ask(query, user_session)
  89. e_context.action = EventAction.BREAK_PASS
  90. all_sessions.session_reply(_reply, e_context["context"]["session_id"])
  91. except Exception as e:
  92. logger.exception(e)
  93. logger.error(str(e))
  94. e_context["context"].content = "请你随机用一种聊天风格,提醒用户:这个问题tool插件暂时无法处理"
  95. reply.type = ReplyType.ERROR
  96. e_context.action = EventAction.BREAK
  97. return
  98. reply.content = _reply
  99. e_context["reply"] = reply
  100. return
  101. def _read_json(self) -> dict:
  102. default_config = {"tools": [], "kwargs": {}}
  103. return super().load_config() or default_config
  104. def _build_tool_kwargs(self, kwargs: dict):
  105. tool_model_name = kwargs.get("model_name")
  106. request_timeout = kwargs.get("request_timeout")
  107. return {
  108. "debug": kwargs.get("debug", False),
  109. "openai_api_key": conf().get("open_ai_api_key", ""),
  110. "open_ai_api_base": conf().get("open_ai_api_base", "https://api.openai.com/v1"),
  111. "deployment_id": conf().get("azure_deployment_id", ""),
  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_search_host": kwargs.get("searx_search_host", ""),
  127. # for wolfram-alpha tool
  128. "wolfram_alpha_appid": kwargs.get("wolfram_alpha_appid", ""),
  129. # for morning-news tool
  130. "morning_news_api_key": kwargs.get("morning_news_api_key", ""),
  131. # for visual_dl tool
  132. "cuda_device": kwargs.get("cuda_device", "cpu"),
  133. "think_depth": kwargs.get("think_depth", 3),
  134. "arxiv_summary": kwargs.get("arxiv_summary", True),
  135. "morning_news_use_llm": kwargs.get("morning_news_use_llm", False),
  136. }
  137. def _filter_tool_list(self, tool_list: list):
  138. valid_list = []
  139. for tool in tool_list:
  140. if tool in get_all_tool_names():
  141. valid_list.append(tool)
  142. else:
  143. logger.warning("[tool] filter invalid tool: " + repr(tool))
  144. return valid_list
  145. def _reset_app(self) -> App:
  146. tool_config = self._read_json()
  147. app_kwargs = self._build_tool_kwargs(tool_config.get("kwargs", {}))
  148. app = AppFactory()
  149. app.init_env(**app_kwargs)
  150. # filter not support tool
  151. tool_list = self._filter_tool_list(tool_config.get("tools", []))
  152. return app.create_app(tools_list=tool_list, **app_kwargs)