Class Tool
java.lang.Object
com.codename1.ai.Tool
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 Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionThe optional executor wired up by the constructor.getName()Invokes the handler with the given arguments JSON.
-
Constructor Details
-
Tool
-
Tool
Creates a tool definition with an application executor.- Parameters:
name- provider-visible function namedescription- guidance that helps the model choose the toolparametersJsonSchema- JSON Schema for accepted argumentshandler- executor called byinvoke(String), ornull
-
-
Method Details
-
getName
- Returns:
- provider-visible function name
-
getDescription
- Returns:
- description used by the model to decide when to call the tool
-
getParametersJsonSchema
- Returns:
- JSON Schema describing accepted function arguments
-
getHandler
The optional executor wired up by the constructor. Returnsnullfor description-only tools.- Returns:
- registered executor, or
null
-
invoke
Invokes the handler with the given arguments JSON. ThrowsIllegalStateExceptionwhen no handler was registered.- Parameters:
argumentsJson- model-generated arguments- Returns:
- handler result encoded as JSON
- Throws:
Exception- when the handler rejects or cannot execute the call
-