Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Json response #12

Closed
asivaneswaran opened this issue Jun 24, 2024 · 2 comments
Closed

Json response #12

asivaneswaran opened this issue Jun 24, 2024 · 2 comments

Comments

@asivaneswaran
Copy link

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
Copy link

chrisribal commented Jun 25, 2024

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
}

@aydinfatih
Copy link
Contributor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants