Anthropic | Użycie narzędzi

Claude obsługuje użycie narzędzi (wywoływanie funkcji), umożliwiając definiowanie narzędzi, które Claude może wywoływać podczas rozmowy. Gdy Claude zdecyduje się użyć narzędzia, zwraca blok treści tool_use. Następnie należy wykonać narzędzie i odesłać wynik jako blok treści tool_result.

Przebieg użycia narzędzia

  1. Definiowanie narzędzi z nazwą, opisem i input_schema (JSON Schema).
  2. Wyślij wiadomość z określonymi narzędziami.
  3. Claude odpowiada blokiem zawartości tool_use (stop_reason = 'tool_use').
  4. Wykonanie narzędzia z podanymi danymi wejściowymi.
  5. Wyślij nową wiadomość z blokiem treści tool_result zawierającym wynik.
  6. Claude odpowiada ostateczną odpowiedzią.

Przykład

Zdefiniuj narzędzie pogodowe i obsłuż pętlę użycia narzędzia.


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;