Back

Step by Step Guide to Building a Gemini API Integration in PHP

Aug 2, 2024 • 5 minute read

Introduction

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!

Prerequisites

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

  • PHP 8.1 or higher (time to upgrade if you haven't already!)
  • Composer installed (because who doesn't love dependency management?)

Installation

First things first, let's get that package installed:

composer require google-gemini-php/client

Easy peasy, right?

Setting up the Gemini Client

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.

Basic Usage

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!

Advanced Features

Multi-turn Conversations

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

Image Input

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

Streaming Responses

For those who can't wait:

$result = $model->generateContentStream('Tell me a long story'); foreach ($result as $part) { echo $part->text(); }

Error Handling

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

Best Practices

  • Keep an eye on those rate limits. Nobody likes a timeout.
  • Guard that API key with your life. Seriously.

Example Project: Simple Chatbot

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

Conclusion

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!