调用ChatGPT接口完成聊天任务
下面的代码调用ChatGPT的ChatCompletion接口实现聊天任务,生成的结果如下图打印的信息所示。而且,在封装Conversation class中,message一直使用append进行追加,即每次调用ChatCompletion接口时都传入了聊天的上下文信息,这里为了节省tokens的消耗,设置了只记住最近的三轮问题。所以在问第一个问题“what is first question I asked?”,chatgpt能准确回答出第一个问的问题。
import openai
import os
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.environ.get("OPENAI_API_KEY")
class Conversation2:
def __init__(self, prompt, num_of_round):
self.prompt = prompt
self.num_of_round = num_of_round
self.messages = []
self.messages.append({"role": "system", "content": self.prompt})
def ask(self, question):
try:
self.messages.append({"role": "user", "content": question})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=self.messages,
temperature=0.5,
max_tokens=2048,
top_p=1,
)
except Exception as e:
print(e)
return e
message = response["choices"][0]["message"]["content"]
num_of_tokens = response['usage']['total_tokens']
self.messages.append({"role": "assistant", "content": message})
if len(self.messages) > self.num_of_round*2 + 1:
del self.messages[1:3]
return message, num_of_tokens
prompt = """you are a ai assistor"""
conv2 = Convers