Last active
October 29, 2023 20:41
-
-
Save vgmoose/a54408a28189b19501ed1afb7ee8d4e1 to your computer and use it in GitHub Desktop.
ChatGPT example for openAI using the terminal and python directly, and their new API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment