Code Monkey home page Code Monkey logo

openai-delphi's Introduction

OpenAI for Delphi and Lazarus/FPC.

OpenAI for Delphi is a client library to connect to the OpenAI API from Delphi and Lazarus/FPC (Free Pascal Compiler). From this library you can use popular OpenAI services, like ChatGPT, directly from your Delphi or Lazarus application.

This is an unofficial library. OpenAI does not provide any official library for Delphi.

Installation

To use the library, just add the Source folder to the IDE library path, or your project source path.

Usage

To use the client, add units OpenAIClient and OpenAIDtos to your unit uses clause.

uses 
  OpenAIClient, OpenAIDtos;

Creating the client

The library needs to be configured with your account's secret API key, which is available on the website. We recommend setting it as an environment variable named OPENAI_API_KEY. Once you have the API key, just create the client and set the key as the following:

var
  Client: IOpenAIClient;
{...}
  Client := TOpenAIClient.Create;
  Client.Config.AccessToken := GetEnvironmentVariable('OPENAI_API_KEY');

Executing methods

Most of OpenAI API endpoints are available in the client, under the interface provided in the OpenAI property. The following example shows how to ask a question and receive an answer using the CreateCompletion endpoint:

function AskQuestion(const Question: string): string;
var
  Request: TCreateCompletionRequest;
  Response: TCreateCompletionResponse;
begin
  Response := nil;
  Request := TCreateCompletionRequest.Create;
  try
    Request.Prompt := Question;
    Request.Model := 'text-davinci-003';
    Request.MaxTokens := 2048; // Be careful as this can quickly consume your API quota.
    Response := Client.OpenAI.CreateCompletion(Request);
    if Assigned(Response.Choices) and (Response.Choices.Count > 0) then
      Result := Response.Choices[0].Text
    else
      Result := '';
  finally
    Request.Free;
    Response.Free;
  end;
end;

All objects created and passed as input parameters, as well all objects created by the client and provided as function results, must be destroyed by you, otherwise you will get a memory leak.

You can use Delphi code completion to check the available methods, parameters, types and read documentation comments.

Requirements

This library does not require any 3rd party library. It works on all recent Delphi versions that provides unit (System.Net.HttpClient) and Lazarus/FPC. Althought not fully tested, it should also work on all supported platforms (Windows, Linux, macOS, etc.).

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.

Request customization

You can customize the request for your own need by using your own request factory. Just implement the interface IRestRequestFactory and set it in the property Config.RequestFactory.

For example, if you want to setup a custom organization (which is provided in an HTTP header), this is a sample code:

uses {...}, OpenApiRest;

type
  TMyRequestFactory = class(TInterfacedObject, IRestRequestFactory)
  strict private
    FFactory: IRestRequestFactory;
  public
    constructor Create(AFactory: IRestRequestFactory);
    function CreateRequest: IRestRequest;
  end;

constructor TMyRequestFactory.Create(AFactory: IRestRequestFactory);
begin
  FFactory := AFactory;
end;

function TMyRequestFactory.CreateRequest: IRestRequest;
begin
  Result := FFactory.CreateRequest;
  Result.AddHeader('OpenAI-Organization', 'org-nUilalMOTvqGjGeAopTDIsSB');
end;

// Set it after creating the client
    FClient := TOpenAIClient.Create;
    FClient.Config.RequestFactory := TMyRequestFactory.Create(FClient.Config.RequestFactory);

Integrating with WhatsApp in Delphi

Example of using openai-delphi with WPP4Delphi in WPPConnect-Team

Component Opensource for sending messages integrated into whatsapp web using Delphi

Example: Demo View image

Code Example in Delphi:

if SwtChatGPT.IsOn then
begin
if Question <> '' then
begin
	//Credits --> https://github.com/landgraf-dev/openai-delphi
	Answer      := AskQuestion(Question, AChat.id);
	phoneNumber := Copy(Answer, 1, pos('#', Answer)-1);
	Answer      := StringReplace(Answer, phoneNumber + '#', '',[]);

	if Trim(Answer) <> '' then
	frDemo.TWPPConnect1.SendTextMessageEx(phoneNumber, '๐Ÿค–' + ' *ChatGPT* ' + Answer, 'createChat: true', '123')
	else
	frDemo.TWPPConnect1.SendTextMessageEx(phoneNumber, '๐Ÿค–' + ' *ChatGPT* ' + 'Could not retrieve an answer.', 'createChat: true', '123');

end;
end;

Complete Code in WPP4Delphi

openai-delphi's People

Contributors

wlandgraf avatar fraurino avatar gidesa avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.