Json Mode - gunpal5/Google_GenerativeAI GitHub Wiki
The Google Generative AI SDK for C# simplifies working with JSON data returned by Gemini models. This page explains how to use the SDK's features for automatic and manual JSON handling.
The SDK offers two primary approaches for handling JSON responses: automatic deserialization and manual parsing.
This approach streamlines the process of receiving and using JSON data by automatically deserializing the response into a C# object.
Using GenerateObjectAsync
This method directly deserializes the JSON response into an object of the specified type T
.
GenerateObjectAsync<T>
has several overloads to simplify creating requests.
public class SampleJsonClass
{
public string? Name { get; set; }
public int Age { get; set; }
}
var person = await googleAI.GenerateObjectAsync<SampleJsonClass>("Give me a JSON object representing a person.");
if (person != null)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
This is the simplest form, directly passing the text prompt to the method.
var content = new Content("Give me a JSON object representing a person.");
var person = await googleAI.GenerateObjectAsync<SampleJsonClass>(content);
if (person != null)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
This overload allows you to create a Content
object with more options (e.g., specifying a role) if needed.
With a List of Part Objects
var parts = new List<Part>
{
new Part { Text = "Give me a JSON object representing a person." }
};
var person = await googleAI.GenerateObjectAsync<SampleJsonClass>(parts);
if (person != null)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
This overload is useful when you need more fine-grained control over the request content, using Part
objects for different modalities.
The underlying GenerateContentRequest can still be used for maximum flexibility:
var request = new GenerateContentRequest();
request.AddText("Give me a JSON object representing a person.");
var person = await googleAI.GenerateObjectAsync<SampleJsonClass>(request);
if (person != null)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
Using GenerateContentAsync and ToObject
This approach first retrieves the raw JSON response and then deserializes it using the ToObject<T>
extension method.
This approach is still useful when you need access to the full GenerateContentResponse
object, not just the deserialized object. The overloads for GenerateObjectAsync<T>
are generally preferred if you only need the deserialized object.
var request = new GenerateContentRequest();
request.AddText("Give me a JSON object representing a person.");
var response = await googleAI.GenerateContentAsync(request);
var person = response.ToObject<SampleJsonClass>();
if (person != null)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
Using UseJsonMode
The UseJsonMode<T>
extension method configures the GenerateContentRequest
to expect a JSON response of a specific type. This is used in conjunction with GenerateContentAsync
.
var request = new GenerateContentRequest();
request.UseJsonMode<SampleJsonClass>(); // Important: Specify the expected type
request.AddText("Give me a JSON object representing a person.");
var response = await googleAI.GenerateContentAsync(request); // No generic type here
var person = response.ToObject<SampleJsonClass>(); // Now convert the response
if (person != null)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
This ensures the SDK is prepared to handle a JSON response of the specified type.
This method provides more control over the JSON processing, allowing you to extract and parse JSON blocks directly.
Create a standard GenerateContentRequest
. You can optionally specify the expected MIME type and schema.
var request1 = new GenerateContentRequest();
request1.AddText("Give me some JSON.");
var request2 = new GenerateContentRequest();
request2.GenerationConfig = new GenerationConfig()
{
ResponseMimeType = "application/json",
ResponseSchema = new SampleJsonClass()
};
request2.AddText("Give me a really good response.");
Use ExtractJsonBlocks to get the raw JSON blocks from the response, and then use ToObject to deserialize them.
var response = await googleAI.GenerateContentAsync(request1); // Use one of the requests from above
var jsonBlocks = response.ExtractJsonBlocks();
var myObjects = jsonBlocks.Select(block => block.ToObject<SampleJsonClass>());
foreach (var obj in myObjects)
{
if (obj != null)
Console.WriteLine($"Name: {obj.Name}, Age: {obj.Age}");
}
This code extracts the JSON blocks and then deserializes each block into a SampleJsonClass
object.
-
Supported Types: While the SDK simplifies JSON handling, ensure that the types you use for deserialization are compatible with the JSON structure. Complex types like
Dictionary
might not be fully supported. - Error Handling: Implement proper error handling to manage cases where the JSON response cannot be deserialized into the specified type.
- Model Compatibility: Ensure the model you are using is designed to return JSON responses.