Friday, May 12, 2023

A CLI script to interact with ChatGPT via API


I built this script to find out how much faster would I be translating from the command line interface (CLI) using ChatGPT API versus translating from its web interface, and I was not disappointed. My new poetry book is coming up in English as well as in Spanish at once. Writing in both languages at the same time is test driven delivery (#TDD) because at the time I am done creating, I am also done with reviewed everything, and therefore it is ready to be shipped to my Editor. Exiting times in front of us with #LLMs. These engines are our best pals when it comes to productivity.
#!/usr/bin/env python3
#
# clichatgpt.py
#
# A CLI script to interact with ChatGPT via API
#
# Nestor Urquiza 20230512
#
import sys
import openai
import os
from sty import fg, rs
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
if OPENAI_API_KEY is None:
print(fg.red + 'ERROR: You must set the OPENAI_API_KEY environment variable.' + fg.rs)
exit(1)
openai.api_key = OPENAI_API_KEY
one_line_content = ''
msgs = []
try:
print(fg.blue + 'Type a session prompt or press enter to skip (will be sent with your next prompts)' + fg.rs)
session_prompt = input()
print(fg.blue + 'Type your prompt and press enter on an empty line to get the response from ChatGPT:' + fg.rs)
for line in sys.stdin:
one_line_content += line
if line == '\n':
if session_prompt != '':
msgs.append({"role": "user", "content": session_prompt})
msgs.append({"role": "user", "content": one_line_content})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages = msgs
)
print(response.choices[0].message.content + '\n')
one_line_content = ''
msgs = []
except KeyboardInterrupt:
print('\n')
exit
view raw clichatgpt.py hosted with ❤ by GitHub

No comments:

Followers