首先是使用Python安裝openai官方封裝的調用包,並設置自己的api_key。命令如下:
pip install openai openai.api_key='sk-xxxxxxxxxxxxxxxxxxxxx'
然後我們設置一下打印的樣式和樣式。
class bcolors: # 文本顏色 GREEN = '\033[92m' BLUE = '\033[94m' def print_w(s): #打印文本,內容寬度設置 width = 150 while len(s) > width: print(f'{s[:width]:<{width}}') s = s[width:] print(s)
然後我們封裝一個調使用chatgpt對話接口的方法
def chatGPT_api(list_msg,list_ans,message): # API調用函數 # 設置system role system_role = "\u5C06\u6587\u672C\u7FFB\u8BD1\u4E3A\u82F1\u8BED" #@param {type:"string",title:""} send_msg=[{"role":"system","content": system_role}] # 讀取歷史對話記錄 for i in range(len(list_msg)): _msg={"role":"user","content": list_msg[i]} send_msg.append(_msg) _ans={"role":"assistant","content": list_ans[i]} send_msg.append(_ans) # 準備用戶的新消息 _msg={"role":"user","content": message} send_msg.append(_msg) # 調用API,返回結果 response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=send_msg ) #返回結果 return response["choices"][0]["message"]["content"]
最後我們調用使用該方法進行對話:
def main(): # 歷史對話記錄列表 history_list_msg=[] history_list_ans=[] while(True): # 等待用戶輸入 print(f"👧 {bcolors.GREEN}", end="") message = input() # 調用API,返回結果 answer = chatGPT_api(history_list_msg, history_list_ans, message) print(f"⚛️ {bcolors.BLUE}") print_w(answer) history_list_msg.append(message) history_list_ans.append(answer) if __name__ == "__main__": main()
以上就簡單實現了基於上下文的對話功能,但是還有很多地方需要優化的,比如歷史消息保存條數的設置,避免消耗大量的token等等,當然這些還需要大家去優化。源碼地址:GitHub