Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
24320f22a6 | ||
|
|
98cf218cc3 | ||
|
|
7abe73e7bd | ||
|
|
a05ddacff3 | ||
|
|
20b18de60a | ||
|
|
d5c98dd62f | ||
|
|
61d08fa05a | ||
|
|
1ea2e713d8 | ||
|
|
38dce57666 | ||
|
|
8f255b8bde |
@@ -81,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
|
||||||
}
|
}
|
||||||
@@ -204,6 +205,15 @@ func hasNumericSearchTerm(values []string) bool {
|
|||||||
return false
|
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 {
|
||||||
|
|||||||
@@ -46,3 +46,12 @@ func TestSearchConnectorFallsBackToAnotherAllowedSource(t *testing.T) {
|
|||||||
t.Fatalf("search result source = %#v", results[0].Source)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+42
-18
@@ -30,6 +30,7 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -571,7 +572,8 @@ func main() {
|
|||||||
semantic.NeedsCognition = false
|
semantic.NeedsCognition = false
|
||||||
semantic.Interpretation.NeedsCognition = false
|
semantic.Interpretation.NeedsCognition = false
|
||||||
}
|
}
|
||||||
if locationReply := interactiondomain.LocationContextReply(utterance.Content); locationReply != "" {
|
locationReply := interactiondomain.LocationContextReply(utterance.Content)
|
||||||
|
if locationReply != "" {
|
||||||
semantic.Reply = locationReply
|
semantic.Reply = locationReply
|
||||||
semantic.NeedsCognition = false
|
semantic.NeedsCognition = false
|
||||||
semantic.Interpretation.NeedsCognition = false
|
semantic.Interpretation.NeedsCognition = false
|
||||||
@@ -584,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))
|
||||||
@@ -751,7 +748,7 @@ func main() {
|
|||||||
PropositionKey: fmt.Sprintf("question:%s:%d", utterance.ID, index), Query: part,
|
PropositionKey: fmt.Sprintf("question:%s:%d", utterance.ID, index), Query: part,
|
||||||
})
|
})
|
||||||
cancelResearch()
|
cancelResearch()
|
||||||
reply, backed := renderResearchReply(result, researchErr)
|
reply, backed := renderResearchReply(part, result, researchErr)
|
||||||
if backed {
|
if backed {
|
||||||
researchBacked = true
|
researchBacked = true
|
||||||
}
|
}
|
||||||
@@ -871,7 +868,7 @@ 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 && (!researchBacked || reviewPreservesResearchEvidence(reviewedReply, planningReply)) {
|
} else if !stableSemanticReply && (!researchBacked || reviewPreservesResearchEvidence(reviewedReply, planningReply)) {
|
||||||
@@ -1629,7 +1626,7 @@ 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
|
||||||
}
|
}
|
||||||
@@ -1654,7 +1651,17 @@ 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 {
|
func reviewPreservesResearchEvidence(reviewed, draft string) bool {
|
||||||
@@ -1672,20 +1679,37 @@ func humanMemoryInventory(history []interaction.HumanUtterance, assistantName st
|
|||||||
if assistantName != "" {
|
if assistantName != "" {
|
||||||
rows = append(rows, "| Имя помощника | "+assistantName+" |")
|
rows = append(rows, "| Имя помощника | "+assistantName+" |")
|
||||||
}
|
}
|
||||||
for index := len(history) - 1; index >= 0; index-- {
|
latestPreferenceAt := int64(-1)
|
||||||
message := strings.TrimSpace(history[index].Content)
|
latestPreference := ""
|
||||||
|
for _, utterance := range history {
|
||||||
|
message := strings.TrimSpace(utterance.Content)
|
||||||
lower := strings.ToLower(message)
|
lower := strings.ToLower(message)
|
||||||
if strings.Contains(lower, "нравится") || strings.Contains(lower, "люблю") {
|
if (strings.Contains(lower, "нравится") || strings.Contains(lower, "люблю")) && utterance.ReceivedAtUnixMillis >= latestPreferenceAt {
|
||||||
rows = append(rows, "| Предпочтение пользователя | "+message+" |")
|
latestPreferenceAt = utterance.ReceivedAtUnixMillis
|
||||||
break
|
latestPreference = message
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if latestPreference != "" {
|
||||||
|
rows = append(rows, "| Предпочтение пользователя | "+latestPreference+" |")
|
||||||
|
}
|
||||||
if len(rows) == 0 {
|
if len(rows) == 0 {
|
||||||
return "| Ячейка памяти | Значение |\n|---|---|\n| — | Сохранённых пользовательских предпочтений пока не найдено. |"
|
return "| Ячейка памяти | Значение |\n|---|---|\n| — | Сохранённых пользовательских предпочтений пока не найдено. |"
|
||||||
}
|
}
|
||||||
return "| Ячейка памяти | Значение |\n|---|---|\n" + strings.Join(rows, "\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 {
|
func humanTimeDifferenceReply(message string) string {
|
||||||
lower := strings.ToLower(message)
|
lower := strings.ToLower(message)
|
||||||
if strings.Contains(lower, "моск") && strings.Contains(lower, "шанх") {
|
if strings.Contains(lower, "моск") && strings.Contains(lower, "шанх") {
|
||||||
@@ -1703,9 +1727,9 @@ func researchSourceLabel(finding epistemics.ResearchFinding) string {
|
|||||||
}
|
}
|
||||||
if title != "" && publisher != "" {
|
if title != "" && publisher != "" {
|
||||||
if locator != "" {
|
if locator != "" {
|
||||||
return title + " — " + publisher + " (" + locator + ")"
|
return publisher + " (" + locator + ")"
|
||||||
}
|
}
|
||||||
return title + " — " + publisher
|
return publisher
|
||||||
}
|
}
|
||||||
if title != "" {
|
if title != "" {
|
||||||
return title
|
return title
|
||||||
|
|||||||
@@ -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") {
|
||||||
|
|||||||
Reference in New Issue
Block a user