OpenAI Function Calling

· 기능

 Chat Completions API와 유사하게, Assistants API함수 호출을 지원해요. 함수 호출을 사용하면 Assistants API에 함수를 설명하고, API가 호출이 필요한 함수와 그 인수를 지능적으로 반환하도록 할 수 있어요.

이 예제에서는 날씨 어시스턴트를 만들고, get_current_temperature와 get_rain_probability라는 두 함수를 Assistant가 호출할 수 있는 도구로 정의해요. 병렬 함수 호출을 사용하는 예제에서는 San Francisco의 오늘 날씨와 비올 확률을 Assistant에게 물어볼 거예요. 또한 스트리밍으로 Assistant의 응답을 출력하는 방법도 보여드려요.

어시스턴트를 만들 때, 먼저 어시스턴트의 tools 매개변수 아래에 함수를 정의해요. 

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단계: Thread 만들기와 메시지 추가

사용자가 대화를 시작할 때 Thread를 만들고, 사용자가 질문할 때마다 Thread에 메시지를 추가하세요. 

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 데모를 확인하세요.