使用Python调用ChatGPT最新官方API,实现上下文的对话功能
首先是使用Python安装openai官方封装的调用包,并设置自己的api_key。命令如下:
1 2 | pip install openai openai.api_key = 'sk-xxxxxxxxxxxxxxxxxxxxx' |
然后我们设置一下打印的样式和样式。
1 2 3 4 5 6 7 8 9 10 | 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对话接口的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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" ] |
最后我们调用使用该方法进行对话:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)