반응형
curl 사용 코드
<?php
// Your OpenAI API key
$api_key = 'your-api-key';
$data_string = json_encode([
'prompt' => 'Translate this sentence into French: "{text}"',
'max_tokens' => 60
]);
$ch = curl_init('https://api.openai.com/v1/engines/davinci-codex/completions');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key,
'Content-Length: ' . strlen($data_string)
));
$result = curl_exec($ch);
$response = json_decode($result, true);
// print result
echo $response['choices'][0]['text'];
?>
GuzzleHttp 사용 코드
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
// Your OpenAI API key
$api_key = 'your-api-key';
$data = [
'prompt' => 'Translate this sentence into French: "{text}"',
'max_tokens' => 60
];
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://api.openai.com',
// You can set any number of default request options.
'timeout' => 2.0,
]);
$response = $client->request('POST', '/v1/engines/davinci-codex/completions', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key,
],
'json' => $data
]);
$body = $response->getBody();
$arr_body = json_decode($body, true);
echo $arr_body['choices'][0]['text'];
?>
max_tokens => 60은 결과로 반환될 토큰의 최대 수를 지정
davinci-codex/completions는 OpenAI의 GPT-3엔진에 대한 요청을 보내는 엔드포인트로 GPT-4 또는 다른 엔진을 사용하려면 해당 엔진의 엔드포인트를 사용해야 한다.
API키는 OpenAI의 웹사이트(https://platform.openai.com/account/api-keys)에서 발급할 수 있다.
반응형
'DEVEL > PHP' 카테고리의 다른 글
PHP 이더리움 주소 검증 (0) | 2024.01.19 |
---|---|
PHP 비트코인 주소 검증 (0) | 2024.01.19 |
PHP Bitcoin Core - 비트코인(BTC) 전송 (0) | 2023.07.06 |
PHP Coinbase API를 사용해서 비트코인(BTC) 전송 (0) | 2023.07.06 |
PHP Google 인증 토큰 유효성 체크 (0) | 2023.04.11 |