我正在创建一个PHP脚本来访问Open Ai的API,以提出查询并获得响应。
我收到以下错误:
您未提供API密钥。您需要使用承载身份验证在授权标头中提供API密钥(即授权:您的钥匙持有人)
...但我以为我在第一个变量中提供了API密钥?
下面是我的代码:
$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;
1条答案
按热度按时间elcex8rz1#
所有Engines endpoints都已弃用。
这是正确的Completions endpoint:
工作示例
如果您在CMD中运行
php test.php
,OpenAI API将返回以下完成:字符串(23)“
这确实是一次考验”
测试.php