google-gemini-php / laravel

⚡️ Gemini PHP for Laravel is a community-maintained PHP API client that allows you to interact with the Gemini AI API.
MIT License
251 stars 29 forks source link

Json response #12

Open asivaneswaran opened 2 weeks ago

asivaneswaran commented 2 weeks ago

Hi,

I am wondering how can I return a json response as per the document here: https://ai.google.dev/gemini-api/docs/api-overview?_gl=1*1rnrc7o*_ga*ODAxNjQ3NDk0LjE3MTc1NTE4NjE.*_ga_P1DBVKWT6V*MTcxOTE4ODg3Ny4zMi4xLjE3MTkxODkwNTguNjAuMC44MTkzNTYwMjU.#json

chrisribal commented 2 weeks ago

I ran into the same problem recently.

The link you provided uses the Gemini API v1beta version, which supports an responseMimeType option in the GenerationConfig object to be set to application/json. This great library uses Gemini v1 API, which does not support that parameter.

But you can easily tell gemini to only answer with a JSON response. Unfortunately, Gemini embeds the JSON code in a markdown code block. You then have to extract the JSON from that.

Example

$result = Gemini::geminiPro()
        ->generateContent('Please generate a list of the worlds biggest car manufacturers in JSON format, with the name of the manufacturer as key and yearly sold vehicles in float as value. IMPORTANT: Please answer in JSON format only, without any explanation.');

preg_match('/```json(.*?)```/s', $result->text(), $matches);

if (empty($matches[1])) {
    throw new \Exception('No valid JSON found in gemini response.');
}

// trim leading and trailng space
$json = trim($matches[1]);

echo $json;

Result

{
  "Toyota": 10.5,
  "Volkswagen": 10.3,
  "Hyundai Motor Group": 10.0,
  "General Motors": 9.3,
  "Stellantis": 8.7,
  "Honda": 8.5,
  "Ford": 8.2,
  "Renault-Nissan-Mitsubishi Alliance": 7.5,
  "BMW Group": 2.5,
  "SAIC Motor": 6.8
}