Przeglądaj źródła

feat: bring in openai completion api

zhayujie 3 lat temu
rodzic
commit
e5e0979bfa

+ 41 - 27
README.md

@@ -1,61 +1,61 @@
 # 简介
 
-本项目是基于ChatGPT模型实现的微信聊天机器人,通过[revChatGPT](https://github.com/acheong08/ChatGPT) 访问 ChatGPT接口,使用 [itchat](https://github.com/littlecodersh/ItChat) 实现微信消息的接收和发送。已实现的功能如下:
+本项目是基于ChatGPT模型实现的微信聊天机器人,通过 [OpenAI](https://github.com/acheong08/ChatGPT) 访提供的API,使用 [itchat](https://github.com/littlecodersh/ItChat) 实现微信消息的接收和发送。已实现的功能如下:
 
 - [x] **基础功能:** 接收私聊及群组中的微信消息,使用ChatGPT生成回复内容,完成自动回复
 - [x] **规则定制化:** 支持私聊中按指定规则触发自动回复,支持对群组设置自动回复白名单
-- [x] **会话上下文:** 支持用户维度的上下文保存和过期清理
-- [x] **Session刷新:** 支持ChatGPT session的定时刷新保鲜
 - [x] **多账号:** 支持多微信账号同时运行
- 
- 
+- [ ] **会话上下文:** 支持用户维度的上下文记忆
+
+# 更新
+> **2022.12.17:**  原来的方案是从 [ChatGPT页面](https://chat.openai.com/chat) 获取session_token,使用 [revChatGPT](https://github.com/acheong08/ChatGPT) 直接访问web接口,但随着ChatGPT接入Cloudflare人机验证,这一方案难以在服务器顺利运行。 所以目前使用的方案是调用 OpenAI 官方提供的 [API](https://beta.openai.com/docs/api-reference/introduction),劣势是暂不支持有上下文记忆的对话、且回复内容的智能性上相比ChatGPT稍差一些,优势是稳定性和响应速度较好。
+
+
 # 快速开始
 
 ## 准备
-###  1.网页版微信
+### 1.网页版微信
 
 本方案中实现微信消息的收发依赖了网页版微信的登录,可以尝试登录 <https://wx.qq.com/>,如果能够成功登录就可以开始后面的步骤了。
 
-### 2.运行环境
+### 2. OpenAI账号注册
+
+前往 [OpenAI注册页面](https://beta.openai.com/signup) 创建账号,参考这篇 [博客](https://www.cnblogs.com/damugua/p/16969508.html) 可以通过虚拟手机号来接收验证码。创建完账号则前往 [API管理页面](https://beta.openai.com/account/api-keys) 创建一个 API Key 并保存下来,后面需要在项目中配置这个key。 
+
+> 项目中使用的对话模型是 davinci,计费方式是每1k字 (包含请求和回复) 消耗 $0.02,账号创建有免费的 $18 额度,使用完可以更换邮箱重新注册。
 
-操作系统支持 Linux、MacOS、Windows,并需安装 `Python3.6` 及以上版本。推荐使用Linux服务器,可以托管在后台长期运行。
 
-### 3.项目安装
+### 3.运行环境
 
-克隆本项目代码:
+支持运行在 Linux、MacOS、Windows 操作系统上,需安装 `Python3.6` 及以上版本。推荐使用Linux服务器,可以托管在后台长期运行。
+
+克隆项目代码:
 
 ```bash
 https://github.com/zhayujie/chatgpt-on-wechat
 ```
 
-安装所需依赖:
+安装所需核心依赖:
 
 ```bash
-pip3 install revChatGPT
 pip3 install itchat
+pip3 install openai
 ```
 
-
 ## 配置
 
-配置文件在根目录的 `config.json` 中,示例文件及各配置项解析如下: (TODO)
+配置文件在根目录的 `config.json` 中,示例文件及各配置项含义如下:
 
 ```bash
 { 
-  "session_token": "YOUR SESSION TOKEN",           # 从页面获取的token
-  "single_chat_prefix": ["bot", "@bot"],           # 私聊触发自动回复的前缀
-  "group_chat_prefix": ["@bot"],                   # 群聊触发自动回复的前缀
-  "group_name_white_list": ["群名称1", "群名称2"]    # 开启自动回复的群名称
+  "open_ai_api_key": "${YOUR API KEY}$"                      # 上面在创建的 API KEY
+  "single_chat_prefix": ["bot", "@bot"],                     # 私聊时文本需要包含该前缀才能触发机器人回复
+  "single_chat_reply_prefix": "[bot] ",                      # 私聊时自动回复的前缀,用于区分真人
+  "group_chat_prefix": ["@bot"],                             # 群聊时包含该前缀则会触发机器人回复
+  "group_name_white_list": ["ChatGPT测试群", "ChatGPT测试群2"] # 开启自动回复的群名称列表
 }
 ```
-
-其中 session_token 需要在openAI网页端获取:
-
-- 打开 <https://chat.openai.com/chat> 并登录,可使用测试账号 (lgfo353p@linshiyouxiang.net, 密码yy123123),账号来源为该[文章](https://www.bilibili.com/read/cv20257021)
-- F12 进入开发者控制台
-- 选择Application -> Cookies,将 session-token 中的值填入配置中
-
-![](docs/images/chatgpt-token.png)
+关于OpenAI对话接口的参数配置,可以参考 [接口文档](https://beta.openai.com/docs/api-reference/completions) 直接在代码 `bot\openai\open_ai_bot.py` 中进行调整。
 
 
 ## 运行
@@ -71,8 +71,22 @@ python3 app.py
 2.如果是服务器部署,则使用nohup在后台运行:
 
 ```
-nohup python3 app.py &
+nohup python3 app.py & tail -f nohup.out
 ```
+同样在扫码后程序即可运行于后台。
+
 
 ## 使用
 
+### 个人聊天
+
+![single-chat-sample.jpg](docs/images/single-chat-sample.jpg)
+
+默认配置中,个人聊天会以 "bot" 或 "@bot" 为开头的内容触发机器人,对应配置中的 `single_chat_prefix`;机器人回复的内容会以 "[bot]" 作为前缀, 以区分真人,对应的配置为 `single_chat_reply_prefix`。
+
+
+### 群组聊天
+
+![group-chat-sample.jpg](docs/images/group-chat-sample.jpg)
+
+群名称需要配置在 `group_name_white_list ` 中才能开启群聊自动回复,默认只要被@就会触发机器人自动回复,另外群聊天中只要检测到以 "@bot" 开头的内容,同样会自动回复,这对应配置 `group_chat_prefix`。

+ 1 - 0
bot/baidu/baidu_unit_bot.py

@@ -4,6 +4,7 @@ import requests
 from bot.bot import Bot
 
 
+# Baidu Unit对话接口 (可用, 但能力较弱)
 class BaiduUnitBot(Bot):
     def reply(self, query, context=None):
         token = self.get_token()

+ 10 - 3
bot/bot_factory.py

@@ -2,9 +2,6 @@
 channel factory
 """
 
-from bot.baidu.baidu_unit_bot import BaiduUnitBot
-from bot.chatgpt.chat_gpt_bot import ChatGPTBot
-
 
 def create_bot(bot_type):
     """
@@ -13,7 +10,17 @@ def create_bot(bot_type):
     :return: channel instance
     """
     if bot_type == 'baidu':
+        # Baidu Unit对话接口
+        from bot.baidu.baidu_unit_bot import BaiduUnitBot
         return BaiduUnitBot()
+
     elif bot_type == 'chatGPT':
+        # ChatGPT 网页端web接口
+        from bot.chatgpt.chat_gpt_bot import ChatGPTBot
         return ChatGPTBot()
+
+    elif bot_type == 'openAI':
+        # OpenAI 官方对话模型API
+        from bot.openai.open_ai_bot import OpenAIBot
+        return OpenAIBot()
     raise RuntimeError

+ 2 - 0
bot/chatgpt/chat_gpt_bot.py

@@ -7,6 +7,8 @@ from config import conf
 user_session = dict()
 last_session_refresh = time.time()
 
+
+# ChatGPT web接口 (暂时不可用)
 class ChatGPTBot(Bot):
     def __init__(self):
         config = {

+ 30 - 0
bot/openai/open_ai_bot.py

@@ -0,0 +1,30 @@
+from bot.bot import Bot
+from config import conf
+from common.log import logger
+import openai
+
+
+# OpenAI对话模型API (可用)
+class OpenAIBot(Bot):
+    def __init__(self):
+        openai.api_key = conf().get('open_ai_api_key')
+
+    def reply(self, query, context=None):
+        logger.info("[OPEN_AI] query={}".format(query))
+        try:
+            response = openai.Completion.create(
+                model="text-davinci-003",      #对话模型的名称
+                prompt=query,
+                temperature=0.9,               #值在[0,1]之间,越大表示回复越具有不确定性
+                max_tokens=1200,               #回复最大的字符数
+                top_p=1,
+                frequency_penalty=0.0,         #[-2,2]之间,该值越大则更倾向于产生不同的内容
+                presence_penalty=0.2,          #[-2,2]之间,该值越大则更倾向于产生不同的内容
+                stop=["#"]
+            )
+            res_content = response.choices[0]["text"].strip()
+        except Exception as e:
+            logger.error(e)
+            return None
+        logger.info("[OPEN_AI] reply={}".format(res_content))
+        return res_content

+ 1 - 1
bridge/bridge.py

@@ -6,4 +6,4 @@ class Bridge(object):
         pass
 
     def fetch_reply_content(self, query, context):
-        return bot_factory.create_bot("chatGPT").reply(query, context)
+        return bot_factory.create_bot("openAI").reply(query, context)

+ 19 - 10
channel/wechat/wechat_channel.py

@@ -36,20 +36,25 @@ class WechatChannel(Channel):
     def handle(self, msg):
         logger.info("[WX]receive msg: " + json.dumps(msg, ensure_ascii=False))
         from_user_id = msg['FromUserName']
+        to_user_id = msg['ToUserName']
         other_user_id = msg['User']['UserName']
         content = msg['Text']
         if from_user_id == other_user_id and \
-                self.check_prefix(content, conf().get('group_chat_prefix')):
+                self.check_prefix(content, conf().get('single_chat_prefix')):
             str_list = content.split('bot', 1)
             if len(str_list) == 2:
                 content = str_list[1].strip()
             thead_pool.submit(self._do_send, content, from_user_id)
-
+        elif to_user_id == other_user_id and \
+                self.check_prefix(content, conf().get('single_chat_prefix')):
+            str_list = content.split('bot', 1)
+            if len(str_list) == 2:
+                content = str_list[1].strip()
+            thead_pool.submit(self._do_send, content, to_user_id)
 
 
     def handle_group(self, msg):
         logger.info("[WX]receive group msg: " + json.dumps(msg, ensure_ascii=False))
-        group_id = msg['User']['UserName']
         group_name = msg['User'].get('NickName', None)
         if not group_name:
             return ""
@@ -72,18 +77,22 @@ class WechatChannel(Channel):
         logger.info('[WX] sendMsg={}, receiver={}'.format(msg, receiver))
         itchat.send(msg, toUserName=receiver)
 
-    def _do_send(self, send_msg, reply_user_id):
+    def _do_send(self, query, reply_user_id):
+        if not query:
+            return
         context = dict()
         context['from_user_id'] = reply_user_id
-        content = super().build_reply_content(send_msg, context)
-        if content:
-            self.send("[bot] " + content, reply_user_id)
+        reply_text = super().build_reply_content(query, context).strip()
+        if reply_text:
+            self.send(conf().get("single_chat_reply_prefix") + reply_text, reply_user_id)
 
-    def _do_send_group(self, content, msg):
+    def _do_send_group(self, query, msg):
+        if not query:
+            return
         context = dict()
         context['from_user_id'] = msg['ActualUserName']
-        reply_text = super().build_reply_content(content, context)
-        reply_text = '@' + msg['ActualNickName'] + ' ' + reply_text
+        reply_text = super().build_reply_content(query, context)
+        reply_text = '@' + msg['ActualNickName'] + ' ' + reply_text.strip()
         if reply_text:
             self.send(reply_text, msg['User']['UserName'])
 

Plik diff jest za duży
+ 0 - 0
config.json


BIN
docs/images/chatgpt-token.png


BIN
docs/images/group-chat-sample.jpg


BIN
docs/images/single-chat-sample.jpg


Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików