Gemini API working in localhost, but not on server

68 Views Asked by At

I am calling free Gemini API using PHP. It is working absolutely fine on localhost.

I encountered an issue upon deploying it to a shared hosting server. Irrespective of the location, even when accessed from New York, the system consistently returns an error message:

{"error":"Gemini API operation failed: operation=models/gemini-pro:generateContent, status_code=400, response={\n "error": {\n "code": 400,\n "message": "User location is not supported for the API use.",\n "status": "FAILED_PRECONDITION"\n }\n}\n"}

Could you kindly assist me in resolving this issue?

php
<?php
require 'vendor/autoload.php';
use GeminiAPI\Client;
use GeminiAPI\Enums\MimeType;
use GeminiAPI\Resources\Parts\ImagePart;
use GeminiAPI\Resources\Parts\TextPart;

// Path to the image containing the voucher
$imagePath = "PATH";

// API key for accessing Gemini API
$apiKey = 'MY_API_KEY';
$client = new Client($apiKey);

// Read the image file content and encode it in base64
$imageData = base64_encode(file_get_contents($imagePath));

// Prompt to provide context for content generation
$prompt = "MY_PROMPT";

try {
    // Send the image and text to Gemini API for processing
    $response = $client->geminiProVision()->generateContent(
        new TextPart($prompt),
        new ImagePart(MimeType::IMAGE_JPEG, $imageData)
    );

    // Extract the JSON response
    $content = $response->text();

    // Return the JSON data
    echo extractJSON($content);
} catch (Exception $e) {
    // If an error occurs, return an error message
    echo json_encode(['error' => $e->getMessage()]);
}

function extractJSON($string) {
    $pattern = '/\{(.*?)\}/s'; // pattern to match
    preg_match($pattern, $string, $matches); // perform the match
    if (isset($matches[0])) {
        return $matches[0]; // return the first captured group
    } else {
        return "{}"; // return null if no match found
    }
}
?>
0

There are 0 best solutions below