Hey there, fellow PHP enthusiasts! Ready to dive into the exciting world of AI with Google's Gemini API? You're in for a treat. We'll be using the google-gemini-php/client
package to make our lives easier. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get that package installed:
composer require google-gemini-php/client
Easy peasy, right?
Alright, now for the fun part. You'll need an API key from Google. Once you've got that:
use Google\Generative\AI\GenerativeAI; $client = new GenerativeAI('YOUR_API_KEY');
Boom! You're ready to roll.
Let's start with something simple:
$model = $client->getGenerativeModel('gemini-pro'); $result = $model->generateContent('What's the meaning of life?'); echo $result->text();
Run this, and watch the magic happen!
Want to keep the conversation going? Here's how:
$chat = $model->startChat(); $chat->sendMessage("Hi, I'm learning PHP!"); $response = $chat->sendMessage("What should I learn next?"); echo $response->text();
Got an image? No problem:
$model = $client->getGenerativeModel('gemini-pro-vision'); $result = $model->generateContent([ 'parts' => [ ['text' => 'What's in this image?'], ['inline_data' => [ 'mime_type' => 'image/jpeg', 'data' => base64_encode(file_get_contents('path/to/image.jpg')) ]] ] ]); echo $result->text();
For those who can't wait:
$result = $model->generateContentStream('Tell me a long story'); foreach ($result as $part) { echo $part->text(); }
Things don't always go smoothly, so be prepared:
try { // Your Gemini API call here } catch (\Google\Generative\AI\Exception\GenerativeAIException $e) { echo "Oops! " . $e->getMessage(); }
Let's put it all together:
$model = $client->getGenerativeModel('gemini-pro'); $chat = $model->startChat(); while (true) { $input = readline("You: "); if ($input == 'quit') break; $response = $chat->sendMessage($input); echo "Bot: " . $response->text() . "\n"; }
And there you have it! You're now equipped to harness the power of Gemini in your PHP projects. Remember, the sky's the limit with AI – so go forth and create something awesome!
Want to dive deeper? Check out the official documentation for more advanced features and best practices.
Happy coding, and may your responses always be coherent!