Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions changelog/v0.2.18.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# v0.2.18

Localised prompts and a multilingual console.

## Added

- The gateway default system prompt accepts `translations` for `hi` and `bn`.
A request's `Accept-Language` selects the matching text; an absent or blank
translation falls back to the default prompt. `GET /admin/system-prompt`
returns the stored map.
- The admin console has a language switch (English, Hindi, Bengali), persisted
per browser, and the Configuration prompt editor exposes the Hindi/Bengali
variants alongside the default.
4 changes: 3 additions & 1 deletion docs/ADMIN-UI.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ providers (create/edit with a
provider API key, probe, delete), routes (add a model, enable/disable, delete), client keys
(create with budgets and allowlists, top up, revoke), **configuration** (the gateway
switches, the default system prompt, alert email and the daily digest) and **settings**
(the session: identity, scopes, token, sign out).
(the session: identity, scopes, token, sign out). The sidebar language selector switches
the console between English, Hindi and Bengali and remembers the choice per browser; the
Configuration prompt editor stores Hindi/Bengali variants selected by `Accept-Language`.

## Auth

Expand Down
4 changes: 3 additions & 1 deletion docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,9 @@ curl -s -X PUT http://localhost:8080/admin/system-prompt \

`text` accepts up to 100,000 characters. Enabling with blank text returns 400; disabling
keeps the stored text. The console edits this same endpoint and reads the live limit from
`max_chars`.
`max_chars`. `translations` accepts `hi` and `bn`; a request's `Accept-Language` selects
one, and an absent/blank translation falls back to `text`. `GET /admin/system-prompt`
returns the stored `translations` map.

**Non-streaming**

Expand Down
2 changes: 1 addition & 1 deletion path-gateway/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<parent>
<groupId>io.github.an1ndra</groupId>
<artifactId>path-parent</artifactId>
<version>0.2.17</version>
<version>0.2.18</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,15 +157,16 @@ public Map<String, Object> systemPrompt() {

@PutMapping("/system-prompt")
public Map<String, Object> updateSystemPrompt(@RequestBody SystemPromptInput input) {
var updated = systemPromptService.save(input.text(), input.enabled());
var updated = systemPromptService.save(input.text(), input.enabled(), input.translations());
// The prompt itself may contain sensitive instructions: audit the shape only.
audit.record("system-prompt.update", "system-prompt", java.util.Map.of(
"enabled", String.valueOf(updated.get("enabled")),
"chars", String.valueOf(String.valueOf(updated.get("text")).length())));
return updated;
}

public record SystemPromptInput(String text, Boolean enabled) {
public record SystemPromptInput(String text, Boolean enabled,
java.util.Map<String, String> translations) {
}

@PostMapping("/alerts/test")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

/**
Expand All @@ -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.
*
* <p>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.
* <p>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
Expand All @@ -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<String> SUPPORTED = Set.of("en", "hi", "bn");

private final SystemPromptSettingsRepository repository;
private final SystemPromptTranslationRepository translations;
private final ObjectMapper mapper;
private final AtomicReference<Cached> 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;
}
Expand All @@ -85,6 +102,12 @@ public Map<String, Object> view() {
Map<String, Object> out = new LinkedHashMap<>();
out.put("enabled", settings != null && settings.isEnabled());
out.put("text", settings == null || settings.getText() == null ? "" : settings.getText());
Map<String, String> 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);
Expand All @@ -93,10 +116,29 @@ public Map<String, Object> view() {

@Transactional
public Map<String, Object> save(String text, Boolean enabled) {
return save(text, enabled, null);
}

@Transactional
public Map<String, Object> save(String text, Boolean enabled, Map<String, String> 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<String, String> 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();
Expand All @@ -115,6 +157,27 @@ public Map<String, Object> save(String text, Boolean enabled) {
settings.setEnabled(turnOn);
settings.setUpdatedAt(Instant.now());
repository.save(settings);

if (newTranslations != null) {
for (Map.Entry<String, String> 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
Expand All @@ -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<String, String> 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<String, String> translations, Instant loadedAt) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -297,7 +297,8 @@ public Map<String, Object> 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);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
Original file line number Diff line number Diff line change
@@ -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<SystemPromptTranslation, String> {
}
Original file line number Diff line number Diff line change
@@ -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)
);
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion path-spring-ai/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<parent>
<groupId>io.github.an1ndra</groupId>
<artifactId>path-parent</artifactId>
<version>0.2.17</version>
<version>0.2.18</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

<groupId>io.github.an1ndra</groupId>
<artifactId>path-parent</artifactId>
<version>0.2.17</version>
<version>0.2.18</version>
<packaging>pom</packaging>
<name>path-parent</name>
<description>Build parent for Path, the provider-agnostic LLM gateway, and its Spring AI adapter</description>
Expand Down