Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

157 lignes
6.4KB

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