#!/usr/bin/env python import requests # replace with API key from https://platform.openai.com/account/api-keys API_KEY = "YOUR API KEY HERE" TONE = "friendly" BOT_NAME = "AI" YOUR_NAME = "Human" DEFAULT_PROMPT = f"You are a {TONE} chat bot named {BOT_NAME}, talking to {YOUR_NAME} and trying to assist them. Try your best to give a helpful response, and directly answer questions or tasks." # this function sends the text verabtim to the openai endpoint # it may need an initial prompt to get the conversation going def send_to_gpt(messages): # talk to the openai endpoint and make a request # https://beta.openai.com/docs/api-reference/completions/create headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json", } data = { "messages": messages, "model": "gpt-3.5-turbo", } r = requests.post( "https://api.openai.com/v1/chat/completions", headers=headers, json=data, ) if "choices" not in r.json(): print("Error: ", r.json()) return "" return r.json()["choices"][0]["message"]["content"] # An example of using a loop to keep track of previous messages and have a back and forth conversation messages = [] messages.append({ "role": "system", "content": DEFAULT_PROMPT }) while True: messages.append({ "role": "user", "content": input(YOUR_NAME + ": ") }) response = send_to_gpt(messages) print(BOT_NAME + ": " + response) messages.append({ "role": "assistant", "content": response })