This section covers how to build a simple personality-based chatbot function using Google's Gemini API in JavaScript, Python, and PHP.
npm install @google/genai
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
apiKey: "GEMINI_API_KEY", // Replace with your actual API key
});
const chat = ai.chats.create({
model: "gemini-2.0-flash",
config: {
systemInstruction: "You are a clone of person Garvit", // SYSTEM_PROMPT
},
});
async function get_ai_response(user_input) {
const response = await chat.sendMessage({
message: user_input,
});
return response.text;
}
// Example call
await get_ai_response("Kya haal hai bhai?"); // "Thik hai bhai, tu suna"
systemInstruction
: Defines bot's personality.sendMessage
: Sends user input to Gemini.response.text
: AI-generated reply.
pip install google-genai
from google import genai
from google.genai import types
GEMINI_API_KEY = "GEMINI_API_KEY"
client = genai.Client(api_key=GEMINI_API_KEY)
chat = client.chats.create(
model="gemini-2.0-flash",
config=types.GenerateContentConfig(
system_instruction="You are a clone of person Garvit"
),
)
def get_ai_response(user_input):
response = chat.send_message(user_input)
return response.text
# Example call
get_ai_response("Kya haal hai bhai?") # "Thik hai bhai, tu suna"
genai.Client
: Gemini client object.system_instruction
: Sets up clone personality.send_message
: Sends user input, returns reply.
PHP doesn’t have an official Gemini SDK, but you can use Gemini’s REST API with
curl
.
<?php
function get_ai_response(string $userInput): string
{
$apiKey = 'GEMINI_API_KEY';
$url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$apiKey";
$payload = json_encode([
"system_instruction" => [
"parts" => [
["text" => "You are a clone of person Garvit"]
]
],
"contents" => [
[
"role" => "user",
"parts" => [
["text" => $userInput]
]
]
]
]);
$headers = ['Content-Type: application/json'];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $payload
]);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
error_log("Curl Error: " . $error);
return 'Error contacting AI';
}
$responseData = json_decode($response, true);
return trim($responseData['candidates'][0]['content']['parts'][0]['text'] ?? 'No reply found');
}
// Example call
get_ai_response("Kya haal hai bhai?"); // "Thik hai bhai, tu suna"
system_instruction
: Same as SYSTEM_PROMPT.curl
: Used to send API request.- Response is parsed from Gemini’s JSON output.
Language | SDK/Method | Function Name | Prompt Support |
---|---|---|---|
JavaScript | @google/genai |
get_ai_response() |
✅ |
Python | google-genai |
get_ai_response() |
✅ |
PHP | curl (manual) |
get_ai_response() |
✅ |