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.

1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. trigger_prefix = conf().get("plugin_trigger_prefix", "$")
  30. if not verbose:
  31. return help_text
  32. help_text += "\n使用说明:\n"
  33. help_text += f"{trigger_prefix}tool " + "命令: 根据给出的{命令}使用一些可用工具尽力为你得到结果。\n"
  34. help_text += f"{trigger_prefix}tool reset: 重置工具。\n\n"
  35. help_text += f"已加载工具列表: \n"
  36. for idx, tool in enumerate(self.app.get_tool_list()):
  37. if idx != 0:
  38. help_text += ", "
  39. help_text += f"{tool}"
  40. return help_text
  41. def on_handle_context(self, e_context: EventContext):
  42. if e_context["context"].type != ContextType.TEXT:
  43. return
  44. # 暂时不支持未来扩展的bot
  45. if Bridge().get_bot_type("chat") not in (
  46. const.CHATGPT,
  47. const.OPEN_AI,
  48. const.CHATGPTONAZURE,
  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. curdir = os.path.dirname(__file__)
  103. config_path = os.path.join(curdir, "config.json")
  104. tool_config = {"tools": [], "kwargs": {}}
  105. if not os.path.exists(config_path):
  106. return tool_config
  107. else:
  108. with open(config_path, "r") as f:
  109. tool_config = json.load(f)
  110. return tool_config
  111. def _build_tool_kwargs(self, kwargs: dict):
  112. tool_model_name = kwargs.get("model_name")
  113. request_timeout = kwargs.get("request_timeout")
  114. return {
  115. "debug": kwargs.get("debug", False),
  116. "openai_api_key": conf().get("open_ai_api_key", ""),
  117. "open_ai_api_base": conf().get("open_ai_api_base", "https://api.openai.com/v1"),
  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_search_host": kwargs.get("searx_search_host", ""),
  133. # for wolfram-alpha tool
  134. "wolfram_alpha_appid": kwargs.get("wolfram_alpha_appid", ""),
  135. # for morning-news tool
  136. "morning_news_api_key": kwargs.get("morning_news_api_key", ""),
  137. # for visual_dl tool
  138. "cuda_device": kwargs.get("cuda_device", "cpu"),
  139. "think_depth": kwargs.get("think_depth", 3),
  140. "arxiv_summary": kwargs.get("arxiv_summary", True),
  141. "morning_news_use_llm": kwargs.get("morning_news_use_llm", False),
  142. }
  143. def _filter_tool_list(self, tool_list: list):
  144. valid_list = []
  145. for tool in tool_list:
  146. if tool in get_all_tool_names():
  147. valid_list.append(tool)
  148. else:
  149. logger.warning("[tool] filter invalid tool: " + repr(tool))
  150. return valid_list
  151. def _reset_app(self) -> App:
  152. tool_config = self._read_json()
  153. app_kwargs = self._build_tool_kwargs(tool_config.get("kwargs", {}))
  154. app = AppFactory()
  155. app.init_env(**app_kwargs)
  156. # filter not support tool
  157. tool_list = self._filter_tool_list(tool_config.get("tools", []))
  158. return app.create_app(tools_list=tool_list, **app_kwargs)