首页 > 编程语言 >使用Python调用ChatGPT最新官方API,实现上下文的对话功能

使用Python调用ChatGPT最新官方API,实现上下文的对话功能

时间:2023-03-05 18:11:27浏览次数:33  
标签:Python list API role ans msg ChatGPT message history

首先是使用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"

标签:Python,list,API,role,ans,msg,ChatGPT,message,history
From: https://www.cnblogs.com/wzf-Learning/p/17181183.html

相关文章

  • Vue3组合式API学习笔记
    setup方法与script_setup及ref响应式setup方法与script_setup在Vue3.1版本的时候,提供了setup方法;而在Vue3.2版本的时候,提供了script_setup属性。那么setup属性比setup方......
  • Python 字符串详解
    Python访问字符串中的值:Python访问子字符串,可以使用方括号来截取字符串,如下实例:#!/usr/bin/python#coding:UFT-8var1='HelloWorld!'var2="PythonRunoob"print"var......
  • Python 文件处理方法详解
    打开和关闭文件:open函数:打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写。语法:fileobject=open(file_name[,access_mode][,buffering])#各个参数的细节......
  • python操作mysql
    1、mysql查询操作:#!/usr/bin/python#-*-coding:UTF-8-*-importMySQLdb#打开数据库连接db=MySQLdb.connect("localhost","root","111111","analysis2")#使用cursor......
  • python beautifulsoup 安装教程
    linux版:pipinstallbeautifulsoup4windows版:下载beautifulsoup安装包下载地址:​​​http://www.cr173.com/soft/109251.html​​​下载解压后,将文件夹放到C:/Pyth......
  • python装饰器
    装饰器本质上是一个Python函数(其实就是闭包),它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。装饰器用于有以下场景,比如:插......
  • CSS-8.CSS浏览器兼容性写法,了解不同API在不同浏览器下的兼容性情况
    -moz代表firefox浏览器私有属性-ms代表IE浏览器私有属性-webkit代表chrome、safari私有属性-o代表opera私有属性-webkit-transform:rotate(-3deg);/*为Chrome/Safa......
  • 在线图书借阅网站( Python +Vue 实现)
    功能介绍平台采用B/S结构,后端采用主流的Python语言进行开发,前端采用主流的Vue.js进行开发。整个平台包括前台和后台两个部分。前台功能包括:首页、图书详情页、用户中心......
  • python 循环结构 for循环 输出1到100的数值
    """for循环语法:foriinrange(起点包含,终点不包含):要重复做的事情"""foriinrange(1,101):print(i)......
  • python 循环结构 for循环遍历列表 输出所有列表成员
    """for临时变量in列表:处理临时变量"""li=["刘备","关羽","张飞"]print("准备欢迎每个同学")fornameinli:print(name,"你好")......