Specify a MIME response type for the Gemini API

Specify a MIME response type for the Gemini API so that the generated response is compliant with that type.

Code sample

C#

Before trying this sample, follow the C# setup instructions in the Vertex AI quickstart using client libraries. For more information, see the Vertex AI C# API reference documentation.

To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

public async Task<string> GenerateContentWithResponseSchema(  string projectId = "your-project-id",  string location = "us-central1",  string publisher = "google",  string model = "gemini-2.0-flash-001") {  var predictionServiceClient = new PredictionServiceClientBuilder  {  Endpoint = $"{location}-aiplatform.googleapis.com"  }.Build();  var responseSchema = new OpenApiSchema  {  Type = Type.Array,  Items = new()  {  Type = Type.Object,  Properties =  {  ["recipe_name"] = new() { Type = Type.String },  },  Required = { "recipe_name" }  }  };  var generateContentRequest = new GenerateContentRequest  {  Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",  Contents =  {  new Content  {  Role = "USER",  Parts =  {  new Part { Text = "List a few popular popular cookie recipes" }  }  }  },  GenerationConfig = new GenerationConfig  {  ResponseMimeType = "application/json",  ResponseSchema = responseSchema  },  };  GenerateContentResponse response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);  string responseText = response.Candidates[0].Content.Parts[0].Text;  Console.WriteLine(responseText);  return responseText; }

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.