Simple openai API for ChatGPT in Python

Опубликовано: 29 Март 2026
на канале: Learning Channel
113
like

#The python code:

import requests
import json

Load API key from the environment
api_key = "sk-mykey"

Define the endpoint and headers for the API request
url = "https://api.openai.com/v1/engines/tex..."
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
}

Define the prompt and parameters for the API request
prompt = "Why is python a great programming language?"
data = {
"prompt": prompt,
"temperature": 0.7,
"max_tokens": 60,
}

Send the API request to generate text based on the prompt
response = requests.post(url, headers=headers, data=json.dumps(data))

Parse the response JSON and print the generated text
response_json = json.loads(response.text)
#print(response_json)
generated_text = response_json["choices"][0]["text"].strip()
print(generated_text)

#by Szymon Machajewski