XAP

xap-ai-sdk: Developer Guide

xap-ai-sdk lets your application call large language models (LLMs) through one entry point, AgenticAIGateway. It builds on Spring AI and adds four things on top of a plain chat call:

  • Model profiles. Name a provider and model once, then pick a profile per call.

  • Personas and tools. Give the model a role and Java methods it can call.

  • Self-checking calls. advancedCall has a judge score each answer and asks for a better one until it passes.

  • Planning and agentic calls. taskPlanner breaks a goal into steps. agenticCall plans, runs, validates, and synthesizes the result.

The gateway is stateless, so one instance can serve your whole application.

Reference examples: gs-home/examples/ai-sdk and gs-home/examples/ai-sdk-nospring

Add the Dependencies

<dependency>
    <groupId>com.gigaspaces</groupId>
    <artifactId>xap-ai-sdk</artifactId>
    <version>${gs.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-anthropic</artifactId>
</dependency>

Add the Spring AI starter for each provider you use. The SDK includes the Anthropic and OpenAI modules as optional dependencies, so an application needs only the providers it calls.

Configure a Profile (Spring Boot)

Spring Boot registers the gateway automatically. Only the default profile is required:

spring.ai.anthropic.api-key=${ANTHROPIC_API_KEY}
ai-sdk.profiles.default.provider=anthropic
ai-sdk.profiles.default.model=claude-sonnet-5-5
ai-sdk.profiles.default.timeout=5m

# Optional: a second profile. Unset fields fall back to the default profile.
ai-sdk.profiles.cheap.provider=openai
ai-sdk.profiles.cheap.model=gpt-5-mini

# Optional: price per million tokens. Adds a dollar price to Response.cost().
ai-sdk.pricing[claude-sonnet-5-5].input-per-million=2.00
ai-sdk.pricing[claude-sonnet-5-5].output-per-million=10.00

Each Spring AI ChatModel bean becomes a provider, named after the bean's class with ChatModel removed: AnthropicChatModel gives anthropic, and OpenAiChatModel gives openai. Startup fails if the default profile is missing, or if a profile names a provider with no ChatModel bean.

Some settings are provider-specific and fail at startup if they are wrong for the provider:

  • effort works only with Anthropic and OpenAI models.

  • timeout works only with Anthropic and OpenAI models, and it must be positive.

  • Recent Claude models reject temperature, so leave it unset for them.

Use It Without Spring

For a plain Java application, build the Spring AI ChatModels yourself and pass them to AgenticAIGateway.create:

ChatModel anthropic = AnthropicChatModel.builder()
        .options(AnthropicChatOptions.builder().apiKey(System.getenv("ANTHROPIC_API_KEY")).build())
        .build();

AgenticAIProperties properties = new AgenticAIProperties();
properties.getProfiles().put("default", new AgenticAIProperties.Profile("anthropic", "claude-sonnet-5-5", null));
properties.getProfiles().put("precise", new AgenticAIProperties.Profile(null, "claude-opus-5-5", null, "high"));

AgenticAIGateway gateway = AgenticAIGateway.create(properties, Map.of("anthropic", anthropic));

The map keys are the provider names that profiles use. create throws the same startup errors as the Spring configuration. In a plain Spring (non-Boot) application, declare the gateway as a bean with create(...). Component scanning alone does not register its collaborators.

Make a Call

Inject AgenticAIGateway and choose one of four entry points. Each returns a builder, and nothing is sent until execute().

Entry Point Use It For
simpleCall(prompt) One request, with optional tools.
advancedCall(prompt) An answer that a judge scores, and that is regenerated until it passes.
taskPlanner(goal) An ordered plan for a goal. The plan is not executed.
agenticCall(goal) Plans, runs, validates, and synthesizes a goal end to end.
Response<String> response = gateway.simpleCall("Is it safe to land at KJFK right now?")
        .persona(flightOpsPersona)                 // system prompt and the persona's tools
        .systemMessage("Answer in 3 sentences.")   // added after the persona's system prompt
        .tools(new AviationWeatherTools())         // call-specific tools
        .config(CallConfig.builder().modelProfile("cheap").build())
        .execute();                                // or execute(MyRecord.class) for typed output

String answer = response.result();

Every builder accepts persona, systemMessage, tools, config, and conversationId. execute() returns text. execute(Class<T>) returns typed output, which is parsed from the model's JSON. taskPlanner returns PlanResult and has no execute(Class).

Personas

A Persona is a name, a system prompt, and optionally tools:

Persona flightOpsAdvisor = Persona.builder()
        .name("Flight Operations Advisor")
        .systemPrompt("You are an experienced flight operations advisor. Answer clearly.")
        .tools(new RunwayTools())
        .build();

A JudgePersona is the same kind of object, used to score answers. JudgePersona.defaultJudge() provides a general-purpose judge.

Tools

Tools are plain Java methods annotated with Spring AI's @Tool and @ToolParam:

public class RunwayTools {

    @Tool(description = "List the runways of an airport with heading, length and ILS availability")
    public List<Runway> getRunways(@ToolParam(description = "4-letter ICAO airport code, e.g. KJFK") String icaoCode) {
        return RUNWAYS.getOrDefault(icaoCode.toUpperCase(), List.of());
    }
}

Pass tools with .tools(...). You can pass @Tool objects, Spring AI ToolCallbacks, or ToolCallbackProviders such as an MCP client. The model gets the persona's tools plus the call's tools. If a call tool has the same name as a persona tool, the call tool replaces it.

Typed Output

record LandingAssessment(String airport, boolean safeToLand, String recommendedRunway, List<String> hazards) {}

Response<LandingAssessment> assessment = gateway.simpleCall("Assess landing conditions at KJFK.")
        .persona(dispatcher)
        .tools(new AviationWeatherTools(), new RunwayTools())
        .execute(LandingAssessment.class);

Conversations

Pass conversationId(...) to continue an earlier call. A conversation ID is generated when you don't pass one, and it comes back in response.conversationId(). Conversations are not persisted yet, so the SDK does not keep them between runs.

Model Profiles and CallConfig

A profile is a named set of provider, model, temperature, effort, and timeout. CallConfig overrides any of them for one call.

For each field, the value comes from the first source that sets it:

  1. The field on the CallConfig

  2. The profile named by CallConfig.modelProfile

  3. The default profile

If modelProfile names a profile that does not exist, the default profile is used.

CallConfig config = CallConfig.builder()
        .modelProfile("precise")     // profile for the generate step
        .effort("low")               // overrides the profile's effort for this call
        .timeout(Duration.ofMinutes(10))
        .build();

CallConfig also holds the settings for the judge and the reflection and validation limits. The next section lists them.

Effort is sent in each provider's own field: output_config.effort for Anthropic and reasoning_effort for OpenAI. The value is passed through lowercased, so the provider decides which values are valid.

Self-Checking Calls

advancedCall

advancedCall generates an answer, asks a judge to score it from 0.0 to 1.0 with improvement notes, and regenerates with those notes until the score reaches the threshold or the iteration limit is hit.

Response<String> brief = gateway.advancedCall("Draft a go/no-go decision brief for departing KJFK.")
        .persona(flightOpsAdvisor)
        .tools(new NotamTools())
        .judgePersona(safetyReviewJudge)
        .config(CallConfig.builder()
                .judgeModelProfile("precise")       // the judge runs on this profile
                .reflectionThreshold(0.9)           // overrides ai-sdk.reflection.threshold
                .reflectionMaxIterations(2)         // overrides ai-sdk.reflection.max-iterations
                .build())
        .execute();

brief.steps().forEach(step ->
        System.out.println(step.name() + ": " + step.judgment().score()));

The judge's tools are the judge persona's own. The caller's tools are not given to the judge. The judge's model comes only from judgeModelProfile, or from default. Other model fields in CallConfig apply to the generate step only.

response.result() is the accepted answer. If no answer reaches the threshold, it is the highest-scoring one.

taskPlanner

taskPlanner produces an ordered plan of steps and checks it with the same generate-and-judge loop. It does not execute the plan.

Response<PlanResult> plan = gateway.taskPlanner("Prepare a flight dispatch release for JFK to LHR.")
        .persona(dispatchPlanner)                   // optional: a built-in planner otherwise
        .availableTools(new AviationWeatherTools(), new NotamTools())  // described to the planner, never called
        .systemMessage("Use at most 8 steps.")
        .execute();

plan.result().steps().forEach(step ->
        System.out.println(step.order() + ": " + step.description()));

Each PlanStep has an order starting at 1, a description, a passOutputToNextStep flag, and optional model settings and suggestedToolUsage. The planner sees the profiles and tools you give it. A step's model settings always come from one configured profile, so the planner cannot invent a model. availableTools describes tools to the planner, but the planner cannot invoke them.

agenticCall

agenticCall does the whole job: it plans, runs each step, checks that the steps together reach the goal, and writes the final answer.

record DispatchReleaseBrief(String weatherSummary, String fuelPlanSummary, String recommendation) {}

Response<DispatchReleaseBrief> brief = gateway.agenticCall(
                "Prepare a full dispatch release brief for JFK to LHR, including weather, fuel and a go/no-go recommendation.")
        .persona(dispatchOfficer)
        .tools(new AviationWeatherTools(), new FuelPlanningTools())
        .config(CallConfig.builder()
                .judgeModelProfile("precise")     // used by every internal judge and the validator
                .validationThreshold(0.9)
                .validationMaxRetries(1)
                .build())
        .execute(DispatchReleaseBrief.class);

It runs four stages:

  1. Plan. A taskPlanner call plans the goal, using the persona's and the call's tools.

  2. Execute. Each step runs as an advancedCall with the persona's tools. A step receives the previous step's result only when that step's passOutputToNextStep is true.

  3. Validate. A validator checks whether all the step results, together, accomplish the goal. If not, the steps run again from the same plan, with the validator's notes added, up to validationMaxRetries times. If no attempt passes, the call still returns the last attempt, and the low score is recorded in the steps.

  4. Synthesize. A final advancedCall combines the results into the output type.

agenticCall has no judgePersona(...). Its internal calls use built-in judges.

Reading the Response

Response<T> response = ...;

response.result();          // the answer, typed if you used execute(Class)
response.steps();           // one Step per iteration or stage; empty for simpleCall
response.cost();            // token counts, plus a price when every model in the call is priced
response.rtt();             // total round-trip time
response.conversationId();  // pass to the next call to continue the conversation

Each Step has a name, an output, a judgment (score and notes, where there is one), and its own cost and rtt. For agenticCall, steps are named plan, implementation-N.step-K, implementation-N.validation, and synthesis.

cost.price() is null unless every model in the call has a price. Pricing is configured per model with ai-sdk.pricing[model]. A total that is only partly priced is not reported as a price.

Limits

Setting Default Applies To Set With
ai-sdk.reflection.threshold 0.8 advancedCall, taskPlanner reflectionThreshold in CallConfig
ai-sdk.reflection.max-iterations 3 advancedCall, taskPlanner reflectionMaxIterations in CallConfig
ai-sdk.agentic.validation.threshold 0.8 agenticCall validationThreshold in CallConfig
ai-sdk.agentic.validation.max-retries 2 agenticCall validationMaxRetries in CallConfig
ai-sdk.profiles.<name>.timeout 60s (provider default) each request timeout in CallConfig

An invalid value in properties fails startup. An invalid value in a CallConfig fails the call before any request is sent.

Set ai-sdk.profiles.<name>.timeout rather than spring.ai.openai.timeout. Spring AI's OpenAI client sends its own 60-second timeout with every request, which overrides the Spring setting.

Examples

Two runnable examples are in xap-examples. Both use the same tools and personas, and both are configured for Anthropic by default.

  ai-sdk ai-sdk-nospring
Style Spring Boot application Plain Java, AgenticAIGateway.create
Config application*.properties per provider Code in AiSdkNoSpringExample.properties(...)
Calls shown Five examples, one per feature (below) Three: simple call, typed output, advancedCall
Providers Anthropic, OpenAI, OpenRouter (Llama and Claude) Anthropic, OpenAI, and OpenRouter (through --provider=openai)

ai-sdk Examples

Each run executes one example, chosen with --example=<name>:

Name Feature
flight-ops simpleCall with a persona and tools
landing-assessment Persona tools merged with call tools, typed output, profile selection, conversation continuation
go-no-go advancedCall with a judge and the reflection trace
dispatch-plan taskPlanner with available tools and a judge
dispatch-brief agenticCall: plan, execute, validate, and synthesize
mvn package
export ANTHROPIC_API_KEY=...
java -jar target/xap-example-ai-sdk-*.jar --example=flight-ops

To use another provider, activate its Spring profile: openai, openrouter, or openrouter-anthropic. The example code does not change. Only the properties change.

dispatch-brief makes the most model requests, so expect it to take the longest and cost the most.

ai-sdk-nospring Example

mvn package
export ANTHROPIC_API_KEY=...
java -jar target/xap-example-ai-sdk-nospring-*.jar

Use --provider=openai with OPENAI_API_KEY for OpenAI. For OpenRouter, set OPENAI_BASE_URL to https://openrouter.ai/api/v1 and change the model names in the code to OpenRouter IDs, such as openai/gpt-5-mini.

Run the jar from the module directory, or keep its lib/ directory next to the jar. The manifest refers to the dependencies there.

Troubleshooting

Symptom Likely Cause What to Do
Startup fails: no default profile ai-sdk.profiles.default is not set Add the default profile.
Startup fails: unknown provider A profile names a provider with no ChatModel bean Add the provider's Spring AI starter, or fix the provider name.
Startup fails: effort or timeout not allowed Set on a provider that does not support it Remove it, or use an Anthropic or OpenAI profile.
Request rejected: temperature not supported A newer Claude or GPT-5 model rejects temperature Leave temperature unset for that profile.
Requests time out on large tasks Default 60 s per request Set ai-sdk.profiles.<name>.timeout, such as 5m.
advancedCall returns a low score No draft reached the threshold in the allowed iterations Raise reflectionMaxIterations, or lower reflectionThreshold, after checking the judge's notes in steps().
cost.price() is null One model in the call is not priced Add ai-sdk.pricing[model] for every model the call uses, including the judge's.
Tool not called The model did not choose it, or its description is unclear Improve the @Tool description, and check the persona's system prompt.

Checklist

  • The default profile is set, and each other profile names an existing provider.

  • The API key for each provider is set in the environment.

  • Temperature and effort are set only for models that accept them.

  • timeout is set for profiles that run tool-using calls on large models.

  • Every @Tool method has a clear description, and every parameter has a @ToolParam description.

  • Judges run on a profile you trust, because they decide when an answer is accepted.

  • Pricing is set for every model used, if you need dollar costs.

  • Conversation IDs are stored by your application if you need to continue a conversation later.