Browse Source

plugin(tool): 新增tool插件

goldfishh 3 years ago
parent
commit
a5f7dec011
4 changed files with 148 additions and 1 deletions
  1. 53 0
      plugins/tool/README.md
  2. 0 0
      plugins/tool/__init__.py
  3. 93 0
      plugins/tool/tool.py
  4. 2 1
      requirements.txt

+ 53 - 0
plugins/tool/README.md

@@ -0,0 +1,53 @@
+## 插件描述
+一个能让chatgpt联网,搜索,数字运算的插件,将赋予强大且丰富的扩展能力  
+### 本插件所有工具同步存放至专用仓库:[chatgpt-tool-hub](https://github.com/goldfishh/chatgpt-tool-hub)
+  
+  
+## 使用说明
+使用该插件后将默认使用4个工具, 无需额外配置长期生效: 
+### 1. python_repl  
+###### python解释器,使用它来解释执行python指令
+  
+### 2. requests
+###### 往往用来获取某个网站具体内容
+
+### 3. terminal
+###### 在你运行的电脑里执行shell命令
+
+### 4. meteo-weather
+###### 回答你有关天气的询问, 本工具使用了[meteo open api](https://open-meteo.com/)
+
+
+## 使用本插件对话(prompt)技巧 
+### 1. 有指引的询问 
+#### 例如:
+- 总结这个链接的内容 https://www.36kr.com/p/2186160784654466 
+- 使用Terminal执行curl cip.cc 
+- 借助python_repl和meteo-weather获取深圳天气情况 
+  
+### 2. 使用搜索引擎工具
+- 如果有这个工具就能让chatgpt在不理解某个问题时去使用  
+  
+  
+## 其他插件
+###### 除上述以外还有其他插件,比如搜索联网、数学运算、百科、新闻需要获取api-key, 
+###### 由于这些插件使用方法暂时还在整理中,如果你不熟悉请不要尝试使用这些工具
+
+
+## config 配置说明
+###### 一个例子
+```json
+{
+  "tools": ["wikipedia"],
+  "kwargs": {
+      "top_k_results": 2
+  }
+}
+```
+- `tools`:本插件初始化时加载的工具, 目前可选集:["wikipedia", "wolfram-alpha", "google-search", "news-api"]
+- `kwargs`:工具执行时的配置,一般在这里存放api-key
+  
+  
+## 备注
+- 请不要使用本插件做危害他人的事情,请自行判断本插件输出内容的真实性
+- 未来一段时间我会实现一些有意思的工具,比如stable diffusion 中文prompt翻译、cv方向的模型推理,欢迎有想法的朋友关注,一起扩展这个项目

+ 0 - 0
plugins/tool/__init__.py


+ 93 - 0
plugins/tool/tool.py

@@ -0,0 +1,93 @@
+import json
+import os
+
+from chatgpt_tool_hub.apps import load_app
+from chatgpt_tool_hub.apps.app import App
+
+import plugins
+from bridge.context import ContextType
+from bridge.reply import Reply, ReplyType
+from common.log import logger
+from config import conf
+from plugins import *
+
+
+@plugins.register(name="tool", desc="Arming your ChatGPT bot with various tools", version="0.1", author="goldfishh", desire_priority=0)
+class Tool(Plugin):
+    def __init__(self):
+        super().__init__()
+        self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
+        os.environ["OPENAI_API_KEY"] = conf().get("open_ai_api_key", "")
+        os.environ["PROXY"] = conf().get("proxy", "")
+
+        self.app = self._reset_app()
+
+        logger.info("[tool] inited")
+
+    def get_help_text(self, **kwargs):
+        help_text = "这是一个能让chatgpt联网,搜索,数字运算的插件,将赋予强大且丰富的扩展能力"
+        return help_text
+
+    def on_handle_context(self, e_context: EventContext):
+        if e_context['context'].type != ContextType.TEXT:
+            return
+
+        content = e_context['context'].content
+        content_list = e_context['context'].content.split(maxsplit=1)
+
+        if not content or len(content_list) < 1:
+            e_context.action = EventAction.CONTINUE
+            return
+
+        logger.debug("[tool] on_handle_context. content: %s" % content)
+        reply = Reply()
+        reply.type = ReplyType.TEXT
+
+        # todo: 有些工具必须要api-key,需要修改config文件,所以这里没有实现query增删tool的功能
+        if content.startswith("$tool"):
+            if len(content_list) == 1:
+                logger.debug("[tool]: get help")
+                reply.content = self.get_help_text()
+                e_context['reply'] = reply
+                e_context.action = EventAction.BREAK_PASS
+                return
+            elif len(content_list) > 1:
+                if content_list[1].strip() == "reset":
+                    logger.debug("[tool]: reset config")
+                    self._reset_app()
+                    reply.content = "重置工具成功"
+                    e_context['reply'] = reply
+                    e_context.action = EventAction.BREAK_PASS
+                    return
+                elif content_list[1].startswith("reset"):
+                    logger.debug("[tool]: remind")
+                    reply.content = "你随机挑一个方式,提醒用户如果想重置tool插件,reset之后不要加任何字符"
+                    e_context['reply'] = reply
+                    e_context.action = EventAction.BREAK
+                    return
+                logger.debug("[tool]: just-go")
+
+                # chatgpt-tool-hub will reply you with many tools
+                # todo: I don't know how to pass someone session into this ask method yet
+                reply.content = self.app.ask(content_list[1])
+                e_context['reply'] = reply
+                e_context.action = EventAction.BREAK_PASS
+        return
+
+    def _read_json(self) -> dict:
+        curdir = os.path.dirname(__file__)
+        config_path = os.path.join(curdir, "config.json")
+        tool_config = {
+            "tools": [],
+            "kwargs": {}
+        }
+        if not os.path.exists(config_path):
+            return tool_config
+        else:
+            with open(config_path, "r") as f:
+                tool_config = json.load(f)
+        return tool_config
+
+    def _reset_app(self) -> App:
+        tool_config = self._read_json()
+        return load_app(tools_list=tool_config.get("tools"), **tool_config.get("kwargs"))

+ 2 - 1
requirements.txt

@@ -13,4 +13,5 @@ wechaty>=0.10.7
 wechaty_puppet>=0.4.23
 chardet>=5.1.0
 SpeechRecognition
-tiktoken>=0.3.2
+tiktoken>=0.3.2
+chatgpt_tool_hub>=0.2.2