Compare commits

..

28 Commits

Author SHA1 Message Date
zhayujie ad7ab088fe docs: update chatgpt sign up tutorial 2023-03-06 22:23:00 +08:00
zhayujie f2ae3e2fd8 Merge pull request #362 from zhayujie/fix-tokens-limit
fix: tokens limit optimization
2023-03-06 00:54:02 +08:00
ubuntu 733f9d1f10 fix: tokens limit optimization 2023-03-06 00:51:53 +08:00
zhayujie 2886f48788 Merge pull request #360 from zwssunny/master
修正会话tokens计算
2023-03-06 00:25:46 +08:00
zwssunny 04078fd4fa Merge branch 'master' of github.com:zwssunny/chatgpt-on-wechat 2023-03-05 22:26:26 +08:00
zhanws 2c2217daad Merge branch 'zhayujie:master' into master 2023-03-05 22:16:26 +08:00
zwssunny 5de600c689 修正会话tokens计算 2023-03-05 22:15:15 +08:00
zhayujie 1d4966b69c docs: update issue template 2023-03-05 19:54:35 +08:00
zwssunny 7ad16731fd scripts/目录有相应的脚本可以启动服务器部署 2023-03-05 17:54:00 +08:00
zhanws 5df341fef2 Merge branch 'zhayujie:master' into master 2023-03-05 17:51:06 +08:00
zwssunny 39a5487f39 openai 接口返回token数量来修剪会话长度 2023-03-05 17:46:35 +08:00
zhayujie 6a98bc2d5a Merge pull request #354 from zwssunny/master
增加处理会话超长问题
2023-03-05 17:23:56 +08:00
zhanws b154dd7e86 Merge branch 'zhayujie:master' into master 2023-03-05 09:51:08 +08:00
zwssunny 3d4d1c734a 增加会话超长问题 2023-03-05 09:43:59 +08:00
zhayujie f10911bc3b Merge branch 'master' of github.com:zhayujie/chatgpt-on-wechat 2023-03-05 01:19:44 +08:00
zhayujie 44e5979a03 docs: update README.md 2023-03-05 01:18:46 +08:00
zhayujie 598bc6569d docs: update README.md 2023-03-05 00:47:40 +08:00
zhayujie d667ccb396 docs: update README.md for proxy 2023-03-05 00:36:20 +08:00
zwssunny efbc9de9d1 增加会话超长处理 2023-03-04 23:44:57 +08:00
zhayujie ebed4e7832 Merge pull request #348 from lanvent/dev
历史对话增加超时释放
2023-03-04 22:20:25 +08:00
zhayujie fb598fba82 Merge pull request #349 from sunxin18/add_more_exception
[feat] catch connection failed exception
2023-03-04 21:51:31 +08:00
lanvent 2c4d79e952 添加会话过期时间 2023-03-04 21:50:18 +08:00
sunxin.181 a2db765ade [feat] catch connection failed exception 2023-03-04 21:43:58 +08:00
lanvent df3f19b534 忽略引用消息 2023-03-04 20:39:24 +08:00
zhayujie f67dae5b0b fix: use default max_token 2023-03-04 17:01:26 +08:00
zhayujie cd5f58ff2c docs: temporarily removed optional config 2023-03-04 12:57:47 +08:00
zhayujie 7be9e7d0a8 Merge pull request #330 from alin299/master
feat:add proxy option
2023-03-04 12:44:04 +08:00
alin 47c675f999 feat:add proxy option 2023-03-03 15:23:14 +08:00
6 changed files with 106 additions and 22 deletions
+2 -2
View File
@@ -1,7 +1,7 @@
### 前置确认
1. 运行于国内网络环境,未开代理
2. python 已安装:版本在 3.7 ~ 3.10 之间,依赖已安装
1. 网络能够访问openai接口 [#351](https://github.com/zhayujie/chatgpt-on-wechat/issues/351)
2. python 已安装:版本在 3.7 ~ 3.10 之间,依赖已安装
3. 在已有 issue 中未搜索到类似问题
4. [FAQS](https://github.com/zhayujie/chatgpt-on-wechat/wiki/FAQs) 中无类似问题
+6 -3
View File
@@ -13,9 +13,9 @@
# 更新日志
>**2023.03.02** 接入[ChatGPT API](https://platform.openai.com/docs/guides/chat) (gpt-3.5-turbo),默认使用该模型进行对话,需升级openai依赖 (`pip3 install --upgrade openai`)
>**2023.03.02** 接入[ChatGPT API](https://platform.openai.com/docs/guides/chat) (gpt-3.5-turbo),默认使用该模型进行对话,需升级openai依赖 (`pip3 install --upgrade openai`)。网络问题参考 [#351](https://github.com/zhayujie/chatgpt-on-wechat/issues/351)
>**2023.02.20** 增加 [python-wechaty](https://github.com/wechaty/python-wechaty) 支持,Pad协议相对稳定,不易封号,但Token收费,可申请七天体验Token (使用参考[#244](https://github.com/zhayujie/chatgpt-on-wechat/pull/244)contributed by [ZQ7](https://github.com/ZQ7))
>**2023.02.20** 增加 [python-wechaty](https://github.com/wechaty/python-wechaty) 作为可选渠道,使用Pad协议相对稳定,但Token收费 (使用参考[#244](https://github.com/zhayujie/chatgpt-on-wechat/pull/244)contributed by [ZQ7](https://github.com/ZQ7))
>**2023.02.09** 扫码登录存在封号风险,请谨慎使用,参考[#58](https://github.com/AutumnWhj/ChatGPT-wechat-bot/issues/158)
@@ -48,7 +48,7 @@
### 1. OpenAI账号注册
前往 [OpenAI注册页面](https://beta.openai.com/signup) 创建账号,参考这篇 [教程](https://freepac.siterubix.com/chatgpt%e6%b3%a8%e5%86%8c%e6%95%99%e7%a8%8b%ef%bc%88%e5%ae%8c%e6%95%b4%e6%8c%87%e5%8d%97%ef%bc%89/) 可以通过虚拟手机号来接收验证码。创建完账号则前往 [API管理页面](https://beta.openai.com/account/api-keys) 创建一个 API Key 并保存下来,后面需要在项目中配置这个key。
前往 [OpenAI注册页面](https://beta.openai.com/signup) 创建账号,参考这篇 [教程](https://www.pythonthree.com/register-openai-chatgpt/) 可以通过虚拟手机号来接收验证码。创建完账号则前往 [API管理页面](https://beta.openai.com/account/api-keys) 创建一个 API Key 并保存下来,后面需要在项目中配置这个key。
> 项目中使用的对话模型是 davinci,计费方式是约每 750 字 (包含请求和回复) 消耗 $0.02,图片生成是每张消耗 $0.016,账号创建有免费的 $18 额度,使用完可以更换邮箱重新注册。
@@ -89,6 +89,7 @@ cp config-template.json config.json
# config.json文件内容示例
{
"open_ai_api_key": "YOUR API KEY", # 填入上面创建的 OpenAI API KEY
"proxy": "127.0.0.1:7890", # 代理客户端的ip和端口
"single_chat_prefix": ["bot", "@bot"], # 私聊时文本需要包含该前缀才能触发机器人回复
"single_chat_reply_prefix": "[bot] ", # 私聊时自动回复的前缀,用于区分真人
"group_chat_prefix": ["@bot"], # 群聊时包含该前缀则会触发机器人回复
@@ -113,6 +114,7 @@ cp config-template.json config.json
**3.其他配置**
+ `proxy`:由于目前 `openai` 接口国内无法访问,需配置代理客户端的地址,详情参考 [#351](https://github.com/zhayujie/chatgpt-on-wechat/issues/351)
+ 对于图像生成,在满足个人或群组触发条件外,还需要额外的关键词前缀来触发,对应配置 `image_create_prefix `
+ 关于OpenAI对话及图片接口的参数配置(内容自由度、回复字数限制、图片大小等),可以参考 [对话接口](https://beta.openai.com/docs/api-reference/completions) 和 [图像接口](https://beta.openai.com/docs/api-reference/completions) 文档直接在 [代码](https://github.com/zhayujie/chatgpt-on-wechat/blob/master/bot/openai/open_ai_bot.py) `bot/openai/open_ai_bot.py` 中进行调整。
+ `conversation_max_tokens`:表示能够记忆的上下文最大字数(一问一答为一组对话,如果累积的对话字数超出限制,就会优先移除最早的一组对话)
@@ -140,6 +142,7 @@ touch nohup.out # 首次运行需要新建日
nohup python3 app.py & tail -f nohup.out # 在后台运行程序并通过日志输出二维码
```
扫码登录后程序即可运行于服务器后台,此时可通过 `ctrl+c` 关闭日志,不会影响后台程序的运行。使用 `ps -ef | grep app.py | grep -v grep` 命令可查看运行于后台的进程,如果想要重新启动程序可以先 `kill` 掉对应的进程。日志关闭后如果想要再次打开只需输入 `tail -f nohup.out`
scripts/目录有相应的脚本可以调用
> **注意:** 如果 扫码后手机提示登录验证需要等待5s,而终端的二维码再次刷新并提示 `Log in time out, reloading QR code`,此时需参考此 [issue](https://github.com/zhayujie/chatgpt-on-wechat/issues/8) 修改一行代码即可解决。
+66 -14
View File
@@ -3,15 +3,22 @@
from bot.bot import Bot
from config import conf
from common.log import logger
from common.expired_dict import ExpiredDict
import openai
import time
user_session = dict()
if conf().get('expires_in_seconds'):
user_session = ExpiredDict(conf().get('expires_in_seconds'))
else:
user_session = dict()
# OpenAI对话模型API (可用)
class ChatGPTBot(Bot):
def __init__(self):
openai.api_key = conf().get('open_ai_api_key')
proxy = conf().get('proxy')
if proxy:
openai.proxy = proxy
def reply(self, query, context=None):
# acquire reply content
@@ -21,6 +28,9 @@ class ChatGPTBot(Bot):
if query == '#清除记忆':
Session.clear_session(from_user_id)
return '记忆已清除'
elif query == '#清除所有':
Session.clear_all_session()
return '所有人记忆已清除'
new_query = Session.build_session_query(query, from_user_id)
logger.debug("[OPEN_AI] session query={}".format(new_query))
@@ -30,29 +40,36 @@ class ChatGPTBot(Bot):
# return self.reply_text_stream(query, new_query, from_user_id)
reply_content = self.reply_text(new_query, from_user_id, 0)
logger.debug("[OPEN_AI] new_query={}, user={}, reply_cont={}".format(new_query, from_user_id, reply_content))
if reply_content:
Session.save_session(query, reply_content, from_user_id)
return reply_content
logger.debug("[OPEN_AI] new_query={}, user={}, reply_cont={}".format(new_query, from_user_id, reply_content["content"]))
if reply_content["completion_tokens"] > 0:
Session.save_session(reply_content["content"], from_user_id, reply_content["total_tokens"])
return reply_content["content"]
elif context.get('type', None) == 'IMAGE_CREATE':
return self.create_img(query, 0)
def reply_text(self, query, user_id, retry_count=0):
def reply_text(self, query, user_id, retry_count=0) ->dict:
'''
call openai's ChatCompletion to get the answer
:param query: query content
:param user_id: from user id
:param retry_count: retry count
:return: {}
'''
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # 对话模型的名称
messages=query,
temperature=0.9, # 值在[0,1]之间,越大表示回复越具有不确定性
max_tokens=1200, # 回复最大的字符数
#max_tokens=4096, # 回复最大的字符数
top_p=1,
frequency_penalty=0.0, # [-2,2]之间,该值越大则更倾向于产生不同的内容
presence_penalty=0.0, # [-2,2]之间,该值越大则更倾向于产生不同的内容
)
# res_content = response.choices[0]['text'].strip().replace('<|endoftext|>', '')
logger.info(response.choices[0]['message']['content'])
# log.info("[OPEN_AI] reply={}".format(res_content))
return response.choices[0]['message']['content']
logger.info("[ChatGPT] reply={}, total_tokens={}".format(response.choices[0]['message']['content'], response["usage"]["total_tokens"]))
return {"total_tokens": response["usage"]["total_tokens"],
"completion_tokens": response["usage"]["completion_tokens"],
"content": response.choices[0]['message']['content']}
except openai.error.RateLimitError as e:
# rate limit exception
logger.warn(e)
@@ -61,12 +78,21 @@ class ChatGPTBot(Bot):
logger.warn("[OPEN_AI] RateLimit exceed, 第{}次重试".format(retry_count+1))
return self.reply_text(query, user_id, retry_count+1)
else:
return "提问太快啦,请休息一下再问我吧"
return {"completion_tokens": 0, "content": "提问太快啦,请休息一下再问我吧"}
except openai.error.APIConnectionError as e:
# api connection exception
logger.warn(e)
logger.warn("[OPEN_AI] APIConnection failed")
return {"completion_tokens": 0, "content":"我连接不到你的网络"}
except openai.error.Timeout as e:
logger.warn(e)
logger.warn("[OPEN_AI] Timeout")
return {"completion_tokens": 0, "content":"我没有收到你的消息"}
except Exception as e:
# unknown exception
logger.exception(e)
Session.clear_session(user_id)
return "请再问我一次吧"
return {"completion_tokens": 0, "content": "请再问我一次吧"}
def create_img(self, query, retry_count=0):
try:
@@ -117,14 +143,40 @@ class Session(object):
return session
@staticmethod
def save_session(query, answer, user_id):
def save_session(answer, user_id, total_tokens):
max_tokens = conf().get("conversation_max_tokens")
if not max_tokens:
# default 3000
max_tokens = 1000
max_tokens=int(max_tokens)
session = user_session.get(user_id)
if session:
# append conversation
gpt_item = {'role': 'assistant', 'content': answer}
session.append(gpt_item)
# discard exceed limit conversation
Session.discard_exceed_conversation(session, max_tokens, total_tokens)
@staticmethod
def discard_exceed_conversation(session, max_tokens, total_tokens):
dec_tokens = int(total_tokens)
# logger.info("prompt tokens used={},max_tokens={}".format(used_tokens,max_tokens))
while dec_tokens > max_tokens:
# pop first conversation
if len(session) > 3:
session.pop(1)
session.pop(1)
else:
break
dec_tokens = dec_tokens - max_tokens
@staticmethod
def clear_session(user_id):
user_session[user_id] = []
@staticmethod
def clear_all_session():
user_session.clear()
+6 -1
View File
@@ -46,6 +46,9 @@ class WechatChannel(Channel):
other_user_id = msg['User']['UserName'] # 对手方id
content = msg['Text']
match_prefix = self.check_prefix(content, conf().get('single_chat_prefix'))
if "\n- - - - - - - - - - - - - - -" in content:
logger.debug("[WX]reference query skipped")
return
if from_user_id == other_user_id and match_prefix is not None:
# 好友向自己发送消息
if match_prefix != '':
@@ -87,7 +90,9 @@ class WechatChannel(Channel):
content = context_special_list[1]
elif len(content_list) == 2:
content = content_list[1]
if "\n- - - - - - - - - - - - - - -" in content:
logger.debug("[WX]reference query skipped")
return ""
config = conf()
match_prefix = (msg['IsAt'] and not config.get("group_at_off", False)) or self.check_prefix(origin_content, config.get('group_chat_prefix')) \
or self.check_contain(origin_content, config.get('group_chat_keyword'))
+23
View File
@@ -0,0 +1,23 @@
from datetime import datetime, timedelta
class ExpiredDict(dict):
def __init__(self, expires_in_seconds):
super().__init__()
self.expires_in_seconds = expires_in_seconds
def __getitem__(self, key):
value, expiry_time = super().__getitem__(key)
if datetime.now() > expiry_time:
del self[key]
raise KeyError("expired {}".format(key))
self.__setitem__(key, value)
return value
def __setitem__(self, key, value):
expiry_time = datetime.now() + timedelta(seconds=self.expires_in_seconds)
super().__setitem__(key, (value, expiry_time))
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
+3 -2
View File
@@ -1,11 +1,12 @@
{
"open_ai_api_key": "YOUR API KEY",
"wechaty_puppet_service_token": "WECHATY PUPPET SERVICE TOKEN",
"proxy": "",
"single_chat_prefix": ["bot", "@bot"],
"single_chat_reply_prefix": "[bot] ",
"group_chat_prefix": ["@bot"],
"group_name_white_list": ["ChatGPT测试群", "ChatGPT测试群2"],
"image_create_prefix": ["画", "看", "找"],
"conversation_max_tokens": 1000,
"character_desc": "你是ChatGPT, 一个由OpenAI训练的大型语言模型, 你旨在回答并解决人们的任何问题,并且可以使用多种语言与人交流。"
"character_desc": "你是ChatGPT, 一个由OpenAI训练的大型语言模型, 你旨在回答并解决人们的任何问题,并且可以使用多种语言与人交流。",
"expires_in_seconds": 3600
}