### Install PerplexityAI SDK via Composer Source: https://github.com/softcreatr/php-perplexity-ai-sdk/blob/main/README.md Installs the PerplexityAI PHP SDK using Composer, a dependency manager for PHP. This is the standard method for adding the library to your project. ```bash composer require softcreatr/php-perplexity-ai-sdk ``` -------------------------------- ### Initialize PHP Perplexity AI SDK Source: https://context7.com/softcreatr/php-perplexity-ai-sdk/llms.txt Demonstrates how to initialize the PerplexityAI class in PHP. It requires setting up PSR-17 and PSR-18 compliant factories and an HTTP client, then instantiating the SDK with your API key. ```php true]); // Create PerplexityAI instance $pplx = new PerplexityAI( requestFactory: $psr17Factory, streamFactory: $psr17Factory, uriFactory: $psr17Factory, httpClient: $httpClient, apiKey: 'your_api_key_here' ); ``` -------------------------------- ### Initialize PerplexityAI SDK in PHP Source: https://github.com/softcreatr/php-perplexity-ai-sdk/blob/main/README.md Demonstrates how to initialize the PerplexityAI SDK in PHP. It requires including the autoloader, setting up an API key, and instantiating the PerplexityAI class with necessary HTTP client and factory implementations. ```php createChatCompletion([], [ 'model' => 'sonar', 'messages' => [ [ 'role' => 'user', 'content' => 'What is quantum computing?' ] ], 'customHeaders' => [ 'X-Custom-Header' => 'custom-value', 'X-Request-ID' => 'req-12345' ] ]); $result = json_decode($response->getBody()->getContents(), true); echo $result['choices'][0]['message']['content']; ``` -------------------------------- ### Build Perplexity AI URLs and Manage Endpoints (PHP) Source: https://context7.com/softcreatr/php-perplexity-ai-sdk/llms.txt Illustrates how to use the PerplexityAIURLBuilder to retrieve endpoint configurations (method and path) and construct complete API URLs. This is useful for understanding API structure and for manual URL generation if needed. ```php true]); return new PerplexityAI( requestFactory: $psr17Factory, streamFactory: $psr17Factory, uriFactory: $psr17Factory, httpClient: $httpClient, apiKey: $apiKey ); } public static function request( string $method, array $parameters = [], array $options = [], ?callable $streamCallback = null ): mixed { $pplx = self::create($_ENV['PERPLEXITY_API_KEY']); if ($streamCallback !== null) { $pplx->{$method}($parameters, $options, $streamCallback); return null; } $response = $pplx->{$method}($parameters, $options); return json_decode($response->getBody()->getContents(), true); } } // Usage $result = PerplexityAIFactory::request( 'createChatCompletion', [], [ 'model' => 'sonar', 'messages' => [ ['role' => 'user', 'content' => 'What is machine learning?'] ] ] ); echo $result['choices'][0]['message']['content']; ``` -------------------------------- ### Use Advanced Parameters for Chat Completions in PHP Source: https://context7.com/softcreatr/php-perplexity-ai-sdk/llms.txt Demonstrates how to utilize advanced parameters such as model selection, token limits, temperature, sampling, penalties, stop sequences, and citation/image return options when creating chat completions with the Perplexity AI SDK. This allows for fine-tuning the AI's response generation for specific use cases. ```php createChatCompletion([], [ 'model' => 'llama-3.1-sonar-large-128k-online', 'messages' => [ [ 'role' => 'user', 'content' => 'Explain quantum entanglement.' ] ], 'max_tokens' => 500, // Maximum tokens to generate 'temperature' => 0.2, // Lower = more focused, higher = more creative 'top_p' => 0.9, // Nucleus sampling parameter 'presence_penalty' => 0.0, // Penalize new topics (-2.0 to 2.0) 'frequency_penalty' => 0.0, // Penalize repetition (-2.0 to 2.0) 'stop' => ["\n\n", "###"], // Stop sequences 'return_citations' => true, // Include source citations 'return_images' => false, // Include image results 'search_recency_filter' => 'month' // Filter by time (hour, day, week, month, year) ]); $data = json_decode($response->getBody()->getContents(), true); // Access response with metadata echo "Content: " . $data['choices'][0]['message']['content'] . "\n"; // Access citations if available if (isset($data['citations'])) { echo "\nCitations:\n"; foreach ($data['citations'] as $citation) { echo "- " . $citation . "\n"; } } ``` -------------------------------- ### Create Chat Completion with PHP Perplexity AI SDK Source: https://context7.com/softcreatr/php-perplexity-ai-sdk/llms.txt This PHP code snippet illustrates how to create a synchronous chat completion request using the Perplexity AI SDK. It includes sending messages, setting parameters like model and temperature, and handling the response, including potential API errors. ```php 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?' ] ], 'max_tokens' => 150, 'temperature' => 0.7 ]); // Process successful response if ($response->getStatusCode() === 200) { $data = json_decode($response->getBody()->getContents(), true); // Extract the assistant's message $assistantMessage = $data['choices'][0]['message']['content']; echo "Response: " . $assistantMessage . "\n"; // Access usage information echo "Tokens used: " . $data['usage']['total_tokens'] . "\n"; } } catch (PerplexityAIException $e) { echo "API Error: " . $e->getMessage() . "\n"; echo "Status Code: " . $e->getCode() . "\n"; } ``` -------------------------------- ### Implement Multi-turn Conversations with Perplexity AI SDK (PHP) Source: https://context7.com/softcreatr/php-perplexity-ai-sdk/llms.txt Shows how to manage conversation history for multi-turn interactions with the Perplexity AI chat completion endpoint. This involves sending initial messages, receiving assistant responses, and including them in subsequent requests to maintain context. ```php 'system', 'content' => 'You are a helpful coding assistant.' ], [ 'role' => 'user', 'content' => 'Write a PHP function to calculate factorial.' ] ]; // First turn $response1 = $pplx->createChatCompletion([], [ 'model' => 'llama-3.1-sonar-small-128k-online', 'messages' => $conversationHistory ]); $data1 = json_decode($response1->getBody()->getContents(), true); $assistantReply1 = $data1['choices'][0]['message']; // Add assistant's response to history $conversationHistory[] = $assistantReply1; // Add follow-up question $conversationHistory[] = [ 'role' => 'user', 'content' => 'Now add error handling for negative numbers.' ]; // Second turn $response2 = $pplx->createChatCompletion([], [ 'model' => 'llama-3.1-sonar-small-128k-online', 'messages' => $conversationHistory ]); $data2 = json_decode($response2->getBody()->getContents(), true); echo $data2['choices'][0]['message']['content']; ``` -------------------------------- ### Create Chat Completion using PerplexityAI SDK (PHP) Source: https://github.com/softcreatr/php-perplexity-ai-sdk/blob/main/README.md Shows how to create a chat completion using the PerplexityAI PHP SDK. It sends a request with model and message details and processes the response, checking for a 200 status code before decoding the JSON body. ```php $response = $pplx->createChatCompletion([], [ 'model' => 'sonar', '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(); } ``` -------------------------------- ### Stream Chat Completion Responses with PerplexityAI SDK (PHP) Source: https://github.com/softcreatr/php-perplexity-ai-sdk/blob/main/README.md Illustrates how to enable and handle streaming responses for chat completions using the PerplexityAI PHP SDK. A callback function processes incoming data chunks, echoing the content from the 'choices' array. ```php $streamCallback = static function ($data) { if (isset($data['choices'][0]['delta']['content'])) { echo $data['choices'][0]['delta']['content']; } }; $pplx->createChatCompletion([], [ 'model' => 'sonar', 'messages' => [ [ 'role' => 'user', 'content' => 'Tell me a story about a brave knight.', ], ], 'stream' => true, ], $streamCallback ); ``` -------------------------------- ### Handle Perplexity AI SDK Errors Gracefully (PHP) Source: https://context7.com/softcreatr/php-perplexity-ai-sdk/llms.txt Provides a comprehensive error handling structure for the PerplexityAI SDK, catching specific exceptions like PerplexityAIException, ClientExceptionInterface, InvalidArgumentException, and JsonException. This ensures robust handling of API, network, and data processing issues. ```php createChatCompletion([], [ 'model' => 'invalid-model-name', 'messages' => [ ['role' => 'user', 'content' => 'Test'] ] ]); $data = json_decode($response->getBody()->getContents(), true); } catch (PerplexityAIException $e) { // Handles API-level errors (4xx, 5xx responses) echo "API Error: " . $e->getMessage() . "\n"; echo "HTTP Status: " . $e->getCode() . "\n"; // Check for previous exception if ($previous = $e->getPrevious()) { echo "Underlying cause: " . $previous->getMessage() . "\n"; } } catch (ClientExceptionInterface $e) { // Handles HTTP client errors (network issues, timeouts) echo "HTTP Client Error: " . $e->getMessage() . "\n"; } catch (\InvalidArgumentException $e) { // Handles invalid parameters or configuration echo "Invalid Argument: " . $e->getMessage() . "\n"; } catch (\JsonException $e) { // Handles JSON encoding/decoding errors echo "JSON Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Stream Chat Completion with PHP Perplexity AI SDK Source: https://context7.com/softcreatr/php-perplexity-ai-sdk/llms.txt This PHP code snippet demonstrates how to create a streaming chat completion request using the Perplexity AI SDK. It defines a callback function to process response chunks in real-time and handles potential streaming errors. ```php createChatCompletion( [], [ 'model' => 'llama-3.1-sonar-small-128k-online', 'messages' => [ [ 'role' => 'user', 'content' => 'Tell me a story about a brave knight in three paragraphs.' ] ], 'stream' => true, 'temperature' => 0.8 ], $streamCallback ); // Note: Returns null for streaming requests } catch (PerplexityAIException $e) { echo "Streaming Error: " . $e->getMessage() . "\n"; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.