Skip to content

Instantly share code, notes, and snippets.

@duplaja
Last active August 1, 2023 22:08
Show Gist options
  • Save duplaja/99308240913c1197587d8b9d9ed1294c to your computer and use it in GitHub Desktop.
Save duplaja/99308240913c1197587d8b9d9ed1294c to your computer and use it in GitHub Desktop.
OpenAI Assistant
#!/usr/bin/env python
import openai
import ast
import os
openai.api_key = 'sk-SAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxj'
userprompt ="""
You can have a multi-line prompt here.
Feel free to use paragraphs, etc.
"""
if os.path.exists("conversation.txt"):
# Read the previous conversation from the text file
with open('conversation.txt', 'r') as file:
content = file.read()
messages = ast.literal_eval(content)
new_user_prompt = {"role":"user", "content":userprompt}
messages.append(new_user_prompt)
else:
messages=[
{"role": "system", "content": "You are a helpful and friendly assistant."},
{"role": "user", "content": userprompt},
]
response = openai.ChatCompletion.create(
model="gpt-4",
messages=messages,
)
response_message = response["choices"][0]["message"]
total_tokens = response["usage"]["total_tokens"]
response_text = response_message["content"]
response_role = response_message["role"]
formatted_response = {"role": response_role, "content": response_text}
messages.append(formatted_response)
# Write the conversation to a text file
with open('conversation.txt', 'w') as file:
file.write(str(messages))
#print(responselength)
#print(str(total_tokens))
#print(messages)
print(response_text)
@duplaja
Copy link
Author

duplaja commented May 3, 2023

Basic, command line python3 script to interface with OpenAI GPT.

  • Set OpenAI key (line 7)

  • userprompt is your prompt you want to send. (Line 9)

  • Set any particulars for the role you want GPT to play ( Line 27)

  • Set the GPT model, gpt-3.5-turbo or gpt-4 (Line 32)

  • Creates an ongoing conversation history. This is written (raw) to conversation.txt, created in the same directory you run this script in. To reset your conversation history, delete or rename conversation.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment