Back

Step by Step Guide to Building an Azure OpenAI Service API Integration in PHP

Aug 7, 20245 minute read

Introduction

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.

Prerequisites

Before we jump in, make sure you've got:

  • A PHP environment (you're a pro, so I'm sure you've got this covered)
  • Composer installed (because who doesn't love dependency management?)
  • An Azure account with OpenAI Service set up (if you haven't done this yet, hop to it!)

Installation

First things first, let's get that openai-php/client package installed:

composer require openai-php/client

Easy peasy, right?

Configuration

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();

Basic Usage

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.

Advanced Features

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' ]);

Error Handling and Best Practices

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); } }

Performance Optimization

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);

Security Considerations

Keep those API keys safe! Use environment variables:

$apiKey = getenv('AZURE_OPENAI_API_KEY');

Testing

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();

Deployment

When you're ready to go live, remember to:

  • Use production-grade error logging
  • Implement proper monitoring
  • Scale your application as needed

Conclusion

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!