Search code examples
jsoncurlgoogle-gemini

How to get JSON output from gemini-1.5-pro-001 using curl


How can I retrieve data in JSON format from the Gemini 1.5 API using curl? The code below works correctly:

curl -H 'Content-Type: application/json'      
-H "x-goog-api-key: ${API_KEY}"      
-d '{"contents":[
            {"role": "user",
              "parts":[{"text": "Give me five subcategories of jazz?"}]}]}'      
"https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent"

But when I try to add:

,"generation_config": {"response_mime_type": "application/json"}}

Giving:

curl -H 'Content-Type: application/json' 
-H "x-goog-api-key: ${API_KEY}" 
-d '{"contents":[
            {"role": "user",
              "parts":[{"text": "Give me five subcategories of jazz?"}]},"generation_config": {"response_mime_type": "application/json"},]'      
"https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent"

I receive this error response:

"error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"response_mime_type\" at 'generation_config': Cannot find field.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "field": "generation_config",
            "description": "Invalid JSON payload received. Unknown name \"response_mime_type\" at 'generation_config': Cannot find field."
          }
        ]
      }
    ]
  }

I've tried with several different models (e.g. gemini-1.5-pro-latest) always with the same result.


Solution

  • Try this.

    curl https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GOOGLE_API_KEY \
        -H 'Content-Type: application/json' \
        -X POST \
        -d '{
            "contents": [{
                "parts":[
                    {"text": "Write a story about a magic backpack."}
                ]
            }],
            "safetySettings": [
                {
                    "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
                    "threshold": "BLOCK_ONLY_HIGH"
                }
            ],
            "generationConfig": {
                "stopSequences": [
                    "Title"
                ],
                "temperature": 1.0,
                "maxOutputTokens": 800,
                "topP": 0.8,
                "topK": 10,
                "responseMimeType": "application/json"
            }
        }'  2> /dev/null | grep "text"