Anthropic | Tool Use

Claude는 도구 사용(function calling)을 지원하여, Claude가 대화 중에 호출할 수 있는 도구를 정의할 수 있도록 합니다. Claude가 도구를 사용하기로 결정하면 tool_use 콘텐츠 블록을 반환합니다. 그런 다음 도구를 실행하고 결과를 tool_result 콘텐츠 블록으로 다시 보냅니다.

Tool Use Flow

  1. 이름, 설명 및 input_schema(JSON Schema)로 도구를 정의합니다.
  2. 정의된 tools와 함께 메시지를 보냅니다.
  3. Claude는 tool_use 콘텐츠 블록(stop_reason = 'tool_use')으로 응답합니다.
  4. 제공된 입력으로 도구를 실행합니다.
  5. 출력을 포함하는 tool_result content 블록과 함께 새 메시지를 보냅니다.
  6. Claude가 최종 답변으로 응답합니다.

예제

weather 도구를 정의하고 tool use 루프를 처리합니다.


Anthropic := TsgcHTTP_API_Anthropic.Create(nil);
Anthropic.AnthropicOptions.ApiKey := 'API_KEY';

// Step 1: Create request with tools
oRequest := TsgcAnthropicClass_Request_Messages.Create;
Try
  oRequest.Model := 'claude-sonnet-4-20250514';
  oRequest.MaxTokens := 4096;

  // Define user message
  oMessage := TsgcAnthropicClass_Request_Message.Create;
  oMessage.Role := 'user';
  oMessage.Content := 'What is the weather in San Francisco?';
  SetLength(oMessages, 1);
  oMessages[0] := oMessage;
  oRequest.Messages := oMessages;

  // Define tool
  oTool := TsgcAnthropicClass_Request_Tool.Create;
  oTool.Name := 'get_weather';
  oTool.Description := 'Get the current weather in a given location';
  oTool.InputSchema :=
    '{"type":"object","properties":{"location":{"type":"string",' +
    '"description":"The city and state"}},"required":["location"]}';
  SetLength(oTools, 1);
  oTools[0] := oTool;
  oRequest.Tools := oTools;

  // Step 2: Send request
  oResponse := Anthropic.CreateMessage(oRequest);
  Try
    // Step 3: Check if Claude wants to use a tool
    if oResponse.StopReason = 'tool_use' then
    begin
      // Find the tool_use content block
      for i := 0 to Length(oResponse.Content) - 1 do
      begin
        if oResponse.Content[i].ContentType = 'tool_use' then
        begin
          vToolUseId := oResponse.Content[i].Id;
          vToolName := oResponse.Content[i].Name;
          vToolInput := oResponse.Content[i].Input;
          // Step 4: Execute your tool (get_weather) and get result
          vToolResult := '72 degrees and sunny';
          Break;
        end;
      end;

      // Step 5: Send tool result back
      // Build new message array with assistant response + tool result
      // ... (continue the conversation with tool_result content block)
    end;
  Finally
    oResponse.Free;
  End;
Finally
  oMessage.Free;
  oTool.Free;
  oRequest.Free;
End;