Gemini can return responses in structured JSON format conforming to a schema you define. This guarantees valid, parseable JSON output matching your schema definition.
Use the convenience method to create content with JSON schema output.
Gemini := TsgcHTTP_API_Gemini.Create(nil);
Gemini.GeminiOptions.ApiKey := 'API_KEY';
vSchema := '{"type":"object","properties":{"name":{"type":"string"},' +
'"age":{"type":"integer"}},"required":["name","age"]}';
WriteLn(Gemini._CreateContentJSON('gemini-2.0-flash',
'Extract the name and age: John is 30 years old.', vSchema));
Use the typed classes to configure structured output with ResponseMimeType and ResponseSchema.
Gemini := TsgcHTTP_API_Gemini.Create(nil);
Gemini.GeminiOptions.ApiKey := 'API_KEY';
oRequest := TsgcGeminiClass_Request_GenerateContent.Create;
Try
oRequest.Model := 'gemini-2.0-flash';
oRequest.MaxOutputTokens := 4096;
oRequest.ResponseMimeType := 'application/json';
oRequest.ResponseSchema :=
'{"type":"object","properties":{"sentiment":{"type":"string"},' +
'"confidence":{"type":"number"}},"required":["sentiment","confidence"]}';
SetLength(oContents, 1);
oContents[0] := TsgcGeminiClass_Request_Content.Create;
oContents[0].Role := 'user';
SetLength(oParts, 1);
oParts[0] := TsgcGeminiClass_Request_Part.Create;
oParts[0].Text := 'Analyze the sentiment: I love this product!';
oContents[0].Parts := oParts;
oRequest.Contents := oContents;
oResponse := Gemini.CreateContent(oRequest);
Try
if Length(oResponse.Candidates) > 0 then
if Length(oResponse.Candidates[0].Parts) > 0 then
WriteLn(oResponse.Candidates[0].Parts[0].Text);
Finally
oResponse.Free;
End;
Finally
oParts[0].Free;
oContents[0].Free;
oRequest.Free;
End;