feat: {response,mood} output contract + router removal, TTS piper plan

Daemon side of Decision B: parse {"response","mood"} across the 4 consumers
(replier, nudges, reminders, chat), fall back to legacy formats. Drop the
LLM router — the classifier handles routing; replier/phraser share one
llm.Client (timeout 20s->60s). llm.Client reads reasoning_content when
content is empty (thinking models).

Docs: TTS piper-student plan (OmniVoice teacher -> piper student, from
scratch, phoneme-first). CLAUDE.md training guide.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
kami
2026-07-11 22:51:50 +04:00
parent 22b43c07a9
commit 6a5121657a
13 changed files with 952 additions and 51 deletions
+2
View File
@@ -37,6 +37,7 @@ type PhrasedNudge struct {
Candidate loop.Candidate
Body string
Summary string
Mood string
}
// PhrasedReminder — the phraser's output for a reminder.
@@ -44,6 +45,7 @@ type PhrasedReminder struct {
Decision loop.ReminderDecision
Body string
Summary string
Mood string
}
// Dispatch — record of one successful send. returned to the daemon for
+10 -4
View File
@@ -35,8 +35,10 @@ type Req struct {
}
type msg struct {
Role string `json:"role"`
Content string `json:"content"`
Role string `json:"role"`
Content string `json:"content"`
Reasoning string `json:"reasoning,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
}
type body struct {
Messages []msg `json:"messages"`
@@ -54,7 +56,7 @@ type resp struct {
func (c *Client) Complete(ctx context.Context, r Req) (string, error) {
b, _ := json.Marshal(body{
Messages: []msg{{"system", r.System}, {"user", r.User}},
Messages: []msg{{Role: "system", Content: r.System}, {Role: "user", Content: r.User}},
MaxTokens: r.MaxTokens,
Grammar: r.Grammar,
Temp: 0,
@@ -81,5 +83,9 @@ func (c *Client) Complete(ctx context.Context, r Req) (string, error) {
if len(out.Choices) == 0 {
return "", fmt.Errorf("llm: no choices")
}
return out.Choices[0].Message.Content, nil
content := out.Choices[0].Message.Content
if content == "" {
content = out.Choices[0].Message.ReasoningContent
}
return content, nil
}
+93 -27
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os/exec"
"regexp"
@@ -161,14 +162,18 @@ func (p *LLMPhraser) PhraseNudge(ctx context.Context, c loop.Candidate) (deliver
if err != nil {
return delivery.PhrasedNudge{}, err
}
body, summary := parsePhrase(resp)
body, mood := parseResponseMood(resp)
if body == "" {
// fallback: try old body/summary format
body, _ = parsePhrase(resp)
}
if body == "" {
body = fmt.Sprintf("%s — %s", c.Rule.Name, sevLabel(c.Severity))
}
if summary == "" {
summary = c.Rule.Name
if mood == "" {
mood = "neutral"
}
return delivery.PhrasedNudge{Candidate: c, Body: body, Summary: summary}, nil
return delivery.PhrasedNudge{Candidate: c, Body: body, Summary: body, Mood: mood}, nil
}
// PhraseQuery prompts the LLM with the user's utterance and matching notes to
@@ -184,6 +189,9 @@ func (p *LLMPhraser) PhraseQuery(ctx context.Context, utterance string, notes []
if err != nil || resp == "" {
return "не знаю.", nil
}
if text, _ := parseResponseMood(resp); text != "" {
return text, nil
}
return resp, nil
}
if len(notes) == 1 {
@@ -201,6 +209,9 @@ func (p *LLMPhraser) PhraseQuery(ctx context.Context, utterance string, notes []
}
return "вот что я нашла: " + strings.Join(notes, "; "), nil
}
if text, _ := parseResponseMood(resp); text != "" {
return text, nil
}
return resp, nil
}
@@ -212,20 +223,28 @@ func (p *LLMPhraser) PhraseChat(ctx context.Context, utterance string, history [
msgs := []chatMsg{
{Role: "system", Content: sys},
}
// Append dialogue history: user turns become "user" messages, and since we
// don't store assistant replies in the dialogue history, we reconstruct the
// pattern as alternating user messages. The model can infer maven's presence.
// Combine history and current utterance into one user message.
// Some model chat templates (Ministral, etc.) reject consecutive user turns.
var combined string
for _, t := range history {
msgs = append(msgs, chatMsg{Role: "user", Content: t.Text})
combined += t.Text + "\n"
}
// Current utterance as the final user message.
msgs = append(msgs, chatMsg{Role: "user", Content: utterance})
combined += utterance
msgs = append(msgs, chatMsg{Role: "user", Content: strings.TrimSpace(combined)})
resp, err := p.chatWithMessages(ctx, msgs, 512)
if err != nil {
log.Printf("phraser: PhraseChat: %v", err)
return "поговорили.", nil
}
return resp, nil
if text, _ := parseResponseMood(resp); text != "" {
return text, nil
}
// fallback: plain text without JSON
if i := strings.IndexByte(resp, '\n'); i >= 0 {
resp = resp[:i]
}
return strings.TrimSpace(resp), nil
}
// chatSystemPrompt returns the system prompt for conversational chat.
@@ -235,7 +254,7 @@ func chatSystemPrompt(persona string) string {
Keep replies brief (1-3 sentences) and natural. You're helpful, curious, and a little warm.
Respond in the user's language (Russian or English, matching their last message).
Never roleplay emotions you don't have, but stay friendly.
Just answer directly — no JSON wrapper, no meta-commentary.`
Respond ONLY with valid JSON: {"response": "...", "mood": "neutral"}. "response" is your reply text; "mood" reflects your tone (neutral/happy/thinking/tired/confused).`
if persona != "" {
base = persona + "\n\n" + base
}
@@ -279,7 +298,12 @@ func (p *LLMPhraser) chatWithMessages(ctx context.Context, msgs []chatMsg, maxTo
if len(cr.Choices) == 0 {
return "", fmt.Errorf("llm: no choices in response")
}
return cr.Choices[0].Message.Content, nil
content := cr.Choices[0].Message.Content
if content == "" {
content = cr.Choices[0].Message.ReasoningContent
}
log.Printf("llm raw content: %q", content)
return stripThink(content), nil
}
func (p *LLMPhraser) PhraseReminder(ctx context.Context, d loop.ReminderDecision) (delivery.PhrasedReminder, error) {
@@ -289,24 +313,29 @@ func (p *LLMPhraser) PhraseReminder(ctx context.Context, d loop.ReminderDecision
}
prompt := fmt.Sprintf(
`The user set a reminder: "%s". Rephrase it briefly as a gentle nudge. Respond as JSON: {"body": "...", "summary": "..."}`,
`The user set a reminder: "%s". Rephrase it briefly as a gentle nudge. Respond as JSON: {"response": "...", "mood": "..."}`,
text,
)
resp, err := p.chat(ctx, prompt)
if err != nil {
return delivery.PhrasedReminder{}, err
}
body, summary := parsePhrase(resp)
body, mood := parseResponseMood(resp)
if body == "" {
// fallback: try old body/summary format
body, _ = parsePhrase(resp)
}
if body == "" {
body = text
}
if summary == "" {
summary = text
if len(summary) > 60 {
summary = summary[:57] + "..."
}
if mood == "" {
mood = "neutral"
}
return delivery.PhrasedReminder{Decision: d, Body: body, Summary: summary}, nil
summary := body
if len(summary) > 60 {
summary = summary[:57] + "..."
}
return delivery.PhrasedReminder{Decision: d, Body: body, Summary: summary, Mood: mood}, nil
}
type chatMsg struct {
@@ -324,13 +353,15 @@ type chatReq struct {
type chatResp struct {
Choices []struct {
Message struct {
Content string `json:"content"`
Content string `json:"content"`
Reasoning string `json:"reasoning"`
ReasoningContent string `json:"reasoning_content"`
} `json:"message"`
} `json:"choices"`
}
func (p *LLMPhraser) chat(ctx context.Context, userPrompt string) (string, error) {
return p.chatWithSystem(ctx, p.systemPrompt(), userPrompt, 256)
return p.chatWithSystem(ctx, p.systemPrompt(), userPrompt, 512)
}
func (p *LLMPhraser) chatWithSystem(ctx context.Context, system, user string, maxTokens int) (string, error) {
@@ -374,11 +405,15 @@ func (p *LLMPhraser) chatWithSystem(ctx context.Context, system, user string, ma
if len(cr.Choices) == 0 {
return "", fmt.Errorf("llm: no choices in response")
}
return cr.Choices[0].Message.Content, nil
content := cr.Choices[0].Message.Content
if content == "" {
content = cr.Choices[0].Message.ReasoningContent
}
return stripThink(content), nil
}
func (p *LLMPhraser) systemPrompt() string {
base := `You are maven, a self-hosted personal assistant. Generate brief, natural nudge messages in the user's language (Russian or English). Respond ONLY with valid JSON: {"body": "full voice message", "summary": "brief away-channel version (<60 chars)"}. body is what the user hears on voice; summary is for push notifications (ntfy/telegram) — minimal, no exfil detail.`
base := `You are maven, a self-hosted personal assistant. Generate brief, natural nudge messages in the user's language (Russian or English). Respond ONLY with valid JSON: {"response": "full voice message", "mood": "neutral"}. "response" is what the user hears; "mood" reflects maven's tone (neutral/happy/thinking/tired/confused).`
if p.cfg.Persona != "" {
base = p.cfg.Persona + "\n\n" + base
}
@@ -388,7 +423,7 @@ func (p *LLMPhraser) systemPrompt() string {
// querySystemPrompt returns the system prompt for PhraseQuery (notes + general
// knowledge). Prepends the configured persona when set.
func (p *LLMPhraser) querySystemPrompt() string {
base := "You are maven, a self-hosted personal assistant answering from your notes. Answer briefly and naturally in Russian starting with \"вот что я нашла: \". Respond with just the answer text, no JSON wrapper."
base := "You are maven, a self-hosted personal assistant answering from your notes. Answer briefly and naturally in Russian starting with \"вот что я нашла: \". Respond ONLY with valid JSON: {\"response\": \"...\", \"mood\": \"neutral\"}."
if p.cfg.Persona != "" {
base = p.cfg.Persona + "\n\n" + base
}
@@ -408,11 +443,33 @@ func buildNudgePrompt(c loop.Candidate) string {
`Generate a nudge message. Context:
%s
Respond as JSON: {"body": "...", "summary": "..."}`,
Respond as JSON: {"response": "...", "mood": "..."}`,
strings.Join(ctxParts, "\n"),
)
}
type responseMood struct {
Response string `json:"response"`
Mood string `json:"mood"`
}
// parseResponseMood extracts {"response","mood"} from LLM output, tolerant
// of thinking tokens and extra text before/after the JSON block. Returns
// ("", "") when no valid JSON is found.
func parseResponseMood(raw string) (response, mood string) {
cleaned := strings.TrimSpace(raw)
start := strings.Index(cleaned, "{")
end := strings.LastIndex(cleaned, "}")
if start < 0 || end < 0 || end <= start {
return "", ""
}
var parsed responseMood
if err := json.Unmarshal([]byte(cleaned[start:end+1]), &parsed); err != nil {
return "", ""
}
return parsed.Response, parsed.Mood
}
func parsePhrase(raw string) (body, summary string) {
cleaned := strings.TrimSpace(raw)
start := strings.Index(cleaned, "{")
@@ -437,3 +494,12 @@ func extractPort(listen string) string {
}
return port
}
// stripThink removes the <think> block that Thinking-variant models emit
// before the actual response. No-op when no think block is present.
func stripThink(s string) string {
if i := strings.LastIndex(s, "</think>"); i >= 0 {
s = strings.TrimSpace(s[i+8:])
}
return s
}
+1 -1
View File
@@ -3,5 +3,5 @@ package router
// KnowledgePrompt returns the system prompt for general knowledge questions
// that the phraser uses when no notes match the query.
func KnowledgePrompt() string {
return `Ты — Мавена, персональный ассистент. Ответь кратко из своих знаний. Если не знаешь — скажи "не знаю". Не выдумывай.`
return `Ты — Мавена, персональный ассистент. Ответь кратко из своих знаний. Если не знаешь — скажи "не знаю". Не выдумывай. Respond ONLY with valid JSON: {"response": "...", "mood": "neutral"}.`
}