Class Tool

java.lang.Object
com.codename1.ai.Tool

public final class Tool extends Object

A function the model can call. parametersJsonSchema is a raw JSON-Schema string; each provider wraps it differently on the wire (OpenAI {type:"function",function:{...}}, Anthropic {name,description,input_schema}, Gemini functionDeclarations), but the inner schema shape is the same across all of them, so we hand it through as a string and let the provider client wrap.

Linking a tool to its executor

Pass an optional ToolHandler at construction time and the matching ToolCall can dispatch through it without the caller having to match names by hand:

Tool weather = new Tool(
    "get_weather",
    "Returns the current weather for a location",
    "{\"type\":\"object\",\"properties\":{" +
       "\"location\":{\"type\":\"string\"}}," +
       "\"required\":[\"location\"]}",
    argumentsJson -> {
        Map args = JSONParser.parseJSON(argumentsJson);
        return "{\"temp\":21,\"city\":\""
                + JSONParser.getString(args, "location") + "\"}";
    });

// Later, when the model returns a ToolCall:
for (ToolCall call : response.getToolCalls()) {
    String resultJson = call.execute(Arrays.asList(weather));
    conversation.add(ChatMessage.toolResult(call.getId(), resultJson));
}

The handler is optional -- a Tool constructed without one is a pure description for the model, and the caller can dispatch however they like via the raw ToolCall.getName() / ToolCall.getArgumentsJson() accessors.

  • Constructor Details

  • Method Details

    • getName

      public String getName()
    • getDescription

      public String getDescription()
    • getParametersJsonSchema

      public String getParametersJsonSchema()
    • getHandler

      public ToolHandler getHandler()
      The optional executor wired up by the constructor. Returns null for description-only tools.
    • invoke

      public String invoke(String argumentsJson) throws Exception
      Invokes the handler with the given arguments JSON. Throws IllegalStateException when no handler was registered.
      Throws:
      Exception