nonebot插件之chatgpt使用詳解
前言
今天我要教大家的是 如何實現(xiàn)nonebot插件之ChatGpt
注意,本文涉及異步爬蟲,json文件讀寫等知識點
準備
1.獲取開發(fā)者key
獲取key的地址:Account API Keys - OpenAI API
如圖所示,我已經(jīng)創(chuàng)建好一個key了,大家也可以點擊Create new secret key
按鈕來創(chuàng)建一個新的key,注意,千萬不要泄露自己的key哦
2.魔法
在獲取key的過程我們還是需要用到魔法的,且代理必須為國外的,只要key搞到手,后續(xù)的步驟就不用用到魔法了
開始
1.找接口
之前我原本是想要教大家去對接OpenAI的官方接口的,但是想到大部分同學可能不會“魔法”,如果沒有“魔法”體驗感會大打折扣,所以我們就要借助其他大佬幫助我們完成代理這個過程
在網(wǎng)上沖浪的時候,我發(fā)現(xiàn)了這個寶藏網(wǎng)站 GPT3.5 (cutim.top)
可以看到這個網(wǎng)站是需要我們提供key的,我這里淺淺解釋一下本次程序的主要思路
整體思路大概就是這樣
到這里,大家應(yīng)該都有key了吧,我們打開剛才的網(wǎng)站,按F12打開開發(fā)者調(diào)試工具
在這里我們可以看到請求的api地址: gpt.cutim.top/question
我們可以看到他是post請求
那么我們打開源分析,不難看出數(shù)據(jù)就是json格式,且有兩個參數(shù),一個key
,一個question
既然我們已經(jīng)找到接口了,那么下一步就是重頭戲——寫代碼了
2.快樂的敲代碼
先上猛料
from nonebot import on_keyword from nonebot.typing import T_State from nonebot.adapters.onebot.v11 import GroupMessageEvent, Bot, Message import httpx import json ''' 實現(xiàn)qq群聊調(diào)用chatgpt write by 萌新源 at 2023/3/5 ''' chatgpt = on_keyword({"#gpt"}) @chatgpt.handle() async def yy(bot: Bot, event: GroupMessageEvent, state: T_State): get_msg = str(event.message).strip() # 獲取用戶發(fā)送的鏈接 user_question = get_msg.strip("#gpt") msg_id = event.message_id # 獲取消息id user_id = event.user_id file_name = "chatgpt.json" try: with open(file_name, "r", encoding="UTF-8") as f: person_data = json.load(f) # 讀取數(shù)據(jù) try: user_data = person_data[str(user_id)] except KeyError: user_data = "" form_data = {'key': '填寫你自己的key', 'question': user_data + f"----{user_question}"} async with httpx.AsyncClient() as client: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE' } url = f"http://gpt.cutim.top/question" data = await client.post(url=url, headers=headers, json=form_data, timeout=None) # 請求數(shù)據(jù) response = data.json() try: # 規(guī)避內(nèi)容獲取失敗 res_ai = str(response['content']) try: user_data = person_data[str(user_id)] + f"----{user_question}" question = user_data + f'\n{res_ai}' person_data[str(user_id)] = question except KeyError: person_data[str(user_id)] = f'----{user_question}' with open(file_name, "w", encoding="UTF-8") as f: json.dump(person_data, f, ensure_ascii=False) ai_res = str(response['content']).strip("\n") except KeyError: # 重置會話 person_data[user_id] = "" with open(file_name, "w", encoding="UTF-8") as f: json.dump(person_data, f, ensure_ascii=False) ai_res = '很抱歉,內(nèi)容獲取失敗,請確認您的問題沒有非法成分,如沒有可能是您的會話歷史已達到上限,請更換您的提問方式或再試一次' except FileNotFoundError: with open(file_name, "w", encoding="UTF-8") as f: json.dump({user_id: f'----{user_question}'}, f, ensure_ascii=False) form_data = {'key': '填寫你自己的key', 'question': user_question} async with httpx.AsyncClient() as client: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE' } url = f"http://gpt.cutim.top/question" data = await client.post(url=url, headers=headers, json=form_data, timeout=None) # 請求數(shù)據(jù) response = data.json() ai_res = str(response['content']).strip("\n") res = f"[CQ:reply,id={msg_id}]{ai_res}" await chatgpt.send(Message(res))
這里我也是直接上全部代碼
接下來我挑一些我認為比較有研究價值的代碼出來講講
try: with open(file_name, "r", encoding="UTF-8") as f: #① person_data = json.load(f) # 讀取數(shù)據(jù) try: user_data = person_data[str(user_id)] except KeyError: user_data = "" form_data = {'key': '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', 'question': user_data + f"----{user_question}"}
比如這一段,在①這個地方,我讀取了一個用來儲存用戶會話的json文件,那么可能有人會問了,為什么要讀取這樣一個文件呢?或者說這個文件有什么作用?
其實在早期版本沒有會話文件的時候,經(jīng)過群友的測試,我發(fā)現(xiàn)了一個小問題,那就是對話不連續(xù),比如說我要跟gpt玩成語接龍,但是會話是不連續(xù)的呀,于是我就找到了用一個文件儲存用戶會話的方法,文件結(jié)構(gòu)大概是這樣
就是把每個人的會話數(shù)據(jù)分別儲存起來,這樣對話就有了連續(xù)性
連續(xù)性問題是解決了,但是又產(chǎn)生了一個新的問題——會話太長,gpt不知道怎么回答或者說是無法正常獲取內(nèi)容,那又怎么辦,于是我想到了下面的方法來解決這個問題
try: # 規(guī)避內(nèi)容獲取失敗 res_ai = str(response['content']) try: user_data = person_data[str(user_id)] + f"----{user_question}" question = user_data + f'\n{res_ai}' person_data[str(user_id)] = question except KeyError: person_data[str(user_id)] = f'----{user_question}' with open(file_name, "w", encoding="UTF-8") as f: json.dump(person_data, f, ensure_ascii=False) ai_res = str(response['content']).strip("\n") except KeyError: # 重置會話 person_data[user_id] = "" with open(file_name, "w", encoding="UTF-8") as f: json.dump(person_data, f, ensure_ascii=False) ai_res = '很抱歉,內(nèi)容獲取失敗,請確認您的問題沒有非法成分,如沒有可能是您的會話歷史已達到上限,請更換您的提問方式或再試一次'
可以看到,我這里寫了個try語句,當獲取內(nèi)容失敗的時候就把會話清空,并且返回一個提示信息給用戶,好讓用戶重新提問
以上就是我認為需要講解的代碼部分了,相信大家是可以看懂我的思路的,哦對,記得替換key
更多關(guān)于nonebot插件chatgpt的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
在CentOS上配置Nginx+Gunicorn+Python+Flask環(huán)境的教程
這篇文章主要介紹了在CentOS上配置Nginx+Gunicorn+Python+Flask環(huán)境的教程,包括安裝supervisor來管理進程的用法,整套配下來相當實用,需要的朋友可以參考下2016-06-06在Django的form中使用CSS進行設(shè)計的方法
這篇文章主要介紹了在Django的form中使用CSS進行設(shè)計的方法,Django是Python重多人氣開發(fā)框架中最為著名的一個,需要的朋友可以參考下2015-07-07Keras構(gòu)建神經(jīng)網(wǎng)絡(luò)踩坑(解決model.predict預測值全為0.0的問題)
這篇文章主要介紹了Keras構(gòu)建神經(jīng)網(wǎng)絡(luò)踩坑(解決model.predict預測值全為0.0的問題),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07一行python實現(xiàn)樹形結(jié)構(gòu)的方法
今天小編就為大家分享一篇一行python實現(xiàn)樹形結(jié)構(gòu)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08Linux-ubuntu16.04 Python3.5配置OpenCV3.2的方法
下面小編就為大家分享一篇Linux-ubuntu16.04 Python3.5配置OpenCV3.2的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04