The OpenAI Assistant Client has been improved to implement the streaming responses when calling a run thread. Before this new feature, it requires to poll the run object status till it's completed. Now you can use the new Stream events to handle the streaming messages.
Instead of waiting the full response from the assistant, you can stream the response using Server-Sent Events. Just pass the param Stream = True when using the CreateRun function and the response will be using streaming.
The following events are used to handle the streaming responses
An Assistant represents an entity that can be configured to respond to a user's messages using several parameters like model, instructions, and tools.
1234567891011// ... create a new assistantoAssistant := TsgcAIOpenAIAssistant.Create(nil);// ... set your api keyoAssistant.OpenAIOptions.ApiKey := txtAPIKey.Text;// ... assistant optionsoAssistant.AssistantOptions.Name := 'Math Tutor';oAssistant.AssistantOptions.Instructions.Text := 'You are a personal math tutor. Write and run code to answer math questions.';oAssistant.AssistantOptions.Model := 'gpt-4o';// ... create the assistantoAssistant.CreateAssistant();
A Thread represents a conversation between a user and one or many Assistants. You can create a Thread when a user (or your AI application) starts a conversation with your Assistant.
12oThread := oAssistant.CreateThread;
Enter your text here ...
12345678910111213procedure SendMessage(const oAssistant: TsgcAIOpenAIAssistant; const oThread: TsgcAIClass_Thread; const aMessage: string);vari: Integer;oMessage: TsgcOpenAIClass_Message;oMessages: TsgcOpenAIClass_Response_List_Messages;oRun: TsgcOpenAIClass_Run;beginDoLog('[user]: ' + aMessage);oMessage := oAssistant.CreateMessageText(oThread.Id, aMessage);if Assigned(oMessage) thenoRun := oAssistant.CreateRun(oThread.Id, True);end;
Use the event OnStreamMessageDelta to read the server-sent stream message.
1234567891011121314151617procedure OnStreamMessageDelta(Sender: TObject; const aMessageDelta: TsgcOpenAIClass_MessageDelta; const aRaw: string);vari: Integer;vResponse: string;vType: string;beginfor i := Low(aMessageDelta.Content) to High(aMessageDelta.Content) dobeginvType := aMessageDelta.Content[i]._Type;if vType = 'text' thenbeginvResponse := TsgcOpenAIClass_MessageDeltaContent_Text(aMessageDelta.Content[i]).Value;end;end;end;
The following compressed file contains the source code of the Assistants demo built for windows using the sgcWebSockets library.
When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.