Tools & Structured Output
OpenHusky combines declarative Java 21 @Tool authoring, virtual-thread concurrency, real-time state delta emission, and type-safe promptStructured(...) responses.
Declarative @Tool & @ToolParam
Annotate methods on any plain Java object and register them via AgentRuntime.Builder.toolsFrom(beans...). AnnotatedToolScanner inspects method signatures using JDK 21 reflection and builds Jackson JSON Schemas automatically.
Supported Parameter Types & Auto-Injection
- Schema-bound arguments (
@ToolParam): primitives, boxed types,String,BigDecimal,Enum,List<T>/Set<T>/ arrays,Map<String, V>,Optional<T>, and cycle-safe nestedrecords or POJOs. - Runtime-injected parameters (excluded from the LLM JSON Schema):
ToolContext— emit progress (ctx.emitProgress(...)), inspectctx.sessionId(),ctx.toolCallId(), and inheritedctx.attributes().Principal— authenticated caller identity (id(),tenantId()).AbortSignal— cooperative cancellation token for long-running I/O.
Concurrency: PARALLEL_SAFE vs. SEQUENTIAL
Specify execution semantics per tool with @Tool(mode = ..., readOnly = ...):
public final class ShopTools {
@Tool(
name = "search_catalog",
description = "Search products by keyword, category, and max price.",
mode = ToolExecutionMode.PARALLEL_SAFE,
readOnly = true
)
public ToolResult searchCatalog(
ToolContext ctx,
@ToolParam(name = "query", required = false) Optional<String> query,
@ToolParam(name = "maxPrice", required = false) Optional<Double> maxPrice
) {
ctx.emitProgress("Searching catalog...");
List<Product> hits = store.search(query.orElse(""), maxPrice.orElse(null));
return ToolResult.ok(toJson(hits));
}
@Tool(
name = "add_to_cart",
description = "Add a product SKU to the user's live shopping cart.",
mode = ToolExecutionMode.SEQUENTIAL,
readOnly = false
)
public ToolResult addToCart(
@ToolParam(name = "sku") String sku,
@ToolParam(name = "quantity", required = false) Optional<Integer> quantity
) {
CartState cart = store.addToCart(sku, quantity.orElse(1));
return ToolResult.okWithState(
"Added " + sku + " to cart.",
"storefront",
Map.of("cart", cart)
);
}
}When a model issues multiple PARALLEL_SAFE tool calls in one step (for example search_catalog, get_product_reviews, and check_inventory), AgentLoop executes them concurrently on Java 21 Virtual Threads while preserving deterministic result ordering. SEQUENTIAL tools always execute one at a time in order.
Live State Synchronization (ToolResult.okWithState)
ToolResult.okWithState(text, namespace, stateDelta) serves two purposes simultaneously:
- Returns
textto the LLM as the tool output. - Persists a
StatePatchEntryinto theSessionStoreand emitsAgentEvent.StateDelta(automatically translated byopenhusky-aguiinto AG-UI RFC 6902STATE_DELTAJSON Patch operations under/<namespace>/*, withnullvalues deleting keys).
Streaming Tool Progress & Output Offloading
- Call
ctx.emitProgress("...")inside any tool to emitAgentEvent.ToolCallProgress(forwarded asopenhusky:tool_progressover AG-UI SSE). - Register
OutputOffloadToolInterceptor.inMemory(32_768)(or disk-backed spill) to prevent massive tool outputs from overflowing the context window while keepingImageBlocks anddetailsintact.
Typed Structured Output (promptStructured) v0.2.0
Availability
session.promptStructured(...) is available on main and in the upcoming 0.2.0 release.
When your backend needs validated, strongly typed Java objects instead of free-form prose—such as product comparison matrices or support ticket triage—use session.promptStructured(...) with any Java record, POJO, or Jackson TypeReference<T>:
public record TicketTriage(
String category,
String severity,
String sentiment,
double confidence,
List<String> citedPolicies,
boolean requiresSupervisor,
String recommendedAction
) {}
AgentSession session = runtime.openSession("triage-884", Principal.of("agent-1", "nimbus-cloud"));
StructuredRunResult<TicketTriage> result = session.promptStructured(
"Classify ticket #884: Enterprise SSO SAML assertions failing after certificate rotation.",
TicketTriage.class
);
TicketTriage triage = result.value();
System.out.println(triage.severity() + " -> " + triage.recommendedAction());How promptStructured(...) Works
- Generates a JSON Schema from
Class<T>orTypeReference<T>(reusing OpenHusky's cycle-safe schema generator). - Instructs the model via
ResponseFormat.jsonSchema(...)(or structured fallback when a gateway lacks native schema enforcement). - Validates and deserializes the output into
T, automatically retrying up toStructuredOutputOptions.maxValidationRetries()if schema validation fails, or throwingStructuredOutputExceptionwith raw text andRunResultdiagnostics. - Returns
StructuredRunResult<T>containing.value(),.stepsExecuted(),.totalUsage(), and the full.runResult().