OpenAI Function Calling

· Funzionalità

 Come l'API Chat Completions, anche l'API Assistants supporta il function calling. Il function calling ti permette di descrivere funzioni all'API Assistants e ottenere in modo intelligente le funzioni da chiamare insieme ai loro argomenti.

In questo esempio creeremo un assistant meteo e definiremo due funzioni, get_current_temperature e get_rain_probability, come tool che l'Assistant può chiamare. Nel nostro esempio, che usa il parallel function calling, chiederemo all'Assistant com'è il tempo a San Francisco oggi e qual è la probabilità di pioggia. Mostreremo anche come restituire la risposta dell'Assistant in streaming.

Quando crei il tuo assistant, definirai prima le funzioni sotto il parametro tools dell'assistant. 

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; 

Passo 2: creare un Thread e aggiungere Message

Crea un Thread quando un utente avvia una conversazione e aggiungi Message al Thread man mano che l'utente fa domande. 

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: gestire l'evento OnFunctionCall

Quando il componente rileva che è richiesto un valore di parametro di funzione, viene chiamato l'evento OnFunctionCall. Usa il parametro Request._Function per conoscere i dettagli della richiesta e usa Response.Output per inviare la risposta. 

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

Qui sotto trovi la demo Delphi compilata per Windows.