OpenAI Function Calling

· Recursos

 Assim como a Chat Completions API, a Assistants API oferece suporte à chamada de funções. A chamada de funções permite que você descreva funções para a Assistants API, que retornará de forma inteligente as funções que precisam ser chamadas junto com seus argumentos.

Neste exemplo, vamos criar um assistente de clima e definir duas funções, get_current_temperature e get_rain_probability, como ferramentas que o assistente pode chamar. No nosso exemplo com chamada de funções em paralelo, vamos perguntar ao assistente como está o clima em San Francisco hoje e as chances de chuva. Também mostramos como exibir a resposta do assistente com streaming.

Ao criar seu assistente, você primeiro define as funções no parâmetro tools do assistente. 

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":"Obtém o 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":"Obtém o 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; 

Passo 2: Criar uma Thread e adicionar mensagens

Crie uma Thread quando um usuário iniciar uma conversa e adicione mensagens à Thread conforme o usuário faz perguntas. 

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;  

Passo 3: Tratar o evento OnFunctionCall

Quando o componente detecta que o valor de um parâmetro de função é necessário, o evento OnFunctionCall é chamado. Use o parâmetro Request._Function para conhecer os detalhes da requisição e use Response.Output para enviar a resposta. 

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; 

Demo Delphi

Veja abaixo a demo Delphi compilada para Windows.