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.

115 lines
4.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. import plugins
  6. from bridge.bridge import Bridge
  7. from bridge.context import ContextType
  8. from bridge.reply import Reply, ReplyType
  9. from common import const
  10. from common.log import logger
  11. from config import conf
  12. from plugins import *
  13. @plugins.register(name="tool", desc="Arming your ChatGPT bot with various tools", version="0.2", author="goldfishh", desire_priority=0)
  14. class Tool(Plugin):
  15. def __init__(self):
  16. super().__init__()
  17. self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
  18. os.environ["OPENAI_API_KEY"] = conf().get("open_ai_api_key", "")
  19. os.environ["PROXY"] = conf().get("proxy", "")
  20. self.app = self._reset_app()
  21. logger.info("[tool] inited")
  22. def get_help_text(self, **kwargs):
  23. help_text = "这是一个能让chatgpt联网,搜索,数字运算的插件,将赋予强大且丰富的扩展能力"
  24. return help_text
  25. def on_handle_context(self, e_context: EventContext):
  26. if e_context['context'].type != ContextType.TEXT:
  27. return
  28. # 暂时不支持未来扩展的bot
  29. if Bridge().get_bot_type("chat") not in (const.CHATGPT, const.OPEN_AI, const.CHATGPTONAZURE):
  30. return
  31. content = e_context['context'].content
  32. content_list = e_context['context'].content.split(maxsplit=1)
  33. if not content or len(content_list) < 1:
  34. e_context.action = EventAction.CONTINUE
  35. return
  36. logger.debug("[tool] on_handle_context. content: %s" % content)
  37. reply = Reply()
  38. reply.type = ReplyType.TEXT
  39. # todo: 有些工具必须要api-key,需要修改config文件,所以这里没有实现query增删tool的功能
  40. if content.startswith("$tool"):
  41. if len(content_list) == 1:
  42. logger.debug("[tool]: get help")
  43. reply.content = self.get_help_text()
  44. e_context['reply'] = reply
  45. e_context.action = EventAction.BREAK_PASS
  46. return
  47. elif len(content_list) > 1:
  48. if content_list[1].strip() == "reset":
  49. logger.debug("[tool]: reset config")
  50. self.app = self._reset_app()
  51. reply.content = "重置工具成功"
  52. e_context['reply'] = reply
  53. e_context.action = EventAction.BREAK_PASS
  54. return
  55. elif content_list[1].startswith("reset"):
  56. logger.debug("[tool]: remind")
  57. reply.content = "请你随机用一种聊天风格,提醒用户:如果想重置tool插件,reset之后不要加任何字符"
  58. e_context['reply'] = reply
  59. e_context.action = EventAction.BREAK
  60. return
  61. query = content_list[1].strip()
  62. # Don't modify bot name
  63. all_sessions = Bridge().get_bot("chat").sessions
  64. user_session = all_sessions.session_query(query, e_context['context']['session_id'])
  65. # chatgpt-tool-hub will reply you with many tools
  66. logger.debug("[tool]: just-go")
  67. try:
  68. _reply = self.app.ask(content_list[1], user_session)
  69. e_context.action = EventAction.BREAK_PASS
  70. except ValueError as e:
  71. logger.exception(e)
  72. logger.error(str(e))
  73. _reply = "请你随机用一种聊天风格,提醒用户:这个问题你无法处理"
  74. reply.type = ReplyType.ERROR
  75. e_context.action = EventAction.BREAK
  76. reply.content = _reply
  77. e_context['reply'] = reply
  78. return
  79. def _read_json(self) -> dict:
  80. curdir = os.path.dirname(__file__)
  81. config_path = os.path.join(curdir, "config.json")
  82. tool_config = {
  83. "tools": [],
  84. "kwargs": {}
  85. }
  86. if not os.path.exists(config_path):
  87. return tool_config
  88. else:
  89. with open(config_path, "r") as f:
  90. tool_config = json.load(f)
  91. return tool_config
  92. def _reset_app(self) -> App:
  93. tool_config = self._read_json()
  94. return load_app(tools_list=tool_config.get("tools"), **tool_config.get("kwargs"))