Skip to content

Instantly share code, notes, and snippets.

@enukane
Last active March 2, 2023 07:19
Show Gist options
  • Save enukane/6d00a5705d15be4f9951144818b681a4 to your computer and use it in GitHub Desktop.
Save enukane/6d00a5705d15be4f9951144818b681a4 to your computer and use it in GitHub Desktop.
Single conversation with ChatGPT API
#!/usr/bin/env python3
import openai
import pit
import sys
openai.api_key = pit.Pit.get("openai")['api_key']
roles = ["assistant", "user"]
def request_response(msg, history):
entry = {"role": "user", "content": msg}
if history == None or len(history) == 0:
history = [ entry ]
else:
history.append(entry)
result = openai.ChatCompletion.create(
model = "gpt-3.5-turbo",
messages = history
)
resp_msg = None
for choice in result["choices"]:
if "message" in choice:
resp_msg = choice["message"]
break
resp_content = resp_msg["content"].strip()
history.append({
"role": "assistant",
"content": resp_content
})
return resp_content, history
history = []
while True:
try:
msg = input("#> ")
if len(msg.strip()) == 0:
continue
resp, history = request_response(msg, history)
print("==========")
print(resp)
print("==========")
except EOFError:
print("INFO: exiting")
break
#!/usr/bin/env python3
import openai
import pit
import sys
openai.api_key = pit.Pit.get("openai")['api_key']
roles = ["assistant", "user"]
past_messages = [
{ "role": "user", "content": sys.argv[1]}
]
result = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages = past_messages
)
resp_content = None
for choice in result["choices"]:
if "message" in choice:
resp_content = choice["message"]["content"]
break
print("AI: {}".format(resp_content))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment