Requirements:
Python 3.7…1 - 3.9.x
OpenAI latest version (pip install --upgrade openai)
Here is a working chatbot demo I wrote as instructional that shows:
- construction of role messages
- proper use of chat API
- chat history with rudimentary management of past turns
- streaming words and parsing the delta chunks of the stream
- no error handling of API errors
import openai
openai.api_key = "sk-12341234"
system = [{"role": "system",
"content": """You are chatbot who enjoys weather talk."""}]
user = [{"role": "user", "content": "brief introduction?"}]
chat = []
while not user[0]['content'] == "exit":
response = openai.ChatCompletion.create(
messages = system + chat[-20:] + user,
model="gpt-3.5-turbo", temperature=0.1, stream=True)
reply = ""
for delta in response:
if not delta['choices'][0]['finish_reason']:
word = delta['choices'][0]['delta']['content']
reply += word
print(word, end ="")
chat += user + [{"role": "assistant", "content": reply}]
user = [{"role": "user", "content": input("\nPrompt: ")}]
Hopefully you find what you need and can expand from there.
( I also have print function that will word wrap to a line length and others where the scope of “example” is lost )