OpenAI の関数呼び出し

· 機能

 Chat Completions API と同様に、Assistants API関数呼び出し(function calling)をサポートしています。関数呼び出しを使用すると、Assistants API に関数を説明し、呼び出す必要のある関数とその引数をインテリジェントに返させることができます。

この例では、天気アシスタントを作成し、get_current_temperature と get_rain_probability という 2 つの関数をアシスタントが呼び出せるツールとして定義します。並列関数呼び出しを使用するこのサンプルでは、今日のサンフランシスコの天気と降水確率をアシスタントに尋ねます。ストリーミングでアシスタントのレスポンスを出力する方法も示します。

アシスタントを作成する際、まずアシスタントの 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:スレッドを作成してメッセージを追加する

ユーザーが会話を開始したときにスレッドを作成し、ユーザーが質問するたびにスレッドにメッセージを追加します。 

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 デモです。