диалог с chatgpt из ide консоли
Не получается вести диалог с chatgpt из под ide консоли. Выдаёт ошибку 401
def send_message(api_url, api_token, message):
headers = {
"Authorization": "Bearer _тут api токен_" + api_token }
data = {
"text": message}
# Make a request to the API with the message and API token as parameters
response = requests.post(api_url, headers=headers, json=data)
# Check the response from the API
if response.status_code == 200:
# If the request is successful, print the response text
print(response.json()["text"])
else:
# If the request is unsuccessful, print an error message
print("Failed to send message. Error code: " +
str(response.status_code))
if
__name__ == "__main__":
model_name = "text-davinci-003"
api_url = f"https://api.openai.com/v1/engines/{model_name}/chat"
api_token = "тут api токен"
message = input("Enter a message to send: ")
# Call the send_message function to send the message
send_message(api_url, api_token, message)
Ответы (1 шт):
Автор решения: gfd2
→ Ссылка
Строка с токеном должна выглядеть так: "Bearer {api_key}". В переменной api_key хранится токен.
Вот немного другой рабочий вариант кода:
import requests
# API
url = "https://api.openai.com/v1/engines/text-davinci-003/completions"
# API(токен)
api_key = "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"
prompt = "Привет бот!"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
# API request data
data = {
"prompt": prompt,
"temperature": 0.5,
"max_tokens": 1024,
"n": 1,
"stop": None,
}
# Отправляем запрос
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
print(response.json()["choices"][0]["text"])
else:
print(f"Error: {response.text}")