TsgcAIChat › Methods › ChatJSON

ChatJSON Method

Sends a user message and returns the answer as a JSON document, retrying once when it does not parse.

Syntax

function ChatJSON(const aMessage: string): string;

Parameters

NameTypeDescription
aMessageconst stringUser message to append to the conversation history and send to the selected provider.

Return Value

The answer of the provider, as JSON text. (string)

Remarks

ChatJSON builds the request with the current ChatOptions, ResponseFormat included, so set that property to rfJSON or to rfJSONSchema before calling it. See TsgcAIChat Structured Output for what each provider receives.

 

The answer is parsed in strict mode. When it parses, it is returned as it came, stored in the history as the assistant turn and raised through OnChatMessage. When it does not parse, or when the provider returned an empty message content, the question is sent again once, with the parse error and the json instruction appended to it, and a second unparseable answer raises EsgcAIChat. Markdown fences are not stripped, so a fenced answer is simply an answer that does not parse.

 

Unlike Chat, ChatJSON does not swallow errors: a transport error, a provider error and the schema validation of ChatOptions.JSONSchema all propagate to the caller instead of reaching OnChatError.

Example

oChat.ChatOptions.ResponseFormat := rfJSON;
try
  vJSON := oChat.ChatJSON('List three Delphi IDE shortcuts as JSON');
except
  on E: EsgcAIChat do
    ShowMessage(E.Message);
end;

Back to Methods