Skip to content

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 nested records or POJOs.
  • Runtime-injected parameters (excluded from the LLM JSON Schema):
    • ToolContext — emit progress (ctx.emitProgress(...)), inspect ctx.sessionId(), ctx.toolCallId(), and inherited ctx.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 = ...):

java
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:

  1. Returns text to the LLM as the tool output.
  2. Persists a StatePatchEntry into the SessionStore and emits AgentEvent.StateDelta (automatically translated by openhusky-agui into AG-UI RFC 6902 STATE_DELTA JSON Patch operations under /<namespace>/*, with null values deleting keys).

Streaming Tool Progress & Output Offloading ​

  • Call ctx.emitProgress("...") inside any tool to emit AgentEvent.ToolCallProgress (forwarded as openhusky:tool_progress over AG-UI SSE).
  • Register OutputOffloadToolInterceptor.inMemory(32_768) (or disk-backed spill) to prevent massive tool outputs from overflowing the context window while keeping ImageBlocks and details intact.

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>:

java
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 ​

  1. Generates a JSON Schema from Class<T> or TypeReference<T> (reusing OpenHusky's cycle-safe schema generator).
  2. Instructs the model via ResponseFormat.jsonSchema(...) (or structured fallback when a gateway lacks native schema enforcement).
  3. Validates and deserializes the output into T, automatically retrying up to StructuredOutputOptions.maxValidationRetries() if schema validation fails, or throwing StructuredOutputException with raw text and RunResult diagnostics.
  4. Returns StructuredRunResult<T> containing .value(), .stepsExecuted(), .totalUsage(), and the full .runResult().

Released under the MIT License. Built with Java 21 Virtual Threads.