Hey there, fellow developer! Ready to supercharge your PHP project with some AI goodness? Let's dive into integrating Azure OpenAI Service using the awesome openai-php/client package. This guide assumes you're already familiar with PHP and Azure, so we'll keep things snappy and focus on the good stuff.
Before we jump in, make sure you've got:
First things first, let's get that openai-php/client package installed:
composer require openai-php/client
Easy peasy, right?
Now, let's set up those Azure OpenAI Service credentials. You'll need your API key and endpoint from the Azure portal. Here's how to configure the client for Azure:
use OpenAI\Client; $client = OpenAI::factory() ->withApiKey('your-api-key') ->withBaseUri('https://your-resource-name.openai.azure.com/') ->withHttpHeader('api-key', 'your-api-key') ->make();
Time to make some magic happen! Let's initialize the client and make a simple completion call:
$result = $client->completions()->create([ 'model' => 'your-deployment-name', 'prompt' => 'Hello, Azure OpenAI!', 'max_tokens' => 50 ]); echo $result['choices'][0]['text'];
Boom! You've just tapped into the power of Azure OpenAI.
Want to chat or generate embeddings? No sweat:
// Chat $result = $client->chat()->create([ 'model' => 'your-chat-deployment-name', 'messages' => [ ['role' => 'user', 'content' => 'What's the meaning of life?'] ] ]); // Embeddings $result = $client->embeddings()->create([ 'model' => 'your-embeddings-deployment-name', 'input' => 'Your text here' ]);
Don't let rate limits get you down. Implement some retry logic:
$maxRetries = 3; $retryDelay = 1000; // milliseconds for ($i = 0; $i < $maxRetries; $i++) { try { $result = $client->completions()->create([/* your params */]); break; } catch (\Exception $e) { if ($i === $maxRetries - 1) throw $e; usleep($retryDelay * 1000); } }
Want to kick it up a notch? Try async requests:
$promises = [ $client->completions()->createAsync([/* params */]), $client->completions()->createAsync([/* params */]) ]; $results = \GuzzleHttp\Promise\Utils::unwrap($promises);
Keep those API keys safe! Use environment variables:
$apiKey = getenv('AZURE_OPENAI_API_KEY');
Don't forget to test! Mock those API responses:
use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\Psr7\Response; $mock = new MockHandler([ new Response(200, [], json_encode(['choices' => [['text' => 'Mocked response']]]) ]); $client = OpenAI::factory() ->withApiKey('fake-key') ->withHttpClient(new \GuzzleHttp\Client(['handler' => $mock])) ->make();
When you're ready to go live, remember to:
And there you have it! You're now equipped to harness the power of Azure OpenAI in your PHP projects. Remember, with great power comes great responsibility (and awesome applications). Happy coding!
For more in-depth info, check out the openai-php/client documentation and Azure OpenAI Service docs.
Now go forth and build something amazing!