与聊天补全 API 类似,Assistants API 支持函数调用。函数调用允许您向 Assistants API 描述函数,并让其智能地返回需要调用的函数及其参数。
在本示例中,我们将创建一个天气助手,并定义两个函数 get_current_temperature 和 get_rain_probability 作为助手可以调用的工具。在使用并行函数调用的示例中,我们将询问助手今天旧金山的天气情况及降雨概率。我们还将展示如何使用流式传输输出助手的响应。创建助手时,首先在助手的工具参数下定义函数。
Assistant := TsgcAIOpenAIAssistant.Create(nil);
Assistant.OpenAIOptions.ApiKey := 'sk-askdjfalskdjfl23kjkjasdefasdfj';
Assistant.AssistantOptions.Name := 'Delphi Weather Bot';
Assistant.AssistantOptions.Instructions.Text := 'You are a weather bot. Use the provided functions to answer questions.';
Assistant.AssistantOptions.Model := 'gpt-4o';
Assistant.AssistantOptions.Tools.Functions.Enabled := False;
Assistant.AssistantOptions.Tools.Functions.Functions.Text := '[{"type":"function","function":{"name":"get_current_temperature","description":"Get the current temperature for a specific location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g., San Francisco, CA"},"unit":{"type":"string","enum":["Celsius","Fahrenheit"],"description":"The temperature unit to use. Infer this from the user location."}},"required":["location","unit"]}}},{"type":"function","function":{"name":"get_rain_probability","description":"Get the probability of rain for a specific location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g., San Francisco, CA"}},"required":["location"]}}}]'
Assistant.AssistantOptions.Tools.FileSearch.Enabled := False;
Assistant.AssistantOptions.Tools.CodeInterpreter.Enabled := False;
步骤 2:创建线程并添加消息
当用户开始对话时创建线程,并随着用户提问向线程添加消息。
procedure SendMessage()
var
i: Integer;
oMessage: TsgcOpenAIClass_Message;
oMessages: TsgcOpenAIClass_Response_List_Messages;
oRun: TsgcOpenAIClass_Run;
begin
DoLog('[user]: ' + memoMessage.Lines.Text);
Screen.Cursor := crHourGlass;
Try
oMessage := Assistant.CreateMessageText('thread_id', 'What is the weather in San Francisco today and the likelihood it will rain?');
if Assigned(oMessage) then
begin
oRun := Assistant.CreateRunAndWait('thread_id');
if Assigned(oRun) then
begin
oMessages := Assistant.GetMessages('thread_id', oRun.Id);
if Assigned(oMessages) and (Length(oMessages.Messages) > 0) then
begin
memoMessage.Lines.Text := '';
for i := 0 to Length(oMessages.Messages) - 1 do
DoLog('[assistant]: ' + DoFormatResponse(oMessages.Messages[i]
.ContentText + #13#10));
end;
end;
end;
Finally
Screen.Cursor := crDefault;
End;
end;
步骤 3:处理 OnFunctionCall 事件
当组件检测到需要函数参数值时,将调用 OnFunctionCall 事件。使用 Request._Function 参数了解请求详情,使用 Response.Output 发送响应。
procedure TFRMOpenAIAssistant.AssistantFunctionCall(Sender: TObject;
const aRequest: TsgcOpenAIClass_ToolCall;
const aResponse: TsgcHTTPOpenAI_ToolCall_Response);
begin
if aRequest._Function._Name = 'get_current_temperature' then
aResponse.Output := 30
else if aRequest._Function._Name = 'get_rain_probability' then
aResponse.Output := 10;
end;
});
Delphi 示例
以下是为 Windows 编译的 Delphi 示例。
