gpt4 book ai didi

php - OpenAI API 错误 : "You didn' t provide an API key. 您需要使用 Bearer auth 在授权 header 中提供您的 API key ”

转载 作者:行者123 更新时间:2023-12-02 05:47:01 27 4
gpt4 key购买 nike

我正在创建一个 PHP 脚本来访问 Open Ai 的 API,提出查询并获得响应。

我收到以下错误:

You didn't provide an API key. You need to provide your API key in anAuthorization header using Bearer auth (i.e. Authorization: BearerYOUR_KEY)

...但我以为我在第一个变量中提供了 API key ?

这是我的代码:

$api_key = "sk-U3B.........7MiL";

$query = "How are you?";

$url = "https://api.openai.com/v1/engines/davinci/jobs";

// Set up the API request headers
$headers = array(
"Content-Type: application/json",
"Authorization: Bearer " . $api_key
);

// Set up the API request body
$data = array(
"prompt" => $query,
"max_tokens" => 100,
"temperature" => 0.5
);

// Use WordPress's built-in HTTP API to send the API request
$response = wp_remote_post( $url, array(
'headers' => $headers,
'body' => json_encode( $data )
) );

// Check if the API request was successful
if ( is_wp_error( $response ) ) {
// If the API request failed, display an error message
echo "Error communicating with OpenAI API: " . $response->get_error_message();
} else {
// If the API request was successful, extract the response text
$response_body = json_decode( $response['body'] );
//$response_text = $response_body->choices[0]->text;
var_dump($response_body);
// Display the response text on the web page
echo $response_body;

最佳答案

全部Engines endpoints已弃用。

Deprecated

这是正确的 Completions endpoint :

https://api.openai.com/v1/completions

工作示例

如果您运行 test.php,OpenAI API 将返回以下完成信息:

string(23) "

This is indeed a test"

test.php

<?php
$ch = curl_init();

$url = 'https://api.openai.com/v1/completions';

$api_key = 'sk-xxxxxxxxxxxxxxxxxxxx';

$post_fields = '{
"model": "text-davinci-003",
"prompt": "Say this is a test",
"max_tokens": 7,
"temperature": 0
}';

$header = [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
];

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);

$response = json_decode($result);
var_dump($response->choices[0]->text);
?>

关于php - OpenAI API 错误 : "You didn' t provide an API key. 您需要使用 Bearer auth 在授权 header 中提供您的 API key ”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75401992/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com