feat(router): array route contract + shorter RU router prompt

Route contract is now a JSON array of action objects (one per ask) so
compound utterances route all their intents, not just the first. Grammar
root emits `[{intent...},...]`; parseActions tolerates a bare object.
Cascade still returns one Decision — full N-action dispatch lands with the
engine turn-on (marked in-code).

Router prompt rewritten shorter + decision-ordered (prompt-guy feedback),
fact redefined as "implicit update" not "trackable state", kept in Russian
to match the CPT base + phraser. "интент" → "намерение".

CLAUDE.md: routing-architecture section + refreshed open items.
docs/plans: route-data generation plan.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GMrVfuYN3nE4L1vEiFYC9
This commit is contained in:
kami
2026-07-11 23:27:44 +04:00
parent 6a5121657a
commit 0c65387a5f
3 changed files with 129 additions and 18 deletions
+57 -16
View File
@@ -21,10 +21,12 @@ type LLMRouter struct{ c Completer }
func NewLLMRouter(c Completer) *LLMRouter { return &LLMRouter{c: c} }
// routeGrammar — GBNF constraining the model to a fixed-shape JSON object with
// an intent enum. Prevents free-form drift from a sub-1B model.
// routeGrammar — GBNF constraining the model to a JSON ARRAY of fixed-shape
// action objects (one per ask; compound utterances → multiple). Enum + key set
// prevent free-form drift from a sub-1B model.
const routeGrammar = `
root ::= "{" ws "\"intent\"" ws ":" ws intent ("," ws field)* ws "}"
root ::= "[" ws action ("," ws action)* ws "]"
action ::= "{" ws "\"intent\"" ws ":" ws intent ("," ws field)* ws "}"
intent ::= "\"fact\"" | "\"reminder\"" | "\"note\"" | "\"query\"" | "\"act\"" | "\"chat\"" | "\"system\""
field ::= key ws ":" ws string
key ::= "\"key\"" | "\"value\"" | "\"text\"" | "\"verb\""
@@ -32,19 +34,36 @@ string ::= "\"" ([^"\\] | "\\" .)* "\""
ws ::= [ \t\n]*
`
const routeSystem = `Ты — маршрутизатор Maven. По реплике верни ОДИН JSON-объект: {"intent": ...}.
const routeSystem = `Классифицируй ровно одно сообщение пользователя. Верни ОДИН JSON-объект.
Интенты:
- fact — состояние/показатель, который надо запомнить и ОТСЛЕЖИВАТЬ во времени. "я выпил воду" → {"intent":"fact","key":"water","value":"выпил"}.
- reminder — просьба напомнить о чём-то В БУДУЩЕМ, есть время или срок ("напомни", "не забудь", "через час", "завтра", "в 9:00"). text = что напомнить. "напомни завтра в 9 позвонить маме" → {"intent":"reminder","text":"позвонить маме"}.
- note — заметка «на память» БЕЗ отслеживания и БЕЗ будущего времени ("запомни", "запиши", "заметь"). text = суть. "запомни что кофе закончился" → {"intent":"note","text":"кофе закончился"}.
- query — вопрос, требующий ответа. text = вопрос.
- act — команда выполнить действие на сервере. verb = глагол.
- chat — свободный разговор. text.
- system — вопрос о текущем времени/дате/дне недели.
Ровно одно намерение: fact, reminder, note, query, act, chat, system.
ВАЖНО: «запомни/запиши» = note (просто сохранить), «напомни/не забудь» = reminder (напомнить позже). Нет будущего времени и это не «напомни» → note, НЕ reminder.
Только JSON, без пояснений.`
Классифицируй по цели пользователя. Порядок решения:
1. Хочет напоминание в будущем → reminder
2. Явно просит сохранить информацию → note
3. Сообщает или обновляет текущее состояние/событие → fact
4. Хочет получить информацию → query
5. Просит выполнить работу → act
6. Про ассистента, настройки или память → system
7. Иначе → chat
Различия:
- note — сохранить информацию, без напоминания. text = суть.
- reminder — уведомить позже. text = что напомнить.
- fact — неявное обновление: пользователь сообщает, что что-то в мире изменилось (текущее/изменённое состояние, случившееся событие). key/value.
Примеры:
"запиши пароль" → {"intent":"note","text":"пароль"}
"напомни купить молоко" → {"intent":"reminder","text":"купить молоко"}
"запиши купить молоко" → {"intent":"note","text":"купить молоко"}
"я выпил воду" → {"intent":"fact","key":"water","value":"выпил"}
"мой любимый фильм — Интерстеллар" → {"intent":"note","text":"любимый фильм — Интерстеллар"}
"что такое docker?" → {"intent":"query","text":"что такое docker"}
"напиши письмо" → {"intent":"act","verb":"написать письмо"}
"очисти память" → {"intent":"system"}
"привет" → {"intent":"chat","text":"привет"}
Ответ — JSON-массив: по одному объекту на каждую просьбу. Обычно один. Если в реплике несколько просьб — по объекту на каждую. "напомни купить молоко, и запиши что кофе кончился" → [{"intent":"reminder","text":"купить молоко"},{"intent":"note","text":"кофе кончился"}]. Только JSON, без пояснений.`
type routeAction struct {
Intent string `json:"intent"`
@@ -59,10 +78,18 @@ func (lr *LLMRouter) Route(ctx context.Context, utterance string, now time.Time)
if err != nil {
return Decision{}, false, err
}
var a routeAction
if err := json.Unmarshal([]byte(strings.TrimSpace(raw)), &a); err != nil {
acts, err := parseActions(strings.TrimSpace(raw))
if err != nil {
return Decision{}, false, fmt.Errorf("llmrouter: parse %q: %w", raw, err)
}
if len(acts) == 0 {
return Decision{}, false, fmt.Errorf("llmrouter: empty action list %q", raw)
}
// ponytail: contract is an array (compound utterances → N actions), but the
// Router cascade still returns one Decision. Dispatch of all actions lands
// with the engine turn-on (Router.Route → []Decision, both voice.go handlers
// loop). Until then only the first ask is honored.
a := acts[0]
d := Decision{Utterance: utterance, Stage: 1, Confidence: 1.0}
switch Intent(a.Intent) {
case IntentFact:
@@ -90,6 +117,20 @@ func (lr *LLMRouter) Route(ctx context.Context, utterance string, now time.Time)
return d, true, nil
}
// parseActions accepts the array contract (`[{...},...]`) or a bare object
// (`{...}`) for robustness against a model that drops the wrapper.
func parseActions(raw string) ([]routeAction, error) {
if strings.HasPrefix(raw, "[") {
var as []routeAction
return as, json.Unmarshal([]byte(raw), &as)
}
var a routeAction
if err := json.Unmarshal([]byte(raw), &a); err != nil {
return nil, err
}
return []routeAction{a}, nil
}
func firstNonEmpty(a, b string) string {
if strings.TrimSpace(a) != "" {
return a