Issue with Function Call & Limiting Results (Gemini Flash Exp / Flash 1.5)

Hi everyone,

I’m using Gemini Flash Experimental as well as Flash 1.5, depending on my project needs, and I’m trying to optimize my function call usage to limit the number of results returned in a structured JSON format.

My goal is to ensure that Gemini never returns more than 3 results in a list (level_3_ids), while following specific business logic constraints. Here’s my current approach:

  1. I provide a detailed prompt with strict rules on how many results should be returned.
  2. I use a function call with a strict schema, specifying a maximum of 3 elements in the JSON list.
  3. Despite this, Gemini sometimes returns more than 3 items, or does not fully respect the expected JSON structure.

My Question

  • Is there a more effective way to force Gemini to return a maximum of 3 results in the level_3_ids list?
  • Should I use a specific configuration within the function call (function_calling_config, parameters, etc.), or should I rely on pre-validation at the model level?
  • What are the best practices to ensure the response strictly adheres to the JSON format without requiring post-processing?

Here’s an excerpt of the function call definition I’m using:

{
  "name": "categorize_pdf_catalog",
  "description": "Analyzes the PDF catalog and determines the most relevant level 3 category IDs.",
  "parameters": {
    "type": "object",
    "properties": {
      "level_3_ids": {
        "type": "array",
        "description": "List of the most relevant level 3 category IDs (Maximum 3)",
        "items": {
          "type": "string",
          "pattern": "^[0-9]+$"
        }
      }
    },
    "required": ["level_3_ids"]
  }
}

Any advice or insights would be greatly appreciated! :rocket: Thanks in advance!

Hi,

the specification of response uses JSON Schema which has a property “maxItems” which would limit the amount of items in an array. However, I’m not sure whether this is existent for functionDeclarations which use Open API 3.03 Parameter Object - OpenAPI Specification v3.0.3 - or better said a Schema Object - OpenAPI Specification v3.0.3 - as base.

The OpenAPI specs are derived from JSON Schema, hence the same properties/keys shall be available.

Give it a try with maxItems and see what happens.

Cheers.