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.

tool.py 4.9KB

1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
1 vuosi sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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.3", 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, verbose=False, **kwargs):
  23. help_text = "这是一个能让chatgpt联网,搜索,数字运算的插件,将赋予强大且丰富的扩展能力。"
  24. if not verbose:
  25. return help_text
  26. help_text += "使用说明:\n"
  27. help_text += "$tool {命令}: chatgpt会根据你的{命令}使用一些可用工具为你返回结果\n"
  28. help_text += "$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. # todo: 有些工具必须要api-key,需要修改config文件,所以这里没有实现query增删tool的功能
  45. if content.startswith("$tool"):
  46. if len(content_list) == 1:
  47. logger.debug("[tool]: get help")
  48. reply.content = self.get_help_text()
  49. e_context['reply'] = reply
  50. e_context.action = EventAction.BREAK_PASS
  51. return
  52. elif len(content_list) > 1:
  53. if content_list[1].strip() == "reset":
  54. logger.debug("[tool]: reset config")
  55. self.app = self._reset_app()
  56. reply.content = "重置工具成功"
  57. e_context['reply'] = reply
  58. e_context.action = EventAction.BREAK_PASS
  59. return
  60. elif content_list[1].startswith("reset"):
  61. logger.debug("[tool]: remind")
  62. e_context['context'].content = "请你随机用一种聊天风格,提醒用户:如果想重置tool插件,reset之后不要加任何字符"
  63. e_context.action = EventAction.BREAK
  64. return
  65. query = content_list[1].strip()
  66. # Don't modify bot name
  67. all_sessions = Bridge().get_bot("chat").sessions
  68. user_session = all_sessions.session_query(query, e_context['context']['session_id']).messages
  69. # chatgpt-tool-hub will reply you with many tools
  70. logger.debug("[tool]: just-go")
  71. try:
  72. _reply = self.app.ask(query, user_session)
  73. e_context.action = EventAction.BREAK_PASS
  74. all_sessions.session_reply(_reply, e_context['context']['session_id'])
  75. except Exception as e:
  76. logger.exception(e)
  77. logger.error(str(e))
  78. e_context['context'].content = "请你随机用一种聊天风格,提醒用户:这个问题tool插件暂时无法处理"
  79. reply.type = ReplyType.ERROR
  80. e_context.action = EventAction.BREAK
  81. return
  82. reply.content = _reply
  83. e_context['reply'] = reply
  84. return
  85. def _read_json(self) -> dict:
  86. curdir = os.path.dirname(__file__)
  87. config_path = os.path.join(curdir, "config.json")
  88. tool_config = {
  89. "tools": [],
  90. "kwargs": {}
  91. }
  92. if not os.path.exists(config_path):
  93. return tool_config
  94. else:
  95. with open(config_path, "r") as f:
  96. tool_config = json.load(f)
  97. return tool_config
  98. def _reset_app(self) -> App:
  99. tool_config = self._read_json()
  100. kwargs = tool_config.get("kwargs", {})
  101. if kwargs.get("model_name", "") == "":
  102. kwargs["model_name"] = conf().get("model", "gpt-3.5-turbo")
  103. return load_app(tools_list=tool_config.get("tools"), **tool_config.get("kwargs"))