Skip to content

Instantly share code, notes, and snippets.

@edwardbeckett
Forked from mouredev/chatgpt_api.py
Last active April 3, 2023 06:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edwardbeckett/17de5e57c485a9a6a213f6e771e72404 to your computer and use it in GitHub Desktop.
Save edwardbeckett/17de5e57c485a9a6a213f6e771e72404 to your computer and use it in GitHub Desktop.
Python ChatGPT API
import os # stash our key in the env
import openai # pip install openai
import typer # pip install "typer[all]"
from rich import print # pip install rich
from rich.table import Table
"""
Reference:
- OpenAI Module: https://github.com/openai/openai-python
- ChatGPT API Docs: https://platform.openai.com/docs/api-reference/chat
- Typer: https://typer.tiangolo.com
- Rich: https://rich.readthedocs.io/en/stable/
"""
def main():
# "Get your `OPENAI_API_KEY` & `OPENAI_API_ORG` @: https://platform.openai.com"
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.organization = os.getenv("OPENAI_API_ORG")
print("💬 [bold green] Python ChatGPT API[/bold green]")
table = Table("Command", "Description")
table.add_row("exit", "Exit the app.")
table.add_row("new", "Start a new chat topic.")
print(table)
# Provide context..
context = {"role": "system",
"content": "You are a smart, sexy, fun and flirtatious young lady who's thoughtful and helpful and you always provide supportive dialog and clarifying questions to qualify your tasks. You are a master at providing support to anyone that needs your assistance and you execute with absolute precision and care. You are the incumbent subject matter expert on enterprise software engineering, enterprise architecture, microservices, cloud based and cloud native technologies and you provide throughly researched and proven methodologies using induction proofs and references from machine learning, data structures and algorithms, probability, statistics, business intelligence and analytics."}
messages = [context]
while True:
content = __prompt()
if content == "new":
print("🆕 Conversation created")
messages = [context]
content = __prompt()
messages.append({"role": "user", "content": content})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", messages=messages)
response_content = response.choices[0].message.content
messages.append({"role": "assistant", "content": response_content})
print(f"[bold green]> [/bold green] [green]{response_content}[/green]")
def __prompt() -> str:
prompt = typer.prompt("\nSo, what's up?")
if prompt == "exit":
exit = typer.confirm("✋ Really?")
if exit:
print("👋 Aight... see ya.")
raise typer.Abort()
return __prompt()
return prompt
if __name__ == "__main__":
typer.run(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment