Compare commits

...
Author SHA1 Message Date
m 24320f22a6 Improve price research queries
CI / test (push) Successful in 1m8s
CI / test (pull_request) Successful in 1m13s
2026-08-25 11:01:22 +03:00
m 98cf218cc3 Merge pull request 'Shorten research source labels' (#336) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m16s
2026-08-25 07:58:42 +00:00
m 7abe73e7bd Shorten research source labels
CI / test (push) Successful in 1m5s
CI / test (pull_request) Successful in 1m8s
2026-08-25 10:55:07 +03:00
m a05ddacff3 Merge pull request 'Clarify research results without price evidence' (#335) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m17s
2026-08-25 07:52:31 +00:00
m 20b18de60a Clarify missing price evidence
CI / test (push) Successful in 1m3s
CI / test (pull_request) Successful in 1m8s
2026-08-25 10:49:34 +03:00
m d5c98dd62f Merge pull request 'Preserve durable assistant identity and deterministic replies' (#334) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m15s
2026-08-25 07:42:01 +00:00
m 61d08fa05a Preserve durable conversation identity
CI / test (push) Successful in 1m9s
CI / test (pull_request) Successful in 1m7s
2026-08-25 10:39:05 +03:00
m 1ea2e713d8 Format interaction contract 2026-08-25 10:39:04 +03:00
m 38dce57666 Improve location time and product research 2026-08-25 10:39:04 +03:00
m 8f255b8bde Merge pull request 'Handle memory identity and travel follow-ups' (#333) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m34s
2026-08-25 07:24:45 +00:00
m 6b97d6668b Handle memory identity and travel follow-ups
CI / test (push) Successful in 1m18s
CI / test (pull_request) Successful in 1m35s
2026-08-25 10:20:54 +03:00
m 3fa1d70379 Route completed travel continuations to research 2026-08-25 10:20:53 +03:00
m 2dd05a7aa6 Merge pull request 'Continue travel tasks from departure location' (#332) from codex/chat-semantic-inventory into main
CI / test (push) Failing after 42s
2026-08-25 07:10:22 +00:00
m 02227edc23 Continue travel tasks from departure location
CI / test (push) Successful in 1m20s
CI / test (pull_request) Successful in 1m9s
2026-08-25 10:07:28 +03:00
m a2297a84ad Merge pull request 'Reject reviewed research answers without evidence' (#331) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m16s
2026-08-25 04:22:34 +00:00
m 05cbd8adc7 Reject reviewed research answers without evidence
CI / test (push) Successful in 1m5s
CI / test (pull_request) Successful in 1m12s
2026-08-25 07:19:43 +03:00
m 984731b111 Merge pull request 'Ask departure city for general travel requests' (#330) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m20s
2026-08-25 04:13:55 +00:00
m 0da03c18d1 Ask departure city for general travel requests
CI / test (push) Successful in 1m4s
CI / test (pull_request) Successful in 1m5s
2026-08-25 07:11:09 +03:00
m 302b8fc8cd Merge pull request 'Prefer current travel context in follow-up answers' (#329) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m12s
2026-08-25 04:05:00 +00:00
m 59239635cd Prefer current travel context in follow-up answers
CI / test (push) Successful in 1m9s
CI / test (pull_request) Successful in 1m2s
2026-08-25 07:02:14 +03:00
m 238105a7da Merge pull request 'Polish web research answers and travel context' (#328) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m13s
2026-08-25 03:56:31 +00:00
m d7ca5f7e68 Polish web research answers and travel context
CI / test (push) Successful in 1m11s
CI / test (pull_request) Successful in 1m5s
2026-08-25 06:53:46 +03:00
m 827135a02d Merge pull request 'Keep identity reply consistent across response fields' (#327) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m15s
2026-08-25 03:44:38 +00:00
m a3ddf53207 Keep identity reply consistent across response fields
CI / test (push) Successful in 1m7s
CI / test (pull_request) Successful in 1m8s
2026-08-25 06:41:57 +03:00
m 35ac9015ad Merge pull request 'Remove temporary continuation diagnostics' (#326) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m16s
2026-08-25 03:34:41 +00:00
m 1c196ef675 Remove continuation diagnostics
CI / test (push) Successful in 1m10s
CI / test (pull_request) Successful in 1m4s
2026-08-25 06:31:30 +03:00
m 2ce3b5a9b3 Merge pull request 'Fix semantic routing for location follow-ups' (#325) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m13s
2026-08-25 03:26:06 +00:00
m 7421fd058d Fix semantic routing for location follow-ups
CI / test (push) Successful in 1m4s
CI / test (pull_request) Successful in 1m6s
2026-08-25 06:23:38 +03:00
m 368e9df551 Merge pull request 'Trace conversational continuation selection' (#324) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m8s
2026-08-25 03:17:08 +00:00
m e9629046cb Merge remote-tracking branch 'origin/main' into codex/chat-semantic-inventory
CI / test (push) Successful in 1m3s
CI / test (pull_request) Successful in 1m6s
2026-08-25 06:15:13 +03:00
m b5ccc419f6 Trace conversational continuation selection
CI / test (push) Successful in 1m2s
CI / test (pull_request) Successful in 1m4s
2026-08-25 06:13:19 +03:00
m 615723da2a Merge pull request 'Select latest relevant local search goal' (#323) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m11s
2026-08-25 03:10:44 +00:00
m d1bcd5beff Merge remote-tracking branch 'origin/main' into codex/chat-semantic-inventory
CI / test (push) Successful in 1m4s
CI / test (pull_request) Successful in 1m15s
2026-08-25 06:09:02 +03:00
m 519dc583a0 Select latest relevant local search goal
CI / test (push) Successful in 1m4s
CI / test (pull_request) Successful in 1m6s
2026-08-25 06:07:08 +03:00
m 0bf883cf56 Merge pull request 'Continue location follow-ups from recent context' (#322) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m9s
2026-08-25 03:04:26 +00:00
m c8502c735c Merge remote-tracking branch 'origin/main' into codex/chat-semantic-inventory
CI / test (push) Successful in 1m5s
CI / test (pull_request) Successful in 1m15s
2026-08-25 06:02:39 +03:00
m 48af97fbdd Continue location follow-ups from recent context
CI / test (push) Successful in 1m16s
CI / test (pull_request) Successful in 1m6s
2026-08-25 06:00:45 +03:00
m 13bcf87ea5 Merge pull request 'Continue local search from conversation context' (#321) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m12s
2026-08-25 02:57:39 +00:00
m e271fbb1e1 Merge remote-tracking branch 'origin/main' into codex/chat-semantic-inventory
CI / test (push) Successful in 1m2s
CI / test (pull_request) Successful in 1m3s
2026-08-25 05:55:23 +03:00
m 5678686c57 Continue local search from conversation context
CI / test (push) Successful in 1m8s
CI / test (pull_request) Successful in 1m7s
2026-08-25 05:53:37 +03:00
m 9fc3fd1aa5 Merge pull request 'Ask for location before proximity search' (#320) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m9s
2026-08-25 02:49:13 +00:00
m e3a9c18cb3 Merge remote-tracking branch 'origin/main' into codex/chat-semantic-inventory
CI / test (push) Successful in 1m5s
CI / test (pull_request) Successful in 1m13s
2026-08-25 05:47:27 +03:00
m 9534b041db Ask for location before proximity search
CI / test (push) Successful in 1m3s
CI / test (pull_request) Successful in 1m2s
2026-08-25 05:45:40 +03:00
m 9426fa40a9 Merge pull request 'Route independent chat actions separately' (#319) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m12s
2026-08-25 02:43:11 +00:00
m 51e2b23082 Merge remote-tracking branch 'origin/main' into codex/chat-semantic-inventory
CI / test (push) Successful in 1m4s
CI / test (pull_request) Successful in 1m10s
2026-08-25 05:41:29 +03:00
m aece914fb8 Route independent chat actions separately
CI / test (push) Successful in 1m6s
CI / test (pull_request) Successful in 1m1s
2026-08-25 05:39:31 +03:00
m 762e312730 Merge pull request 'Keep research replies concise' (#318) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m10s
2026-08-25 02:36:16 +00:00
m e9eb529d6e Merge remote-tracking branch 'origin/main' into codex/chat-semantic-inventory
CI / test (push) Successful in 1m6s
CI / test (pull_request) Successful in 1m10s
2026-08-25 05:34:33 +03:00
m e39a2b7dda Keep research replies concise
CI / test (push) Successful in 1m0s
CI / test (pull_request) Successful in 59s
2026-08-25 05:32:42 +03:00
m cdc6baa4c0 Merge pull request 'Align semantic reply with research result' (#317) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m10s
2026-08-25 02:29:42 +00:00
m 255ab8dbf3 Merge remote-tracking branch 'origin/main' into codex/chat-semantic-inventory
CI / test (push) Successful in 1m6s
CI / test (pull_request) Successful in 1m8s
2026-08-25 05:27:59 +03:00
m a76dc42bd8 Align semantic reply with research result
CI / test (push) Successful in 1m4s
CI / test (pull_request) Successful in 1m4s
2026-08-25 05:26:06 +03:00
m f0cbd71129 Merge pull request 'Preserve travel follow-up clarification' (#316) from codex/chat-semantic-inventory into main
CI / test (push) Successful in 1m12s
2026-08-25 02:23:02 +00:00
m aa10c3e093 Merge remote-tracking branch 'origin/main' into codex/chat-semantic-inventory
CI / test (push) Successful in 1m1s
CI / test (pull_request) Successful in 1m13s
2026-08-25 05:21:21 +03:00
m 0d836121d0 Preserve travel follow-up clarification
CI / test (push) Successful in 1m3s
CI / test (pull_request) Successful in 1m0s
2026-08-25 05:19:27 +03:00
11 changed files with 647 additions and 30 deletions
+94 -5
View File
@@ -3,6 +3,7 @@ package research
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"html"
@@ -19,9 +20,9 @@ import (
var ErrSearchRejected = errors.New("web search request rejected")
var (
searchLinkPattern = regexp.MustCompile(`(?is)<a[^>]+class=["'][^"']*result__a[^"']*["'][^>]*>(.*?)</a>`)
searchLinkPattern = regexp.MustCompile(`(?is)(<a[^>]+class=["'][^"']*result__a[^"']*["'][^>]*>)(.*?)</a>`)
searchSnippetPattern = regexp.MustCompile(`(?is)<a[^>]+class=["'][^"']*result__snippet[^"']*["'][^>]*>(.*?)</a>`)
bingLinkPattern = regexp.MustCompile(`(?is)<li[^>]+class=["'][^"']*b_algo[^"']*["'][^>]*>.*?<h2[^>]*><a[^>]*>(.*?)</a>`)
bingLinkPattern = regexp.MustCompile(`(?is)<li[^>]+class=["'][^"']*b_algo[^"']*["'][^>]*>.*?<h2[^>]*>(<a[^>]*>)(.*?)</a>`)
bingSnippetPattern = regexp.MustCompile(`(?is)<li[^>]+class=["'][^"']*b_algo[^"']*["'][^>]*>.*?<p[^>]*>(.*?)</p>`)
tagPattern = regexp.MustCompile(`(?s)<[^>]*>`)
termPattern = regexp.MustCompile(`(?i)[\p{L}\p{N}]{2,}`)
@@ -80,7 +81,8 @@ func (c SearchConnector) collectEndpoint(ctx context.Context, configured SearchE
if !strings.Contains(configured.Template, "%s") {
return nil, ErrSearchRejected
}
endpoint, err := url.Parse(strings.Replace(configured.Template, "%s", url.QueryEscape(strings.TrimSpace(request.Query)), 1))
searchQuery := enrichedSearchQuery(request.Query)
endpoint, err := url.Parse(strings.Replace(configured.Template, "%s", url.QueryEscape(searchQuery), 1))
if err != nil || endpoint.Scheme != "https" || endpoint.Host == "" || !allowedHost(configured.AllowedHosts, strings.ToLower(endpoint.Hostname())) {
return nil, ErrSearchRejected
}
@@ -128,7 +130,8 @@ func (c SearchConnector) collectEndpoint(ctx context.Context, configured SearchE
snapshotID := epistemics.SourceSnapshotID("snapshot:search:" + base)
results := make([]epistemics.ResearchCandidate, 0, len(links))
for index, link := range links {
title := cleanHTML(string(link[1]))
linkURL := resolveSearchResultLocator(extractHref(string(link[1])), endpoint)
title := cleanHTML(string(link[2]))
snippet := ""
if index < len(snippets) {
snippet = cleanHTML(string(snippets[index][1]))
@@ -142,7 +145,7 @@ func (c SearchConnector) collectEndpoint(ctx context.Context, configured SearchE
results = append(results, epistemics.ResearchCandidate{
PropositionKey: request.PropositionKey + ":result:" + ordinal,
Statement: statement,
Source: epistemics.Source{ID: sourceID, Kind: "web-search", Locator: endpoint.String(), Title: title, Publisher: endpoint.Hostname()},
Source: epistemics.Source{ID: sourceID, Kind: "web-search", Locator: linkURL, Title: title, Publisher: sourcePublisher(linkURL, endpoint.Hostname())},
Snapshot: epistemics.SourceSnapshot{ID: snapshotID, SourceID: sourceID, ContentDigest: digestText, CapturedAtUnixMillis: nowUnixMillis, Freshness: epistemics.FreshnessCurrent},
Excerpt: epistemics.SourceExcerpt{ID: excerptID, SnapshotID: snapshotID, Text: statement, Start: 0, End: int64(len(statement))},
Evidence: epistemics.EvidenceObserved, Coverage: epistemics.CoverageComplete, Conflict: epistemics.ConflictNone,
@@ -157,6 +160,11 @@ func (c SearchConnector) collectEndpoint(ctx context.Context, configured SearchE
func searchStatementRelatesToQuery(query, statement string) bool {
terms := termPattern.FindAllString(strings.ToLower(query), -1)
content := strings.ToLower(statement)
productCue := containsSearchTerm(terms, "видеокарт", "gpu", "процессор", "телефон", "ноутбук", "монитор")
if productCue && hasNumericSearchTerm(terms) {
contentTerms := termPattern.FindAllString(content, -1)
return hasNumericSearchTerm(contentTerms) && containsSearchTerm(contentTerms, "видеокарт", "gpu", "процессор", "телефон", "ноутбук", "монитор")
}
usable := 0
for _, term := range terms {
if _, stop := searchStopTerms[term]; stop || len([]rune(term)) < 4 {
@@ -175,6 +183,37 @@ func searchStatementRelatesToQuery(query, statement string) bool {
return usable == 0
}
func containsSearchTerm(values []string, wanted ...string) bool {
for _, value := range values {
for _, candidate := range wanted {
if strings.Contains(value, candidate) {
return true
}
}
}
return false
}
func hasNumericSearchTerm(values []string) bool {
for _, value := range values {
for _, runeValue := range value {
if runeValue >= '0' && runeValue <= '9' {
return true
}
}
}
return false
}
func enrichedSearchQuery(query string) string {
trimmed := strings.TrimSpace(query)
lower := strings.ToLower(trimmed)
if (strings.Contains(lower, "цен") || strings.Contains(lower, "стоим")) && !strings.Contains(lower, "куп") {
return trimmed + " цена купить сегодня"
}
return trimmed
}
func allowedHost(hosts map[string]struct{}, host string) bool { _, ok := hosts[host]; return ok }
func (c SearchConnector) limit() int {
if c.MaxResults <= 0 || c.MaxResults > 8 {
@@ -185,3 +224,53 @@ func (c SearchConnector) limit() int {
func cleanHTML(value string) string {
return strings.Join(strings.Fields(html.UnescapeString(tagPattern.ReplaceAllString(value, ""))), " ")
}
func extractHref(tag string) string {
match := regexp.MustCompile(`(?is)\bhref=["']([^"']+)["']`).FindStringSubmatch(tag)
if len(match) == 2 {
return match[1]
}
return ""
}
func resolveSearchResultLocator(raw string, searchEndpoint *url.URL) string {
value := strings.TrimSpace(html.UnescapeString(raw))
if value == "" {
return searchEndpoint.String()
}
parsed, err := url.Parse(value)
if err != nil {
return searchEndpoint.String()
}
if target := parsed.Query().Get("uddg"); target != "" {
value = target
parsed, err = url.Parse(target)
if err != nil {
return searchEndpoint.String()
}
}
if target := parsed.Query().Get("u"); strings.HasPrefix(target, "a1") {
if decoded, decodeErr := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(target, "a1")); decodeErr == nil {
if targetURL, parseErr := url.Parse(string(decoded)); parseErr == nil {
parsed = targetURL
}
}
}
if parsed.Scheme == "" {
parsed.Scheme = "https"
}
if parsed.Host == "" && strings.HasPrefix(value, "//") {
parsed, err = url.Parse("https:" + value)
}
if err != nil || parsed.Scheme != "https" || parsed.Host == "" {
return searchEndpoint.String()
}
return parsed.String()
}
func sourcePublisher(locator, fallback string) string {
if parsed, err := url.Parse(locator); err == nil && parsed.Hostname() != "" {
return parsed.Hostname()
}
return fallback
}
@@ -42,4 +42,16 @@ func TestSearchConnectorFallsBackToAnotherAllowedSource(t *testing.T) {
if len(results) != 1 || !strings.Contains(results[0].Statement, "18") {
t.Fatalf("fallback evidence = %#v", results)
}
if results[0].Source.Locator != "https://example.test" || results[0].Source.Publisher != "example.test" {
t.Fatalf("search result source = %#v", results[0].Source)
}
}
func TestEnrichedSearchQueryAddsPriceSignalsOnlyToPriceRequests(t *testing.T) {
if got := enrichedSearchQuery("проверь цену на видеокарту 4090"); got != "проверь цену на видеокарту 4090 цена купить сегодня" {
t.Fatalf("price query = %q", got)
}
if got := enrichedSearchQuery("какая погода в Казани"); got != "какая погода в Казани" {
t.Fatalf("non-price query = %q", got)
}
}
+1 -1
View File
@@ -33,7 +33,7 @@ func (c cognitiveInterpretationClient) ReviewResponse(ctx context.Context, sessi
if err != nil {
return "", err
}
prompt := "Ты редактор ответа Домового. Проверь, отвечает ли черновик на сообщение пользователя по смыслу. Верни только готовый ответ пользователю, без разбора проверки, служебных слов и упоминания моделей. Не выдумывай факты, не утверждай невыполненные действия, сохрани важные имена, числа, источники и ограничения. Если черновик уже адекватен, верни его без лишних добавлений.\n\nСообщение пользователя:\n" + userMessage + "\n\nЧерновик ответа:\n" + draft
prompt := "Ты редактор ответа Домового. Проверь черновик по смыслу и подготовь естественный ответ человеку. Учитывай весь запрос, включая недостающие параметры для конкретного результата. Если данных не хватает, задай один короткий полезный уточняющий вопрос, например откуда и куда ехать. Не выдавай поисковые сниппеты как выполненное действие и не показывай служебные URL поисковой выдачи. Сохрани проверяемые факты, названия источников, прямые ссылки и ограничения. Не выдумывай факты и не утверждай невыполненные действия. Верни только готовый ответ без разбора проверки, служебных слов и упоминания моделей. Если черновик уже адекватен, верни его без лишних добавлений.\n\nСообщение пользователя:\n" + userMessage + "\n\nЧерновик ответа:\n" + draft
target := *c.baseURL
target.Path = "/v1/advisories"
payload, err := json.Marshal(cognitive.GatewayAdvisoryRequest{
@@ -40,6 +40,16 @@ func TestReviewResponseUsesCognitiveGatewayAndReturnsOnlyDraftAnswer(t *testing.
}
}
func TestReviewPreservesResearchEvidence(t *testing.T) {
draft := "Нашёл вариант. Источник: Aviasales (https://www.aviasales.ru/search)"
if reviewPreservesResearchEvidence("Нашёл вариант на Авиасейлс.", draft) {
t.Fatal("review without the direct source must be rejected")
}
if !reviewPreservesResearchEvidence("Нашёл вариант. Источник: Aviasales (https://www.aviasales.ru/search)", draft) {
t.Fatal("review with the direct source must be accepted")
}
}
func TestSimpleQuestionUsesStrictInterpretationForSemanticRouting(t *testing.T) {
result := interactiondomain.SemanticResult{
Interpretation: interaction.UtteranceInterpretation{
+173 -22
View File
@@ -30,6 +30,7 @@ import (
"log"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
@@ -509,6 +510,8 @@ func main() {
return
}
var effectiveTaskMessage = interactiondomain.StripAssistantVocative(utterance.Content)
continuationMessage := ""
travelContinuation := false
var previousTask *interaction.HumanUtterance
var conversationHistory []interaction.HumanUtterance
if request.ConversationID != "" {
@@ -528,6 +531,14 @@ func main() {
log.Printf("interaction principal history loaded: %d utterances", len(recentUserHistory))
}
conversationHistory = append(conversationHistory, recentUserHistory...)
if continuation := interactiondomain.ContinueLocalSearch(effectiveTaskMessage, conversationHistory); continuation != "" {
continuationMessage = continuation
effectiveTaskMessage = continuation
} else if continuation := interactiondomain.ContinueTravelOrigin(effectiveTaskMessage, conversationHistory); continuation != "" {
continuationMessage = continuation
travelContinuation = true
effectiveTaskMessage = continuation
}
if request.ConversationID != "" && interactiondomain.IsRetryRequest(utterance.Content) {
if len(conversationHistory) > 0 {
for index := len(conversationHistory) - 1; index >= 0; index-- {
@@ -546,6 +557,27 @@ func main() {
http.Error(w, "interpret chat message", http.StatusServiceUnavailable)
return
}
if continuationMessage != "" {
continuedUtterance := utterance
continuedUtterance.Content = continuationMessage
continuedSemantic, continuedErr := interactiondomain.InterpretUtterance(continuedUtterance, projects, previousFocus, now)
if continuedErr == nil {
continuedSemantic.Interpretation.Source = "CONVERSATION_CONTINUATION"
continuedSemantic.Interpretation.SelectionReason = "location follow-up completed the previous local-search task"
semantic = continuedSemantic
}
}
if travelContinuation && interactiondomain.TravelSearchClarification(effectiveTaskMessage, conversationHistory) == "" {
semantic.CapabilityHints = append(semantic.CapabilityHints, string(capability.CapabilityKindWebResearch))
semantic.NeedsCognition = false
semantic.Interpretation.NeedsCognition = false
}
locationReply := interactiondomain.LocationContextReply(utterance.Content)
if locationReply != "" {
semantic.Reply = locationReply
semantic.NeedsCognition = false
semantic.Interpretation.NeedsCognition = false
}
if previousTask != nil {
previousSemantic, previousErr := interactiondomain.InterpretUtterance(*previousTask, projects, previousFocus, now)
if previousErr == nil {
@@ -554,12 +586,7 @@ func main() {
}
assistantName := interactiondomain.PreferredAssistantName(utterance.Content)
if assistantName == "" {
for index := len(conversationHistory) - 1; index >= 0; index-- {
if name := interactiondomain.PreferredAssistantName(conversationHistory[index].Content); name != "" {
assistantName = name
break
}
}
assistantName = latestAssistantName(conversationHistory)
}
identityReply := ""
log.Printf("interaction identity context: name=%q history=%d", assistantName, len(conversationHistory))
@@ -682,6 +709,12 @@ func main() {
helpPath = work.HelpPath{}
}
switch semantic.InformationRequestKind {
case interaction.InformationRequestMemoryInventory:
planningReply = humanMemoryInventory(conversationHistory, assistantName)
needsCognition = false
case interaction.InformationRequestTimeDifference:
planningReply = humanTimeDifferenceReply(effectiveTaskMessage)
needsCognition = false
case interaction.InformationRequestCapabilityInventory:
kinds, err := capabilityRepository.AvailableCapabilityKinds(r.Context(), session.PrincipalID)
if err == nil && len(kinds) > 0 {
@@ -702,13 +735,32 @@ func main() {
researchBacked := false
if hasChatRoute(routePlan, chatRouteResearch) && semantic.Interpretation.Clarification != interaction.ClarificationRequired {
if planID, idErr := ids.New(); idErr == nil {
researchCtx, cancelResearch := context.WithTimeout(r.Context(), 8*time.Second)
result, researchErr := researchClient.SearchWeb(researchCtx, epistemics.WebSearchRequest{
Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID("plan:" + planID), Question: effectiveTaskMessage, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"},
PropositionKey: "question:" + string(utterance.ID), Query: effectiveTaskMessage,
})
cancelResearch()
planningReply, researchBacked = renderResearchReply(result, researchErr)
parts := interactiondomain.IndependentRequestParts(effectiveTaskMessage)
replies := make([]string, 0, len(parts))
for index, part := range parts {
if clarification := interactiondomain.LocalSearchClarification(part); clarification != "" {
replies = append(replies, "По запросу «"+part+"»: "+clarification)
continue
}
researchCtx, cancelResearch := context.WithTimeout(r.Context(), 8*time.Second)
result, researchErr := researchClient.SearchWeb(researchCtx, epistemics.WebSearchRequest{
Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID(fmt.Sprintf("plan:%s:%d", planID, index)), Question: part, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"},
PropositionKey: fmt.Sprintf("question:%s:%d", utterance.ID, index), Query: part,
})
cancelResearch()
reply, backed := renderResearchReply(part, result, researchErr)
if backed {
researchBacked = true
}
if len(parts) > 1 {
reply = "По запросу «" + part + "»: " + reply
}
replies = append(replies, reply)
}
planningReply = strings.Join(replies, "\n\n")
if researchBacked {
semantic.Reply = planningReply
}
// A failed source must not turn the complete conversation into a
// runtime failure or invite an unsupported local guess for a fact.
needsCognition = false
@@ -816,10 +868,10 @@ func main() {
ConfidenceMillis: semantic.Interpretation.ConfidenceMillis,
})
cancelReview()
stableSemanticReply := identityReply != "" || deterministicSpeechAct == interaction.SpeechActConversational || deterministicSpeechAct == interaction.SpeechActConfirmation || deterministicSpeechAct == interaction.SpeechActRejection
stableSemanticReply := identityReply != "" || semantic.InformationRequestKind != "" || locationReply != "" || deterministicSpeechAct == interaction.SpeechActConversational || deterministicSpeechAct == interaction.SpeechActConfirmation || deterministicSpeechAct == interaction.SpeechActRejection
if reviewErr != nil {
log.Printf("cognitive response review unavailable: %v", reviewErr)
} else if !stableSemanticReply {
} else if !stableSemanticReply && (!researchBacked || reviewPreservesResearchEvidence(reviewedReply, planningReply)) {
planningReply = reviewedReply
} else if reviewedReply != planningReply {
log.Printf("cognitive response review proposed stable semantic rewrite; preserving semantic reply")
@@ -827,13 +879,19 @@ func main() {
}
if identityReply == "" {
stableAct := interactiondomain.ClassifySpeechAct(utterance.Content, utterance.CorrectsUtteranceID)
if stableReply, stable := interactiondomain.StableConversationalReply(utterance.Content, stableAct); stable {
travelClarification := interactiondomain.TravelSearchClarification(effectiveTaskMessage, conversationHistory)
if stableReply, stable := interactiondomain.StableConversationalReply(utterance.Content, stableAct); stable && travelClarification == "" {
planningReply = stableReply
needsCognition = false
}
}
if identityReply != "" {
semantic.Reply = identityReply
needsCognition = false
planningReply = identityReply
}
if strings.TrimSpace(planningReply) != "" {
semantic.Reply = planningReply
}
log.Printf("chat response final message=%q act=%s deterministic=%s handled=%t fallback=%q planning=%q", utterance.Content, semantic.Interpretation.SpeechAct, deterministicSpeechAct, responseResult.Handled, semantic.Reply, planningReply)
response := interaction.ChatMessageResponse{
@@ -1568,20 +1626,24 @@ func hasCapabilityHint(hints []string, wanted string) bool {
return false
}
func renderResearchReply(result epistemics.ResearchResult, researchErr error) (string, bool) {
func renderResearchReply(query string, result epistemics.ResearchResult, researchErr error) (string, bool) {
if researchErr != nil {
return "Сейчас не удалось получить данные из подключённого источника. Попробую снова через доступный маршрут.", false
}
lines := make([]string, 0, 2)
for _, finding := range result.Findings {
for index, finding := range result.Findings {
if finding.State != epistemics.FindingSupported || strings.TrimSpace(finding.Excerpt.Text) == "" || strings.TrimSpace(finding.Source.Locator) == "" {
continue
}
excerpt := strings.TrimSpace(finding.Excerpt.Text)
if len([]rune(excerpt)) > 180 {
excerpt = string([]rune(excerpt)[:180]) + "…"
limit := 180
if index > 0 {
limit = 100
}
lines = append(lines, excerpt+"\nИсточник: "+finding.Source.Locator)
if len([]rune(excerpt)) > limit {
excerpt = string([]rune(excerpt)[:limit]) + "…"
}
lines = append(lines, excerpt+"\nИсточник: "+researchSourceLabel(finding))
if len(lines) == 2 {
break
}
@@ -1589,7 +1651,96 @@ func renderResearchReply(result epistemics.ResearchResult, researchErr error) (s
if len(lines) == 0 {
return "Проверяемых данных пока не найдено. Могу повторить поиск или уточнить, что именно проверить.", false
}
return strings.Join(lines, "\n"), true
reply := strings.Join(lines, "\n")
lowerQuery := strings.ToLower(query)
if (strings.Contains(lowerQuery, "цен") || strings.Contains(lowerQuery, "стоим")) && !containsPriceEvidence(reply) {
reply = "Актуальная цена в найденных фрагментах не указана, поэтому не буду придумывать сумму. Вот страницы, где её можно проверить:\n" + reply
}
return reply, true
}
func containsPriceEvidence(value string) bool {
pricePattern := regexp.MustCompile(`(?i)(\d[\d\s.,]{2,})(?:\s*(?:₽|руб\.?|р\.?|usd|\$|€))`)
return pricePattern.MatchString(value)
}
func reviewPreservesResearchEvidence(reviewed, draft string) bool {
if strings.Contains(draft, "http://") || strings.Contains(draft, "https://") {
return strings.Contains(reviewed, "http://") || strings.Contains(reviewed, "https://")
}
if strings.Contains(draft, "Источник:") {
return strings.Contains(reviewed, "Источник:")
}
return true
}
func humanMemoryInventory(history []interaction.HumanUtterance, assistantName string) string {
rows := make([]string, 0, 4)
if assistantName != "" {
rows = append(rows, "| Имя помощника | "+assistantName+" |")
}
latestPreferenceAt := int64(-1)
latestPreference := ""
for _, utterance := range history {
message := strings.TrimSpace(utterance.Content)
lower := strings.ToLower(message)
if (strings.Contains(lower, "нравится") || strings.Contains(lower, "люблю")) && utterance.ReceivedAtUnixMillis >= latestPreferenceAt {
latestPreferenceAt = utterance.ReceivedAtUnixMillis
latestPreference = message
}
}
if latestPreference != "" {
rows = append(rows, "| Предпочтение пользователя | "+latestPreference+" |")
}
if len(rows) == 0 {
return "| Ячейка памяти | Значение |\n|---|---|\n| — | Сохранённых пользовательских предпочтений пока не найдено. |"
}
return "| Ячейка памяти | Значение |\n|---|---|\n" + strings.Join(rows, "\n")
}
func latestAssistantName(history []interaction.HumanUtterance) string {
latestAt := int64(-1)
latestName := ""
for _, utterance := range history {
if name := interactiondomain.PreferredAssistantName(utterance.Content); name != "" && utterance.ReceivedAtUnixMillis >= latestAt {
latestAt = utterance.ReceivedAtUnixMillis
latestName = name
}
}
return latestName
}
func humanTimeDifferenceReply(message string) string {
lower := strings.ToLower(message)
if strings.Contains(lower, "моск") && strings.Contains(lower, "шанх") {
return "Шанхай опережает Москву на 5 часов. Если в Москве 12:00, в Шанхае 17:00."
}
return "Уточните два города — я сравню их часовые пояса."
}
func researchSourceLabel(finding epistemics.ResearchFinding) string {
title := strings.TrimSpace(finding.Source.Title)
locator := strings.TrimSpace(finding.Source.Locator)
publisher := strings.TrimSpace(finding.Source.Publisher)
if strings.Contains(locator, "duckduckgo.com/html") || strings.Contains(locator, "bing.com/search") {
locator = ""
}
if title != "" && publisher != "" {
if locator != "" {
return publisher + " (" + locator + ")"
}
return publisher
}
if title != "" {
return title
}
if publisher != "" {
return publisher
}
if locator != "" {
return locator
}
return "подключённый источник"
}
func humanCognitiveModelInventory(candidates []capability.ResolvedCognitiveBinding, inventoryErr error) string {
+30
View File
@@ -27,6 +27,36 @@ func TestBearerTokenRequiresBearerScheme(t *testing.T) {
}
}
func TestLatestAssistantNameUsesNewestDurablePreference(t *testing.T) {
history := []interaction.HumanUtterance{
{Content: "я назову тебя Дед", ReceivedAtUnixMillis: 20},
{Content: "теперь тебя зовут Фея", ReceivedAtUnixMillis: 30},
}
if got := latestAssistantName(history); got != "Фея" {
t.Fatalf("latest assistant name = %q", got)
}
}
func TestHumanMemoryInventoryUsesNewestPreference(t *testing.T) {
history := []interaction.HumanUtterance{
{Content: "мне нравится синий цвет", ReceivedAtUnixMillis: 20},
{Content: "мне нравится красный цвет", ReceivedAtUnixMillis: 30},
}
got := humanMemoryInventory(history, "Фея")
if !strings.Contains(got, "красный") || strings.Contains(got, "синий") {
t.Fatalf("memory inventory did not select newest preference: %q", got)
}
}
func TestContainsPriceEvidenceDistinguishesLinksFromPrices(t *testing.T) {
if containsPriceEvidence("RTX 4090 — market.yandex.ru") {
t.Fatal("a product link is not price evidence")
}
if !containsPriceEvidence("Цена: 189 990 ₽") {
t.Fatal("expected a currency amount to count as price evidence")
}
}
func TestCognitiveChannelQuestionUsesHumanSafeHealthReply(t *testing.T) {
reply := humanCognitiveChannelReply(interaction.InformationRequestCognitiveChannelStatus, interaction.SpeechActQuestion, capability.Health{State: capability.HealthAvailable, CapabilityID: "provider-secret-model"}, nil)
if !strings.Contains(reply, "доступен") || strings.Contains(reply, "provider-secret-model") {
+2
View File
@@ -70,6 +70,8 @@ const (
InformationRequestCognitiveModelInventory InformationRequestKind = "COGNITIVE_MODEL_INVENTORY"
InformationRequestCognitiveChannelStatus InformationRequestKind = "COGNITIVE_CHANNEL_STATUS"
InformationRequestCognitiveRecovery InformationRequestKind = "COGNITIVE_RECOVERY"
InformationRequestMemoryInventory InformationRequestKind = "MEMORY_INVENTORY"
InformationRequestTimeDifference InformationRequestKind = "TIME_DIFFERENCE"
)
type Conversation struct {
+28 -2
View File
@@ -133,7 +133,7 @@ func PreferredAssistantName(message string) string {
continue
}
for _, candidate := range tokens[index+1:] {
if candidate == "тебя" || candidate == "тебе" || candidate == "себя" || candidate == "меня" {
if candidate == "тебя" || candidate == "тебе" || candidate == "себя" || candidate == "меня" || candidate == "в" || candidate == "теперь" || candidate == "же" {
continue
}
if candidate == "буду" || candidate == "будет" || candidate == "запомни" || candidate == "помни" || candidate == "ты" || candidate == "это" {
@@ -144,12 +144,19 @@ func PreferredAssistantName(message string) string {
}
runes := []rune(candidate)
runes[0] = []rune(strings.ToUpper(string(runes[0])))[0]
return string(runes)
return normalizeAssistantName(string(runes))
}
}
return ""
}
func normalizeAssistantName(value string) string {
if strings.HasSuffix(value, "ю") {
return strings.TrimSuffix(value, "ю") + "я"
}
return value
}
// IsIdentityInquiry identifies a request about the assistant itself by its
// interrogative meaning. Punctuation is optional and wording may vary.
func IsIdentityInquiry(message string) bool {
@@ -592,6 +599,12 @@ func informationRequestKind(message string, candidate interaction.SemanticCandid
if len(tokens) == 0 {
return ""
}
if containsStemInTokens(tokens, "памят", "помнишь", "ячейк") && (containsMeaningfulInterrogative(tokens) || containsStemInTokens(tokens, "вывед", "покаж", "напиш", "сообщ")) {
return interaction.InformationRequestMemoryInventory
}
if containsStemInTokens(tokens, "разниц") && containsStemInTokens(tokens, "времен", "час") {
return interaction.InformationRequestTimeDifference
}
inquiry := candidate.PrimarySpeechAct == interaction.SpeechActQuestion || candidate.PrimarySpeechAct == interaction.SpeechActRequestToInvestigate || candidate.SecondarySpeechAct == interaction.SpeechActQuestion || candidate.SecondarySpeechAct == interaction.SpeechActRequestToInvestigate
cognitiveSubject := containsStemInTokens(tokens, "модел", "ии", "ai", "локальн", "когнитив", "канал")
inventoryCue := containsStemInTokens(tokens, "список", "доступ", "подключ", "вариант") || (containsMeaningfulInterrogative(tokens) && containsStemInTokens(tokens, "настро"))
@@ -613,6 +626,19 @@ func informationRequestKind(message string, candidate interaction.SemanticCandid
return ""
}
func LocationContextReply(message string) string {
tokens := semanticTokens(message)
if len(tokens) < 4 || tokens[0] != "я" || !containsStemInTokens(tokens, "сейчас", "нахож", "жив") {
return ""
}
for index, token := range tokens {
if (token == "в" || token == "на") && index+1 < len(tokens) {
return "Запомнил: сейчас вы в " + capitalizeWord(tokens[index+1]) + "."
}
}
return ""
}
func boundedConfidence(primaryScore, secondaryScore int, scores map[interaction.SpeechAct]int) int64 {
total := 0
for _, score := range scores {
+26
View File
@@ -198,11 +198,37 @@ func TestNamingPreferenceIsSemanticAndProducesNaturalAcceptance(t *testing.T) {
if name := PreferredAssistantName("я назову тебя дед, запомни"); name != "Дед" {
t.Fatalf("expected conversational name form to be extracted, got %q", name)
}
if name := PreferredAssistantName("давай переименуем тебя в фею. теперь тебя зовут фея"); name != "Фея" {
t.Fatalf("rename phrase returned %q", name)
}
if !IsIdentityInquiry("ты кто?") || !IsIdentityInquiry("как тебя зовут") {
t.Fatal("identity variants should be recognized")
}
}
func TestMemoryInventoryRequestIsSemantic(t *testing.T) {
for _, message := range []string{"выведи свою память", "напиши что ты помнишь в виде таблицы"} {
candidate := BuildDeterministicCandidate(message, "", time.Unix(10, 0).UnixMilli())
if got := informationRequestKind(message, candidate); got != interaction.InformationRequestMemoryInventory {
t.Fatalf("%q: expected memory inventory, got %q", message, got)
}
}
}
func TestLocationContextReply(t *testing.T) {
if got := LocationContextReply("я сейчас в Москве"); got != "Запомнил: сейчас вы в Москве." {
t.Fatalf("unexpected location reply %q", got)
}
}
func TestTimeDifferenceRequestIsSemantic(t *testing.T) {
message := "какая разница во времени между Москвой и Шанхаем?"
candidate := BuildDeterministicCandidate(message, "", time.Unix(10, 0).UnixMilli())
if got := informationRequestKind(message, candidate); got != interaction.InformationRequestTimeDifference {
t.Fatalf("expected time difference, got %q", got)
}
}
func TestDeterministicCandidateKeepsFirstPersonCompletedWorkAsAssertion(t *testing.T) {
candidate := BuildDeterministicCandidate("Я всё уже настроил.", "", time.Unix(10, 0).UnixMilli())
if candidate.PrimarySpeechAct != interaction.SpeechActAssertion {
@@ -69,10 +69,52 @@ func TestStripAssistantVocative(t *testing.T) {
}
}
func TestIndependentRequestParts(t *testing.T) {
parts := IndependentRequestParts("Дед, узнай погоду в Сочи и найди ресторан")
if len(parts) != 2 || parts[0] != "узнай погоду в Сочи" || parts[1] != "найди ресторан" {
t.Fatalf("unexpected request parts: %#v", parts)
}
}
func TestLocalSearchClarification(t *testing.T) {
if got := LocalSearchClarification("найди ближайший ресторан"); got == "" {
t.Fatal("proximity search without place must ask for location")
}
if got := LocalSearchClarification("найди ближайший ресторан в Сочи"); got != "" {
t.Fatalf("explicit place must proceed, got %q", got)
}
}
func TestContinueLocalSearch(t *testing.T) {
history := []interaction.HumanUtterance{{Content: "Найди ближайший ресторан"}}
if got := ContinueLocalSearch("в Сочи", history); got != "Найди ближайший ресторан в Сочи" {
t.Fatalf("unexpected continuation: %q", got)
}
if got := ContinueLocalSearch("в Сочи", nil); got != "" {
t.Fatalf("location must not create a goal without conversation context: %q", got)
}
}
func TestContinueTravelOrigin(t *testing.T) {
history := []interaction.HumanUtterance{{Content: "Как можно добраться до Сочи?"}}
if got := ContinueTravelOrigin("я в Казани", history); got != "Как можно добраться до Сочи из Казани" {
t.Fatalf("unexpected travel continuation: %q", got)
}
if got := ContinueTravelOrigin("я в Казани", nil); got != "" {
t.Fatalf("location must not create a travel task without context: %q", got)
}
if got := ContinueTravelOrigin("Москва", history); got != "Как можно добраться до Сочи из города Москва" {
t.Fatalf("bare city should complete travel origin: %q", got)
}
}
func TestTravelSearchClarification(t *testing.T) {
if got := TravelSearchClarification("Найди билеты", nil); got == "" {
t.Fatal("underspecified travel request must ask for missing route and date")
}
if got := TravelSearchClarification("Покажи ближайшие рейсы до Сочи", nil); got != "Из какого города вылетать?" {
t.Fatalf("nearest-flight request should default date to now, got %q", got)
}
if got := TravelSearchClarification("Найди билеты из Москвы в Сочи на 12 сентября", nil); got != "" {
t.Fatalf("complete travel request must proceed, got %q", got)
}
@@ -83,6 +125,23 @@ func TestTravelSearchClarification(t *testing.T) {
if got := TravelSearchClarification("какая погода в Сочи?", history); got != "" {
t.Fatalf("unrelated question must not inherit travel goal, got %q", got)
}
if got := TravelSearchClarification("Как можно добраться до Сочи?", nil); got != "Из какого города выезжать в Сочи? Подберу самолёт, поезд, автобус или машину." {
t.Fatalf("general travel question should ask departure city, got %q", got)
}
if got := TravelSearchClarification("Как можно добраться до Сочи из Казани", nil); got != "" {
t.Fatalf("complete general travel route must proceed, got %q", got)
}
contextHistory := []interaction.HumanUtterance{{Content: "Как можно добраться до Сочи?"}}
if got := TravelSearchClarification("Найди билеты, какой ближайший самолёт", contextHistory); got != "Из какого города вылетать в Сочи?" {
t.Fatalf("travel destination should be inherited from context, got %q", got)
}
noisyContext := []interaction.HumanUtterance{
{Content: "Как можно добраться до Сочи?"},
{Content: "Какая погода в Питере?"},
}
if got := TravelSearchClarification("Найди билеты", noisyContext); got != "Из какого города вылетать в Сочи и на какую дату?" {
t.Fatalf("unrelated weather history must not replace travel destination, got %q", got)
}
}
func TestInterpretUtteranceDirectiveRecordsOutcomeWithoutExecution(t *testing.T) {
+212
View File
@@ -25,11 +25,127 @@ func StripAssistantVocative(message string) string {
return trimmed
}
// IndependentRequestParts keeps separate user actions visible to the
// orchestrator. It is intentionally limited to the ordinary coordinating
// conjunction; the cognitive route remains responsible for ambiguous prose.
func IndependentRequestParts(message string) []string {
cleaned := StripAssistantVocative(message)
parts := strings.Split(cleaned, " и ")
if len(parts) < 2 {
return []string{cleaned}
}
result := make([]string, 0, len(parts))
for _, part := range parts {
part = strings.TrimSpace(part)
if part != "" {
result = append(result, part)
}
}
if len(result) < 2 {
return []string{cleaned}
}
return result
}
// LocalSearchClarification prevents a proximity search from silently using a
// default city when the user did not provide a place.
func LocalSearchClarification(message string) string {
tokens := semanticTokens(StripAssistantVocative(message))
if !containsStemInTokens(tokens, "ресторан", "кафе") || !containsStemInTokens(tokens, "ближ", "рядом") {
return ""
}
for index, token := range tokens {
if token != "в" && token != "на" && token != "около" && !containsStem(token, "район", "город") {
continue
}
if index+1 < len(tokens) || containsStem(token, "район", "город") {
return ""
}
}
return "В каком городе или районе искать ресторан?"
}
// ContinueLocalSearch turns a location-only follow-up into the previous local
// search request, but only when that request is present in this conversation.
func ContinueLocalSearch(message string, history []interaction.HumanUtterance) string {
current := strings.TrimSpace(StripAssistantVocative(message))
tokens := semanticTokens(current)
if len(tokens) == 0 || len(tokens) > 3 || (tokens[0] != "в" && tokens[0] != "на" && tokens[0] != "около") {
return ""
}
var latest *interaction.HumanUtterance
for index := range history {
candidate := history[index]
candidateText := strings.TrimSpace(StripAssistantVocative(candidate.Content))
candidateTokens := semanticTokens(candidateText)
if !containsStemInTokens(candidateTokens, "ресторан", "кафе") || !containsStemInTokens(candidateTokens, "ближ", "рядом") {
continue
}
if latest == nil || candidate.ReceivedAtUnixMillis > latest.ReceivedAtUnixMillis {
latest = &candidate
}
}
if latest != nil {
previous := strings.TrimSpace(StripAssistantVocative(latest.Content))
return strings.TrimSpace(previous + " " + current)
}
return ""
}
// ContinueTravelOrigin turns a short location answer into the previous travel
// task. The original utterance remains history; only the effective task is
// completed for routing and research.
func ContinueTravelOrigin(message string, history []interaction.HumanUtterance) string {
current := semanticTokens(StripAssistantVocative(message))
if len(current) == 0 || len(current) > 6 {
return ""
}
location := ""
if current[0] == "я" {
if len(current) < 3 {
return ""
}
for index, token := range current {
if (token == "в" || token == "из") && index+1 < len(current) {
location = capitalizeWord(current[index+1])
break
}
}
} else if len(current) <= 2 && !isTravelDateWord(current[0]) && len([]rune(current[0])) >= 3 {
location = capitalizeWord(current[0])
}
if location == "" {
return ""
}
var latest *interaction.HumanUtterance
for index := range history {
candidate := history[index]
if !travelContextCue(semanticTokens(candidate.Content)) {
continue
}
if latest == nil || candidate.ReceivedAtUnixMillis > latest.ReceivedAtUnixMillis {
latest = &candidate
}
}
if latest == nil {
return ""
}
previous := strings.TrimRight(strings.TrimSpace(StripAssistantVocative(latest.Content)), "?!.,;:")
preposition := " из "
if current[0] != "я" {
preposition = " из города "
}
return strings.TrimSpace(previous + preposition + location)
}
// TravelSearchClarification keeps an incomplete travel request in dialogue
// instead of reducing it to an unrelated generic web search.
func TravelSearchClarification(message string, history []interaction.HumanUtterance) string {
current := semanticTokens(StripAssistantVocative(message))
travel := travelCue(current)
if !travel {
travel = containsStemInTokens(current, "добрат", "передвиг", "поех", "дорог")
}
if !travel && travelFollowUpCue(current) {
for index := len(history) - 1; index >= 0; index-- {
if travelCue(semanticTokens(history[index].Content)) {
@@ -44,6 +160,9 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
origin := containsStemInTokens(current, "из", "откуда", "от")
destination := containsStemInTokens(current, "в", "куда", "до")
date := containsStemInTokens(current, "сегодня", "завтра", "послезавтр", "январ", "феврал", "март", "апрел", "мая", "июн", "июл", "август", "сентябр", "октябр", "ноябр", "декабр")
if containsStemInTokens(current, "ближ") {
date = true
}
if !date {
for _, token := range current {
if hasDigit(token) {
@@ -55,9 +174,102 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
if origin && destination && date {
return ""
}
ticketRequest := containsStemInTokens(current, "билет", "рейс", "самолет", "самолёт", "вылет")
if !ticketRequest && origin && destination {
return ""
}
if !destination {
if contextDestination := travelContextDestination(history); contextDestination != "" {
destination = true
if !origin && !date {
return "Из какого города вылетать в " + contextDestination + " и на какую дату?"
}
if !origin {
return "Из какого города вылетать в " + contextDestination + "?"
}
}
}
if !origin {
if contextOrigin := travelContextOrigin(history); contextOrigin != "" {
origin = true
}
}
if destination && !origin && !date {
if !ticketRequest {
return "Из какого города выезжать в " + destinationLabel(current, history) + "? Подберу самолёт, поезд, автобус или машину."
}
return "Из какого города вылетать и на какую дату?"
}
if destination && !origin {
return "Из какого города вылетать?"
}
if destination && !date {
return "На какую дату нужны билеты?"
}
return "Уточните маршрут и дату: откуда, куда и на какой день нужны билеты?"
}
func isTravelDateWord(value string) bool {
return containsStem(value, "сегодня", "завтра", "послезавтр", "январ", "феврал", "март", "апрел", "мая", "июн", "июл", "август", "сентябр", "октябр", "ноябр", "декабр")
}
func destinationLabel(current []string, history []interaction.HumanUtterance) string {
for index, token := range current {
if (token == "в" || token == "до") && index+1 < len(current) {
return capitalizeWord(current[index+1])
}
}
if destination := travelContextDestination(history); destination != "" {
return destination
}
return "пункт назначения"
}
func travelContextDestination(history []interaction.HumanUtterance) string {
for index := len(history) - 1; index >= 0; index-- {
tokens := semanticTokens(history[index].Content)
if !travelContextCue(tokens) {
continue
}
for tokenIndex, token := range tokens {
if token != "в" && token != "до" {
continue
}
if tokenIndex+1 < len(tokens) && len([]rune(tokens[tokenIndex+1])) >= 3 {
return capitalizeWord(tokens[tokenIndex+1])
}
}
}
return ""
}
func travelContextOrigin(history []interaction.HumanUtterance) string {
for index := len(history) - 1; index >= 0; index-- {
tokens := semanticTokens(history[index].Content)
if len(tokens) < 3 || tokens[0] != "я" || !containsStemInTokens(tokens, "сейчас", "нахож", "жив") {
continue
}
for tokenIndex, token := range tokens {
if (token == "в" || token == "из") && tokenIndex+1 < len(tokens) {
return capitalizeWord(tokens[tokenIndex+1])
}
}
}
return ""
}
func travelContextCue(tokens []string) bool {
return travelCue(tokens) || containsStemInTokens(tokens, "добрат", "передвиг", "ехать", "едем", "лететь", "поездк")
}
func capitalizeWord(value string) string {
runes := []rune(value)
if len(runes) == 0 {
return value
}
return strings.ToUpper(string(runes[0])) + string(runes[1:])
}
func travelCue(tokens []string) bool {
return containsStemInTokens(tokens, "билет", "рейс", "поезд", "автобус", "перелет", "перелёт")
}