Anthropic | Structured Outputs

Gli Output Strutturati forzano Claude a restituire risposte conformi a uno schema JSON. Ciò garantisce un output JSON valido e analizzabile conforme alla definizione dello schema.

Esempio Semplice

Utilizzare il metodo conveniente per creare un messaggio con output in schema JSON.


Anthropic := TsgcHTTP_API_Anthropic.Create(nil);
Anthropic.AnthropicOptions.ApiKey := 'API_KEY';

vSchema := '{"type":"object","properties":{"name":{"type":"string"},' +
  '"age":{"type":"integer"}},"required":["name","age"],' +
  '"additionalProperties":false}';

WriteLn(Anthropic._CreateMessageJSON('claude-sonnet-4-20250514',
  'Extract the name and age: John is 30 years old.', vSchema));

Esempio avanzato

Utilizzare le classi tipizzate per combinare l'output strutturato con il parametro effort.


Anthropic := TsgcHTTP_API_Anthropic.Create(nil);
Anthropic.AnthropicOptions.ApiKey := 'API_KEY';

oRequest := TsgcAnthropicClass_Request_Messages.Create;
Try
  oRequest.Model := 'claude-sonnet-4-20250514';
  oRequest.MaxTokens := 4096;

  // JSON schema for structured output
  oRequest.OutputFormatSchema :=
    '{"type":"object","properties":{"sentiment":{"type":"string",' +
    '"enum":["positive","negative","neutral"]},"confidence":' +
    '{"type":"number"}},"required":["sentiment","confidence"],' +
    '"additionalProperties":false}';

  // Set effort level (low, medium, high, max)
  oRequest.Effort := 'medium';

  oMessage := TsgcAnthropicClass_Request_Message.Create;
  oMessage.Role := 'user';
  oMessage.Content := 'Analyze the sentiment: I love this product!';
  oMessages := oRequest.Messages;
  SetLength(oMessages, 1);
  oMessages[0] := oMessage;
  oRequest.Messages := oMessages;

  oResponse := Anthropic.CreateMessage(oRequest);
  Try
    for i := 0 to Length(oResponse.Content) - 1 do
    begin
      if oResponse.Content[i].ContentType = 'text' then
        WriteLn(oResponse.Content[i].Text);
    end;
  Finally
    oResponse.Free;
  End;
Finally
  oMessage.Free;
  oRequest.Free;
End;

Strict Tool Use

Abilitare la modalità strict sulle definizioni degli strumenti per garantire che gli input degli strumenti siano conformi esattamente all'input_schema.


oTool := TsgcAnthropicClass_Request_Tool.Create;
oTool.Name := 'get_weather';
oTool.Description := 'Get the current weather for a location';
oTool.Strict := True;  // Guarantee schema conformance
oTool.InputSchema := '{"type":"object","properties":{"location":' +
  '{"type":"string"}},"required":["location"],"additionalProperties":false}';

Proprietà