Modeling a writing-tone feature with Spring AI ChatClient
Keep model adapters and prompt files separate from the domain, validate structured drafts, and release database connections before model calls.
I added a writing-tone profile based on a user’s recent posts and comments. The service uses Spring AI to analyze and rewrite text, with model calls placed between short database transactions.
The example project uses Spring Boot 3.5.16, Kotlin 1.9.25, Java 21, and Spring AI 1.1.8 with the Google GenAI starter.
Configuring the model integration
The feature needs two operations. One describes the style found in the user’s recent writing. The other applies that description to a draft. I wanted to keep the provider integration, prompt text, and use cases separate. A slow inference request should also leave database connections available for ordinary requests.
I added the Spring AI BOM and the Google GenAI model starter through Gradle.
1
2
3
4
5
6
7
8
9
10
11
12
// build.gradle.kts
extra["springAiVersion"] = "1.1.8"
dependencies {
implementation("org.springframework.ai:spring-ai-starter-model-google-genai")
}
dependencyManagement {
imports {
mavenBom("org.springframework.ai:spring-ai-bom:${property("springAiVersion")}")
}
}
optional:file:.env[.properties] lets the application read local configuration from a properties-style .env file. The import is optional so container and CI environments can supply environment variables. The placeholder key in the example is only enough for context initialization. A real model request needs valid credentials and a GEMINI_MODEL available to the configured account. Confirm provider availability before deploying the supplied default.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# src/main/resources/application.yml
spring:
config:
import: optional:file:.env[.properties]
jpa:
open-in-view: false
ai:
google:
genai:
api-key: ${GEMINI_API_KEY:dummy-api-key}
chat:
options:
model: ${GEMINI_MODEL:gemini-3.8-flash}
temperature: 0.7
Keeping providers and prompts out of the domain
| Approach | Provider change | Available controls |
|---|---|---|
| Provider-specific model and option classes | Modify adapter imports, options, and setup | Full set of supported provider parameters |
ChatClient.Builder and common ChatOptions | Change the starter and configuration when the needed behavior is portable | Common options such as temperature, top-p, and token limit |
The domain defines WritingToneAnalyzer, WritingToneGenerator, and WritingToneDraft. The infrastructure adapter implements each port with ChatClient.Builder. This keeps classes such as GoogleGenAiChatModel and GoogleGenAiChatOptions outside the domain. A provider swap still needs behavioral checks because the same prompt and options can produce different output.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// writing/tone/domain/WritingToneDraft.kt
data class WritingToneDraft(
val title: String,
val content: String,
)
// writing/tone/domain/WritingToneAnalyzer.kt
interface WritingToneAnalyzer {
fun analyze(text: List<String>): String
}
// writing/tone/domain/WritingToneGenerator.kt
interface WritingToneGenerator {
fun generate(
draft: WritingToneDraft,
toneDescription: String,
tokenLimit: Int = 2000,
): WritingToneDraft
}
The system prompts live in src/main/resources/prompts/writing-tone-analyze.md and writing-tone-generate.md. I can review prompt changes as Markdown without mixing them with service control flow. The analysis adapter combines the resource-backed system instructions with the selected writing samples. It requests a text description and treats a missing response as a failure.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// writing/tone/infrastructure/SpringAiWritingToneAnalyzer.kt
@Component
class SpringAiWritingToneAnalyzer(
chatClientBuilder: ChatClient.Builder,
@Value("classpath:prompts/writing-tone-analyze.md")
systemPromptResource: Resource,
) : WritingToneAnalyzer {
private val chatClient: ChatClient = chatClientBuilder
.defaultSystem(systemPromptResource)
.defaultOptions(
ChatOptions.builder()
.temperature(0.7)
.topP(0.9)
.build(),
)
.build()
override fun analyze(text: List<String>): String {
return chatClient.prompt()
.user(
"""
Analyze the tone and writing style in the following samples from one user:
${text.joinToString(separator = "\n")}
""".trimIndent(),
)
.call()
.content()
?: throw IllegalStateException("Failed to analyze writing tone")
}
}
Converting the generated draft into a response
The generated title and body need to arrive as distinct fields. The generator calls .entity(ArticleWritingForm::class.java). Spring AI’s BeanOutputConverter derives a format from the target type, supplies output instructions, and parses the model response into that type. The example maps Kotlin’s content property to the JSON key description so the response matches its prompt and API contract.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// writing/tone/presentation/request/ArticleWritingForm.kt
@Schema(description = "Writing-style conversion form")
data class ArticleWritingForm(
@field:NotBlank(message = "Enter a title.")
@field:Size(max = 255, message = "The title must be at most 255 characters.")
@field:JsonProperty(required = true, value = "title")
@field:JsonPropertyDescription("Rewritten article title, up to 255 characters")
val title: String,
@field:NotBlank(message = "Enter the body text.")
@field:Size(max = 2000, message = "The body must be at most 2,000 characters.")
@field:JsonProperty(required = true, value = "description")
@field:JsonPropertyDescription("Rewritten article body, up to 2,000 characters")
val content: String,
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// writing/tone/infrastructure/SpringAiWritingToneGenerator.kt
@Component
class SpringAiWritingToneGenerator(
chatClientBuilder: ChatClient.Builder,
@Value("classpath:prompts/writing-tone-generate.md")
systemPromptResource: Resource,
) : WritingToneGenerator {
private val chatClient: ChatClient = chatClientBuilder
.defaultSystem(systemPromptResource)
.build()
override fun generate(
draft: WritingToneDraft,
toneDescription: String,
tokenLimit: Int,
): WritingToneDraft {
val result = chatClient.prompt()
.user(
"""
Rewrite the draft below using the supplied writing style:
--- style description
$toneDescription
--- title
${draft.title}
--- content
${draft.content}
---
""".trimIndent(),
)
.options(
ChatOptions.builder()
.temperature(0.9)
.topP(0.95)
.maxTokens(tokenLimit)
.build(),
)
.call()
.entity(ArticleWritingForm::class.java)
?: throw IllegalStateException("Failed to parse generated writing tone response")
return WritingToneDraft(title = result.title, content = result.content)
}
}
@JsonPropertyDescription gives length guidance to the model. Bean Validation and domain checks still need to enforce the actual limits after parsing. A structurally valid response can contain an empty or oversize field. A maxTokens budget that cuts the reply short can also leave malformed JSON, especially when the prompt already requests a long body.
Releasing the connection during inference
A transaction that covers the entire analyzeWritingTone() method can hold a HikariCP connection while it waits for the model. Several such requests can make unrelated queries queue. I use TransactionTemplate around the two database phases and call the analyzer between them.
flowchart TD
A["POST /api/v1/writing-tones"] --> B["Read writing samples"]
B -->|"Release connection"| C["Call ChatClient"]
C -->|"Obtain description"| D["Save writing tone"]
D --> E["Return result"]
The first phase reads up to ten recent posts and ten recent comments, then returns the user ID and strings. The adapter receives plain data and can run with open-in-view: false. The second phase stores the description and creates the response DTO. The generation path similarly reads the latest writing tone in a short transaction before calling its adapter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// writing/tone/application/WritingToneCommandService.kt
@Service
class WritingToneCommandService(
private val userRepository: UserRepository,
private val articleRepository: ArticleRepository,
private val commentRepository: CommentRepository,
private val writingToneAnalyzer: WritingToneAnalyzer,
private val writingToneGenerator: WritingToneGenerator,
private val writingToneRepository: WritingToneRepository,
private val transactionTemplate: TransactionTemplate,
) {
fun analyzeWritingTone(email: String): WritingToneResponse {
val (userId, texts) = checkNotNull(
transactionTemplate.execute {
val user = userRepository.findByEmail(email)
?: throw NotFoundException(User::class.java, mapOf("email" to email))
val recentPage = PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "createdAt"))
val articles = articleRepository.findByAuthorId(user.id, recentPage).content
val comments = commentRepository.findByAuthorId(user.id, recentPage).content
val collected = articles.map { it.title } +
articles.map { it.content } +
comments.map { it.content }
if (collected.isEmpty()) {
throw BadRequestException("There are no articles or comments to analyze.")
}
user.id to collected
},
)
val analyzedText = writingToneAnalyzer.analyze(texts)
return checkNotNull(
transactionTemplate.execute {
val saved = writingToneRepository.save(
WritingTone(userId = userId, description = analyzedText),
)
WritingToneResponse.from(saved)
},
)
}
fun generateWithWritingTone(
email: String,
articleWritingForm: ArticleWritingForm,
): ArticleWritingForm {
val toneDescription = checkNotNull(
transactionTemplate.execute {
val user = userRepository.findByEmail(email)
?: throw NotFoundException(User::class.java, mapOf("email" to email))
writingToneRepository.findByUserId(
userId = user.id,
pageable = PageRequest.of(0, 1, Sort.by(Sort.Direction.DESC, "createdAt")),
).content.firstOrNull()?.description
?: throw NotFoundException(WritingTone::class.java, mapOf("userId" to user.id))
},
)
val generated = writingToneGenerator.generate(
draft = WritingToneDraft(articleWritingForm.title, articleWritingForm.content),
toneDescription = toneDescription,
tokenLimit = 1000,
)
return ArticleWritingForm(title = generated.title, content = generated.content)
}
}
A separate WritingToneQueryService uses @Transactional(readOnly = true) for history. The controller exposes analysis and history at /api/v1/writing-tones and generation at POST /api/v1/writing-tones/generate. Both use cases can return a model failure without leaving a database transaction open.
Testing failure and resource boundaries
- Output length. Give the model an output budget that can hold the JSON and the expected body. Test a truncated response and a valid JSON object with an invalid field.
- Persistence scope. Keep an integration test with a deliberately slow model stub. Check that the model runs outside an active database transaction.
- Input size. Bound the sample query and truncate or reject very long input when needed. The number of rows is only one part of the model’s context budget.
- Provider configuration. Isolate test credentials and mock the model for ordinary tests. Run a deliberate integration check against the configured model before changing providers.
Treat model output as input at the application boundary. Parsing it into a Kotlin type is useful, and the service still owns validation rules and whether to accept the result.
