translations) {
}
@PostMapping("/alerts/test")
diff --git a/path-gateway/src/main/java/com/anindra/path/admin/SystemPromptService.java b/path-gateway/src/main/java/com/anindra/path/admin/SystemPromptService.java
index e24da72..ba4e27d 100644
--- a/path-gateway/src/main/java/com/anindra/path/admin/SystemPromptService.java
+++ b/path-gateway/src/main/java/com/anindra/path/admin/SystemPromptService.java
@@ -2,7 +2,9 @@
import com.anindra.path.api.ApiException;
import com.anindra.path.domain.SystemPromptSettings;
+import com.anindra.path.domain.SystemPromptTranslation;
import com.anindra.path.repo.SystemPromptSettingsRepository;
+import com.anindra.path.repo.SystemPromptTranslationRepository;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -16,7 +18,9 @@
import java.time.Duration;
import java.time.Instant;
import java.util.LinkedHashMap;
+import java.util.Locale;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
/**
@@ -27,8 +31,9 @@
* in the controller before sanitising, hashing, moderation, caching and metering: every one
* of those sees the same prompt the provider receives.
*
- * The row is cached for a few seconds to avoid a database read on every chat call. A save
- * invalidates this node immediately; other replicas pick up the change within the TTL.
+ *
A request's {@code Accept-Language} selects a stored translation when one exists; the
+ * default text is the fallback. The row and its translations are cached for a few seconds;
+ * a save invalidates this node immediately.
*/
@Service
@RequiredArgsConstructor
@@ -37,34 +42,46 @@ public class SystemPromptService {
/** Large enough for a full upstream prompt; the Claude Code core prompt is ~18k. */
public static final int MAX_CHARS = 100_000;
private static final Duration CACHE_TTL = Duration.ofSeconds(5);
+ private static final Set SUPPORTED = Set.of("en", "hi", "bn");
private final SystemPromptSettingsRepository repository;
+ private final SystemPromptTranslationRepository translations;
private final ObjectMapper mapper;
private final AtomicReference cache = new AtomicReference<>();
/** The prompt to inject, or an empty string when the feature is off. */
public String activeText() {
+ return activeText(null);
+ }
+
+ /** The best prompt for this Accept-Language header, falling back to the default text. */
+ public String activeText(String acceptLanguage) {
Cached hit = cache.get();
- if (fresh(hit)) {
- return hit.text();
+ if (!fresh(hit)) {
+ synchronized (this) {
+ hit = cache.get();
+ if (!fresh(hit)) {
+ hit = load();
+ }
+ }
}
- synchronized (this) {
- hit = cache.get();
- if (fresh(hit)) {
- return hit.text();
+ String locale = pickLocale(acceptLanguage);
+ if (locale != null) {
+ String translated = hit.translations().get(locale);
+ if (translated != null && !translated.isBlank()) {
+ return translated;
}
- String text = repository.findById(SystemPromptSettings.SINGLETON)
- .filter(SystemPromptSettings::isEnabled)
- .map(settings -> settings.getText() == null ? "" : settings.getText())
- .orElse("");
- cache.set(new Cached(text, Instant.now()));
- return text;
}
+ return hit.text();
}
/** Prepends the configured prompt to a chat request body. Invalid bodies are left to the parser. */
public ObjectNode apply(ObjectNode body) {
- String text = activeText();
+ return apply(body, null);
+ }
+
+ public ObjectNode apply(ObjectNode body, String acceptLanguage) {
+ String text = activeText(acceptLanguage);
if (text.isBlank()) {
return body;
}
@@ -85,6 +102,12 @@ public Map view() {
Map out = new LinkedHashMap<>();
out.put("enabled", settings != null && settings.isEnabled());
out.put("text", settings == null || settings.getText() == null ? "" : settings.getText());
+ Map current = new LinkedHashMap<>();
+ for (SystemPromptTranslation translation : translations.findAll()) {
+ current.put(translation.getLocale(),
+ translation.getText() == null ? "" : translation.getText());
+ }
+ out.put("translations", current);
out.put("updated_at", settings == null || settings.getUpdatedAt() == null
? null : settings.getUpdatedAt().toString());
out.put("max_chars", MAX_CHARS);
@@ -93,10 +116,29 @@ public Map view() {
@Transactional
public Map save(String text, Boolean enabled) {
+ return save(text, enabled, null);
+ }
+
+ @Transactional
+ public Map save(String text, Boolean enabled, Map newTranslations) {
if (text != null && text.length() > MAX_CHARS) {
throw ApiException.badRequest(
"'text' must be at most " + MAX_CHARS + " characters.", "text");
}
+ if (newTranslations != null) {
+ for (Map.Entry entry : newTranslations.entrySet()) {
+ String locale = entry.getKey() == null ? "" : entry.getKey().trim().toLowerCase(Locale.ROOT);
+ if (!SUPPORTED.contains(locale) || locale.equals("en")) {
+ throw ApiException.badRequest(
+ "'translations' supports hi and bn.", "translations");
+ }
+ if (entry.getValue() != null && entry.getValue().length() > MAX_CHARS) {
+ throw ApiException.badRequest(
+ "Each translation must be at most " + MAX_CHARS + " characters.",
+ "translations");
+ }
+ }
+ }
SystemPromptSettings settings = repository.findById(SystemPromptSettings.SINGLETON)
.orElseGet(() -> {
SystemPromptSettings created = new SystemPromptSettings();
@@ -115,6 +157,27 @@ public Map save(String text, Boolean enabled) {
settings.setEnabled(turnOn);
settings.setUpdatedAt(Instant.now());
repository.save(settings);
+
+ if (newTranslations != null) {
+ for (Map.Entry entry : newTranslations.entrySet()) {
+ String locale = entry.getKey().trim().toLowerCase(Locale.ROOT);
+ String value = entry.getValue();
+ if (value == null || value.isBlank()) {
+ translations.findById(locale).ifPresent(translations::delete);
+ } else {
+ SystemPromptTranslation translation = translations.findById(locale)
+ .orElseGet(() -> {
+ SystemPromptTranslation created = new SystemPromptTranslation();
+ created.setLocale(locale);
+ return created;
+ });
+ translation.setText(value);
+ translation.setUpdatedAt(Instant.now());
+ translations.save(translation);
+ }
+ }
+ }
+
// A request that starts before the commit must not cache the old row afterwards.
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
@@ -125,10 +188,43 @@ public void afterCommit() {
return view();
}
+ private Cached load() {
+ String text = repository.findById(SystemPromptSettings.SINGLETON)
+ .filter(SystemPromptSettings::isEnabled)
+ .map(settings -> settings.getText() == null ? "" : settings.getText())
+ .orElse("");
+ Map translated = new LinkedHashMap<>();
+ for (SystemPromptTranslation translation : translations.findAll()) {
+ translated.put(translation.getLocale(),
+ translation.getText() == null ? "" : translation.getText());
+ }
+ Cached loaded = new Cached(text, Map.copyOf(translated), Instant.now());
+ cache.set(loaded);
+ return loaded;
+ }
+
+ /** en is the default text; hi/bn are stored translations. */
+ private static String pickLocale(String acceptLanguage) {
+ if (acceptLanguage == null || acceptLanguage.isBlank()) {
+ return null;
+ }
+ for (String token : acceptLanguage.split(",")) {
+ String tag = token.split(";")[0].trim().toLowerCase(Locale.ROOT);
+ if (tag.isEmpty()) {
+ continue;
+ }
+ String base = tag.split("-")[0];
+ if (SUPPORTED.contains(base)) {
+ return base;
+ }
+ }
+ return null;
+ }
+
private static boolean fresh(Cached value) {
- return value != null && value.savedAt().plus(CACHE_TTL).isAfter(Instant.now());
+ return value != null && value.loadedAt().plus(CACHE_TTL).isAfter(Instant.now());
}
- private record Cached(String text, Instant savedAt) {
+ private record Cached(String text, Map translations, Instant loadedAt) {
}
}
diff --git a/path-gateway/src/main/java/com/anindra/path/api/ChatCompletionsController.java b/path-gateway/src/main/java/com/anindra/path/api/ChatCompletionsController.java
index 3c92350..d24d8f9 100644
--- a/path-gateway/src/main/java/com/anindra/path/api/ChatCompletionsController.java
+++ b/path-gateway/src/main/java/com/anindra/path/api/ChatCompletionsController.java
@@ -101,7 +101,7 @@ private ResponseEntity> handle(ObjectNode body, ClientKey key, HttpServletRequ
HttpServletResponse response) throws IOException {
// Inject before sanitising and hashing: the stored, metered and replayed prompt is
// then exactly what the provider receives.
- body = systemPrompts.apply(body);
+ body = systemPrompts.apply(body, request.getHeader("Accept-Language"));
if (sanitizer.redactBeforeSend()) {
// Redact first: the prompt the provider receives is then the prompt we hash,
// store and replay, so a retry cannot resurrect the original text.
@@ -297,7 +297,8 @@ public Map tokenCount(
projectLimit != null && projectLimit > 0 ? projectLimit : limit);
}
try {
- return tokenCount.count(systemPrompts.apply(body), key);
+ return tokenCount.count(
+ systemPrompts.apply(body, request.getHeader("Accept-Language")), key);
} finally {
concurrency.release(key);
}
diff --git a/path-gateway/src/main/java/com/anindra/path/domain/SystemPromptTranslation.java b/path-gateway/src/main/java/com/anindra/path/domain/SystemPromptTranslation.java
new file mode 100644
index 0000000..773552e
--- /dev/null
+++ b/path-gateway/src/main/java/com/anindra/path/domain/SystemPromptTranslation.java
@@ -0,0 +1,26 @@
+package com.anindra.path.domain;
+
+import jakarta.persistence.*;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+import java.time.Instant;
+
+/** A translated variant of the gateway default system prompt. */
+@Entity
+@Table(name = "system_prompt_translations")
+@Getter
+@Setter
+@NoArgsConstructor
+public class SystemPromptTranslation {
+
+ @Id
+ @Column(length = 16)
+ private String locale;
+
+ @Column(nullable = false, length = 100000)
+ private String text = "";
+
+ private Instant updatedAt;
+}
diff --git a/path-gateway/src/main/java/com/anindra/path/repo/SystemPromptTranslationRepository.java b/path-gateway/src/main/java/com/anindra/path/repo/SystemPromptTranslationRepository.java
new file mode 100644
index 0000000..459123e
--- /dev/null
+++ b/path-gateway/src/main/java/com/anindra/path/repo/SystemPromptTranslationRepository.java
@@ -0,0 +1,8 @@
+package com.anindra.path.repo;
+
+import com.anindra.path.domain.SystemPromptTranslation;
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface SystemPromptTranslationRepository
+ extends JpaRepository {
+}
diff --git a/path-gateway/src/main/resources/db/migration/V27__system_prompt_translations.sql b/path-gateway/src/main/resources/db/migration/V27__system_prompt_translations.sql
new file mode 100644
index 0000000..ff3ce4b
--- /dev/null
+++ b/path-gateway/src/main/resources/db/migration/V27__system_prompt_translations.sql
@@ -0,0 +1,8 @@
+-- Localised gateway default system prompts, selected by Accept-Language.
+
+create table system_prompt_translations (
+ locale varchar(16) not null,
+ text varchar(100000) not null default '',
+ updated_at timestamp(6) with time zone,
+ primary key (locale)
+);
diff --git a/path-gateway/src/test/java/com/anindra/path/admin/SystemPromptServiceTest.java b/path-gateway/src/test/java/com/anindra/path/admin/SystemPromptServiceTest.java
index 5c26fbb..87466b8 100644
--- a/path-gateway/src/test/java/com/anindra/path/admin/SystemPromptServiceTest.java
+++ b/path-gateway/src/test/java/com/anindra/path/admin/SystemPromptServiceTest.java
@@ -67,6 +67,24 @@ void disabledPromptLeavesTheRequestUntouched() throws Exception {
assertThat(service.view().get("text")).isEqualTo("Gateway policy.");
}
+ @Test
+ void acceptLanguageSelectsStoredTranslation() throws Exception {
+ service.save("Default policy.", true, java.util.Map.of(
+ "hi", "हिन्दी नीति।",
+ "bn", "বাংলা নীতি।"));
+
+ assertThat(service.apply(body(), "hi-IN,hi;q=0.9").path("messages").get(0).path("content").asText())
+ .isEqualTo("हिन्दी नीति।");
+ assertThat(service.apply(body(), "bn").path("messages").get(0).path("content").asText())
+ .isEqualTo("বাংলা নীতি।");
+ // English and unsupported languages fall back to the default text.
+ assertThat(service.apply(body(), "fr-FR").path("messages").get(0).path("content").asText())
+ .isEqualTo("Default policy.");
+ assertThat(service.view().get("translations"))
+ .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP)
+ .containsEntry("hi", "हिन्दी नीति।");
+ }
+
@Test
void aSaveImmediatelyReplacesTheCachedPrompt() {
service.save("first", true);
diff --git a/path-spring-ai/pom.xml b/path-spring-ai/pom.xml
index 1537bef..a2b17a0 100644
--- a/path-spring-ai/pom.xml
+++ b/path-spring-ai/pom.xml
@@ -7,7 +7,7 @@
io.github.an1ndra
path-parent
- 0.2.17
+ 0.2.18
../pom.xml
diff --git a/pom.xml b/pom.xml
index b1303dc..0913703 100644
--- a/pom.xml
+++ b/pom.xml
@@ -13,7 +13,7 @@
io.github.an1ndra
path-parent
- 0.2.17
+ 0.2.18
pom
path-parent
Build parent for Path, the provider-agnostic LLM gateway, and its Spring AI adapter