{"id":25475074,"url":"https://github.com/maxidonkey/delphigenai","last_synced_at":"2025-08-04T21:35:27.537Z","repository":{"id":276468035,"uuid":"919117703","full_name":"MaxiDonkey/DelphiGenAI","owner":"MaxiDonkey","description":"The GenAI API wrapper for Delphi is designed to seamlessly integrate OpenAI's latest models (GPT-4o, o3, o4, and GPT-4.1), providing robust functionality for chat or response interactions for agents, text generation, vision processing, audio analysis, JSON configuration, web search, and asynchronous operations. Image generation with gpt-image-1","archived":false,"fork":false,"pushed_at":"2025-06-25T11:15:54.000Z","size":4205,"stargazers_count":44,"open_issues_count":0,"forks_count":13,"subscribers_count":8,"default_branch":"main","last_synced_at":"2025-06-25T12:26:14.261Z","etag":null,"topics":["agentic-ai","assistant","batch","chatgpt","delphi","fine-tuning","gpt","gpt-4-1","gpt-image-1","openai","openai-api","openai-o1","openai-o3","openai-o4","wrapper","wrapper-api"],"latest_commit_sha":null,"homepage":"","language":"Pascal","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MaxiDonkey.png","metadata":{"files":{"readme":"README.md","changelog":"Changelog.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-01-19T18:43:27.000Z","updated_at":"2025-06-25T11:15:58.000Z","dependencies_parsed_at":"2025-02-28T11:33:20.555Z","dependency_job_id":"c9bbd40a-1741-44ce-a651-71a88787adb7","html_url":"https://github.com/MaxiDonkey/DelphiGenAI","commit_stats":null,"previous_names":["maxidonkey/delphigenai"],"tags_count":10,"template":false,"template_full_name":null,"purl":"pkg:github/MaxiDonkey/DelphiGenAI","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MaxiDonkey%2FDelphiGenAI","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MaxiDonkey%2FDelphiGenAI/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MaxiDonkey%2FDelphiGenAI/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MaxiDonkey%2FDelphiGenAI/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MaxiDonkey","download_url":"https://codeload.github.com/MaxiDonkey/DelphiGenAI/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MaxiDonkey%2FDelphiGenAI/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263314159,"owners_count":23447294,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agentic-ai","assistant","batch","chatgpt","delphi","fine-tuning","gpt","gpt-4-1","gpt-image-1","openai","openai-api","openai-o1","openai-o3","openai-o4","wrapper","wrapper-api"],"created_at":"2025-02-18T11:52:49.879Z","updated_at":"2025-07-03T11:04:39.432Z","avatar_url":"https://github.com/MaxiDonkey.png","language":"Pascal","funding_links":[],"categories":[],"sub_categories":[],"readme":"# **Delphi GenAI - Optimized OpenAI Integration**\n\n___\n![Delphi async/await supported](https://img.shields.io/badge/Delphi%20async%2Fawait-supported-blue)\n![GitHub](https://img.shields.io/badge/IDE%20Version-Delphi%2010.4/11/12-ffffba)\n[![GetIt – Available](https://img.shields.io/badge/GetIt-Available-baffc9?logo=delphi\u0026logoColor=white)](https://getitnow.embarcadero.com/genai-optimized-openai-integration-wrapper/)\n![GitHub](https://img.shields.io/badge/platform-all%20platforms-baffc9)\n![GitHub](https://img.shields.io/badge/Updated%20on%20June%2013,%202025-blue)\n\n\u003cbr\u003e\n\nNEW: \n- Getit current version: 1.1.0\n- [Changelog v1.1.0](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/Changelog.md)\n- [Mini-lab to experiment with the v1/responses endpoint `File2knowledge`](https://github.com/MaxiDonkey/file2knowledge)  \n- [Responses endpoint](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/Responses.md)\n___\n\n\u003cbr\u003e\n\n- [Introduction](#introduction)\n- [Documentation Overview](#documentation-overview)\n- [TIPS for using the tutorial effectively](#tips-for-using-the-tutorial-effectively)\n    - [Strategies for quickly using the code examples](#strategies-for-quickly-using-the-code-examples)\n    - [Use file2knowledge](#use-file2knowledge)\n    - [Obtain an api key](#obtain-an-api-key)\n- [GenAI functional coverage](#genai-functional-coverage)\n- [Quick Start Guide](#quick-start-guide)\n    - [Responses vs. Chat Completions](#responses-vs-chat-completions)\n        - [Functional differences between the two endpoints](#functional-differences-between-the-two-endpoints)\n        - [Chat completion](#chat-completion)\n        - [Responses](#responses)\n    - [Models](#models)\n        - [List of models](#list-of-models)\n        - [Retrieve a model](#retrieve-a-model)\n        - [Delete a model](#delete-a-model)\n    - [Image generation](#image-generation)\n        - [Dall-e-3 model](#dall-e-3-model)\n        - [Gpt-image-1 model](#gpt-image-1-model)\n        - [Create image edit with gpt-image-1](#create-image-edit-with-gpt-image-1)\n    - [Text to speech](#text-to-speech)\n    - [Speech to text](#speech-to-text)\n    - [Embeddings](#embeddings)\n    - [Moderation](#moderation)\n        - [Moderate text inputs](#moderate-text-inputs)\n        - [Moderate images and text](#moderate-images-and-text)\n    - [Files](#files)\n        - [Files list](#files-list)\n        - [File upload](#file-upload)\n        - [File retrieve](#file-retrieve)\n        - [File retrieve content](#file-retrieve-content)\n        - [File Deletion](#file-deletion)\n- [Beyond the Basics Advanced Usage](#beyond-the-basics-advanced-usage)  \n- [Legacy](#legacy)\n    - [Completion](#completion)\n    - [Streamed completion](#streamed-completion)\n- [Tips and tricks](#tips-and-tricks)\n    - [How to prevent an error when closing an application while requests are still in progress?](#how-to-prevent-an-error-when-closing-an-application-while-requests-are-still-in-progress)\n    - [How to execute multiple background requests to process a batch of responses?](#how-to-execute-multiple-background-requests-to-process-a-batch-of-responses)\n    - [How to structure a chain of thought and develop advanced processing with GenAI?](#how-to-structure-a-chain-of-thought-and-develop-advanced-processing-with-genai)\n    - [How do you structure advanced reasoning using Promises and pipelines?](#how-do-you-structure-advanced-reasoning-using-promises-and-pipelines)\n- [Contributing](#contributing)\n- [License](#license)\n\n___\n\n\u003cbr\u003e\n\n# Introduction\n\n\u003e **Built with Delphi 12 Community Edition** (v12.1 Patch 1)  \n\u003eThe wrapper itself is MIT-licensed.  \n\u003eYou can compile and test it free of charge with Delphi CE; any recent commercial Delphi edition works as well.\n\n**GenAI** is a powerful Delphi library that brings the latest OpenAI APIs to your desktop, mobile, and server apps.\n\n**Core capabilities**  \n- Unified access to text, vision, speech, and audio endpoints  \n- Agentic workflows via the `v1/responses` endpoint, with built-in tools `file_search`, `web_search`, `Code Interpreter`, and `remote MCP`  \n- Supports state-of-the-art models, including ***gpt-4o***, ***gpt-4.1***, ***gpt-4.5*** and the reasoning-centric *o1 · o3 · o4* series  \n\n**Developer tooling**  \n- Ready-made `Sync`, `Async`, and `Await` code snippets (TutorialHUB compatible)  \n- Batch processing, function calling, file management, and content moderation out of the box  \n- Built-in DUnit test helpers and a modular JSON configuration for streamlined setup  \n- Mock-friendly design: the HTTP layer is injected via dependency injection, so you can swap in stubs or fakes for testing  \n\nIntegrate OpenAI into Delphi—no boilerplate, just results.\n\n_Check out the full [GenAI project](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/GenAI.md) for details._\n\n\u003cbr\u003e\n\n\u003e [!IMPORTANT]\n\u003e\n\u003e This is an unofficial library. **OpenAI** does not provide any official library for `Delphi`.\n\u003e This repository contains `Delphi` implementation over [OpenAI](https://openai.com/) public API.\n\n\u003cbr\u003e\n\n___\n\n# Documentation Overview\n\nComprehensive Project Documentation Reference\n\n- [Changelog](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/Changelog.md)\n- [About this project](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/GenAI.md)\n- [Chat completion](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/ChatCompletion.md)\n- [Responses](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/Responses.md)\n- [Beyond the Basics Advanced Usage](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/BeyondBasics.md)\n\n\u003cbr\u003e\n\n___\n\n# TIPS for using the tutorial effectively\n\n## Strategies for quickly using the code examples\n\nTo streamline the implementation of the code examples provided in this tutorial, two support units have been included in the source code: `GenAI.Tutorial.VCL` and `GenAI.Tutorial.FMX` Based on the platform selected for testing the provided examples, you will need to initialize either the `TVCLTutorialHub` or `TFMXTutorialHub` class within the application's OnCreate event, as illustrated below:\n\n\u003e[!IMPORTANT]\n\u003eIn this repository, you will find in the [`sample`](https://github.com/MaxiDonkey/DelphiGenAI/tree/main/sample) folder two ***ZIP archives***, each containing a template to easily test all the code examples provided in this tutorial. \n\u003eExtract the `VCL` or `FMX` version depending on your target platform for testing. \n\u003eNext, add the path to the DelphiGenAI library in your project’s options, then copy and paste the code examples for immediate execution. \n\u003e\n\u003eThese two archives have been designed to fully leverage the TutorialHub middleware and enable rapid upskilling with DelphiGenAI.\n\n- [**`VCL`**](https://github.com/MaxiDonkey/DelphiGenAI/tree/main/sample) support with TutorialHUB: ***TestGenAI_VCL.zip***\n\n- [**`FMX`**](https://github.com/MaxiDonkey/DelphiGenAI/tree/main/sample) support with TutorialHUB: ***TestGenAI_FMX.zip***\n\n\u003cbr\u003e\n\n## [Use file2knowledge](https://github.com/MaxiDonkey/file2knowledge)\n\nThis [project](https://github.com/MaxiDonkey/file2knowledge), built with `DelphiGenAI` , allows you to consult GenAI documentation and code in order to streamline and accelerate your upskilling.\n\n![Preview](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/images/File2knowledge.png?raw=true \"Preview\")\n\n\u003cbr\u003e\n\n## Obtain an api key\n\nTo initialize the API instance, you need to obtain an [API key from OpenAI](https://platform.openai.com/settings/organization/api-keys)\n\nOnce you have a token, you can initialize IGenAI interface, which is an entry point to the API.\n\n\u003e[!NOTE]\n\u003e```Delphi\n\u003e//uses GenAI, GenAI.Types;\n\u003e\n\u003e//Declare \n\u003e//  Client: IGenAI;\n\u003e\n\u003e  Client := TGenAIFactory.CreateInstance(api_key);\n\u003e```\n\nTo streamline the use of the API wrapper, the process for declaring units has been simplified. Regardless of the methods being utilized, you only need to reference the following two core units:\n`GenAI` and `GenAI.Types`.\n\n\u003cbr\u003e\n\n\u003e[!TIP]\n\u003e To effectively use the examples in this tutorial, particularly when working with asynchronous methods, it is recommended to define the client interfaces with the broadest possible scope. For optimal implementation, these clients should be declared in the application's `OnCreate` method.\n\u003e\n\n\u003cbr\u003e\n\n___\n\n# GenAI functional coverage\n\nBelow, the table succinctly summarizes all OpenAI endpoints supported by the GenAI.\n\n|End point | supported | \n|--- |:---: | \n| [/assistants](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/BeyondBasics.md#assistants) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/audio/speech](https://github.com/MaxiDonkey/DelphiGenAI/tree/main?tab=readme-ov-file#text-to-speech) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/audio/transcriptions](https://github.com/MaxiDonkey/DelphiGenAI/tree/main?tab=readme-ov-file#speech-to-text) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/audio/translations](https://github.com/MaxiDonkey/DelphiGenAI/tree/main?tab=readme-ov-file#speech-to-text) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/batches](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/BeyondBasics.md#batch) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/chat/completions](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/ChatCompletion.md#chat-completion) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/completions](https://github.com/MaxiDonkey/DelphiGenAI/tree/main?tab=readme-ov-file#legacy) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/embeddings](https://github.com/MaxiDonkey/DelphiGenAI/tree/main?tab=readme-ov-file#embeddings) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| /evals |  |\n| [/files](https://github.com/MaxiDonkey/DelphiGenAI/tree/main?tab=readme-ov-file#files) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/fine_tuning](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/BeyondBasics.md#fine-tuning) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/images](https://github.com/MaxiDonkey/DelphiGenAI/tree/main?tab=readme-ov-file#image-generation) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/models](https://github.com/MaxiDonkey/DelphiGenAI/tree/main?tab=readme-ov-file#models) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/moderations](https://github.com/MaxiDonkey/DelphiGenAI/tree/main?tab=readme-ov-file#moderation) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| /organization |  |\n| /realtime |  |\n| [/responses](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/Responses.md#responses) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/threads](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/BeyondBasics.md#threads) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/uploads](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/BeyondBasics.md#uploads) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| [/vector_stores](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/BeyondBasics.md#vector-store) | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n\n\u003cbr\u003e\n\n___\n\n# Quick Start Guide\n\n## Responses vs. Chat Completions\n\nThe `v1/responses` API is the new core API, designed as an agentic primitive that combines the simplicity of chat completions with the power of action execution. It natively includes several built‑in tools:\n- Web search\n- File search\n- Computer control\n- Image generation\n- Remote MCP\n- Code interpreter\n\nWith these integrated capabilities, you can build more autonomous, agent‑oriented applications that not only generate text but also interact with their environment.\n\nThe `v1/responses` endpoint is intended to gradually replace `v1/chat/completions`, as it embodies a synthesis of current best practices in AI—especially for those looking to adopt an agentic approach.\n\nTo help you get up to speed on both endpoints, the two following documents provide detailed documentation, complete with numerous request examples and use cases:\n- [v1/chat/completion](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/ChatCompletion.md#chat-completion)\n- [v1/responses](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/Responses.md)\n\n\u003e[!NOTE]\n\u003eIf you're a new user, we recommend using the Responses API.\n\n\u003cbr\u003e\n\n### Functional differences between the two endpoints\n\n|Capabilities | [Chat Completions API](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/ChatCompletion.md#chat-completion) | [Responses API](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/Responses.md) |\n|--- |:---: | :---: |\n|Text generation | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| Audio  | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e | Coming soon | \n| Vision | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| Structured Outputs | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| Function calling | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| Web search | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| File search |  | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| Computer use |  | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| Code interpreter |  | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| Image generation | | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n| Remote MCP | | \u003cdiv align=\"center\"\u003e\u003cspan style=\"color: green;\"\u003e●\u003c/span\u003e\u003c/div\u003e |\n\n\u003e[!WARNING]\n\u003e [Note from OpenAI](https://platform.openai.com/docs/guides/responses-vs-chat-completions#the-chat-completions-api-is-not-going-away) \u003cbr\u003e\n\u003e The Chat Completions API is an industry standard for building AI applications, and we intend to continue supporting this API indefinitely. We're introducing the Responses API to simplify workflows involving tool use, code execution, and state management. We believe this new API primitive will allow us to more effectively enhance the OpenAI platform into the future.\n\n\u003cbr\u003e\n\n### [Chat completion](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/ChatCompletion.md#chat-completion)\n\nCheck out the full [documentation](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/ChatCompletion.md#chat-completion)\n\nText generation (Non streamed, Streamed, Multi-turn conversations), Generating Audio Responses with Chat (Audio and Text to Text, Audio to Audio, Audio multi-turn conversations), Vision (Analyze single source, Analyze multi-source, Low or high fidelity image understanding), Reasoning with o1, o3 or o4,  Web search...\n\n\u003cbr\u003e\n\n### [Responses](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/Responses.md)\n\nCheck out the full [documentation](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/Responses.md)\n\nText generation (Non streamed, Streamed, Multi-turn conversations), Vision (Analyze single source, Analyze multi-source, Low or high fidelity image understanding), Reasoning with o1, o3 or o4, Web search, File search...\n\n\n\u003cbr\u003e\n\n___\n\n## Models\n\nRefert to [official documentation](https://platform.openai.com/docs/models).\n\n### List of models\n\nThe list of available models can be retrieved from the Models API response. The models are ordered by release date, with the most recently published appearing first.\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  TutorialHub.JSONRequestClear;\n\n  //Asynchronous example\n  Client.Models.AsynList(\n    function : TAsynModels\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Models.List;\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n\n  //Asynchronous promise example\n//  var Promise := Client.Models.AsyncAwaitList;\n//\n//  Promise\n//    .\u0026Then\u003cTModels\u003e(\n//      function (Value: TModels): TModels\n//      begin\n//        Display(TutorialHub, Value);\n//        Result := Value;\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\n\n\u003cbr/\u003e\n\n### Retrieve a model\n\nRetrieve a model using its ID.\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  TutorialHub.JSONRequestClear;\n  TutorialHub.ModelId := '...the id tio retrieve...';\n\n  //Asynchronous example\n  Client.Models.AsynRetrieve(TutorialHub.ModelId,\n    function : TAsynModel\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Models.Retrieve(TutorialHub.ModelId);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n\n  //Asynchronous promise example\n//  var Promise := Client.Models.AsyncAwaitRetrieve(TutorialHub.ModelId);\n//\n//  Promise\n//    .\u0026Then\u003cstring\u003e(\n//      function (Value: TModel): string\n//      begin\n//        Result := Value.Id;\n//        Display(TutorialHub, Value);\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\n\n\u003cbr/\u003e\n\n### Delete a model\n\nDeleting a model is only possible if the model is one of your fine-tuned models.\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  TutorialHub.JSONRequestClear;\n  TutorialHub.ModelId := '...Id of the model to delete...';\n\n  //Asynchronous example\n  Client.Models.AsynDelete(TutorialHub.ModelId,\n    function : TAsynDeletion\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Models.Delete(TutorialHub.ModelId);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n\n  //Asynchronous promise example\n//  var Promise := Client.Models.AsyncAwaitDelete(TutorialHub.ModelId);\n//\n//  Promise\n//    .\u0026Then\u003cstring\u003e(\n//      function (Value: TDeletion): string\n//      begin\n//        Result := Value.Id;\n//        Display(TutorialHub, Value);\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\n\n\u003cbr/\u003e\n\n___\n\n## Image generation\n\nRefer to [official documentation](https://platform.openai.com/docs/guides/images).\n\n### Dall-e-3 model\n\nGeneration of an image using `dall-e-3`.\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  TutorialHub.FileName := 'Dalle3_01.png';\n\n  //Asynchronous example\n  Client.Images.AsynCreate(\n    procedure (Params: TImageCreateParams)\n    begin\n      Params.Model('dall-e-3');\n      Params.Prompt('A quarter dollar on a wooden floor close up.');\n      Params.N(1);\n      Params.Size('1024x1024');\n      Params.Style('vivid');\n      Params.ResponseFormat(TResponseFormat.url);\n    end,\n    function : TAsynGeneratedImages\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Images.Create(\n//    procedure (Params: TImageCreateParams)\n//    begin\n//      Params.Model('dall-e-3');\n//      Params.Prompt('A quarter dollar on a wooden floor close up.');\n//      Params.N(1);\n//      Params.Size('1024x1024');\n//      Params.Style('vivid');\n//      Params.ResponseFormat(url);\n//      TutorialHub.JSONResponse := Value.JSONResponse;\n//    end);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n\n  //Asynchronous promise example\n//  var Promise := Client.Images.AsyncAwaitCreate(\n//    procedure (Params: TImageCreateParams)\n//    begin\n//      Params.Model('dall-e-3');\n//      Params.Prompt('A quarter dollar on a wooden floor close up.');\n//      Params.N(1);\n//      Params.Size('1024x1024');\n//      Params.Style('vivid');\n//      Params.ResponseFormat(TResponseFormat.url);\n//    end\n//  );\n//\n//  Promise\n//    .\u0026Then\u003cTGeneratedImages\u003e(\n//      function (Value: TGeneratedImages): TGeneratedImages\n//      begin\n//        Result := Value;\n//        Display(TutorialHub, Value);\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\n\n\u003cbr\u003e\n\nLet’s take a closer look at how the `Display` method handles output to understand how the model’s response is managed.\n\n```Delphi\nprocedure Display(Sender: TObject; Value: TGeneratedImages);\nbegin\n  {--- Load image when url is not null. }\n  if not TutorialHub.FileName.IsEmpty then\n    begin\n      if not Value.Data[0].Url.IsEmpty then\n        Value.Data[0].Download(TutorialHub.FileName) else\n        Value.Data[0].SaveToFile(TutorialHub.FileName);\n    end;\n\n  {--- Load image into a stream }\n  var Stream := Value.Data[0].GetStream;\n  try\n    {--- Display the JSON response. }\n    TutorialHub.JSONResponse := Value.JSONResponse;\n\n    {--- Display the revised prompt. }\n    Display(Sender, Value.Data[0].RevisedPrompt);\n\n    {--- Load the stream into the TImage. }\n    TutorialHub.Image.Picture.LoadFromStream(Stream);\n  finally\n    Stream.Free;\n  end;\nend;\n```\n\n`GenAI` offers optimized methods for managing image responses generated by the model. The `SaveToFile`, `Download`, and `GetStream` methods enable efficient handling of the received image content.\n\n\u003cbr\u003e\n\n![Preview](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/images/DallePreview.png?raw=true \"Preview\")\n\n\u003cbr\u003e\n\n\n### Gpt-image-1 model\n\nSince May 5, 2025, OpenAI has offered the `gpt-image-1` model for image creation and editing. This new model delivers higher quality compared to `dall-e-2` and `dall-e-3`.\n\nIn the configuration, you now have four additional parameters for image generation:\n- **background:** Allows you to set the transparency of the generated image’s background. Only supported by `gpt-image-1`. Must be one of `transparent`, `opaque`, or `auto` (default).\n\n- **moderation:** Controls the content-moderation level for images generated by `gpt-image-1`. Must be either` low` (less restrictive filtering) or `auto` (default).\n\n- **output_compression:** Specifies the compression level (0–100%) for the generated images. Only supported by `gpt-image-1` when using the `webp` or `jpeg` output formats; defaults to 100.\n\n- **output_format:** Determines the format in which generated images are returned. Only supported by `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.\n\n\u003cbr\u003e\n\nAdditionally, several existing parameters have been extended with new values for `gpt-image-1`:\n\nquality: Supports `high`, `medium`, and `low`.\n\nsize: Supports `1536×1024` (landscape), `1024×1536` (portrait), or `auto` (default).\n\nprompt: Allows up to 32,000 characters for `gpt-image-1` (versus 1,000 for `dall-e-2` and 4,000 for `dall-e-3`).\n\n\u003cbr\u003e\n\nAn example of image creation with gpt-image-1 (Asynchronous because response times are much longer):\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  TutorialHub.FileName := 'GptImage1.png';\n\n  //Increased reception timeout (ms) as the model takes longer\n  Client.API.HttpClient.ResponseTimeout := 120000;\n\n  //Asynchronous example\n  Client.Images.AsynCreate(\n    procedure (Params: TImageCreateParams)\n    begin\n      Params.Model('gpt-image-1'); //'dall-e-3');\n      Params.Prompt('A realistic photo of a coffee cup with saucer on a transparent background');\n      Params.N(1);\n      Params.Size('1536x1024');\n      Params.BackGround('transparent');\n      Params.Moderation('low');\n      Params.OutputFormat('png');\n      Params.Quality('high');\n      TutorialHub.JSONRequest := Params.ToFormat();\n    end,\n    function : TAsynGeneratedImages\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Asynchronous promise example\n//  var Promise := Client.Images.AsyncAwaitCreate(\n//    procedure (Params: TImageCreateParams)\n//    begin\n//      Params.Model('gpt-image-1');\n//      Params.Prompt('A realistic photo of a coffee cup with saucer on a transparent background');\n//      Params.N(1);\n//      Params.Size('1536x1024');\n//      Params.BackGround('transparent');\n//      Params.Moderation('low');\n//      Params.OutputFormat('png');\n//      Params.Quality('high');\n//    end\n//  );\n//\n//  Promise\n//    .\u0026Then\u003cTGeneratedImages\u003e(\n//      function (Value: TGeneratedImages): TGeneratedImages\n//      begin\n//        Result := Value;\n//        Display(TutorialHub, Value);\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\n\n\u003cbr\u003e\n\n![Preview](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/images/CreationGpt-image-1.png?raw=true \"Preview\")\n\n\u003cbr\u003e\n\n\u003e[!NOTE]\n\u003eWe can notice in the returned JSON the usage values ​​which are not provided with the dall-e-2 and dall-e-3 models.\n\n\u003cbr\u003e\n\n### Create image edit with gpt-image-1\n\nPreviously, I hadn’t gone into detail about the image-editing process, because the only model available at OpenAI—`DALL·E 2`—produced rather unconvincing results.\n\nHowever, with `gpt-image-1`, the output quality is significantly higher.\n\nTo perform an edit:\n\n1. Prepare your base image\n     - Open the image you wish to modify and erase the area to be reworked using a transparency tool (brush or selection).\n\n2. Generate the mask\n     - The erased (transparent) region becomes the mask that you’ll supply to the model.\n\n3. Compose your extended prompt\n     - In your request, describe exactly what the model should insert into the masked area. You now have up to 32,000 tokens for a fully detailed description.\n\n4. Execute the edit\n     - Provide the model with both the masked image and your prompt; it will then know precisely where and how to apply the changes.\n\nBelow, you’ll find an example of the code to send to gpt-image-1 to initiate the edit.\n\n\u003cbr\u003e\n\n```Delphi\n  TutorialHub.FileName := 'Image-gpt-edit.png';\n\n  //Increased reception timeout (ms) as the model takes longer\n  Client.API.HttpClient.ResponseTimeout := 120000;\n\n  //Asynchronous example\n  Client.Images.AsynEdit(\n    procedure (Params: TImageEditParams)\n    begin\n      Params.Model('gpt-image-1');\n      Params.Image('Dalle05.png');          //\u003c--- Unmodified image\n      Params.Mask('Dalle05Mask.png');       //\u003c--- Modified image with masked part\n      Params.Prompt('Add a pink elephant'); //\u003c--- Replace the mask by building this\n      Params.Size('1024x1024');\n      TutorialHub.JSONRequest := Params.ToFormat();\n    end,\n    function : TAsynGeneratedImages\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Asynchronous promise example\n//  var Promise := Client.Images.AsyncAwaitEdit(\n//    procedure (Params: TImageEditParams)\n//    begin\n//      Params.Model('gpt-image-1');\n//      Params.Image('Dalle05.png');          //\u003c--- Unmodified image\n//      Params.Mask('Dalle05Mask.png');       //\u003c--- Modified image with masked part\n//      Params.Prompt('Add a pink elephant'); //\u003c--- Replace the mask by building this\n//      Params.Size('1024x1024');\n//    end);\n//\n//  Promise\n//    .\u0026Then\u003cTGeneratedImages\u003e(\n//      function (Value: TGeneratedImages): TGeneratedImages\n//      begin\n//        Result := Value;\n//        Display(TutorialHub, Value);\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\n\n\u003cbr\u003e\n\n- Result with the hidden section:\n\n![Preview](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/images/GptImageMask.png?raw=true \"Preview\")\n\n- Result after editing:\n\n![Preview](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/images/GptImageEditResult.png?raw=true \"Preview\")\n\n___\n\n## Text to speech\n\nConvert a text into an audio file. Refer to [official documentation](https://platform.openai.com/docs/guides/text-to-speech)\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  TutorialHub.JSONRequestClear;\n  TutorialHub.FileName := 'Speech.mp3';\n\n  //Asynchronous example\n  Client.Audio.AsynSpeech(\n    procedure (Params: TSpeechParams)\n    begin\n      Params.Model('gpt-4o-mini-tts');\n      Params.Input('Hi! what are you doing ?');\n      Params.Voice('fable');\n      Params.ResponseFormat(TSpeechFormat.mp3);\n      TutorialHub.JSONRequest := Params.ToFormat();\n    end,\n    function : TAsynSpeechResult\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Audio.Speech(\n//    procedure (Params: TSpeechParams)\n//    begin\n//      Params.Model('gpt-4o-mini-tts');\n//      Params.Input('Hi! what are you doing ?');\n//      Params.Voice(alloy);\n//      Params.ResponseFormat(mp3);\n//      TutorialHub.JSONResponse := Value.JSONResponse;\n//    end);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;  \n\n  //Asynchronous promise example\n//  var Promise := Client.Audio.AsyncAwaitSpeech(\n//    procedure (Params: TSpeechParams)\n//    begin\n//      Params.Model('gpt-4o-mini-tts');\n//      Params.Input('Hi! what are you doing ?');\n//      Params.Voice('fable');\n//      Params.ResponseFormat(TSpeechFormat.mp3);\n//      TutorialHub.JSONRequest := Params.ToFormat();\n//    end);\n//\n//  Promise\n//    .\u0026Then\u003cTSpeechResult\u003e(\n//      function (Value: TSpeechResult): TSpeechResult\n//      begin\n//        Result := Value;\n//        Display(TutorialHub, Value);\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\n\u003cbr\u003e\n\nLet’s take a closer look at how the `Display` method handles output to understand how the model’s response is managed.\n\n```Delphi\nprocedure Display(Sender: TObject; Value: TSpeechResult);\nbegin\n  {--- Display the JSON response }\n  TutorialHub.JSONResponse := Value.JSONResponse;\n\n  {--- The file name can not be null }\n  if TutorialHub.FileName.IsEmpty then\n    raise Exception.Create('Set filename value in HFTutorial instance');\n\n  {--- Save the audio into a file. }\n  Value.SaveToFile(TutorialHub.FileName);\n\n  {--- Play the audio result }\n  TutorialHub.PlayAudio;\nend;\n```\n\n`GenAI` provides methods to handle audio responses generated by the model. The `SaveToFile` and `GetStream` methods enable the manipulation of received audio content.\n\n\u003cbr\u003e\n\n___\n\n## Speech to text\n\nConvert data audio into a text. Refer to [official documentation](https://platform.openai.com/docs/guides/speech-to-text) or this [page](https://platform.openai.com/docs/guides/audio).\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  TutorialHub.JSONRequest := 'multipart';\n\n  //Asynchronous example\n  Client.Audio.AsynTranscription(\n    procedure (Params: TTranscriptionParams)\n    begin\n      Params.\u0026File('SpeechRecorded.wav');\n      Params.Model('whisper-1');\n      Params.ResponseFormat(TTranscriptionResponseFormat.verbose_json);\n    end,\n    function : TAsynTranscription\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Audio.Transcription(\n//    procedure (Params: TTranscriptionParams)\n//    begin\n//      Params.\u0026File('SpeechRecorded.wav');\n//      Params.Model('whisper-1');\n//    end);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n\n  //Asynchronous promise example\n//  var Promise := Client.Audio.AsyncAwaitTranscription(\n//    procedure (Params: TTranscriptionParams)\n//    begin\n//      Params.\u0026File('SpeechRecorded.wav');\n//      Params.Model('gpt-4o-transcribe');\n//    end);\n//\n//  Promise\n//    .\u0026Then\u003cTTranscription\u003e(\n//      function (Value: TTranscription): TTranscription\n//      begin\n//        Result := Value;\n//        Display(TutorialHub, Value);\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\n\n\u003cbr\u003e\n\n___\n\n## Embeddings\n\n**OpenAI’s** text embeddings evaluate how closely related different text strings are. These embeddings serve as a powerful tool for various applications, including:\n\n- **Search:** Ranking results based on their relevance to a given query.\n- **Clustering:** Grouping similar text strings together based on shared characteristics.\n- **Recommendations:** Suggesting items that share similar text content.\n- **Anomaly detection:** Identifying outliers by finding text strings with minimal similarity to the rest.\n- **Diversity measurement:** Analyzing the distribution of similarities within a dataset.\n- **Classification:** Assigning text strings to the category or label they closely align with.\n\nAn embedding is represented as a vector, or a list of floating-point numbers. The relatedness between two text strings is determined by measuring the distance between their respective vectors: smaller distances indicate strong similarity, while larger distances imply weaker relatedness.\n\nRefer to [official documentation](https://platform.openai.com/docs/guides/embeddings).\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  TutorialHub.JSONRequestClear;\n\n  //Asynchronous example\n  Client.Embeddings.ASynCreate(\n    procedure (Params: TEmbeddingsParams)\n    begin\n      Params.Input(['Hello', 'how', 'are you?']);\n      Params.Model('text-embedding-3-large');\n      Params.Dimensions(5);\n      Params.EncodingFormat(TEncodingFormat.float);\n      TutorialHub.JSONRequest := Params.ToFormat();\n    end,\n    function : TAsynEmbeddings\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Embeddings.Create(\n//    procedure (Params: TEmbeddingsParams)\n//    begin\n//      Params.Input(['Hello', 'how', 'are you?']);\n//      Params.Model('text-embedding-3-large');\n//      Params.Dimensions(5);\n//      Params.EncodingFormat(TEncodingFormat.float);\n//    end);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n\n  //Asynchronous promise example\n//  var Promise := Client.Embeddings.AsyncAwaitCreate(\n//    procedure (Params: TEmbeddingsParams)\n//    begin\n//      Params.Input(['Hello', 'how', 'are you?']);\n//      Params.Model('text-embedding-3-large');\n//      Params.Dimensions(5);\n//      Params.EncodingFormat(TEncodingFormat.float);\n//      TutorialHub.JSONRequest := Params.ToFormat();\n//    end\n//  );\n//\n//  Promise\n//    .\u0026Then\u003cTArray\u003cTArray\u003cDouble\u003e\u003e\u003e(\n//       function (Value: TEmbeddings): TArray\u003cTArray\u003cDouble\u003e\u003e\n//       begin\n//         Display(TutorialHub, Value);\n//         for var Item in Value.Data do\n//           Result := Result + [Item.Embedding];\n//         ShowMessage(Result[2][3].ToString(ffNumber, 2, 3));\n//       end)\n//    .\u0026Catch(\n//       procedure (E: Exception)\n//       begin\n//         Display(TutorialHub, E.Message);\n//       end);\n```\n\n\u003cbr\u003e\n\n___\n\n## Moderation\n\nThe moderation endpoint is a valuable resource for detecting potentially harmful text or images. When harmful content is identified, developers can take appropriate measures, such as filtering the content or managing user accounts responsible for the violations. This service is provided free of charge.\n\nAvailable models for the moderation endpoint include:\n\n- **omni-moderation-latest:** The most advanced model, supporting a wider range of content categorization and multi-modal inputs (both text and images).\n\n- **text-moderation-latest (Legacy):** An older model designed exclusively for text-based inputs with limited categorization options. For new projects, the omni-moderation model is recommended due to its superior capabilities and broader input support.\n\nRefer to the [official documentation](https://platform.openai.com/docs/guides/moderation).\n\n\u003cbr\u003e\n\n### Moderate text inputs\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  //Asynchronous example\n  Client.Moderation.AsynEvaluate(\n    procedure (Params: TModerationParams)\n    begin\n      Params.Input('...text to classify goes here...');\n      Params.Model('omni-moderation-latest');\n      TutorialHub.JSONRequest := Params.ToFormat();\n    end,\n    function : TAsynModeration\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Moderation.Evaluate(\n//    procedure (Params: TModerationParams)\n//    begin\n//      Params.Input('...text to classify goes here...');\n//      Params.Model('omni-moderation-latest');\n//      TutorialHub.JSONRequest := Params.ToFormat();\n//      TutorialHub.JSONRequest := Params.ToFormat();\n//    end);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n\n  //Asynchronous promise example\n//  var Promise := Client.Moderation.AsyncAwaitEvaluate(\n//    procedure (Params: TModerationParams)\n//    begin\n//      Params.Input('...text to classify goes here...');\n//      Params.Model('omni-moderation-latest');\n//      TutorialHub.JSONRequest := Params.ToFormat();\n//    end);\n//\n//  Promise\n//    .\u0026Then\u003cTModeration\u003e(\n//       function (Value: TModeration): TModeration\n//       begin\n//         Display(TutorialHub, Value);\n//         Result := Value;\n//       end)\n//    .\u0026Catch(\n//       procedure (E: Exception)\n//       begin\n//         Display(TutorialHub, E.Message);\n//       end);\n```\n\n\u003cbr\u003e\n\n### Moderate images and text\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  var Ref := 'https://example.com/image.png';\n\n  //Asynchronous example\n  Client.Moderation.AsynEvaluate(\n    procedure (Params: TModerationParams)\n    begin\n      Params.Input(['...text to classify goes here...', Ref]);\n      Params.Model('omni-moderation-latest');\n      TutorialHub.JSONRequest := Params.ToFormat();\n    end,\n    function : TAsynModeration\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Moderation.Evaluate(\n//    procedure (Params: TModerationParams)\n//    begin\n//      Params.Input(['...text to classify goes here...', Ref]);\n//      Params.Model('omni-moderation-latest');\n//      TutorialHub.JSONRequest := Params.ToFormat();\n//      TutorialHub.JSONRequest := Params.ToFormat();\n//    end);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n\n  //Asynchronous promise example\n//  var Promise := Client.Moderation.AsyncAwaitEvaluate(\n//    procedure (Params: TModerationParams)\n//    begin\n//      Params.Input(['...text to classify goes here...', Ref]);\n//      Params.Model('omni-moderation-latest');\n//      TutorialHub.JSONRequest := Params.ToFormat();\n//    end);\n//\n//  Promise\n//    .\u0026Then\u003cTModeration\u003e(\n//       function (Value: TModeration): TModeration\n//       begin\n//         Display(TutorialHub, Value);\n//         Result := Value;\n//       end)\n//    .\u0026Catch(\n//       procedure (E: Exception)\n//       begin\n//         Display(TutorialHub, E.Message);\n//       end);\n```\n\u003cbr\u003e\n\n`GenAI` offers an efficient and streamlined approach for handling categories and scores generated by the moderation process. Specifically, the display method is designed for simplicity and ease of use, as demonstrated in the example below.\n\n```Delphi\nprocedure Display(Sender: TObject; Value: TModerationResult);\nbegin\n {--- GenAI built the FlaggedDetail property which contains only active moderation categories. }\n  for var Item in Value.FlaggedDetail do\n    Display(Sender, [\n      EmptyStr,\n      F(Item.Category.ToString, Item.Score.ToString(ffNumber, 3, 3))\n    ]);\n  Display(Sender);\nend;\n\nprocedure Display(Sender: TObject; Value: TModeration);\nbegin\n  TutorialHub.JSONResponse := Value.JSONResponse;\n  for var Item in Value.Results do\n    Display(Sender, Item);\n  Display(Sender);\nend;\n```\n\n\u003cbr\u003e\n\n___\n\n## Files\n\nFiles are used to upload documents that can be used with features like **Assistants**, **Fine-tuning**, and **Batch API**.\n\n\u003cbr/\u003e\n\n### Files list\n\nExample without parameters\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  //Asynchronous example\n  Client.Files.AsynList(\n    function : TAsynFiles\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Files.List;\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n\n    //Asynchronous promise example\n//  var Promise := Client.Files.AsyncAwaitList;\n//\n//  Promise\n//    .\u0026Then\u003cInteger\u003e(\n//      function (List: TFiles): Integer\n//      begin\n//        Display(TutorialHub, List);\n//        Result := Length(List.Data);\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\n\nExample using parameters\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  //Asynchronous example\n  Client.Files.AsynList(\n    procedure (Params: TFileUrlParams)\n    begin\n      Params.Purpose('batch');\n      Params.Limit(10);\n    end,\n    function : TAsynFiles\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Files.List(\n//    procedure (Params: TFileUrlParams)\n//    begin\n//      Params.Purpose('batch');\n//      Params.Limit(10);\n//    end);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n\n  //Asynchronous promise example\n//  var Promise := Client.Files.AsyncAwaitList(\n//    procedure (Params: TFileUrlParams)\n//    begin\n//      Params.Purpose('user_data');\n//      Params.Limit(10);\n//    end);\n//\n//  Promise\n//    .\u0026Then\u003cInteger\u003e(\n//      function (List: TFiles): Integer\n//      begin\n//        Display(TutorialHub, List);\n//        Result := Length(List.Data);\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\n\nRefer to [parameters documentation](https://platform.openai.com/docs/api-reference/files/list).\n\n\u003cbr/\u003e\n\n### File upload\n\nYou can upload files for use across multiple endpoints. Each file can be as large as 512 MB, with a maximum combined storage limit of 100 GB per organization.\n\nThe Assistants API accommodates files containing up to 2 million tokens and accepts specific file formats. For more information, refer to the [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools).\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  //Asynchronous example\n  Client.Files.AsynUpload(\n    procedure (Params: TFileUploadParams)\n    begin\n      Params.\u0026File('BatchExample.jsonl');\n      Params.Purpose(TFilesPurpose.batch);\n    end,\n    function : TAsynFile\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Files.Upload(\n//    procedure (Params: TFileUploadParams)\n//    begin\n//      Params.\u0026File('BatchExample.jsonl');\n//      Params.Purpose(fp_batch);\n//    end);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n\n    //Asynchronous promise example\n//  var Promise := Client.Files.AsyncAwaitUpload(\n//    procedure (Params: TFileUploadParams)\n//    begin\n//      Params.\u0026File(Document);\n//      Params.Purpose(TFilesPurpose.user_data);\n//    end,\n//    function : TPromiseFile\n//    begin\n//      Result.Sender := TutorialHub;\n//      Result.OnStart := Start;\n//    end);\n//\n//  Promise\n//    .\u0026Then\u003cTFile\u003e(\n//      function (Value: TFile): TFile\n//      begin\n//        Result := Value;\n//        Display(TutorialHub, Value);\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\nExample with batch file.\n\n\u003cbr/\u003e\n\n### File retrieve\n\nReturns information about a specific file.\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  TutorialHub.Id := '...Id file to retrieve...';\n\n  //Asynchronous example\n  Client.Files.AsynRetrieve(TutorialHub.Id,\n    function : TAsynFile\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Files.Retrieve(TutorialHub.Id);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n\n    //Asynchronous promise example\n//  var Promise := Client.Files.AsyncAwaitRetrieve(\n//    TutorialHub.Id,\n//    function : TPromiseFile\n//    begin\n//      Result.Sender := TutorialHub;\n//      Result.OnStart := Start;\n//    end);\n//\n//  Promise\n//    .\u0026Then\u003cTFile\u003e(\n//      function (Value: TFile): TFile\n//      begin\n//        Result := Value;\n//        Display(TutorialHub, Value);\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\n\n\u003cbr/\u003e\n\n### File retrieve content\n\nReturns the contents of the specified file.\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  TutorialHub.Id := '...Id of the file to retrieve content...';\n\n  //Asynchronous example\n  Client.Files.AsynRetrieveContent(TutorialHub.Id,\n    function : TAsynFileContent\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Files.RetrieveContent(TutorialHub.Id);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n```\n\n\u003cbr/\u003e\n\n### File Deletion\n\nDelete a file.\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  TutorialHub.Id := '...Id file to delete...';\n\n  //Synchronous example\n  var Value := Client.Files.Delete(TutorialHub.Id);\n  try\n    Display(TutorialHub, F('Deleted', BoolToStr(Value.Deleted, True)));\n  finally\n    Value.Free;\n  end;\n\n  //Asynchronous promise example\n//  var Promise := Client.Files.AsyncAwaitDelete(\n//    TutorialHub.Id);\n//\n//  promise\n//    .\u0026Then\u003cTDeletion\u003e(\n//      function (Value: TDeletion): TDeletion\n//      begin\n//        Result := Value;\n//        Display(TutorialHub, F('Deleted', BoolToStr(Value.Deleted, True)));\n//      end)\n//    .\u0026Catch(\n//      procedure (E: Exception)\n//      begin\n//        Display(TutorialHub, E.Message);\n//      end);\n```\n\n\u003cbr/\u003e\n\n# [Beyond the Basics Advanced Usage](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/BeyondBasics.md)\n\n[This section](https://github.com/MaxiDonkey/DelphiGenAI/blob/main/BeyondBasics.md) covers the advanced use of OpenAI's APIs, including key features such as `upload` management, `batch` processing, `vector` stores, and the use of `assistants`, `threads`, `messages`, and `runs`. It also addresses model `fine-tuning` and includes a note on `distillation`.\n\n\u003cbr\u003e\n\n___\n\n# Legacy\n\nFor practical purposes, **completion APIs** can be utilized through `GenAI`, enabling the use of models such as ***gpt-3.5-turbo-instruct***, among others. However, the assistant system in Beta 1 is not supported by `GenAI`.\n\n\u003cbr\u003e\n\n## Completion\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  //Asynchronous example\n  Client.Completion.AsynCreate(\n    procedure (Params: TCompletionParams)\n    begin\n      Params.Model('gpt-3.5-turbo-instruct');\n      Params.Prompt('Give a simple explanation of what curiosity is, in one short sentence.');\n      Params.Logprobs(5);\n      Params.MaxTokens(96);\n      TutorialHub.JSONRequest := Params.ToFormat();\n    end,\n    function : TAsynCompletion\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnSuccess := Display;\n      Result.OnError := Display;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Completion.Create(\n//    procedure (Params: TCompletionParams)\n//    begin\n//      Params.Model('gpt-3.5-turbo-instruct');\n//      Params.Prompt('Give a simple explanation of what curiosity is, in one short sentence.');\n//      Params.Logprobs(5);\n//      Params.MaxTokens(96);\n//      TutorialHub.JSONRequest := Params.ToFormat();\n//    end);\n//  try\n//    Display(TutorialHub, Value);\n//  finally\n//    Value.Free;\n//  end;\n```\n\u003cbr\u003e\n\n___\n\n## Streamed completion\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  //Asynchronous example\n  Client.Completion.AsynCreateStream(\n    procedure (Params: TCompletionParams)\n    begin\n      Params.Model('gpt-3.5-turbo-instruct');\n      Params.Prompt('Say this is a test');\n      Params.MaxTokens(96);\n      Params.Stream;\n      TutorialHub.JSONRequest := Params.ToFormat();\n    end,\n    function : TAsynCompletionStream\n    begin\n      Result.Sender := TutorialHub;\n      Result.OnStart := Start;\n      Result.OnProgress := DisplayStream;\n      Result.OnError := Display;\n      Result.OnDoCancel := DoCancellation;\n      Result.OnCancellation := Cancellation;\n    end);\n\n  //Synchronous example\n//  var Value := Client.Completion.CreateStream(\n//    procedure (Params: TCompletionParams)\n//    begin\n//      Params.Model('gpt-3.5-turbo-instruct');\n//      Params.Prompt('Say this is a test');\n//      Params.MaxTokens(96);\n//      Params.Stream;\n//      TutorialHub.JSONRequest := Params.ToFormat();\n//    end,\n//    procedure (var Data: TCompletion; IsDone: Boolean; var Cancel: Boolean)\n//    begin\n//      if Assigned(Data) and not IsDone then\n//        DisplayStream(TutorialHub, Data);\n//    end);\n```\n\n\u003cbr\u003e\n\n___\n\n# Tips and tricks\n\n- #### How to prevent an error when closing an application while requests are still in progress?\n\nStarting from version ***1.0.1 of GenAI***, the `GenAI.Monitoring` unit is **responsible for monitoring ongoing HTTP requests.**\n\nThe `Monitoring` interface is accessible by including the `GenAI.Monitoring` unit in the `uses` clause. \u003cbr\u003e\nAlternatively, you can access it via the `HttpMonitoring` function, declared in the `GenAI` unit.\n\n**Usage Example**\n\n```Delphi\n//uses GenAI;\n\nprocedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);\nbegin\n  CanClose := not HttpMonitoring.IsBusy;\n  if not CanClose then\n    MessageDLG(\n      'Requests are still in progress. Please wait for them to complete before closing the application.\"',\n      TMsgDlgType.mtInformation, [TMsgDlgBtn.mbOK], 0);\nend;\n\n```\n\n\u003cbr\u003e\n\n- #### How to execute multiple background requests to process a batch of responses?\n\nIn the `GenAI.Chat` unit, the `CreateParallel` method allows for executing multiple prompts asynchronously in the background ***(since the version 1.0.1 of GenAI)***.\n\nAmong the method's parameters, you can specify the model to be used for the entire batch of prompts. However, assigning a different model to each prompt individually is not supported.\n\n**Usage Example**\n\n```Delphi\n//uses GenAI, GenAI.Types, GenAI.Tutorial.VCL;\n\n  Client.Chat.CreateParallel(\n    procedure (Params: TBundleParams)\n    begin\n      Params.Prompts([\n        'How many television channels were there in France in 1980?',\n        'How many TV channels were there in Germany in 1980?.'\n      ]);\n      Params.System('Write the text in capital letters.');\n      Params.Model('gpt-4o-mini');\n    end,\n    function : TAsynBundleList\n    begin\n      Result.Sender := TutorialHub;\n\n      Result.OnStart :=\n        procedure (Sender: TObject)\n        begin\n          Display(Sender, 'Start the job' + sLineBreak);\n        end;\n\n      Result.OnSuccess :=\n        procedure (Sender: TObject; Bundle: TBundleList)\n        begin\n          // Background bundle processing\n          for var Item in Bundle.Items do\n            begin\n              Display(Sender, 'Index : ' + Item.Index.ToString);\n              Display(Sender, 'FinishIndex : ' + Item.FinishIndex.ToString);\n              Display(Sender, Item.Prompt + sLineBreak);\n              Display(Sender, Item.Response + sLineBreak + sLineBreak);\n              // or Display(Sender, TChat(Item.Chat).Choices[0].Message.Content);\n            end;\n        end;\n\n      Result.OnError := Display;\n    end);\n```\n\n\u003e[!TIP]\n\u003e The provided example is somewhat simplified. It would be better to adopt this approach with ***JSON-formatted outputs***, as this allows for the implementation of more complex and tailored processing during the final stages. \n\n\u003cbr\u003e\n\n- #### How to structure a chain of thought and develop advanced processing with GenAI?\n\nTo achieve this, it is recommended to use a Promise-based pattern to efficiently construct a chain of thought with GenAI. The [CerebraChain](https://github.com/MaxiDonkey/CerebraChainAI) project offers a method that can be used with GenAI.\n\n\u003cbr\u003e\n\n- #### How do you structure advanced reasoning using Promises and pipelines?\n\nOrchestrate AI thought chains elegantly and efficiently. By leveraging a dynamic pipeline model, a configurable sequential scheduler, and Promises, you can meet the complex requirements of working with modern AI models like OpenAI. Check out the [SynkFlow repository](https://github.com/MaxiDonkey/SynkFlowAI).\n\n\u003cbr\u003e\n\n___\n\n\n\n# Contributing\n\nPull requests are welcome. If you're planning to make a major change, please open an issue first to discuss your proposed changes.\n\n\u003cbr\u003e\n\n___\n\n# License\n\nThis project is licensed under the [MIT](https://choosealicense.com/licenses/mit/) License.\n\n\u003cbr\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaxidonkey%2Fdelphigenai","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmaxidonkey%2Fdelphigenai","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmaxidonkey%2Fdelphigenai/lists"}