Compare commits
58
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
24320f22a6 | ||
|
|
98cf218cc3 | ||
|
|
7abe73e7bd | ||
|
|
a05ddacff3 | ||
|
|
20b18de60a | ||
|
|
d5c98dd62f | ||
|
|
61d08fa05a | ||
|
|
1ea2e713d8 | ||
|
|
38dce57666 | ||
|
|
8f255b8bde | ||
|
|
6b97d6668b | ||
|
|
3fa1d70379 | ||
|
|
2dd05a7aa6 | ||
|
|
02227edc23 | ||
|
|
a2297a84ad | ||
|
|
05cbd8adc7 | ||
|
|
984731b111 | ||
|
|
0da03c18d1 | ||
|
|
302b8fc8cd | ||
|
|
59239635cd | ||
|
|
238105a7da | ||
|
|
d7ca5f7e68 | ||
|
|
827135a02d | ||
|
|
a3ddf53207 | ||
|
|
35ac9015ad | ||
|
|
1c196ef675 | ||
|
|
2ce3b5a9b3 | ||
|
|
7421fd058d | ||
|
|
368e9df551 | ||
|
|
e9629046cb | ||
|
|
b5ccc419f6 | ||
|
|
615723da2a | ||
|
|
d1bcd5beff | ||
|
|
519dc583a0 | ||
|
|
0bf883cf56 | ||
|
|
c8502c735c | ||
|
|
48af97fbdd | ||
|
|
13bcf87ea5 | ||
|
|
e271fbb1e1 | ||
|
|
5678686c57 | ||
|
|
9fc3fd1aa5 | ||
|
|
e3a9c18cb3 | ||
|
|
9534b041db | ||
|
|
9426fa40a9 | ||
|
|
51e2b23082 | ||
|
|
aece914fb8 | ||
|
|
762e312730 | ||
|
|
e9eb529d6e | ||
|
|
e39a2b7dda | ||
|
|
cdc6baa4c0 | ||
|
|
255ab8dbf3 | ||
|
|
a76dc42bd8 | ||
|
|
f0cbd71129 | ||
|
|
aa10c3e093 | ||
|
|
0d836121d0 | ||
|
|
6e8ecbf5e5 | ||
|
|
8088ff197e | ||
|
|
55ee967f2f |
@@ -3,6 +3,7 @@ package research
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"html"
|
"html"
|
||||||
@@ -19,9 +20,9 @@ import (
|
|||||||
var ErrSearchRejected = errors.New("web search request rejected")
|
var ErrSearchRejected = errors.New("web search request rejected")
|
||||||
|
|
||||||
var (
|
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>`)
|
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>`)
|
bingSnippetPattern = regexp.MustCompile(`(?is)<li[^>]+class=["'][^"']*b_algo[^"']*["'][^>]*>.*?<p[^>]*>(.*?)</p>`)
|
||||||
tagPattern = regexp.MustCompile(`(?s)<[^>]*>`)
|
tagPattern = regexp.MustCompile(`(?s)<[^>]*>`)
|
||||||
termPattern = regexp.MustCompile(`(?i)[\p{L}\p{N}]{2,}`)
|
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") {
|
if !strings.Contains(configured.Template, "%s") {
|
||||||
return nil, ErrSearchRejected
|
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())) {
|
if err != nil || endpoint.Scheme != "https" || endpoint.Host == "" || !allowedHost(configured.AllowedHosts, strings.ToLower(endpoint.Hostname())) {
|
||||||
return nil, ErrSearchRejected
|
return nil, ErrSearchRejected
|
||||||
}
|
}
|
||||||
@@ -128,7 +130,8 @@ func (c SearchConnector) collectEndpoint(ctx context.Context, configured SearchE
|
|||||||
snapshotID := epistemics.SourceSnapshotID("snapshot:search:" + base)
|
snapshotID := epistemics.SourceSnapshotID("snapshot:search:" + base)
|
||||||
results := make([]epistemics.ResearchCandidate, 0, len(links))
|
results := make([]epistemics.ResearchCandidate, 0, len(links))
|
||||||
for index, link := range links {
|
for index, link := range links {
|
||||||
title := cleanHTML(string(link[1]))
|
linkURL := resolveSearchResultLocator(extractHref(string(link[1])), endpoint)
|
||||||
|
title := cleanHTML(string(link[2]))
|
||||||
snippet := ""
|
snippet := ""
|
||||||
if index < len(snippets) {
|
if index < len(snippets) {
|
||||||
snippet = cleanHTML(string(snippets[index][1]))
|
snippet = cleanHTML(string(snippets[index][1]))
|
||||||
@@ -142,7 +145,7 @@ func (c SearchConnector) collectEndpoint(ctx context.Context, configured SearchE
|
|||||||
results = append(results, epistemics.ResearchCandidate{
|
results = append(results, epistemics.ResearchCandidate{
|
||||||
PropositionKey: request.PropositionKey + ":result:" + ordinal,
|
PropositionKey: request.PropositionKey + ":result:" + ordinal,
|
||||||
Statement: statement,
|
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},
|
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))},
|
Excerpt: epistemics.SourceExcerpt{ID: excerptID, SnapshotID: snapshotID, Text: statement, Start: 0, End: int64(len(statement))},
|
||||||
Evidence: epistemics.EvidenceObserved, Coverage: epistemics.CoverageComplete, Conflict: epistemics.ConflictNone,
|
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 {
|
func searchStatementRelatesToQuery(query, statement string) bool {
|
||||||
terms := termPattern.FindAllString(strings.ToLower(query), -1)
|
terms := termPattern.FindAllString(strings.ToLower(query), -1)
|
||||||
content := strings.ToLower(statement)
|
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
|
usable := 0
|
||||||
for _, term := range terms {
|
for _, term := range terms {
|
||||||
if _, stop := searchStopTerms[term]; stop || len([]rune(term)) < 4 {
|
if _, stop := searchStopTerms[term]; stop || len([]rune(term)) < 4 {
|
||||||
@@ -175,6 +183,37 @@ func searchStatementRelatesToQuery(query, statement string) bool {
|
|||||||
return usable == 0
|
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 allowedHost(hosts map[string]struct{}, host string) bool { _, ok := hosts[host]; return ok }
|
||||||
func (c SearchConnector) limit() int {
|
func (c SearchConnector) limit() int {
|
||||||
if c.MaxResults <= 0 || c.MaxResults > 8 {
|
if c.MaxResults <= 0 || c.MaxResults > 8 {
|
||||||
@@ -185,3 +224,53 @@ func (c SearchConnector) limit() int {
|
|||||||
func cleanHTML(value string) string {
|
func cleanHTML(value string) string {
|
||||||
return strings.Join(strings.Fields(html.UnescapeString(tagPattern.ReplaceAllString(value, ""))), " ")
|
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") {
|
if len(results) != 1 || !strings.Contains(results[0].Statement, "18") {
|
||||||
t.Fatalf("fallback evidence = %#v", results)
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ func (c cognitiveInterpretationClient) ReviewResponse(ctx context.Context, sessi
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
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 := *c.baseURL
|
||||||
target.Path = "/v1/advisories"
|
target.Path = "/v1/advisories"
|
||||||
payload, err := json.Marshal(cognitive.GatewayAdvisoryRequest{
|
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) {
|
func TestSimpleQuestionUsesStrictInterpretationForSemanticRouting(t *testing.T) {
|
||||||
result := interactiondomain.SemanticResult{
|
result := interactiondomain.SemanticResult{
|
||||||
Interpretation: interaction.UtteranceInterpretation{
|
Interpretation: interaction.UtteranceInterpretation{
|
||||||
|
|||||||
+173
-22
@@ -30,6 +30,7 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -509,6 +510,8 @@ func main() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
var effectiveTaskMessage = interactiondomain.StripAssistantVocative(utterance.Content)
|
var effectiveTaskMessage = interactiondomain.StripAssistantVocative(utterance.Content)
|
||||||
|
continuationMessage := ""
|
||||||
|
travelContinuation := false
|
||||||
var previousTask *interaction.HumanUtterance
|
var previousTask *interaction.HumanUtterance
|
||||||
var conversationHistory []interaction.HumanUtterance
|
var conversationHistory []interaction.HumanUtterance
|
||||||
if request.ConversationID != "" {
|
if request.ConversationID != "" {
|
||||||
@@ -528,6 +531,14 @@ func main() {
|
|||||||
log.Printf("interaction principal history loaded: %d utterances", len(recentUserHistory))
|
log.Printf("interaction principal history loaded: %d utterances", len(recentUserHistory))
|
||||||
}
|
}
|
||||||
conversationHistory = append(conversationHistory, 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 request.ConversationID != "" && interactiondomain.IsRetryRequest(utterance.Content) {
|
||||||
if len(conversationHistory) > 0 {
|
if len(conversationHistory) > 0 {
|
||||||
for index := len(conversationHistory) - 1; index >= 0; index-- {
|
for index := len(conversationHistory) - 1; index >= 0; index-- {
|
||||||
@@ -546,6 +557,27 @@ func main() {
|
|||||||
http.Error(w, "interpret chat message", http.StatusServiceUnavailable)
|
http.Error(w, "interpret chat message", http.StatusServiceUnavailable)
|
||||||
return
|
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 {
|
if previousTask != nil {
|
||||||
previousSemantic, previousErr := interactiondomain.InterpretUtterance(*previousTask, projects, previousFocus, now)
|
previousSemantic, previousErr := interactiondomain.InterpretUtterance(*previousTask, projects, previousFocus, now)
|
||||||
if previousErr == nil {
|
if previousErr == nil {
|
||||||
@@ -554,12 +586,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
assistantName := interactiondomain.PreferredAssistantName(utterance.Content)
|
assistantName := interactiondomain.PreferredAssistantName(utterance.Content)
|
||||||
if assistantName == "" {
|
if assistantName == "" {
|
||||||
for index := len(conversationHistory) - 1; index >= 0; index-- {
|
assistantName = latestAssistantName(conversationHistory)
|
||||||
if name := interactiondomain.PreferredAssistantName(conversationHistory[index].Content); name != "" {
|
|
||||||
assistantName = name
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
identityReply := ""
|
identityReply := ""
|
||||||
log.Printf("interaction identity context: name=%q history=%d", assistantName, len(conversationHistory))
|
log.Printf("interaction identity context: name=%q history=%d", assistantName, len(conversationHistory))
|
||||||
@@ -682,6 +709,12 @@ func main() {
|
|||||||
helpPath = work.HelpPath{}
|
helpPath = work.HelpPath{}
|
||||||
}
|
}
|
||||||
switch semantic.InformationRequestKind {
|
switch semantic.InformationRequestKind {
|
||||||
|
case interaction.InformationRequestMemoryInventory:
|
||||||
|
planningReply = humanMemoryInventory(conversationHistory, assistantName)
|
||||||
|
needsCognition = false
|
||||||
|
case interaction.InformationRequestTimeDifference:
|
||||||
|
planningReply = humanTimeDifferenceReply(effectiveTaskMessage)
|
||||||
|
needsCognition = false
|
||||||
case interaction.InformationRequestCapabilityInventory:
|
case interaction.InformationRequestCapabilityInventory:
|
||||||
kinds, err := capabilityRepository.AvailableCapabilityKinds(r.Context(), session.PrincipalID)
|
kinds, err := capabilityRepository.AvailableCapabilityKinds(r.Context(), session.PrincipalID)
|
||||||
if err == nil && len(kinds) > 0 {
|
if err == nil && len(kinds) > 0 {
|
||||||
@@ -702,13 +735,32 @@ func main() {
|
|||||||
researchBacked := false
|
researchBacked := false
|
||||||
if hasChatRoute(routePlan, chatRouteResearch) && semantic.Interpretation.Clarification != interaction.ClarificationRequired {
|
if hasChatRoute(routePlan, chatRouteResearch) && semantic.Interpretation.Clarification != interaction.ClarificationRequired {
|
||||||
if planID, idErr := ids.New(); idErr == nil {
|
if planID, idErr := ids.New(); idErr == nil {
|
||||||
researchCtx, cancelResearch := context.WithTimeout(r.Context(), 8*time.Second)
|
parts := interactiondomain.IndependentRequestParts(effectiveTaskMessage)
|
||||||
result, researchErr := researchClient.SearchWeb(researchCtx, epistemics.WebSearchRequest{
|
replies := make([]string, 0, len(parts))
|
||||||
Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID("plan:" + planID), Question: effectiveTaskMessage, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"},
|
for index, part := range parts {
|
||||||
PropositionKey: "question:" + string(utterance.ID), Query: effectiveTaskMessage,
|
if clarification := interactiondomain.LocalSearchClarification(part); clarification != "" {
|
||||||
})
|
replies = append(replies, "По запросу «"+part+"»: "+clarification)
|
||||||
cancelResearch()
|
continue
|
||||||
planningReply, researchBacked = renderResearchReply(result, researchErr)
|
}
|
||||||
|
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
|
// A failed source must not turn the complete conversation into a
|
||||||
// runtime failure or invite an unsupported local guess for a fact.
|
// runtime failure or invite an unsupported local guess for a fact.
|
||||||
needsCognition = false
|
needsCognition = false
|
||||||
@@ -816,10 +868,10 @@ func main() {
|
|||||||
ConfidenceMillis: semantic.Interpretation.ConfidenceMillis,
|
ConfidenceMillis: semantic.Interpretation.ConfidenceMillis,
|
||||||
})
|
})
|
||||||
cancelReview()
|
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 {
|
if reviewErr != nil {
|
||||||
log.Printf("cognitive response review unavailable: %v", reviewErr)
|
log.Printf("cognitive response review unavailable: %v", reviewErr)
|
||||||
} else if !stableSemanticReply {
|
} else if !stableSemanticReply && (!researchBacked || reviewPreservesResearchEvidence(reviewedReply, planningReply)) {
|
||||||
planningReply = reviewedReply
|
planningReply = reviewedReply
|
||||||
} else if reviewedReply != planningReply {
|
} else if reviewedReply != planningReply {
|
||||||
log.Printf("cognitive response review proposed stable semantic rewrite; preserving semantic reply")
|
log.Printf("cognitive response review proposed stable semantic rewrite; preserving semantic reply")
|
||||||
@@ -827,13 +879,19 @@ func main() {
|
|||||||
}
|
}
|
||||||
if identityReply == "" {
|
if identityReply == "" {
|
||||||
stableAct := interactiondomain.ClassifySpeechAct(utterance.Content, utterance.CorrectsUtteranceID)
|
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
|
planningReply = stableReply
|
||||||
needsCognition = false
|
needsCognition = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if identityReply != "" {
|
if identityReply != "" {
|
||||||
|
semantic.Reply = identityReply
|
||||||
needsCognition = false
|
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)
|
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{
|
response := interaction.ChatMessageResponse{
|
||||||
@@ -1568,20 +1626,24 @@ func hasCapabilityHint(hints []string, wanted string) bool {
|
|||||||
return false
|
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 {
|
if researchErr != nil {
|
||||||
return "Сейчас не удалось получить данные из подключённого источника. Попробую снова через доступный маршрут.", false
|
return "Сейчас не удалось получить данные из подключённого источника. Попробую снова через доступный маршрут.", false
|
||||||
}
|
}
|
||||||
lines := make([]string, 0, 2)
|
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) == "" {
|
if finding.State != epistemics.FindingSupported || strings.TrimSpace(finding.Excerpt.Text) == "" || strings.TrimSpace(finding.Source.Locator) == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
excerpt := strings.TrimSpace(finding.Excerpt.Text)
|
excerpt := strings.TrimSpace(finding.Excerpt.Text)
|
||||||
if len([]rune(excerpt)) > 180 {
|
limit := 180
|
||||||
excerpt = string([]rune(excerpt)[: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 {
|
if len(lines) == 2 {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -1589,7 +1651,96 @@ func renderResearchReply(result epistemics.ResearchResult, researchErr error) (s
|
|||||||
if len(lines) == 0 {
|
if len(lines) == 0 {
|
||||||
return "Проверяемых данных пока не найдено. Могу повторить поиск или уточнить, что именно проверить.", false
|
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 {
|
func humanCognitiveModelInventory(candidates []capability.ResolvedCognitiveBinding, inventoryErr error) string {
|
||||||
|
|||||||
@@ -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) {
|
func TestCognitiveChannelQuestionUsesHumanSafeHealthReply(t *testing.T) {
|
||||||
reply := humanCognitiveChannelReply(interaction.InformationRequestCognitiveChannelStatus, interaction.SpeechActQuestion, capability.Health{State: capability.HealthAvailable, CapabilityID: "provider-secret-model"}, nil)
|
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") {
|
if !strings.Contains(reply, "доступен") || strings.Contains(reply, "provider-secret-model") {
|
||||||
|
|||||||
@@ -70,6 +70,8 @@ const (
|
|||||||
InformationRequestCognitiveModelInventory InformationRequestKind = "COGNITIVE_MODEL_INVENTORY"
|
InformationRequestCognitiveModelInventory InformationRequestKind = "COGNITIVE_MODEL_INVENTORY"
|
||||||
InformationRequestCognitiveChannelStatus InformationRequestKind = "COGNITIVE_CHANNEL_STATUS"
|
InformationRequestCognitiveChannelStatus InformationRequestKind = "COGNITIVE_CHANNEL_STATUS"
|
||||||
InformationRequestCognitiveRecovery InformationRequestKind = "COGNITIVE_RECOVERY"
|
InformationRequestCognitiveRecovery InformationRequestKind = "COGNITIVE_RECOVERY"
|
||||||
|
InformationRequestMemoryInventory InformationRequestKind = "MEMORY_INVENTORY"
|
||||||
|
InformationRequestTimeDifference InformationRequestKind = "TIME_DIFFERENCE"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Conversation struct {
|
type Conversation struct {
|
||||||
|
|||||||
@@ -133,7 +133,7 @@ func PreferredAssistantName(message string) string {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for _, candidate := range tokens[index+1:] {
|
for _, candidate := range tokens[index+1:] {
|
||||||
if candidate == "тебя" || candidate == "тебе" || candidate == "себя" || candidate == "меня" {
|
if candidate == "тебя" || candidate == "тебе" || candidate == "себя" || candidate == "меня" || candidate == "в" || candidate == "теперь" || candidate == "же" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if candidate == "буду" || candidate == "будет" || candidate == "запомни" || candidate == "помни" || candidate == "ты" || candidate == "это" {
|
if candidate == "буду" || candidate == "будет" || candidate == "запомни" || candidate == "помни" || candidate == "ты" || candidate == "это" {
|
||||||
@@ -144,12 +144,19 @@ func PreferredAssistantName(message string) string {
|
|||||||
}
|
}
|
||||||
runes := []rune(candidate)
|
runes := []rune(candidate)
|
||||||
runes[0] = []rune(strings.ToUpper(string(runes[0])))[0]
|
runes[0] = []rune(strings.ToUpper(string(runes[0])))[0]
|
||||||
return string(runes)
|
return normalizeAssistantName(string(runes))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return ""
|
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
|
// IsIdentityInquiry identifies a request about the assistant itself by its
|
||||||
// interrogative meaning. Punctuation is optional and wording may vary.
|
// interrogative meaning. Punctuation is optional and wording may vary.
|
||||||
func IsIdentityInquiry(message string) bool {
|
func IsIdentityInquiry(message string) bool {
|
||||||
@@ -592,6 +599,12 @@ func informationRequestKind(message string, candidate interaction.SemanticCandid
|
|||||||
if len(tokens) == 0 {
|
if len(tokens) == 0 {
|
||||||
return ""
|
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
|
inquiry := candidate.PrimarySpeechAct == interaction.SpeechActQuestion || candidate.PrimarySpeechAct == interaction.SpeechActRequestToInvestigate || candidate.SecondarySpeechAct == interaction.SpeechActQuestion || candidate.SecondarySpeechAct == interaction.SpeechActRequestToInvestigate
|
||||||
cognitiveSubject := containsStemInTokens(tokens, "модел", "ии", "ai", "локальн", "когнитив", "канал")
|
cognitiveSubject := containsStemInTokens(tokens, "модел", "ии", "ai", "локальн", "когнитив", "канал")
|
||||||
inventoryCue := containsStemInTokens(tokens, "список", "доступ", "подключ", "вариант") || (containsMeaningfulInterrogative(tokens) && containsStemInTokens(tokens, "настро"))
|
inventoryCue := containsStemInTokens(tokens, "список", "доступ", "подключ", "вариант") || (containsMeaningfulInterrogative(tokens) && containsStemInTokens(tokens, "настро"))
|
||||||
@@ -613,6 +626,19 @@ func informationRequestKind(message string, candidate interaction.SemanticCandid
|
|||||||
return ""
|
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 {
|
func boundedConfidence(primaryScore, secondaryScore int, scores map[interaction.SpeechAct]int) int64 {
|
||||||
total := 0
|
total := 0
|
||||||
for _, score := range scores {
|
for _, score := range scores {
|
||||||
|
|||||||
@@ -198,11 +198,37 @@ func TestNamingPreferenceIsSemanticAndProducesNaturalAcceptance(t *testing.T) {
|
|||||||
if name := PreferredAssistantName("я назову тебя дед, запомни"); name != "Дед" {
|
if name := PreferredAssistantName("я назову тебя дед, запомни"); name != "Дед" {
|
||||||
t.Fatalf("expected conversational name form to be extracted, got %q", 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("как тебя зовут") {
|
if !IsIdentityInquiry("ты кто?") || !IsIdentityInquiry("как тебя зовут") {
|
||||||
t.Fatal("identity variants should be recognized")
|
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) {
|
func TestDeterministicCandidateKeepsFirstPersonCompletedWorkAsAssertion(t *testing.T) {
|
||||||
candidate := BuildDeterministicCandidate("Я всё уже настроил.", "", time.Unix(10, 0).UnixMilli())
|
candidate := BuildDeterministicCandidate("Я всё уже настроил.", "", time.Unix(10, 0).UnixMilli())
|
||||||
if candidate.PrimarySpeechAct != interaction.SpeechActAssertion {
|
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) {
|
func TestTravelSearchClarification(t *testing.T) {
|
||||||
if got := TravelSearchClarification("Найди билеты", nil); got == "" {
|
if got := TravelSearchClarification("Найди билеты", nil); got == "" {
|
||||||
t.Fatal("underspecified travel request must ask for missing route and date")
|
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 != "" {
|
if got := TravelSearchClarification("Найди билеты из Москвы в Сочи на 12 сентября", nil); got != "" {
|
||||||
t.Fatalf("complete travel request must proceed, got %q", got)
|
t.Fatalf("complete travel request must proceed, got %q", got)
|
||||||
}
|
}
|
||||||
@@ -80,6 +122,26 @@ func TestTravelSearchClarification(t *testing.T) {
|
|||||||
if got := TravelSearchClarification("а куда летим?", history); got == "" {
|
if got := TravelSearchClarification("а куда летим?", history); got == "" {
|
||||||
t.Fatal("follow-up must remain attached to the travel goal")
|
t.Fatal("follow-up must remain attached to the travel goal")
|
||||||
}
|
}
|
||||||
|
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) {
|
func TestInterpretUtteranceDirectiveRecordsOutcomeWithoutExecution(t *testing.T) {
|
||||||
|
|||||||
@@ -25,12 +25,128 @@ func StripAssistantVocative(message string) string {
|
|||||||
return trimmed
|
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
|
// TravelSearchClarification keeps an incomplete travel request in dialogue
|
||||||
// instead of reducing it to an unrelated generic web search.
|
// instead of reducing it to an unrelated generic web search.
|
||||||
func TravelSearchClarification(message string, history []interaction.HumanUtterance) string {
|
func TravelSearchClarification(message string, history []interaction.HumanUtterance) string {
|
||||||
current := semanticTokens(StripAssistantVocative(message))
|
current := semanticTokens(StripAssistantVocative(message))
|
||||||
travel := travelCue(current)
|
travel := travelCue(current)
|
||||||
if !travel {
|
if !travel {
|
||||||
|
travel = containsStemInTokens(current, "добрат", "передвиг", "поех", "дорог")
|
||||||
|
}
|
||||||
|
if !travel && travelFollowUpCue(current) {
|
||||||
for index := len(history) - 1; index >= 0; index-- {
|
for index := len(history) - 1; index >= 0; index-- {
|
||||||
if travelCue(semanticTokens(history[index].Content)) {
|
if travelCue(semanticTokens(history[index].Content)) {
|
||||||
travel = true
|
travel = true
|
||||||
@@ -44,6 +160,9 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
|
|||||||
origin := containsStemInTokens(current, "из", "откуда", "от")
|
origin := containsStemInTokens(current, "из", "откуда", "от")
|
||||||
destination := containsStemInTokens(current, "в", "куда", "до")
|
destination := containsStemInTokens(current, "в", "куда", "до")
|
||||||
date := containsStemInTokens(current, "сегодня", "завтра", "послезавтр", "январ", "феврал", "март", "апрел", "мая", "июн", "июл", "август", "сентябр", "октябр", "ноябр", "декабр")
|
date := containsStemInTokens(current, "сегодня", "завтра", "послезавтр", "январ", "феврал", "март", "апрел", "мая", "июн", "июл", "август", "сентябр", "октябр", "ноябр", "декабр")
|
||||||
|
if containsStemInTokens(current, "ближ") {
|
||||||
|
date = true
|
||||||
|
}
|
||||||
if !date {
|
if !date {
|
||||||
for _, token := range current {
|
for _, token := range current {
|
||||||
if hasDigit(token) {
|
if hasDigit(token) {
|
||||||
@@ -55,13 +174,110 @@ func TravelSearchClarification(message string, history []interaction.HumanUttera
|
|||||||
if origin && destination && date {
|
if origin && destination && date {
|
||||||
return ""
|
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 "Уточните маршрут и дату: откуда, куда и на какой день нужны билеты?"
|
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 {
|
func travelCue(tokens []string) bool {
|
||||||
return containsStemInTokens(tokens, "билет", "рейс", "поезд", "автобус", "перелет", "перелёт")
|
return containsStemInTokens(tokens, "билет", "рейс", "поезд", "автобус", "перелет", "перелёт")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func travelFollowUpCue(tokens []string) bool {
|
||||||
|
return containsStemInTokens(tokens, "куда", "откуда", "маршрут", "летим", "дата", "число")
|
||||||
|
}
|
||||||
|
|
||||||
func hasDigit(value string) bool {
|
func hasDigit(value string) bool {
|
||||||
for _, runeValue := range value {
|
for _, runeValue := range value {
|
||||||
if runeValue >= '0' && runeValue <= '9' {
|
if runeValue >= '0' && runeValue <= '9' {
|
||||||
|
|||||||
Reference in New Issue
Block a user