PHP code example of softcreatr / php-perplexity-ai-sdk
1. Go to this page and download the library: Download softcreatr/php-perplexity-ai-sdk library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
softcreatr / php-perplexity-ai-sdk example snippets
use SoftCreatR\PerplexityAI\PerplexityAI;
$apiKey = 'your_api_key';
// Replace these lines with your chosen PSR-17 and PSR-18 compatible HTTP client and factories
$httpClient = new YourChosenHttpClient();
$requestFactory = new YourChosenRequestFactory();
$streamFactory = new YourChosenStreamFactory();
$uriFactory = new YourChosenUriFactory();
$pplx = new PerplexityAI($requestFactory, $streamFactory, $uriFactory, $httpClient, $apiKey);
$response = $pplx->createChatCompletion([
'model' => 'llama-3.1-sonar-small-128k-online',
'messages' => [
[
'role' => 'system',
'content' => 'Be precise and concise.'
],
[
'role' => 'user',
'content' => 'How many stars are there in our galaxy?'
]
],
]);
// Process the API response
if ($response->getStatusCode() === 200) {
$responseObj = json_decode($response->getBody()->getContents(), true);
print_r($responseObj);
} else {
echo "Error: " . $response->getStatusCode();
}
$streamCallback = static function ($data) {
if (isset($data['choices'][0]['delta']['content'])) {
echo $data['choices'][0]['delta']['content'];
}
};
$pplx->createChatCompletion(
[
'model' => 'llama-3.1-sonar-small-128k-online',
'messages' => [
[
'role' => 'user',
'content' => 'Tell me a story about a brave knight.',
],
],
'stream' => true,
],
$streamCallback
);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.