import requests
import json
import sys

KEY = "/home/paul/src/chatgpt/key.txt"

def key():
    with open(KEY) as f:
        return f.read().strip()

# Set up the API endpoint URL and headers
url = "https://api.openai.com/v1/engines/davinci/completions"
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {key()}"
}

# Read the prompt text from stdin
prompt = sys.stdin.read().strip()

# Set up the API request payload
data = {
    "prompt": prompt,
    "temperature": 0.7,
    "max_tokens": 60,
    "top_p": 1,
    "frequency_penalty": 0,
    "presence_penalty": 0
}

# Send the API request
response = requests.post(url, headers=headers, data=json.dumps(data))

# Check if the request was successful
if response.status_code == 200:
    # Parse the response JSON and print the generated text
    json_data = json.loads(response.text)
    generated_text = json_data["choices"][0]["text"].strip()
    print(generated_text)
else:
    print("Error:", response.text)
