AI Chat
TsgcAIChat is a single chat client for seven large language model providers. Set Provider, set an API key and a model, then call Chat. Changing vendor is one assignment, the rest of your code stays the same.
TsgcAIChat is a single chat client for seven large language model providers. Set Provider, set an API key and a model, then call Chat. Changing vendor is one assignment, the rest of your code stays the same.
A provider-neutral chat component. It keeps the conversation history, builds the provider-specific JSON body, drives the matching HTTP API client and hands you back the assistant text, either in one call or token by token.
TsgcAIChat
Provider-neutral LLM chat
Win32 and Win64
sgcAI is self-contained. This component ships inside sgcAI together with the sgcWebSockets Core runtime it is built on.
Pick the provider, set the key and the model, call Chat. Streaming and async variants use the same configuration.
uses
sgcAI, sgcAI_Chat;
var
oChat: TsgcAIChat;
vAnswer: string;
begin
oChat := TsgcAIChat.Create(nil);
oChat.Provider := aicpAnthropic;
oChat.ChatOptions.ApiKey := 'sk-ant-...';
oChat.ChatOptions.Model := 'claude-sonnet-4-5';
oChat.ChatOptions.MaxTokens := 4096;
oChat.SystemMessage := 'You are a Delphi expert.';
oChat.MaxHistoryMessages := 20;
// Blocking call, returns the assistant text.
vAnswer := oChat.Chat('How do I keep a WebSocket connection alive?');
// Token by token, delivered on OnChatStream.
oChat.OnChatStream := OnChatStreamHandler;
oChat.ChatStream('Now explain it to a beginner.');
end;
procedure TForm1.OnChatStreamHandler(Sender: TObject;
const aChunk: string; var Cancel: Boolean);
begin
Memo1.Text := Memo1.Text + aChunk;
Cancel := StopRequested; // abort a long generation
end;
// includes: sgcAI.hpp, sgcAI_Chat.hpp
TsgcAIChat *oChat = new TsgcAIChat(NULL);
oChat->Provider = aicpOpenAI;
oChat->ChatOptions->ApiKey = "sk-...";
oChat->ChatOptions->Model = "gpt-6-astra";
oChat->SystemMessage = "You are a Delphi expert.";
String vAnswer = oChat->Chat("How do I keep a WebSocket connection alive?");
// Local models: same code, no data leaves the machine.
oChat->Provider = aicpOllama;
oChat->ChatOptions->BaseUrl = "http://127.0.0.1:11434";
oChat->ChatOptions->Model = "llama3";
vAnswer = oChat->Chat("Same question, local model.");
The members you reach for most often.
Provider selects the vendor: aicpOpenAI, aicpAnthropic, aicpGemini, aicpDeepSeek, aicpOllama, aicpGrok or aicpMistral. Changing it releases the cached client for the previous provider.
ApiKey, Model, MaxTokens, Temperature, TopP and BaseUrl. Leave Temperature and TopP at their default and they are omitted from the request, so the provider default applies.
SystemMessage sets the persona for every turn. MaxHistoryMessages caps how many past messages are replayed, which bounds token cost. ClearHistory and GetHistory reset and read the transcript.
Chat blocks and returns the answer. ChatStream streams over SSE. ChatWithSystem overrides the system prompt for a single turn. ChatAsync returns a future on Delphi 2010 and later.
OnChatMessage reports each completed message with its role. OnChatStream delivers every chunk and carries a Cancel flag. OnChatError surfaces provider and transport errors.
ChatWithDocument and ChatWithDocumentBase64 send a PDF or an image with the message, ChatWithAttachments and ChatJSONWithAttachments send several, held in a TsgcAIChatAttachments list. OpenAI, Anthropic and Gemini read PDFs natively, the other providers take images. Link the chat to a TsgcAIDocumentExtractor to turn invoices, receipts and ID cards into JSON validated against a schema, with a confidence per field.
With Provider set to aicpOllama, ChatOptions.BaseUrl points the component at your own Ollama host, so prompts and answers never leave the machine.
ChatWithTools sends your tool definitions (name, description and JSON Schema) with the message and returns the tool calls the model asks for. Run them, hand each result back with AddToolResult and call again. It works on all seven providers, each in its own format. TsgcAIAgent runs this loop for you.
ChatOptions.Model can be an alias such as fast or smart, mapped in ModelAliases to a model or to provider:model, and loaded with LoadModelAliasesFromFile, LoadModelAliasesFromJSON or LoadModelAliasesFromURL. Fallbacks lists the next provider and model to try on a connection error, HTTP 5xx, HTTP 429 or an unknown model, and OnFallback reports every switch.
LastUsage and OnChatUsage report the provider, model, input, output and cached tokens of every request, with UserId and SessionId, and LastFinishReason tells why the last answer ended, such as stop or length. Assign a TsgcAIUsageMeter to UsageMeter for costs and budgets, and a TsgcAIGuardrails to Guardrails for PII redaction, tool rules and schema validation.
Name models by role, keep answering when a provider fails, and read the tokens of every request. New in 2026.11.0.
uses
sgcAI, sgcAI_Chat;
procedure TForm1.ChatWithFallback;
var
oFallback: TsgcAIChatFallback;
begin
sgcAIChat1.Provider := aicpOpenAI;
sgcAIChat1.ChatOptions.ApiKey := 'sk-...';
// aliases: alias=model or alias=provider:model
sgcAIChat1.ModelAliases.Add('fast=gpt-6-luna');
sgcAIChat1.ModelAliases.Add('smart=anthropic:claude-opus-5-5');
sgcAIChat1.ProviderApiKeys.Add('anthropic=sk-ant-...');
sgcAIChat1.ChatOptions.Model := 'fast';
// tried in order on a connection error, HTTP 5xx, HTTP 429 or an unknown model
oFallback := sgcAIChat1.Fallbacks.Add;
oFallback.Provider := aicpGemini;
oFallback.Model := 'gemini-3-flash';
oFallback.ApiKey := 'AIza...';
sgcAIChat1.OnFallback := DoFallback;
Memo1.Lines.Add(sgcAIChat1.Chat('Write a haiku about Delphi.'));
Memo1.Lines.Add(Format('Answered by %s %s: %d input, %d output tokens',
[sgcAIChat1.LastUsage.Provider, sgcAIChat1.LastUsage.Model,
sgcAIChat1.LastUsage.InputTokens, sgcAIChat1.LastUsage.OutputTokens]));
end;
procedure TForm1.DoFallback(Sender: TObject; const aFromProvider, aFromModel,
aToProvider, aToModel, aError: string);
begin
Memo1.Lines.Add('Fallback from ' + aFromProvider + ' to ' + aToProvider +
': ' + aError);
end;
Authoritative sources for the services and protocols this component uses.
| Online HelpFull API reference and usage guide for the sgcAI components. | Open | |
| All sgcAI ComponentsBrowse the full feature matrix of all 15 components. | Open | |
| Download Free TrialTry all seven providers with your own API keys. | Open | |
| PricingSingle, Team and Site licenses, full source code. | Open |