by Horațiu Dan
From the Playground to code
A previous article introduced TypeSafe Jev, a System One model that answers questions about a piece of text with typed values and probabilities instead of generated prose. It covered the three primitives, noul (a yes/no probability), choice (one option out of a fixed set) and score (a position on an ordered scale) and tuned a set of three questions about code review comments in the TypeSafe Playground.
This article moves the same questions into a Java application. The integration is deliberately plain: no SDK, no AI framework, just the HTTP API and Spring’s RestClient. The result is a small Spring Boot 4 project with four parts, each of which gets a section below:
- a handful of Java records that mirror the request and response JSON
- a
RestClientbean configured fromapplication.yaml - a thin
JevClientthat sends a state and a map of questions in one call - a
CommandLineRunnerthat asks the three code review questions about three comments and prints the answers
Every snippet below is taken unchanged from the accompanying project, jev-spring-intro (Resource 6). It is built with Spring Boot 4.1 on Java 25, although Java 21 is the practical minimum here.
The REST contract
Everything the client needs is one endpoint, authenticated with the API key as a bearer token (Reference 1).
POST https://api.typesafe.ai/v1/systemone
The request body has three members: the model name, the state to judge and a questions object keyed by names that the caller picks. The response echoes the model that actually served the call and returns an answers object with the same keys, plus a usage object with the token counts.
| Member | Request | Response |
|---|---|---|
model | Model name, for example jev-latest | Concrete version that answered, for example jev-1.13.0 |
state | Any JSON value: a string, an object, an array | Not returned |
questions / answers | Question name mapped to a question with a type, instructions and criteria | Question name mapped to an answer with the same type |
usage | Not sent | input_tokens and output_tokens |
The type discriminator is what makes the contract typed:
- A
noulquestion comes back as{"type": "noul", "noul": 0.95}. - A
choicequestion comes back with the “winning”choice, aprobabilitiesmap over every option and aconfidence. - A
scorequestion comes back with the weightedscore, alegendthat maps each level index to its description, theprobabilitiesper level and aconfidence.
On the Java side this discriminator maps naturally onto a sealed interface with one record per type, which is the subject of the next sections.
Project setup
The project is a standard Spring Boot application with a single production dependency, the RestClient starter. Spring Boot 4 split the former web starter into smaller pieces, so a client-only application no longer pulls in an embedded server or Spring MVC.
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>4.1.1</version></parent><properties> <java.version>25</java.version></properties><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-restclient</artifactId> </dependency></dependencies>
The connection settings live in application.yaml. The API key is read from the TYPESAFE_API_KEY environment variable, the same one the previous article recommended for the Playground key, so it never lands in the repository. The model is jev-latest, an alias that the API resolves to a concrete version. The response’s own model field reports which one actually answered.
jev: base-url: https://api.typesafe.ai api-key: ${TYPESAFE_API_KEY:} model: jev-latest
A small record binds these three values. @ConfigurationPropertiesScan on the application class registers it, so there is no extra configuration class.
@ConfigurationProperties(prefix = "jev")public record JevProperties(String baseUrl, String apiKey, String model) {}
Modelling the contract in Java
The JSON contract maps onto four records and two sealed interfaces. Records are immutable, serialize with Jackson without any configuration and allow validation in a compact constructor, so an invalid request fails in the application before any HTTP call is made.
Questions
Question is a sealed interface with one record per primitive. The @JsonTypeInfo annotation tells Jackson to write a type property and each @JsonTypeName supplies its value, so a Question.Noul serializes with "type": "noul" without the record having to carry that field. The compact constructors enforce what the API would otherwise reject: a noul needs exactly the true and false criteria, a choice needs at least one option and a score needs at least one level.
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")@JsonSubTypes({ @JsonSubTypes.Type(Question.Noul.class), @JsonSubTypes.Type(Question.Choice.class), @JsonSubTypes.Type(Question.Score.class)})public sealed interface Question { @JsonTypeName("noul") record Noul(String instructions, Map<String, String> criteria) implements Question { public Noul { if (instructions == null || instructions.isEmpty()) { throw new IllegalArgumentException("instructions shall not be null or empty"); } if (criteria == null || criteria.size() != 2 || !criteria.keySet().containsAll(Set.of("true", "false"))) { throw new IllegalArgumentException("criteria keys must be \"true\" and \"false\""); } } } @JsonTypeName("choice") record Choice(String instructions, Map<String, String> criteria) implements Question { // validation omitted } @JsonTypeName("score") record Score(String instructions, List<String> criteria) implements Question { // validation omitted }}
The three records differ only in the shape of criteria: a map with two fixed keys, a map of option names to descriptions and an ordered list of levels. That difference is exactly the one the previous article’s primitives section described, now enforced by the compiler.
Request
JevRequest is the body of the POST. The state is typed as Object on purpose: the API accepts any JSON value, so a caller can pass a string, a record or a map and Jackson serializes whatever it gets. The questions map uses names chosen by the caller. These names are not seen by the model, which is why the keys here are only used to look the answers up later.
public record JevRequest(String model, Object state, Map<String, Question> questions) { public JevRequest { if (model == null || model.isEmpty()) { throw new IllegalArgumentException("model shall not be null or empty"); } if (state == null) { throw new IllegalArgumentException("state shall not be null"); } if (questions == null || questions.isEmpty()) { throw new IllegalArgumentException("questions shall not be null or empty"); } }}
Answers
Answer mirrors Question on the way back. Here Jackson reads the type property instead of writing it, so the subtype names are declared in @JsonSubTypes and Jackson picks the record to instantiate. Each record holds exactly the fields the API documents for that type, with Map<String, Double> for the probability distributions and Map<String, String> for the score legend, whose keys are the level indexes as strings.
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")@JsonSubTypes({ @JsonSubTypes.Type(value = Answer.Noul.class, name = "noul"), @JsonSubTypes.Type(value = Answer.Choice.class, name = "choice"), @JsonSubTypes.Type(value = Answer.Score.class, name = "score")})public sealed interface Answer { record Noul(double noul) implements Answer {} record Choice(String choice, Map<String, Double> probabilities, double confidence) implements Answer {} record Score(double score, Map<String, String> legend, Map<String, Double> probabilities, double confidence) implements Answer {}}
JevResponse wraps the answers and the usage. Jackson’s default naming is camel case, so the two token counts carry a @JsonProperty to match the API’s snake case. The three accessors at the bottom are a convenience: when the caller knows which type a question had, response.noul("blocking") saves a cast at every call site.
public record JevResponse(String model, Map<String, Answer> answers, Usage usage) { public record Usage(@JsonProperty("input_tokens") int inputTokens, @JsonProperty("output_tokens") int outputTokens) { } public Answer.Noul noul(String questionId) { return (Answer.Noul) answers.get(questionId); } public Answer.Choice choice(String questionId) { return (Answer.Choice) answers.get(questionId); } public Answer.Score score(String questionId) { return (Answer.Score) answers.get(questionId); }}
The client: Spring RestClient
RestClient is the synchronous, fluent HTTP client that Spring Framework 6.1 introduced as the successor of RestTemplate (Reference 2). Spring Boot auto-configures a RestClient.Builder with the application’s Jackson ObjectMapper and its HTTP settings already applied (Reference 3), so the only thing left to do is to inject the builder and fix the parts that are the same for every call: the base URL and the authorization header.
@Componentpublic class JevClient { private final JevProperties properties; private final RestClient restClient; public JevClient(JevProperties properties, RestClient.Builder builder) { this.properties = properties; this.restClient = builder .baseUrl(properties.baseUrl()) .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + properties.apiKey()) .build(); } public JevResponse ask(Object state, Map<String, Question> questions) { return restClient.post() .uri("/v1/systemone") .contentType(MediaType.APPLICATION_JSON) .body(new JevRequest(properties.model(), state, questions)) .retrieve() .body(JevResponse.class); }}
The whole integration is the ask method. It builds a JevRequest from the configured model, the caller’s state and the caller’s questions, posts it as JSON and asks RestClient to deserialize the body into a JevResponse. Jackson handles the type discriminators in both directions, so a caller receives a Map<String, Answer> whose values are already Answer.Noul, Answer.Choice or Answer.Score instances.
Asking the three questions from Java
PrimitivesRunner is a CommandLineRunner that repeats the Playground experiment from the previous article in code. The three code review comments become the states and the three questions, a noul, a choice and a score, are declared once as a Map<String, Question> and sent with every comment. The Map.of and List.of literals read almost like the JSON they produce.
private static final List<String> REVIEW_COMMENTS = List.of( "This builds the SQL query by concatenating `userId` from the request, which allows SQL injection. " + "Please switch to a PreparedStatement before we merge.", "Nit: I'd rename `tmp` to `pendingOrders` so the loop reads better. Not a blocker.", "Did you even run this? The cache is never invalidated, so users will see stale prices.");private static final Map<String, Question> QUESTIONS = Map.of( // Noul: the probability that a yes/no condition holds "blocking", new Question.Noul( "Does this code review comment require a change before the pull request can be merged?", Map.of("true", "Points out a defect or risk that must be fixed, or explicitly asks for a change before merging", "false", "An optional suggestion, nit, question or praise that does not block the merge")), // Choice: exactly one option, with a probability distribution over all of them "category", new Question.Choice( "What is the main concern of this code review comment?", Map.of("bug", "Incorrect behavior, a logic error or a missing case", "security", "A vulnerability such as injection, leaked secrets or missing authorization", "performance", "Speed, memory or resource usage", "readability", "Naming, formatting, structure or style", "other", "Anything else, such as tests, documentation or a question")), // Score: a position on ordered levels; the value can fall between two levels "tone", new Question.Score( "How constructive is the tone of this code review comment towards the author?", List.of("Hostile: insults or mocks the author", "Curt: dismissive or sarcastic, no explanation", "Neutral: states the problem without explaining or suggesting a fix", "Constructive: explains the problem and suggests a fix", "Very constructive: explains the problem, suggests a fix and is encouraging")));
The run loop is one call per comment.
@Overridepublic void run(String... args) { StringBuilder out = new StringBuilder("\nJev primitives playground\n"); for (String comment : REVIEW_COMMENTS) { JevResponse response = jevClient.ask(comment, QUESTIONS); out.append("\n\"").append(comment).append("\"\n"); out.append(describe("blocking", response)); out.append(describe("category", response)); out.append(describe("tone", response)); out.append(" tokens %d in, %d out%n".formatted( response.usage().inputTokens(), response.usage().outputTokens())); } log.info(out.toString());}private static String describe(String questionId, JevResponse response) { var answer = response.answers().get(questionId); return switch (answer) { case Answer.Noul noul -> " %-9s noul %.2f%n" .formatted(questionId, noul.noul()); case Answer.Choice choice -> " %-9s choice %s (confidence %.2f) %s%n" .formatted(questionId, choice.choice(), choice.confidence(), choice.probabilities()); case Answer.Score score -> " %-9s score %.2f / %d (confidence %.2f) %s%n" .formatted(questionId, score.score(), score.legend().size() - 1, score.confidence(), score.probabilities()); };}
This is the division of labor the previous article described. Jev supplies three judgments per comment; the Java code decides what to do with them. In a real tool the describe method would be replaced by rules such as if (response.noul("blocking").noul() > 0.8) to hold a merge, or a check on score.confidence() to send ambiguous cases to a person. The thresholds live in code, where they can be tested and tuned.
Running it
With the API key exported, the application starts, runs the three requests and stops. Against the version that jev-latest resolved to, it printed the following.
export TYPESAFE_API_KEY=..../mvnw spring-boot:run
Jev primitives playground"This builds the SQL query by concatenating `userId` from the request, which allows SQL injection. Please switch to a PreparedStatement before we merge." blocking noul 0.98 category choice security (confidence 1.00) {bug=0.0, security=1.0, performance=0.0, readability=0.0, other=0.0} tone score 3.03 / 4 (confidence 0.97) {0=0.0, 1=0.0, 2=0.0, 3=0.97, 4=0.03} tokens 605 in, 84 out"Nit: I'd rename `tmp` to `pendingOrders` so the loop reads better. Not a blocker." blocking noul 0.04 category choice readability (confidence 1.00) {bug=0.0, security=0.0, performance=0.0, readability=1.0, other=0.0} tone score 3.45 / 4 (confidence 0.62) {0=0.0, 1=0.0, 2=0.0, 3=0.55, 4=0.45} tokens 596 in, 86 out"Did you even run this? The cache is never invalidated, so users will see stale prices." blocking noul 0.86 category choice bug (confidence 0.99) {bug=0.99, security=0.0, performance=0.0, readability=0.0, other=0.01} tone score 1.30 / 4 (confidence 0.72) {0=0.02, 1=0.72, 2=0.21, 3=0.05, 4=0.0} tokens 593 in, 84 out
The numbers match the Playground results of the previous article to within a few hundredths:
- the SQL injection comment is blocking,
securityand constructive - the naming nit is not blocking,
readabilityand split between Constructive and Very constructive - the stale cache comment is blocking, a
bugand curt
The nit’s tone is the case the previous article warned about (Reference 4): a score of 3.45 says little on its own, and the 0.62 confidence is what tells code that the comment sits between two levels rather than firmly on one.
The small differences, for example 0.04 instead of 0.05 for the nit’s blocking, are the expected variation between runs and between the model versions behind jev-preview and jev-latest.
Each request costs about 600 input tokens, almost all of them the question definitions, which is the price of sending the full criteria on every call.
Conclusion
Integrating Jev from Java needs no SDK. One endpoint, one bearer header and a request body with three members are enough, and Spring’s RestClient reduces the call to a handful of fluent lines.
The work that remains is modelling, which has been easily addressed with Java records and sealed interfaces, which fit the contract closely.
The questions tuned in the Playground moved into code unchanged and returned the same judgments, which is the workflow the previous article suggested: design and tune in the Playground, then ship the JSON as Java literals.
From here the natural next steps are to wrap the typed answers in domain rules with explicit thresholds, to add error handling and timeouts on the builder for production use and to keep the questions under test so that a reworded criterion is a deliberate change rather than an accident.
References
[1] – TypeSafe HTTP API
[2] – Spring Framework RestClient
[3] – Spring Boot Calling REST Services
[4] – TypeSafe Primitives (Questions) and Confidence
[5] – The previous article, Introducing TypeSafe Jev: Typed Judgments as Programming Primitives
[6] – Article source code
[7] – Picture was taken in Zakynthos, Greece























