Grok Delphi API Client

Grok, developed by xAI, is a high-performance AI model designed for fast, intelligent responses with real-time knowledge and advanced reasoning capabilities. For Delphi developers looking to integrate Grok into their applications, sgcWebSockets provides TsgcHTTP_API_Grok — a native component that wraps the entire xAI Grok API with clean, type-safe Delphi code.

Whether you are building conversational assistants, analyzing images, orchestrating tool-augmented workflows, or streaming real-time responses, this component gives you direct access to every Grok feature. No REST boilerplate. No JSON wrangling. Just drop the component, set your API key, and start building.

Complete API Coverage

Every major feature of the xAI Grok API is supported out of the box.

Chat Completions
Send messages with system prompts, receive responses synchronously or streamed. Full control over temperature, top-p, frequency and presence penalties.
Real-Time Streaming
Stream responses token-by-token using Server-Sent Events. Build responsive UIs that display answers as they are generated.
Vision
Analyze images by sending base64-encoded data or image URLs alongside text prompts. Grok describes, interprets, and reasons about visual content.
Tool Use — Function Calling
Define custom tools with JSON Schema. Grok decides when to invoke them, enabling agentic, multi-step workflows.
Model Management
List all available Grok models programmatically. Query model IDs and capabilities to select the best fit.
Built-in Retry & Logging
Automatic retry on transient failures with configurable attempts and wait intervals. Full request/response logging for debugging.

Getting Started

Integrate xAI Grok into your Delphi project in under a minute. Drop the component, configure your API key, and send your first message.

// Create the component and configure the API key
var
  Grok: TsgcHTTP_API_Grok;
  vResponse: string;
begin
  Grok := TsgcHTTP_API_Grok.Create(nil);
  Try
    Grok.GrokOptions.ApiKey := 'YOUR_API_KEY';

    // Send a simple message to Grok
    vResponse := Grok._CreateMessage(
      'grok-3', 'Hello, Grok!');

    ShowMessage(vResponse);
  Finally
    Grok.Free;
  End;
end;

Two API styles. Every feature offers both convenience methods (string-based, minimal code) and typed request/response classes (full control, type safety). Choose the approach that best suits your use case.

Chat Completions & Streaming

The Chat Completions API is the foundation of every Grok interaction. Send text with optional system prompts, and receive responses synchronously or streamed in real-time.

System Prompts

Control Grok's behavior by providing a system prompt that sets the context, personality, or constraints for the conversation.

vResponse := Grok._CreateMessageWithSystem(
  'grok-3',
  'You are a helpful assistant that responds in Spanish.',
  'What is the capital of France?');
// Returns: "La capital de Francia es París."

Real-Time Streaming

For responsive user interfaces, stream Grok's response token-by-token using Server-Sent Events. Assign the OnHTTPAPISSE event handler and call _CreateMessageStream.

// Enable streaming via SSE
Grok.OnHTTPAPISSE := OnSSEEvent;
Grok._CreateMessageStream('grok-3',
  'Explain the theory of relativity.');

procedure TForm1.OnSSEEvent(Sender: TObject;
  const aEvent, aData: string; var Cancel: Boolean);
begin
  // aData: JSON payload with generated content
  Memo1.Lines.Add(aData);
end;

Advanced Typed API

For full control over request parameters — temperature, top-p, frequency penalty, presence penalty, stop sequences, number of completions — use the typed request and response classes.

var
  oRequest: TsgcGrokClass_Request_ChatCompletion;
  oMessage: TsgcGrokClass_Request_Message;
  oResponse: TsgcGrokClass_Response_ChatCompletion;
begin
  oRequest := TsgcGrokClass_Request_ChatCompletion.Create;
  Try
    oRequest.Model := 'grok-3';
    oRequest.MaxTokens := 2048;
    oRequest.Temperature := 0.7;
    oRequest.TopP := 0.9;
    oRequest.FrequencyPenalty := 0.5;
    oRequest.N := 1;

    oMessage := TsgcGrokClass_Request_Message.Create;
    oMessage.Role := 'user';
    oMessage.Content := 'Explain quantum computing in simple terms.';
    oRequest.Messages.Add(oMessage);

    oResponse := Grok.CreateMessage(oRequest);
    Try
      if Length(oResponse.Choices) > 0 then
        ShowMessage(oResponse.Choices[0].Message.Content);
    Finally
      oResponse.Free;
    End;
  Finally
    oRequest.Free;
  End;
end;

Vision — Image Understanding

Grok can analyze and reason about images. Send photographs, screenshots, diagrams, or charts alongside a text prompt and receive detailed descriptions, data extraction, or visual Q&A.

// Load an image and ask Grok to analyze it
var
  vBase64: string;
begin
  vBase64 := sgcBase64Encode(LoadFileToBytes('dashboard-screenshot.png'));

  ShowMessage(Grok._CreateVisionMessage(
    'grok-3',
    'Analyze this dashboard and summarize the key metrics.',
    vBase64, 'image/png'));
end;

Use case. Automate report analysis, extract data from screenshots, generate descriptions of visual content, or build image-aware assistants — all from native Delphi code.

Tool Use — Function Calling

Define custom tools with JSON Schema, and Grok will decide when and how to invoke them. This is the foundation for building agentic, multi-step workflows that connect the AI to your business logic.

var
  oRequest: TsgcGrokClass_Request_ChatCompletion;
  oTool: TsgcGrokClass_Request_Tool;
  oResponse: TsgcGrokClass_Response_ChatCompletion;
begin
  // Define a tool with JSON Schema
  oTool := TsgcGrokClass_Request_Tool.Create;
  oTool.Name := 'search_database';
  oTool.Description := 'Search the product database by keyword';
  oTool.Parameters :=
    '{"type":"object","properties":{"query":{"type":"string",' +
    '"description":"Search keyword"}},"required":["query"]}';
  oRequest.Tools.Add(oTool);
  oRequest.ToolChoice := 'auto';

  oResponse := Grok.CreateMessage(oRequest);

  // Check if Grok wants to call a tool
  if oResponse.Choices[0].FinishReason = 'tool_calls' then
  begin
    for i := 0 to Length(oResponse.Choices[0].Message.ToolCalls) - 1 do
    begin
      vToolId   := oResponse.Choices[0].Message.ToolCalls[i].Id;
      vFuncName := oResponse.Choices[0].Message.ToolCalls[i].FunctionCall.Name;
      vFuncArgs := oResponse.Choices[0].Message.ToolCalls[i].FunctionCall.Arguments;
      // Execute the tool and return the result
    end;
  end;

Model Management

Query available Grok models programmatically. List all models to discover new capabilities as they become available.

// List all available Grok models
vModels := Grok._GetModels;

// Typed API: access model properties directly
var
  oModels: TsgcGrokClass_Response_Models;
  i: Integer;
begin
  oModels := Grok.GetModels;
  Try
    for i := 0 to Length(oModels.Data) - 1 do
      Memo1.Lines.Add(oModels.Data[i].Id);
  Finally
    oModels.Free;
  End;
end;

Configuration & Options

Fine-tune the component behavior with comprehensive configuration options.

Property Description
GrokOptions.ApiKey Your xAI API key (required)
HttpOptions.ReadTimeout HTTP read timeout in milliseconds (default: 60000)
LogOptions.Enabled Enable request/response logging
RetryOptions.Enabled Automatic retry on transient failures
RetryOptions.Retries Maximum number of retry attempts (default: 3)
RetryOptions.Wait Wait time between retries in milliseconds (default: 3000)

Request Parameters

Parameter Description
Temperature Sampling temperature (0.0–2.0). Lower values = more deterministic.
TopP Nucleus sampling (0.0–1.0). Controls cumulative probability cutoff.
MaxTokens Maximum number of tokens in the response (default: 4096).
FrequencyPenalty Penalize tokens based on frequency in the text so far.
PresencePenalty Penalize tokens based on whether they appear in the text so far.
N Number of completions to generate (default: 1).
ToolChoice Control tool selection: 'auto', 'none', or 'required'.

Why Grok? Built by xAI with a focus on helpfulness and real-time knowledge, Grok excels at tasks requiring up-to-date information and nuanced reasoning. The sgcWebSockets component makes it easy to switch between Grok and other AI providers while keeping your Delphi code clean and consistent.

Delphi Grok Demo

sgcGrok
2.9 mb
×
Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

Mistral Delphi API Client
Ollama Delphi API Client