# Delphi OpenAI API
![logo](https://github.com/HemulGM/DelphiOpenAI/blob/main/openai+delphi.png?raw=true)
___
![GitHub](https://img.shields.io/github/license/hemulgm/DelphiOpenAI)
![GitHub](https://img.shields.io/github/last-commit/hemulgm/DelphiOpenAI)
![GitHub](https://img.shields.io/badge/coverage-100%25-green)
![GitHub](https://img.shields.io/badge/IDE%20Version-Delphi%2010.3+-yellow)
![GitHub](https://img.shields.io/badge/platform-all%20platforms-green)
This repositorty contains Delphi implementation over [OpenAI](https://beta.openai.com/docs/api-reference/) public API.
â*This is an unofficial library. OpenAI does not provide any official library for Delphi.*
- [What is OpenAI](#what-is-openai)
- [Installation](#installation)
- [Usage](#usage)
- [Initialization](#initialization)
- [Models](#models)
- [Completions](#completions)
- [Chats](#chats)
- [Images](#images)
- [Errors](#errors)
- [Exceptions](#exceptions)
- [Usage proxy](#proxy)
- [Examples](#examples)
- [Requirements](#requirements)
- [Links](#links)
- [License](#license)
<details>
<summary> Coverage </summary>
|API|Status|
|---|---|
|Models|ð¢ Done|
|Completions|ð¢ Done|
|Chat|ð¢ Done|
|Edits|ð¢ Done|
|Images|ð¢ Done|
|Embeddings|ð¢ Done|
|Audio|ð¢ Done|
|Files|ð¢ Done|
|Fine-tunes|ð¢ Done|
|Moderations|ð¢ Done|
|Engines (Depricated)|ð¢ Done|
</details>
## 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](https://openai.com/api/), on the basis of which [ChatGPT](https://openai.com/blog/chatgpt) works and, for example, the generation of images from text using `DALL-E`.
## Installation
You can install the package from `GetIt` [directly](https://getitnow.embarcadero.com/openai-for-delphi) in the IDE. Or, to use the library, just add the `root` folder to the IDE library path, or your project source path.
## Usage
### Initialization
To initialize API instance you need to [obtain](https://beta.openai.com/account/api-keys) 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.
```Pascal
uses OpenAI;
var OpenAI := TOpenAIComponent.Create(Self, API_TOKEN);
```
or
```Pascal
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.
```Pascal
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](https://platform.openai.com/docs/api-reference/models) 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.
```Pascal
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](https://platform.openai.com/docs/api-reference/completions) 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.
```Pascal
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
```Pascal
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);
```
Review [Chat Documentation](https://platform.openai.com/docs/api-reference/chat) for more info.
### Images
Given a prompt and/or an input image, the model will generate a new image.
```Pascal
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](https://platform.openai.com/docs/api-reference/images) for more info.
### Errors
```Pascal
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
```Pascal
OpenAI.API.Client.ProxySettings := TProxySettings.Create(ProxyHost, ProxyPort, ProxyUserName, ProxyPassword);
```
## Examples
|Source|Preview|Source|Preview|
|---|---|---|---|
|[Playground (FMX)](https://github.com/HemulGM/DelphiOpenAIPlayground)|<img src="https://github.com/HemulGM/DelphiOpenAIPlayground/blob/main/preview.png?raw=true" height="150" align="right">|[ChatGPT (FMX)](https://github.com/HemulGM/ChatGPT)|<img src="https://github.com/HemulGM/ChatGPT/raw/main/preview.png
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
DelphiOpenAI.zip (49个子文件)
DelphiOpenAI
OpenAI.Moderations.pas 5KB
OpenAI.Completions.pas 13KB
.gitattributes 68B
OpenAI.FineTunes.pas 14KB
OpenAL-GPT3.png 101KB
LICENSE 1KB
Icon.png 17KB
OpenAI.API.pas 14KB
.git
index 2KB
HEAD 21B
refs
heads
main 41B
tags
remotes
origin
HEAD 30B
objects
pack
pack-582562604f715cd681c3e0940aec35afa2c87ce5.pack 316KB
pack-582562604f715cd681c3e0940aec35afa2c87ce5.idx 2KB
info
description 73B
packed-refs 112B
shallow 41B
info
exclude 240B
logs
HEAD 186B
refs
heads
main 186B
remotes
origin
HEAD 186B
hooks
post-update.sample 189B
prepare-commit-msg.sample 1KB
commit-msg.sample 896B
pre-receive.sample 544B
update.sample 4KB
pre-commit.sample 2KB
pre-rebase.sample 5KB
applypatch-msg.sample 478B
fsmonitor-watchman.sample 5KB
pre-applypatch.sample 424B
pre-push.sample 1KB
pre-merge-commit.sample 416B
config 308B
OpenAI.Images.pas 19KB
OpenAI.Chat.pas 13KB
OpenAI.pas 22KB
OpenAI.Utils.ChatHistory.pas 4KB
openai+delphi.png 173KB
OpenAI.Errors.pas 719B
OpenAI.Embeddings.pas 4KB
OpenAI.API.Params.pas 6KB
OpenAI.Audio.pas 8KB
OpenAI.Edits.pas 4KB
.gitignore 2KB
OpenAI.Models.pas 3KB
OpenAI.Engines.pas 2KB
README.md 10KB
OpenAI.Files.pas 6KB
共 49 条
- 1
资源评论
qqww155
- 粉丝: 34
- 资源: 23
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功