Mock ChatGPT with gpt-3 5-turbo


Mock ChatGPT with gpt-3.5-turbo

With Stream

import openai
class chatGPT():
    def __init__(self):
        self.openaiKey = openai.api_key = "sk-<your api key>"
        self.messages = [{"role": "system", "content": "assistant"}]
        self.username = "username"
        
        
    def generateContent(self, inPut):
        self.messages.append({"role": "user", "content": inPut})
        response = openai.ChatCompletion.create(
                    model="gpt-3.5-turbo",
                    messages = self.messages,
                    user = self.username,
                    stream = True
                    )
        
        sentence = ""
        print("response")
        for i in response:
            if 'content' in i['choices'][0]['delta']:
                sentence += i['choices'][0]['delta']['content']
                print(i['choices'][0]['delta']['content'],end = '',flush=True)
        print("")
        self.messages.append({"role": "user", "content": sentence})

    
# user = input("please assign a username.\n")
# print("")
# role = input("Please assign a role to assistant.\n")
chat = chatGPT()
print("")
while 1:
    userInput = input("Prompt\n")
    print("")
    if userInput == "end":
        break
    chat.generateContent(userInput)
    print("")

without Stream

import openai
class chatapp():
    def __init__(self, role):
        self.openaiKey = openai.api_key = "sk-<your api key>"
        self.messages = [{"role": "system", "content": role}]
        
        
    def generateContent(self, inPut):
        self.messages.append({"role": "user", "content": inPut})
        response = openai.ChatCompletion.create(
                    model="gpt-3.5-turbo",
                    messages = self.messages
                    
                    )
        self.messages.append({"role": "user", "content": response['choices'][0]['message']['content']})
        print("assistant\n" + response['choices'][0]['message']['content'])
role = input("Please assign a role to assistant.\n")
chat = chatapp(role)
print("")
while 1:
    userInput = input("Prompt\n")
    print("")
    if userInput == "end":
        break
    chat.generateContent(userInput)
    print("")

Author: Happy
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source Happy !
  TOC