Spring AI — Improving LLM recommendations in my Runs application

In one of my earlier posts on Testcontainers, I discussed how I was using multiple databases to maintain information from the different running applications that I use.

As I continue to enhance my Runs project, one of the areas that I have been spending time on is integrating Spring AI and using the running information that I have accumulated over the years to generate meaningful insights.

The intention is to see if the application can help me plan my subsequent runs based on my historical running activities, races and other forms of exercise.

While using this functionality, I noticed that the recommendations from the LLM were not necessarily applicable to me. It was recommending interval training, hill repeats and strength training. I already do strength training, and my current running routine is focused on easy-effort running.

Before trying to change the LLM or enhance the prompt, I wanted to understand what was being passed to the LLM.

In this post, I want to share some of the changes I made to the application, along with the code and some of the architectural considerations that came out of this exercise.

1. Current architecture

There are two applications that are primarily involved in this implementation.

  • runs-app – Responsible for importing Garmin activities, maintaining the information in PostgreSQL and providing the APIs for the front-end application.
  • runs-ai-analyzer – Responsible for calculating the metrics, integrating with the LLM using Spring AI and maintaining the generated analysis in a vector store.

The analyzer also provides a RAG-based functionality that allows me to ask questions based on my previous running analyses and journal entries.

The source code for both applications is available in my GitHub.

2. Understanding the information being passed to the LLM

Here is what the application was analyzing on November 26, 2026, compared to the actual information from my last ten runs.

MetricBeforeAfter
Number of runs510
Total distance13.9 miles66.01 miles
Average pace21:19 min/mile12.06 min/mile (decimal)
Analysis window12 days40 days
Half marathons02

Interestingly, I had completed two half marathons during this period, one in Des Moines and another in Albuquerque.

Neither of these was being considered by the LLM.

There were three issues that I identified while tracing the information between the applications.

3. Maintaining data consistency between microservices

The Garmin information in the Runs application is stored in miles. However, the analyzer was converting this information again, assuming that the distance was in kilometers.

Here is the earlier implementation in RunAnalysisServiceImpl.

Java
sb.append(" - Distance: ")
.append(String.format("%.2f",
parseDouble(run.getDistance()) * KM_TO_MILES))
.append(" mi\n");

Since the information from the Runs application is already in miles, the conversion is not required.

Java
sb.append(" - Distance: ")
.append(String.format("%.2f",
parseDouble(run.getDistance())))
.append(" mi\n");

The same correction was made to the calculation of the running metrics.

One of the considerations here is the way we maintain the semantics of the information being exchanged between microservices.

In the Runs application, the distance is represented as distanceMiles. In the analyzer, it is represented as distance.

While the contract was syntactically valid, the two applications were interpreting the information differently.

I would like to revisit this contract in a subsequent iteration and explicitly represent the unit of measurement.

The changes to the implementation can be found in this commit.

4. Using Spring Data JPA to select the right information

The next issue was with the selection of the running activities.

Garmin records my running, strength training, walking and elliptical activities. The earlier implementation was retrieving recent activities and subsequently filtering out the non-running activities.

What I needed was the ten most recent running activities.

To accomplish this, I added a method to the existing Spring Data repository.

Java
Page<GarminRun> findAllByActivityType(
String activityType,
Pageable pageable
);

The existing REST API was enhanced to take an optional activityType parameter.

Here is the relevant portion of GarminRunResource.

Java
Page<GarminRunDTO> page =
activityType != null && !activityType.isBlank()
? garminRunService.findAllByActivityType(
activityType, pageable)
: garminRunService.findAll(filter, pageable);
return ResponseEntity.ok(new PagedResponse<>(page));

With this change, the filtering is performed at the database-query level before applying pagination.

The React application can now retrieve the ten most recent runs using the following API invocation.

TypeScript
const runsRes = await axios.get(
'/api/garminRuns?activityType=running&size=10&sort=activityDate,desc'
);
const runs = (
runsRes.data?.content ?? runsRes.data ?? []
).slice(0, 10);

The advantage of this implementation is that other activities do not take up the ten records that I intend to use for the running analysis.

The repository, service and REST API changes are available in this commit.

5. Normalizing the Garmin activity types

Another issue that I identified was in the Garmin CSV parser.

The earlier implementation recognized strength training and elliptical activities. Everything else was classified as running.

The following changes were made to the GarminCsvParser.

Java
static String normalizeActivityType(String csvType) {
String lower = csvType == null
? ""
: csvType.toLowerCase(java.util.Locale.ROOT);
if (lower.contains("strength"))
return "strength_training";
if (lower.contains("elliptical"))
return "elliptical";
if (lower.contains("run"))
return "running";
if (lower.contains("cycl")
|| lower.contains("bik")
|| lower.contains("ride"))
return "cycling";
if (lower.contains("walk"))
return "walking";
if (lower.contains("hik"))
return "hiking";
return "other";
}

The important change is that an activity that is not recognized is no longer automatically treated as running.

When I looked at the information that I had accumulated in PostgreSQL, there were 96 activities that had been incorrectly classified as running.

The code changes would address future imports. However, I also needed to correct the existing information in the database.

Since the PostgreSQL instance running on my home server is my source of truth, I took backups and captured the existing record counts before making the changes.

I also had to consider the information that was already generated by the LLM and persisted in the vector store.

Eight previously generated analyses were based on incorrect running information. These were removed while retaining my journal entries.

This brings up an interesting consideration when working with RAG-based applications. Correcting the source information does not necessarily correct the information that has already been derived from it.

The SQL script for relabeling the historical activities is available in scripts/sql/2026-11-relabel-non-run-activities.sql.

The script uses activity names to infer the original activity type, so the changes need to be reviewed before they are applied.

This is how the application last 10 run analysis looks like:

6. Enhancing the contextual information for Spring AI

After correcting the above issues, the information that the analyzer was providing to the LLM was consistent with my running data.

However, I was still getting recommendations to do interval training and hill repeats.

This gave me an opportunity to look at the way I was building the prompt.

The earlier prompt primarily consisted of the individual running activities and derived metrics. There was very little information about me as a runner or the other activities that I was doing.

There were a few enhancements that I wanted to make.

Providing the athlete profile

I wanted to externalize the information about the runner rather than hard-code it as part of the system prompt.

The following entry was added to application.yaml.

YAML
analysis:
athlete-profile: ${ANALYSIS_ATHLETE_PROFILE:Cannot do tempo, interval, hill-repeat or other speed work. Recommend easy-effort running only.}

This information is injected into the Spring service.

Java
@Value("${analysis.athlete-profile:}")
private String athleteProfile = "";

The same configuration is used by the analysis service and the RAG-based RagAnswerService.

This allows both AI capabilities to have a consistent understanding of the runner.

For my current implementation, I can override the profile through the environment variable without having to make changes to the Java code.

Including cross-training information

Although I did not want strength training and elliptical activities to be included in the running metrics, I still wanted the LLM to be aware of these activities.

The React application retrieves additional activities and passes the non-running activities from the relevant period as contextual information.

TypeScript
const oldestRunDate = runs
.map((r: any) => String(r.activityDate ?? ''))
.sort()[0] ?? '';
let crossTraining: any[] = [];
try {
const recentRes = await axios.get(
'/api/garminRuns?size=100&sort=activityDate,desc'
);
crossTraining = (recentRes.data?.content ?? [])
.filter((a: any) =>
a.activityType !== 'running' &&
String(a.activityDate ?? '') >= oldestRunDate
);
} catch {
crossTraining = [];
}
const jobRes = await axios.post(
'/api/rag/analyze',
{ runs, crossTraining, forceRefresh }
);

The request DTO in the analyzer was also enhanced to accept this additional information.

Java
private List<GarminRunDataDTO> crossTraining;
public List<GarminRunDataDTO> getCrossTrainingOrEmpty() {
return crossTraining == null
? List.of()
: crossTraining;
}

The intention is to keep the running metrics separate while giving the LLM more context when generating the recommendations.

The React changes can be found in this commit.

7. What should the application calculate and what should the LLM calculate?

This was probably the most interesting part of the exercise for me from an architecture standpoint.

The application already has the information required to calculate the running mileage, pace and weekly running volume.

Rather than expecting the LLM to derive all this information, I wanted to perform these calculations within the Java application and provide the results to the LLM.

The following is an extract from the formatGuide method in RunAnalysisServiceImpl.

Java
LocalDate thisWeek = today.with(
TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)
);
TreeMap<LocalDate, double[]> weeks = new TreeMap<>();
for (GarminRunDataDTO run : runs) {
LocalDate d = day(run.getActivityDate());
if (d == null) continue;
double[] w = weeks.computeIfAbsent(
d.with(TemporalAdjusters.previousOrSame(
DayOfWeek.MONDAY)),
k -> new double[2]
);
w[0]++;
w[1] += parseDouble(run.getDistance());
}

The application uses this information to provide a computed guide that includes:

  • The most recent completed week with running activities.
  • A proposed mileage ceiling for the subsequent week.
  • The average running mileage over recent weeks.
  • The longest recent non-race run.
  • The number of days since the last identified race.

For the current implementation, I am experimenting with a mileage ceiling of 10% above the most recent completed week with runs.

This is a planning rule for my own application rather than a general recommendation for runners. I also need to ensure that the information retrieved represents the entire period being analyzed.

The race identification is currently based on the name of the activity.

Java
private static final Pattern LIKELY_RACE =
Pattern.compile(
"(?i)(marathon|half|race|\\b5k\\b|\\b10k\\b)"
);
private static boolean isLikelyRace(
GarminRunDataDTO run) {
return run.getActivityName() != null
&& LIKELY_RACE.matcher(
run.getActivityName()).find();
}

This is something I would like to improve by maintaining an explicit race attribute as part of the activity information.

The architectural consideration here is to use the application for deterministic calculations and use the LLM for interpreting the information and generating recommendations.

8. Building the prompt

With the additional information available, the user prompt has the following structure.

Java
Please analyze this runner's recent training.
Today:
Window:
About the runner:
Derived metrics:
Computed guide:
Weekly volume (weeks start Monday):
Runs, oldest first:
Cross-training in the same window:
Journal entries in the same window:

The implementation uses Java text blocks to build this information dynamically.

Java
return """
Please analyze this runner's recent training.
Today: %s
Window: %s to %s (%d days), %d runs
%s
Derived metrics:
%s
Computed guide (use these numbers as given):
%s
Weekly volume (weeks start Monday):
%s
Runs, oldest first:
%s
Cross-training in the same window:
%s
Journal entries in the same window:
%s
""".formatted(
label(today),
first,
last,
ChronoUnit.DAYS.between(first, last) + 1,
runs.size(),
athleteProfile == null || athleteProfile.isBlank()
? ""
: "\nAbout the runner:\n"
+ athleteProfile.strip() + "\n",
formatMetricsForPrompt(metrics),
formatGuide(runs, today),
formatWeeks(runs, crossInWindow),
runDataSummary,
formatCrossTraining(crossInWindow),
formatJournal(first, today)
);

The system prompt was also enhanced to instruct the LLM to use the computed information, respect the athlete profile and provide recommendations based on the supplied activities.

I am still experimenting with how much of this contextual information is required to get meaningful recommendations without unnecessarily increasing the size of the prompt.

The entire prompt implementation is available in this commit.

The changes to the RAG-based Ask AI functionality are available in this commit.

9. Testing the implementation

In my earlier post on Testcontainers, I discussed how integration testing helped me validate the database implementations across multiple microservices.

With the introduction of AI into the application, I wanted to understand what additional testing was required.

There are three areas that I have been looking at.

Testing the Garmin activity classification

JUnit parameterized tests are useful for validating the different activity types provided by Garmin.

Here is the test from GarminCsvParserActivityTypeTest.

Java
@ParameterizedTest
@CsvSource({
"Running, running",
"Treadmill Running, running",
"Trail Running, running",
"Track Running, running",
"Virtual Run, running",
"Strength Training, strength_training",
"Elliptical, elliptical",
"Indoor Cycling, cycling",
"Cycling, cycling",
"Mountain Biking, cycling",
"Walking, walking",
"Hiking, hiking",
"Pool Swim, other",
"Yoga, other"
})
void mapsGarminTypes(String garminType, String expected) {
assertThat(
GarminCsvParser.normalizeActivityType(garminType)
).isEqualTo(expected);
}

This allows me to validate the classification independently of the rest of the application.

Complete test class

Testing the running metrics

The following is a simple test that validates the pace calculation.

Java
@Test
void nineMinuteMilePaceStaysNineMinutes() {
RunAnalysisResponse response =
service.analyzeRuns(
List.of(run("A1", "5.00", "00:45:00")),
true
);
assertThat(
response.getMetrics().getAveragePaceMinPerMile()
).isEqualTo(9.0);
verify(ragStorageService).storeAnalysis(
anyList(),
eq(response),
anyString(),
anyString()
);
}

For a five-mile run completed in 45 minutes, the average pace should be nine minutes per mile.

This is a deterministic test and does not require an actual invocation of the LLM.

Complete test class

Testing the information being passed to the LLM

Another area that I wanted to validate was the actual prompt being constructed by the application.

Mockito’s ArgumentCaptor provides a simple way to capture the information being passed to the AI provider.

Java
ArgumentCaptor<String> userPrompt =
ArgumentCaptor.forClass(String.class);
verify(aiProviderChain).call(
anyString(),
userPrompt.capture()
);
assertThat(userPrompt.getValue())
.contains("- Distance: 5.00 mi")
.contains("- Distance: 13.10 mi")
.contains("- Total distance: 18.10 mi")
.doesNotContain("3.11 mi");

What I like about this approach is that I can validate the information that is going to the LLM without having to depend on the response from the LLM.

I also have tests that validate the additional contextual information and the instructions in the system prompt.

RunAnalysisPromptTest.java

While these tests provide validation of the input to the LLM, I still need to establish a better mechanism to evaluate the quality of the recommendations generated by the LLM.

10. Observations from the implementation

Here is a comparison of the three iterations of the implementation.

OriginalData correctedContext enhanced
Runs analyzed51010
Distance13.9 mi66.01 mi66.01 mi
Cross-training contextNoNoYes
Athlete profileNoNoYes
Speed workouts recommendedYesYesNo
Approximate prompt size2,700 characters2,700 characters4,400 characters

One of the interesting observations was that I was able to improve the relevance of the recommendations without having to change the model as part of these fixes.

The changes were primarily in the application code, the quality of the data and the contextual information provided to the LLM.

There are still areas of the implementation that I need to improve.

During the code review, I also identified an issue with the background event-driven analysis process. There were 803 pending events that had not been successfully processed. This is something I need to address in the next iteration.

I also want to introduce application-level validation of the generated recommendations rather than relying entirely on the instructions in the prompt.

Here is the before and after look of how the AI is working currently

ask-ai-before
ask-ai-after

Conclusion

The Runs project continues to give me an opportunity to experiment with different technologies and understand some of the practical challenges associated with implementing them.

With microservices, we spend a considerable amount of time defining the contracts between the applications. With the introduction of an LLM, I am beginning to see the importance of applying similar thinking to the information that is being provided to the LLM.

The quality and completeness of the information, how it is represented and what contextual information is available all influence the recommendations that are generated.

I am interested in exploring the testing aspects of AI applications further, particularly how I can validate the recommendations across different LLMs while keeping the input information consistent.

The entire code base for the implementation is available in my GitHub.

Leave a Reply