The idea is simple: upload documents with unstructured data and get structured JSON responses back. In the background, a GenAI-supported ETL pipeline implemented with Spring AI is at work.
We evaluate JPEGs, PNGs and PDF files that contain any kind of data. The goal is to extract data that can be described using JSON Schema. We use Spring AI to access the model. The code for our experiment can be found on GitHub under the name TL;DR (Tool for Linguistic Document Reading).
We implement the whole thing in four steps:
An overview of our requirements
We have set clear parameters for the project:
- Binary data sources: JPEGs, PNGs and PDFs containing image information are to be processed.
- Spring AI as a framework: We use Spring AI's ETL-Pipeline design for a clean architecture.
- Local OCR with Tesseract: Text recognition runs locally to avoid token costs with ChatGPT.
- OpenAI model: We access a model from the Holisticon organisation.
- REST interface: Upload a document via POST request, receive structured JSON in return.
Spring AI and Tesseract
We use Spring AI. Why? Spring AI is our first choice because it:
- offers a uniform API across different model providers
- provides auto-configuration for beans, prompts, and output converters
- integrates seamlessly into existing Spring Boot architectures
Tesseract handles OCR because it:
- is easy to integrate
- generates no cloud costs
- delivers very stable results for printed texts
Practical lessons learned from OCR integration
- Pre-processing pays off: With ImageMagick, you can achieve significantly better results through rectification and contrast adjustment.
- Garbage in, garbage out: Poor OCR results directly lead to poor AI quality.
- Complex layouts: For tables and multi-column layouts, upgrading to Tesseract LSTM or PaddleOCR may be advisable.
The result is a simple but surprisingly powerful ETL pipeline – in other words, a classic “extract, transform, load” chain, this time with AI in the transform step.
Configuration in 3 steps
In addition to a few others, we need these three dependencies in our pom.xml:
Listing1: Maven Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-tika-document-reader</artifactId>
</dependency>
In our application.yml, we add these configurations:
Listing 2: application yaml
tldr:
prompt-template: |
You are a data extraction assistant.
With this request we send a json schema definition. The schema defines an array of objects. The objects in the array
have required fields.
Try to extract the required fields from the given text.
The given text is an unstructured document that was obtained through ocr from a scanned jpeg document.
Return the extracted data in JSON format according to the provided JSON schema.
If a field is missing, set its value to null.
Input text:
{{document}}
spring:
config:
import: optional:file:.env[.properties]
ai:
openai:
api-key: ${OPENAI_API_KEY}
organization-id: ${OPENAI_ORG_ID}
project-id: ${OPENAI_PROJECT_ID}
chat:
options:
model: ${OPENAI_MODEL:gpt-5-mini}
temperature: 1
reasoning-effort: ${OPENAI_MODEL_REASONING_EFFORT:minimal}
We store our API key. Optionally, an organisation ID and a project ID can also be stored.
Important parameters explained:
- Model: We select the desired model using the property spring.ai.openai.chat.options.model. We use gpt-5-mini as the default.
- Temperature: Controls the ‘creativity’ of the model (0.0-0.3 = deterministic, 0.5-0.7 = balanced, higher = more creative, somewhat more unpredictable). In our use case, however, this value had no measurable influence.
- Reasoning Effort: Relevant for GPT-5 models, controls the computational effort of the model for responses. We set it to minimum.
Implementation
With this configuration from application.yaml, we obtain a Spring Bean that we can inject anywhere in our application and use to send prompts to the GenAI model.
In Listing 3, this bean is named chatModel.
What is happening here?
- In line 35, we send a prompt to the model.
- The prompt is assembled in line 34. It contains our natural language question with the text extracted from the image file using OCR.
- The prompt also contains the configuration of the desired return format. In our case, this is a JSON schema definition (see Listing 4).
Listing 3: ChatModel
@RequiredArgsConstructor
@Slf4j
@Service
public class AiModelOutAdaper implements AiModelOutPort {
private final @NonNull OpenAiChatModel chatModel;
private final @NonNull BeanOutputConverter<PartList> partListBeanOutputConverter;
private final @NonNull ApplicationProperties applicationProperties;
/**
* Extracts structured data from the given file content using an AI model and a specified JSON schema.
*
* @param fileContent the content of the file to extract data from
* @param jsonSchema the JSON schema to format the response
* @return an Optional containing the structured data as a String, or an empty Optional if an error occurs
*/
@Override
public Optional<String> extractStructuredData(String fileContent, String jsonSchema) {
final String promptTemplate = applicationProperties.getPromptTemplate();
final String preparedPrompt = promptTemplate.replace("{{document}}", fileContent);
log.info("AiModelOutAdaper prepared prompt {}", preparedPrompt);
try {
final OpenAiChatOptions options = OpenAiChatOptions.builder()
.responseFormat(ResponseFormat.builder()
.type(ResponseFormat.Type.JSON_SCHEMA)
.jsonSchema(jsonSchema)
.build())
.build();
final Prompt prompt = new Prompt(new UserMessage(preparedPrompt), options);
final Generation chatResponse = chatModel.call(prompt).getResult();
return Optional.of(chatResponse)
.map(Generation::getOutput)
.map(AbstractMessage::getText);
} catch (final NonTransientAiException e) {
log.error("AiModelOutAdaper error calling chat model", e);
return Optional.empty();
}
}
}
JSON Schema: The secret weapon for structured data
The JSON schema defines exactly what structure the response should have.
Listing 4: JSON Schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "PartList",
"type": "object",
"properties": {
"parts": {
"type": "array",
"items": {
"type": "object",
"properties": {
"partNumber": {
"type": "string",
"description": "The unique identifier of the part"
},
"manufacturer": {
"type": "string",
"description": "The name of the manufacturer"
},
"serialNumber": {
"type": "string",
"description": "The serial number of the part"
}
},
"required": [
"partNumber",
"manufacturer",
"serialNumber"
],
"additionalProperties": false
}
}
},
"required": [
"parts"
],
"additionalProperties": false
}
The schema forces the model to adhere to the structure – a game changer for reliability.
Conclusion: What we have learned
The project was 80% classic software design of a Spring application – we tried to follow the hexagonal approach. The AI integration itself was surprisingly straightforward.
Our key findings
- OCR is the bottleneck.
Good text recognition is more effective than any prompt optimisation. - JSON Schema works wonders.
It forces the model to adhere to structure. - Spring AI makes AI integrations ready for production.
The Spring conventions (beans, error handling, properties) simply work. - Temperatur und Reasoning-Effort
have little influence on extraction quality – at least in our case.
The complete source code can be found here: https://github.com/holisticon/tl-dr
Outlook: Where could the journey take us?
We have considered the following ideas for further development:
Technical improvements:
- Experiments with other models (Claude, Mistral)
- Testing alternative OCR libraries as an alternative to Tesseract
- Defining document types, which includes:
- Type of document
- Definition of the data to be read
- Prompt specially adapted to this document type
- Cost transparency through token trackingAutomatic validation of read data, e.g. against an existing parts database
User Experience:
- A user interface that displays the extracted data together with the scanned document. Users could then "proofread" it again
- Subsequent correction options for users
Operation:
- Develop an operating model, i.e. describe how TL;DR can be operated in a Kubernetes cluster. Specific questions would include:
- Access to the Gen AI model from within the cluster.
- Installation of Tesseract or other OCR tools in the cluster.
Spring AI makes integrating GenAI models into existing Spring architectures surprisingly straightforward – try it out and be amazed by the results!