Delphi OpenAI API


This repository contains a Delphi client for the OpenAI public API.
❗This is an unofficial library. OpenAI does not provide any official library for Delphi.
Compatibility
Also, the library is compatible with the following AI APIs (tested):
- OpenAI Azure
- DeepSeek
- YandexGPT
- Qwen
- GigaChat
and other compatible with the OpenAI API.
Table of contents
Coverage
| API |
Support |
| Responses |
Create, retrieve, cancel, delete, input items, token count, compaction, polling, typed SSE events, tool runner, WebSocket |
| Conversations |
Conversation and item lifecycle |
| Chat Completions |
Generation, SSE, stored completions and messages, reasoning, structured output |
| Images |
GPT Image generation/editing and SSE; multipart image uploads |
| Audio |
Speech, transcription, translation, diarization, SSE, voice creation and consent lifecycle |
| Embeddings |
Float and base64 float32 vectors |
| Moderation |
Omni moderation, multimodal input, category input types |
| Files / Uploads |
Pagination, expiry, purposes, staged multipart uploads |
| Batch / Vector Stores |
Batch lifecycle; stores, files, batches, search |
| Containers / Skills |
Containers, files, skills and versions |
| Realtime / Live |
Session/call REST controls, Realtime SDP calls and translation, synchronous WebSocket events |
| Agents (beta) |
Agents, sessions, environments/templates, artifacts, subagents, turns, traces, vaults/credentials, SSE; scoped beta headers |
| Webhooks |
Endpoint management and HMAC signature verification |
| Administration |
Projects, users, groups, roles, certificates, admin keys, service accounts, rate limits, invites, audit logs, usage/costs |
| Fine-tuning |
Method configuration, integrations, jobs, events, checkpoints, pause/resume |
| Legacy APIs |
Retained for compatible providers; availability depends on the server |
Coverage is deliberately explicit: advanced resources can also be accessed through
API.Request<TResult, TParams> and configured through inherited TJSONParam.Add.
There is no claim of complete coverage of every beta API or a bundled audio/WebRTC media stack.
What is OpenAI
OpenAI is a non-profit artificial intelligence research organization founded in San Francisco, California in 2015. It was created with the purpose of advancing digital intelligence in ways that benefit humanity as a whole and promote societal progress. The organization strives to develop AI (Artificial Intelligence) programs and systems that can think, act and adapt quickly on their own – autonomously. OpenAI’s mission is to ensure safe and responsible use of AI for civic good, economic growth and other public benefits; this includes cutting-edge research into important topics such as general AI safety, natural language processing, applied reinforcement learning methods, machine vision algorithms etc.
The OpenAI API can be applied to virtually any task that involves understanding or generating natural language or code. We offer a spectrum of models with different levels of power suitable for different tasks, as well as the ability to fine-tune your own custom models. These models can be used for everything from content generation to semantic search and classification.
This library provides access to the API of the OpenAI service, on the basis of which ChatGPT works and, for example, the generation of images from text using DALL-E.
Installation
You can install the package from GetIt directly in the IDE. Or, to use the library, just add the root folder to the IDE library path, or your project source path.
Usage
Responses
New applications should use Responses.
The library keeps the existing route classes and anonymous parameter callbacks.
uses OpenAI, OpenAI.Responses;
var Client: IOpenAI := TOpenAI.Create(GetEnvironmentVariable('OPENAI_API_KEY'));
var Response := Client.Responses.Create(
procedure(Params: TResponseParams)
begin
Params.Model('gpt-6-luna').Input('Explain Delphi interfaces.');
end);
try
Writeln(Response.OutputText);
finally
Response.Free;
end;
Use PreviousResponseId or Conversation to continue a conversation. Output
retains tool calls, reasoning items and other output types. JSON, Value,
StringValue and ToJSON expose server fields without removing unknown types.
Resources and their child items are owned by the returned result; free the result once.
Treat TJSONResource.JSON, Value, Data and TResponse.Output as read-only borrowed
views. To replace data, use LoadJSON; it invalidates all previously borrowed child
items. Unknown response fields and event types remain available through raw JSON.
Every JSON request builder derives from TJSONParam. Add('key', NestedBuilder)
clones the nested builder: the caller must free it. AddOwned consumes a temporary
builder. Arrays of builders are consumed on successful insertion. Raw TJSONValue
arguments transfer ownership. Binary uploads use multipart forms; JSON configuration
inside those forms is serialized through TJSONParam. TChatParams.ResponseFormat
also clones its schema argument: callers now retain ownership and must free the
TJSONSchemaFormat, including when migrating from code that relied on its disposal.
Streaming and WebSockets
uses OpenAI.Streams, OpenAI.Responses;
Client.Responses.CreateStream(
procedure(Params: TResponseParams)
begin
Params.Model('gpt-6-luna').Input('Hello');
end,
procedure(const Message: TSSEMessage; var Cancel: Boolean)
begin
Writeln(Message.Event, ': ', Message.Data);
// Set Cancel := True to stop receiving. The call then returns False.
end);
SSE handles fragmented UTF-8, multiline data, comments, LF/CRLF/CR line endings and
error events. Callbacks run on the calling thread. The HTTP sink discards processed
bytes and retains at most 64 KiB for error diagnostics; one SSE event is limited to
16 MiB. Finite streams require a terminal event. An interrupted response cannot be
mistaken for a successful completion; unterminated events are discarded at EOF.
Long-lived Agents event subscriptions do not require a completion marker.
Responses.CreateStreamTyped provides TResponseStreamEvent.Kind, Delta and raw
JSON. TResponseAccumulator collects text and function/custom-tool arguments;
ToolCalls returns caller-owned copies. CreateStreamResult returns the final
TResponse. Transport error events raise OpenAIException with server error fields.
Responses.RunTools executes a supplied function/custom-tool handler and continues
until the model produces an answer, with a configurable round limit. It uses
previous_response_id for stored responses and carries the full item history,
including encrypted reasoning, when Store(False) is selected.
API.EachPage invokes a callback with a borrowed page, while API.ListAll returns
a caller-owned resource containing all data items. Cursor and page-token pagination
are supported; missing, repeated or cyclic cursors raise an error. API.WaitFor<T>
polls a resource until a supplied terminal status; Responses.WaitFor supplies its
terminal statuses. The polling deadline is checked between requests; each HTTP
request also uses the configured connection/response timeouts.
Responses.Connect, Realtime.Connect and Live.Connect return a synchronous
TOpenAIWebSocket. Use Send(EventType, ParamProc), Receive and Close, and free
each received TJSONResource. Receive returns server error events as JSON so the
application can handle their event types. Windows uses WinHTTP (Windows 8+); on other
platforms supply IWebSocketTransport. The caller manages the receive loop, audio
capture/playback and WebRTC negotiation. Realtime client secrets and Live SDP session
creation are available through their REST routes. WebSocket connections inherit
API proxy settings and timeouts. Custom transports can implement IWebSocketSettings
to receive these settings. Realtime CreateCall posts SDP plus JSON session options
as multipart data and returns the answer SDP, Location and call ID. Translation calls
and translation client secrets have separate helpers.
Client.Project sends OpenAI-Project. API errors expose HTTPStatus, ErrorCode
and RequestId, preserving the legacy numeric Code. Retries are opt-in through
API.MaxRetries (default zero) and apply only to non-streaming GET, HEAD, OPTIONS,
PUT and DELETE requests with transient HTTP statuses. POST requests are never
automatically replayed. List query arrays use repeated key[]=value parameters.
The shared client supports simultaneous HTTP requests when its configuration is
fixed before work starts. Keep the IOpenAI owner alive until all requests finish.
Response headers and LastHTTPStatus are scoped to the calling thread: read them
on the thread that made the request. API.Cancellation is also scoped to that thread.
Assign a TRequestCancellation token in the worker and clear it in a finally block;
call the same token’s Cancel from any thread to interrupt native HTTP I/O.
Cancelled SSE calls return False; cancelled ordinary requests raise EAbort.
The chat component must be created, configured, sent and destroyed on the main
thread. It keeps its client alive during background work, handles removed component
dependencies, and StopStream cancels streaming and non-streaming HTTP requests.
Tool results retain their tool_call_id and the complete conversation; function
and custom-tool chains use MaxToolRounds (default 16). OnEndWork runs once per
chain. Completion, error and tool events run on the main thread. Synchronize=False
allows only OnChatDelta to run on the worker; that handler must not destroy the
component. History AutoTrim removes whole old user turns and preserves leading
system/developer messages. The latest turn is retained whole even if it exceeds
the approximate token budget, so the caller can shorten an oversized input.
Skill directory uploads preserve paths relative to the bundle root. Use
TSkillUploadParams.Directory, or Files(Root, Paths); Files(Paths) infers the root
from the single SKILL.md. Files outside that root are rejected.
TWebhookVerifier.Verify verifies the unchanged raw request body against the
webhook-id, webhook-timestamp and webhook-signature headers.
The default chat model is gpt-6-luna, image generation/editing uses
gpt-image-2.5-flare, and moderation uses omni-moderation-latest. Model access and
supported parameters depend on the account and model. Select reasoning explicitly
when needed; temperature/top_p are omitted by the chat component for active reasoning.
Legacy Completion has no default model. Explicit model names in older examples below
are historical/provider compatibility examples: consult the
deprecation schedule.
Assistants, Edits, Engines and legacy Fine-tunes remain available as compatibility
routes; use Responses/Conversations and FineTuning for supported OpenAI workflows.
Initialization
To initialize API instance you need to obtain API token from your Open AI organization.
Once you have a token, you can initialize TOpenAI class, which is an entry point to the API.
Due to the fact that there can be many parameters and not all of them are required, they are configured using an anonymous function.
uses OpenAI;
var OpenAI := TOpenAIComponent.Create(Self, API_TOKEN);
or
uses OpenAI;
var OpenAI: IOpenAI := TOpenAI.Create(API_TOKEN);
Once token you posses the token, and the instance is initialized you are ready to make requests.
Models
List and describe the various models available in the API. You can refer to the Models documentation to understand what models are available and the differences between them.
var Models := OpenAI.Model.List();
try
for var Model in Models.Data do
MemoChat.Lines.Add(Model.Id);
finally
Models.Free;
end;
Review Models Documentation for more info.
Completions
Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position.
var Completions := OpenAI.Completion.Create(
procedure(Params: TCompletionParams)
begin
Params.Prompt(MemoPrompt.Text);
Params.MaxTokens(2048);
end);
try
for var Choice in Completions.Choices do
MemoChat.Lines.Add(Choice.Index.ToString + ' ' + Choice.Text);
finally
Completions.Free;
end;
Review Completions Documentation for more info.
Chats
Given a chat conversation, the model will return a chat completion response.
ChatGPT is powered by gpt-3.5-turbo, OpenAI’s most advanced language model.
Using the OpenAI API, you can build your own applications with gpt-3.5-turbo to do things like:
- Draft an email or other piece of writing
- Write Python code
- Answer questions about a set of documents
- Create conversational agents
- Give your software a natural language interface
- Tutor in a range of subjects
- Translate languages
- Simulate characters for video games and much more
This guide explains how to make an API call for chat-based language models and shares tips for getting good results.
var Chat := OpenAI.Chat.Create(
procedure(Params: TChatParams)
begin
Params.Messages([TChatMessageBuild.Create(TMessageRole.User, Text)]);
Params.MaxTokens(1024);
end);
try
for var Choice in Chat.Choices do
MemoChat.Lines.Add(Choice.Message.Content);
finally
Chat.Free;
end;
Stream mode
OpenAI.Chat.CreateStream(
procedure(Params: TChatParams)
begin
Params.Messages([TchatMessageBuild.User(Buf.Text)]);
Params.MaxTokens(1024);
Params.Stream;
end,
procedure(Chat: TChat; IsDone: Boolean; var Cancel: Boolean)
begin
if (not IsDone) and Assigned(Chat) then
Writeln(Chat.Choices[0].Delta.Content)
else if IsDone then
Writeln('DONE!');
Writeln('-------');
Sleep(100);
end);
Vision
var Chat := OpenAI.Chat.Create(
procedure(Params: TChatParams)
begin
Params.Model('gpt-4-vision-preview');
var Content: TArray<TMessageContent>;
Content := Content + [TMessageContent.CreateText(Text)];
Content := Content + [TMessageContent.CreateImage(FileToBase64('file path'))];
Params.Messages([TChatMessageBuild.User(Content)]);
Params.MaxTokens(1024);
end);
try
for var Choice in Chat.Choices do
MemoChat.Lines.Add(Choice.Message.Content);
finally
Chat.Free;
end;
Review Chat Documentation for more info.
Images
Given a prompt and/or an input image, the model will generate a new image.
var Images := OpenAI.Image.Create(
procedure(Params: TImageCreateParams)
begin
Params.Prompt(MemoPrompt.Text);
Params.ResponseFormat('url');
end);
try
for var Image in Images.Data do
Image1.Bitmap.LoadFromUrl(Image.Url);
finally
Images.Free;
end;
Review Images Documentation for more info.
Function Calling
In an API call, you can describe functions to gpt-3.5-turbo-0613 and gpt-4-0613, and have the model intelligently choose to output a JSON object containing arguments to call those functions. The Chat Completions API does not call the function; instead, the model generates JSON that you can use to call the function in your code.
The latest models (gpt-3.5-turbo-0613 and gpt-4-0613) have been fine-tuned to both detect when a function should to be called (depending on the input) and to respond with JSON that adheres to the function signature. With this capability also comes potential risks. We strongly recommend building in user confirmation flows before taking actions that impact the world on behalf of users (sending an email, posting something online, making a purchase, etc).
var Chat := OpenAI.Chat.Create(
procedure(Params: TChatParams)
begin
Params.Functions(Funcs); //list of functions (TArray<IChatFunction>)
Params.FunctionCall(TFunctionCall.Auto);
Params.Messages([TChatMessageBuild.User(Text)]);
Params.MaxTokens(1024);
end);
try
for var Choice in Chat.Choices do
if Choice.FinishReason = TFinishReason.FunctionCall then
ProcFunction(Choice.Message.FunctionCall) // execute function (send result to chat, and continue)
else
MemoChat.Lines.Add(Choice.Message.Content);
finally
Chat.Free;
end;
...
procedure ProcFunction(Func: TChatFunctionCall);
begin
var FuncResult := Execute(Func.Name, Func.Arguments); //execute function and get result (json)
var Chat := OpenAI.Chat.Create(
procedure(Params: TChatParams)
begin
Params.Functions(Funcs); //list of functions (TArray<IChatFunction>)
Params.FunctionCall(TFunctionCall.Auto);
Params.Messages([ //need all history
TChatMessageBuild.User(Text),
TChatMessageBuild.NewAsistantFunc(Func.Name, Func.Arguments),
TChatMessageBuild.Func(FuncResult, Func.Name)]);
Params.MaxTokens(1024);
end);
try
for var Choice in Chat.Choices do
MemoChat.Lines.Add(Choice.Message.Content);
finally
Chat.Free;
end;
end;
Review Functions Documentation for more info.
Errors
try
var Images := OpenAI.Image.Create(...);
except
on E: OpenAIExceptionRateLimitError do
ShowError('OpenAI Limit Error: ' + E.Message);
on E: OpenAIException do
ShowError('OpenAI Error: ' + E.Message);
end;
Exceptions
- OpenAIExceptionAPI - errors of wrapper
- OpenAIException - base exception
- OpenAIExceptionInvalidRequestError
- OpenAIExceptionRateLimitError
- OpenAIExceptionAuthenticationError
- OpenAIExceptionPermissionError
- OpenAIExceptionTryAgain
- OpenAIExceptionInvalidResponse - parse error
Proxy
OpenAI.API.ProxySettings := TProxySettings.Create(
ProxyHost,
ProxyPort,
ProxyUserName,
ProxyPassword);
Preparing mechanism
If a third-party API requires some actions before making a request, then use the IAPIPrepare interface and the Prepare property.
var client := TOpenAI.Create('https://gigachat.devices.sberbank.ru/api/v1', '');
сlient.Prepare := TApiPrepareGigaChat.Create(
'<client_id>',
'<auth_key>');
var response := client.Chat.Create(...);
Examples
ChatGPT (FMX)
Requirements
This library does not require a third-party library. It targets Delphi 11+; the
current test suite and package builds are verified with RAD Studio 13.1 on Win32
and Win64. Other compiler versions and non-Windows targets require separate
validation. Native WebSocket transport is available on Windows; other platforms
must supply an adapter. Rebuild dependent packages and applications after updating
the units and extended IOpenAI interface (its GUID has changed).
Since the library requires your secret API key, it’s not recommended you use it on client applications, as your secret key will be exposed, unless you are sure about the security risks.
Links
License
MIT License
Copyright (c) 2023 HemulGM
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Made with :heart: on Delphi
评论