OpenAI Function Calling

· Características

 Al igual que la Chat Completions API, la Assistants API soporta function calling. Function calling te permite describir funciones a la Assistants API y que esta devuelva inteligentemente las funciones que hay que llamar junto con sus argumentos.

En este ejemplo crearemos un asistente del tiempo y definiremos dos funciones, get_current_temperature y get_rain_probability, como herramientas que el Assistant puede llamar. En nuestro ejemplo, que usa function calling en paralelo, le preguntaremos al Assistant cómo está el tiempo hoy en San Francisco y la probabilidad de lluvia. También mostramos cómo emitir la respuesta del Assistant en streaming.

Al crear tu assistant, primero definirás las funciones en el parámetro tools del 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; 

Paso 2: crear un Thread y añadir Messages

Crea un Thread cuando un usuario inicia una conversación y añade Messages al Thread a medida que el usuario hace preguntas. 

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;  

Paso 3: gestionar el evento OnFunctionCall

Cuando el componente detecta que se requiere el valor de un parámetro de una función, se llama al evento OnFunctionCall. Usa el parámetro Request._Function para conocer los detalles de la petición y usa Response.Output para enviar la respuesta. 

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

A continuación encontrarás la demo de Delphi compilada para Windows.