Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46b89577eb | ||
|
|
a6ddbfaaf2 | ||
|
|
362a1bd993 | ||
|
|
735222de0d | ||
|
|
4e3d153557 | ||
|
|
f316f7ec3f | ||
|
|
da5d06895b | ||
|
|
4d1a579132 | ||
|
|
43836af511 | ||
|
|
32457f7142 | ||
|
|
204eee489c | ||
|
|
5cd8665aba | ||
|
|
04018cbd07 | ||
|
|
23a1eeae56 |
@@ -82,6 +82,54 @@ func (c cognitiveInterpretationClient) ReviewResponse(ctx context.Context, sessi
|
|||||||
return strings.TrimSpace(result.AdvisoryText), nil
|
return strings.TrimSpace(result.AdvisoryText), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AnswerStableKnowledge asks the local cognitive route for a short answer to a
|
||||||
|
// non-current question only after evidence retrieval did not produce a usable
|
||||||
|
// result. The model decides whether its knowledge is stable enough; it must
|
||||||
|
// explicitly decline changing or source-dependent facts instead of guessing.
|
||||||
|
func (c cognitiveInterpretationClient) AnswerStableKnowledge(ctx context.Context, session identity.CreatorSession, userMessage, personalMemory string, meaning cognitive.TaskMeaning) (string, error) {
|
||||||
|
requestID, err := ids.New()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
prompt := "Ты отвечаешь как Домовой на обычный вопрос пользователя. Сначала пойми цель вопроса и верни короткий естественный ответ по устойчивому общеизвестному знанию. Начинай сразу с ответа и не представляйся, если пользователь не спросил об имени. Не называй модель или внутреннюю систему. Если истинность ответа зависит от текущего наблюдения, внешнего источника или инструмента, верни ровно NEEDS_VERIFIED_RESEARCH. Не придумывай факты.\n\nВопрос пользователя:\n" + userMessage
|
||||||
|
context := []cognitive.ContextExcerpt{}
|
||||||
|
if strings.TrimSpace(personalMemory) != "" {
|
||||||
|
context = append(context, cognitive.ContextExcerpt{ID: "personal-memory", SourceKind: "derived-personal-memory", SourceID: "interaction:human-utterances", Revision: 1, Sensitivity: cognitive.SensitivityPrivateAllowed, Text: personalMemory})
|
||||||
|
}
|
||||||
|
target := *c.baseURL
|
||||||
|
target.Path = "/v1/advisories"
|
||||||
|
payload, err := json.Marshal(cognitive.GatewayAdvisoryRequest{
|
||||||
|
Version: cognitive.CreatorAdvisoryV1, RequestID: cognitive.RequestID(requestID),
|
||||||
|
ActorID: session.ActorID, PrincipalID: session.PrincipalID, ScopeID: authority.ScopeID("domovoy-global-scope"),
|
||||||
|
Message: prompt, Context: context, Locale: "ru", MaxOutputBytes: 1024, DataPolicy: capability.DataPolicyLocalOnly,
|
||||||
|
Meaning: cognitive.TaskMeaning{SpeechAct: "STABLE_KNOWLEDGE_ANSWER", CapabilityHints: meaning.CapabilityHints, RequestedOutcome: meaning.RequestedOutcome, InformationRequestKind: meaning.InformationRequestKind, ConfidenceMillis: meaning.ConfidenceMillis},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodPost, target.String(), bytes.NewReader(payload))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := c.client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return "", fmt.Errorf("cognitive stable knowledge status %d", response.StatusCode)
|
||||||
|
}
|
||||||
|
var result cognitive.GatewayAdvisoryResponse
|
||||||
|
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if result.FinishReason != cognitive.FinishCompleted || strings.TrimSpace(result.AdvisoryText) == "" {
|
||||||
|
return "", fmt.Errorf("cognitive stable knowledge incomplete: %s", result.FinishReason)
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(result.AdvisoryText), nil
|
||||||
|
}
|
||||||
|
|
||||||
func newCognitiveInterpretationClient(rawURL string, client *http.Client) (cognitiveInterpretationClient, error) {
|
func newCognitiveInterpretationClient(rawURL string, client *http.Client) (cognitiveInterpretationClient, error) {
|
||||||
base, err := url.Parse(rawURL)
|
base, err := url.Parse(rawURL)
|
||||||
if err != nil || base.Scheme == "" || base.Host == "" {
|
if err != nil || base.Scheme == "" || base.Host == "" {
|
||||||
|
|||||||
@@ -45,6 +45,28 @@ func TestReviewResponseUsesCognitiveGatewayAndReturnsOnlyDraftAnswer(t *testing.
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAnswerStableKnowledgeUsesLocalOnlyCognitiveRoute(t *testing.T) {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var request cognitive.GatewayAdvisoryRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||||
|
t.Fatalf("decode stable knowledge request: %v", err)
|
||||||
|
}
|
||||||
|
if request.DataPolicy != capability.DataPolicyLocalOnly || request.Meaning.SpeechAct != "STABLE_KNOWLEDGE_ANSWER" {
|
||||||
|
t.Fatalf("unexpected stable knowledge request: %+v", request)
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(cognitive.GatewayAdvisoryResponse{Version: cognitive.CreatorAdvisoryV1, RequestID: request.RequestID, AdvisoryText: "Санкт-Петербург — город в России.", FinishReason: cognitive.FinishCompleted})
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
client, err := newCognitiveInterpretationClient(server.URL, server.Client())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
answer, err := client.AnswerStableKnowledge(context.Background(), identity.CreatorSession{ActorID: "actor", PrincipalID: "principal"}, "Питер — это где?", "", cognitive.TaskMeaning{SpeechAct: "QUESTION"})
|
||||||
|
if err != nil || answer != "Санкт-Петербург — город в России." {
|
||||||
|
t.Fatalf("answer=%q err=%v", answer, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGenerateImageUsesDedicatedCognitiveMediaRoute(t *testing.T) {
|
func TestGenerateImageUsesDedicatedCognitiveMediaRoute(t *testing.T) {
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != http.MethodPost || r.URL.Path != "/v1/multimodal/generate-image" {
|
if r.Method != http.MethodPost || r.URL.Path != "/v1/multimodal/generate-image" {
|
||||||
|
|||||||
+101
-9
@@ -821,8 +821,18 @@ func main() {
|
|||||||
Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID(fmt.Sprintf("plan:%s:%d", planID, index)), Question: searchQuery, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"},
|
Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID(fmt.Sprintf("plan:%s:%d", planID, index)), Question: searchQuery, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"},
|
||||||
PropositionKey: fmt.Sprintf("question:%s:%d", utterance.ID, index), Query: searchQuery,
|
PropositionKey: fmt.Sprintf("question:%s:%d", utterance.ID, index), Query: searchQuery,
|
||||||
})
|
})
|
||||||
cancelResearch()
|
|
||||||
reply, backed := renderResearchReply(searchQuery, result, researchErr)
|
reply, backed := renderResearchReply(searchQuery, result, researchErr)
|
||||||
|
if !backed && cognitiveAvailable {
|
||||||
|
answerCtx, cancelAnswer := context.WithTimeout(r.Context(), 12*time.Second)
|
||||||
|
answer, answerErr := cognitiveClient.AnswerStableKnowledge(answerCtx, session, part, personalMemory.ContextText(), cognitive.TaskMeaning{
|
||||||
|
SpeechAct: string(semantic.Interpretation.SpeechAct), CapabilityHints: toCapabilityKinds(semantic.CapabilityHints), RequestedOutcome: semantic.Interpretation.RequestedOutcome, InformationRequestKind: semantic.InformationRequestKind, ConfidenceMillis: semantic.Interpretation.ConfidenceMillis,
|
||||||
|
})
|
||||||
|
cancelAnswer()
|
||||||
|
if answerErr == nil && stableKnowledgeAnswer(answer) {
|
||||||
|
reply, backed = answer, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cancelResearch()
|
||||||
if backed {
|
if backed {
|
||||||
researchBacked = true
|
researchBacked = true
|
||||||
}
|
}
|
||||||
@@ -850,6 +860,17 @@ func main() {
|
|||||||
needsCognition = false
|
needsCognition = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if planningReply == "" && needsCognition && semantic.Interpretation.SpeechAct == interaction.SpeechActQuestion && !hasChatRoute(routePlan, chatRouteResearch) && !creativeRequest {
|
||||||
|
answerCtx, cancelAnswer := context.WithTimeout(r.Context(), 12*time.Second)
|
||||||
|
answer, answerErr := cognitiveClient.AnswerStableKnowledge(answerCtx, session, effectiveTaskMessage, personalMemory.ContextText(), cognitive.TaskMeaning{
|
||||||
|
SpeechAct: string(semantic.Interpretation.SpeechAct), CapabilityHints: toCapabilityKinds(semantic.CapabilityHints), RequestedOutcome: semantic.Interpretation.RequestedOutcome, InformationRequestKind: semantic.InformationRequestKind, ConfidenceMillis: semantic.Interpretation.ConfidenceMillis,
|
||||||
|
})
|
||||||
|
cancelAnswer()
|
||||||
|
if answerErr == nil && stableKnowledgeAnswer(answer) {
|
||||||
|
planningReply = answer
|
||||||
|
needsCognition = false
|
||||||
|
}
|
||||||
|
}
|
||||||
if planningReply == "" && needsCognition && cognitiveAttempted && !cognitiveAvailable {
|
if planningReply == "" && needsCognition && cognitiveAttempted && !cognitiveAvailable {
|
||||||
planningReply = humanCognitiveDegradedReply(utterance.Content)
|
planningReply = humanCognitiveDegradedReply(utterance.Content)
|
||||||
needsCognition = false
|
needsCognition = false
|
||||||
@@ -1780,6 +1801,9 @@ func renderResearchReply(query string, result epistemics.ResearchResult, researc
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(lines) == 0 {
|
if len(lines) == 0 {
|
||||||
|
if identifiers := requestedResearchIdentifiers(query); len(identifiers) > 0 {
|
||||||
|
return "Не нашёл проверяемых данных о «" + strings.Join(identifiers, "», «") + "». Возможно, название написано иначе; пришлите ссылку или уточните написание, и я проверю.", false
|
||||||
|
}
|
||||||
return "Проверяемых данных пока не найдено. Могу повторить поиск или уточнить, что именно проверить.", false
|
return "Проверяемых данных пока не найдено. Могу повторить поиск или уточнить, что именно проверить.", false
|
||||||
}
|
}
|
||||||
if isInternetStatusQuery(query) {
|
if isInternetStatusQuery(query) {
|
||||||
@@ -1788,12 +1812,10 @@ func renderResearchReply(query string, result epistemics.ResearchResult, researc
|
|||||||
if nearestFlightQuery(query) && !containsFlightTimeEvidence(strings.Join(lines, " ")) {
|
if nearestFlightQuery(query) && !containsFlightTimeEvidence(strings.Join(lines, " ")) {
|
||||||
return "Нашёл расписание по маршруту, но точное время ближайшего вылета в доступных фрагментах не указано. Откройте источник и выберите ближайший рейс:\n\n" + strings.Join(lines, "\n\n"), true
|
return "Нашёл расписание по маршруту, но точное время ближайшего вылета в доступных фрагментах не указано. Откройте источник и выберите ближайший рейс:\n\n" + strings.Join(lines, "\n\n"), true
|
||||||
}
|
}
|
||||||
reply := "Нашёл проверяемые данные:\n\n" + strings.Join(lines, "\n\n")
|
if trainScheduleQuery(query) && !containsScheduleTimeEvidence(strings.Join(lines, " ")) {
|
||||||
lowerQuery := strings.ToLower(query)
|
return "Нашёл страницу расписания по маршруту, но в доступных фрагментах нет точного времени отправления:\n\n" + strings.Join(lines, "\n\n"), true
|
||||||
if (strings.Contains(lowerQuery, "цен") || strings.Contains(lowerQuery, "стоим")) && !containsPriceEvidence(reply) {
|
|
||||||
reply = "Актуальная цена в найденных фрагментах не указана, поэтому не буду придумывать сумму. Вот страницы, где её можно проверить:\n" + reply
|
|
||||||
}
|
}
|
||||||
return reply, true
|
return "Нашёл проверяемые данные:\n\n" + strings.Join(lines, "\n\n"), true
|
||||||
}
|
}
|
||||||
|
|
||||||
func isInternetStatusQuery(query string) bool {
|
func isInternetStatusQuery(query string) bool {
|
||||||
@@ -1812,6 +1834,12 @@ func nearestFlightQuery(query string) bool {
|
|||||||
// search-engine snippets from becoming a human-facing answer when a search
|
// search-engine snippets from becoming a human-facing answer when a search
|
||||||
// term has a common non-travel meaning.
|
// term has a common non-travel meaning.
|
||||||
func researchFindingMatchesIntent(query string, finding epistemics.ResearchFinding) bool {
|
func researchFindingMatchesIntent(query string, finding epistemics.ResearchFinding) bool {
|
||||||
|
if !findingContainsRequestedIdentifier(query, finding) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if ticketSearchQuery(query) && !ticketFindingMatchesDestination(query, finding) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
if !nearestFlightQuery(query) {
|
if !nearestFlightQuery(query) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -1841,6 +1869,62 @@ func researchFindingMatchesIntent(query string, finding epistemics.ResearchFindi
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ticketSearchQuery(query string) bool {
|
||||||
|
return interactiondomain.TicketSearchDestination(query) != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func ticketFindingMatchesDestination(query string, finding epistemics.ResearchFinding) bool {
|
||||||
|
destination := strings.ToLower(interactiondomain.TicketSearchDestination(query))
|
||||||
|
if destination == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// The source title or URL may describe a category; human-facing proof must
|
||||||
|
// mention the requested destination in the actual displayed excerpt.
|
||||||
|
return strings.Contains(strings.ToLower(finding.Excerpt.Text), destination)
|
||||||
|
}
|
||||||
|
|
||||||
|
// findingContainsRequestedIdentifier prevents a generic landing page from
|
||||||
|
// being presented as a result for a concrete model, article or brand request.
|
||||||
|
// Identifiers are detected by their syntax, not by a catalogue of providers or
|
||||||
|
// entities, so the rule stays valid as user vocabulary changes.
|
||||||
|
func findingContainsRequestedIdentifier(query string, finding epistemics.ResearchFinding) bool {
|
||||||
|
identifiers := requestedResearchIdentifiers(query)
|
||||||
|
if len(identifiers) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
evidence := strings.ToLower(strings.Join([]string{finding.Source.Title, finding.Source.Locator, finding.Excerpt.Text}, " "))
|
||||||
|
for _, identifier := range identifiers {
|
||||||
|
if !strings.Contains(evidence, strings.ToLower(identifier)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestedResearchIdentifiers(query string) []string {
|
||||||
|
rawIdentifiers := regexp.MustCompile(`(?i)[a-z0-9][a-z0-9._-]{3,}`).FindAllString(query, -1)
|
||||||
|
identifiers := make([]string, 0, len(rawIdentifiers))
|
||||||
|
exact := make([]string, 0, len(rawIdentifiers))
|
||||||
|
for _, identifier := range rawIdentifiers {
|
||||||
|
if researchDateIdentifier(identifier) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
identifiers = append(identifiers, identifier)
|
||||||
|
if strings.ContainsAny(identifier, "._-") || strings.IndexFunc(identifier, func(r rune) bool { return r >= '0' && r <= '9' }) >= 0 {
|
||||||
|
exact = append(exact, identifier)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(exact) > 0 {
|
||||||
|
return exact
|
||||||
|
}
|
||||||
|
return identifiers
|
||||||
|
}
|
||||||
|
|
||||||
|
func researchDateIdentifier(value string) bool {
|
||||||
|
return regexp.MustCompile(`^\d{1,2}[.-]\d{1,2}[.-]\d{2,4}$`).MatchString(value) ||
|
||||||
|
regexp.MustCompile(`^\d{4}[.-]\d{1,2}[.-]\d{1,2}$`).MatchString(value)
|
||||||
|
}
|
||||||
|
|
||||||
// nearestFlightRouteTerms retains only the two endpoint-shaped terms from a
|
// nearestFlightRouteTerms retains only the two endpoint-shaped terms from a
|
||||||
// structured flight search. It has no city or provider vocabulary: endpoint
|
// structured flight search. It has no city or provider vocabulary: endpoint
|
||||||
// relevance is determined from the request itself.
|
// relevance is determined from the request itself.
|
||||||
@@ -1902,9 +1986,17 @@ func humanResearchExcerpt(query, raw string) string {
|
|||||||
return text
|
return text
|
||||||
}
|
}
|
||||||
|
|
||||||
func containsPriceEvidence(value string) bool {
|
func trainScheduleQuery(query string) bool {
|
||||||
pricePattern := regexp.MustCompile(`(?i)(\d[\d\s.,]{2,})(?:\s*(?:₽|руб\.?|р\.?|usd|\$|€))`)
|
lower := strings.ToLower(query)
|
||||||
return pricePattern.MatchString(value)
|
return strings.Contains(lower, "поезд") && strings.Contains(lower, "время отправления")
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsScheduleTimeEvidence(value string) bool {
|
||||||
|
return regexp.MustCompile(`\b(?:[01]?\d|2[0-3]):[0-5]\d\b`).MatchString(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func stableKnowledgeAnswer(answer string) bool {
|
||||||
|
return strings.TrimSpace(answer) != "" && strings.TrimSpace(answer) != "NEEDS_VERIFIED_RESEARCH"
|
||||||
}
|
}
|
||||||
|
|
||||||
func reviewPreservesResearchEvidence(reviewed, draft string) bool {
|
func reviewPreservesResearchEvidence(reviewed, draft string) bool {
|
||||||
|
|||||||
@@ -58,6 +58,49 @@ func TestNearestFlightEvidenceRequiresBothRouteEndpointsWhenKnown(t *testing.T)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTicketReplyRejectsGenericCategoryPageWithoutDestination(t *testing.T) {
|
||||||
|
query := "найди билеты до Ялты сегодня"
|
||||||
|
generic := epistemics.ResearchFinding{Source: epistemics.Source{Title: "Купить билеты", Locator: "https://tickets.example"}, Excerpt: epistemics.SourceExcerpt{Text: "Поиск авиабилетов среди множества направлений."}}
|
||||||
|
if researchFindingMatchesIntent(query, generic) {
|
||||||
|
t.Fatal("generic ticket category was presented as destination result")
|
||||||
|
}
|
||||||
|
relevant := epistemics.ResearchFinding{Source: epistemics.Source{Title: "Билеты"}, Excerpt: epistemics.SourceExcerpt{Text: "Билеты до Ялты: варианты на сегодня."}}
|
||||||
|
if !researchFindingMatchesIntent(query, relevant) {
|
||||||
|
t.Fatal("destination-specific ticket result was rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResearchReplyRejectsGenericLandingPageForConcreteIdentifier(t *testing.T) {
|
||||||
|
result := epistemics.ResearchResult{Findings: []epistemics.ResearchFinding{{
|
||||||
|
State: epistemics.FindingSupported,
|
||||||
|
Source: epistemics.Source{Locator: "https://market.example", Title: "Интернет-магазин"},
|
||||||
|
Excerpt: epistemics.SourceExcerpt{Text: "Широкий ассортимент товаров и услуг."},
|
||||||
|
}}}
|
||||||
|
reply, backed := renderResearchReply("на WB бренд marka-wear", result, nil)
|
||||||
|
if backed || !strings.Contains(reply, "marka-wear") || strings.Contains(reply, "wildberries") || !strings.Contains(reply, "уточните написание") {
|
||||||
|
t.Fatalf("generic page was presented as a brand result: %q", reply)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResearchReplyKeepsFindingContainingConcreteIdentifier(t *testing.T) {
|
||||||
|
result := epistemics.ResearchResult{Findings: []epistemics.ResearchFinding{{
|
||||||
|
State: epistemics.FindingSupported,
|
||||||
|
Source: epistemics.Source{Locator: "https://market.example/marka-wear", Title: "Marka-wear"},
|
||||||
|
Excerpt: epistemics.SourceExcerpt{Text: "Бренд marka-wear: товары и карточки."},
|
||||||
|
}}}
|
||||||
|
reply, backed := renderResearchReply("на WB бренд marka-wear", result, nil)
|
||||||
|
if !backed || !strings.Contains(strings.ToLower(reply), "marka-wear") {
|
||||||
|
t.Fatalf("concrete identifier finding was rejected: %q", reply)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResearchIdentifiersExcludeSearchDate(t *testing.T) {
|
||||||
|
identifiers := requestedResearchIdentifiers("ближайший поезд в Петербург сегодня 26.08.2026")
|
||||||
|
if len(identifiers) != 0 {
|
||||||
|
t.Fatalf("search date was treated as a concrete identifier: %#v", identifiers)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestResponseReviewPreservesAttemptedResearchOutcome(t *testing.T) {
|
func TestResponseReviewPreservesAttemptedResearchOutcome(t *testing.T) {
|
||||||
if reviewMayReplacePlanningReply(false, true, false, "Уточните аэропорт.", "Пока не смог получить проверяемый ответ.") {
|
if reviewMayReplacePlanningReply(false, true, false, "Уточните аэропорт.", "Пока не смог получить проверяемый ответ.") {
|
||||||
t.Fatal("review replaced an honest unbacked research outcome")
|
t.Fatal("review replaced an honest unbacked research outcome")
|
||||||
@@ -106,12 +149,12 @@ func TestHumanMemoryInventoryUsesNewestPreference(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestContainsPriceEvidenceDistinguishesLinksFromPrices(t *testing.T) {
|
func TestContainsScheduleTimeEvidence(t *testing.T) {
|
||||||
if containsPriceEvidence("RTX 4090 — market.yandex.ru") {
|
if containsScheduleTimeEvidence("расписание поездов и цена билета") {
|
||||||
t.Fatal("a product link is not price evidence")
|
t.Fatal("a price or schedule label is not a departure time")
|
||||||
}
|
}
|
||||||
if !containsPriceEvidence("Цена: 189 990 ₽") {
|
if !containsScheduleTimeEvidence("Отправление в 07:45") {
|
||||||
t.Fatal("expected a currency amount to count as price evidence")
|
t.Fatal("expected an explicit departure time to be recognized")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -251,6 +251,38 @@ func TestChatMessageUsesLocalAdvisoryForOrdinaryConversationalQuestion(t *testin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestChatMessagePreservesCompletedCoreAnswerInsteadOfSecondAdvisory(t *testing.T) {
|
||||||
|
core := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch {
|
||||||
|
case r.Method == http.MethodGet && r.URL.Path == "/v1/creator/sessions/current":
|
||||||
|
_ = json.NewEncoder(w).Encode(identity.CreatorSession{ActorID: "actor-1", PrincipalID: "principal-1"})
|
||||||
|
case r.Method == http.MethodPost && r.URL.Path == "/v1/creator/chat/messages":
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
_ = json.NewEncoder(w).Encode(interaction.ChatMessageResponse{ConversationID: "conversation-1", UtteranceID: "utterance-1", SpeechAct: interaction.SpeechActQuestion, NeedsCognition: true, FallbackText: "fallback", PlanningReply: "Готовый ответ ядра."})
|
||||||
|
default:
|
||||||
|
t.Fatalf("unexpected core route %s %s", r.Method, r.URL.Path)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer core.Close()
|
||||||
|
cognitiveRuntime := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
t.Fatal("completed core answer must not be replaced by a second advisory")
|
||||||
|
}))
|
||||||
|
defer cognitiveRuntime.Close()
|
||||||
|
handler, err := newHandler(core.URL, "http://continuity", "http://commit", core.Client(), cognitiveRuntime.URL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/api/chat/messages", strings.NewReader(`{"message":"Обычный вопрос"}`))
|
||||||
|
request.Header.Set("Authorization", "Bearer session-token")
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, request)
|
||||||
|
var response browserChatResponse
|
||||||
|
if recorder.Code != http.StatusOK || json.NewDecoder(recorder.Body).Decode(&response) != nil || response.ReplyText != "Готовый ответ ядра." {
|
||||||
|
t.Fatalf("unexpected browser response: status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestChatMessageReturnsHumanCapabilityMetadata(t *testing.T) {
|
func TestChatMessageReturnsHumanCapabilityMetadata(t *testing.T) {
|
||||||
core := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
core := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
switch {
|
switch {
|
||||||
|
|||||||
@@ -480,7 +480,10 @@ func (g *gateway) handleChatMessage(w http.ResponseWriter, r *http.Request) {
|
|||||||
saved.NeedsCognition = false
|
saved.NeedsCognition = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if saved.NeedsCognition && !saved.WorkPlanned && saved.Clarification != interaction.ClarificationRequired {
|
// Core owns the completed planning answer. The browser may ask for a local
|
||||||
|
// advisory only when core explicitly left the turn unanswered; otherwise a
|
||||||
|
// second model pass can replace a grounded result with a weaker one.
|
||||||
|
if saved.NeedsCognition && saved.PlanningReply == "" && !saved.WorkPlanned && saved.Clarification != interaction.ClarificationRequired {
|
||||||
cognition = "unavailable"
|
cognition = "unavailable"
|
||||||
requestID, idErr := ids.New()
|
requestID, idErr := ids.New()
|
||||||
if idErr == nil {
|
if idErr == nil {
|
||||||
|
|||||||
@@ -612,7 +612,7 @@ func sourceDependentQuestion(primary, secondary interaction.SpeechAct, tokens []
|
|||||||
currentCue := containsStemInTokens(tokens, "сейчас", "сегодня", "текущ", "актуаль", "последн", "прямо")
|
currentCue := containsStemInTokens(tokens, "сейчас", "сегодня", "текущ", "актуаль", "последн", "прямо")
|
||||||
observedStateCue := containsStemInTokens(tokens, "погод", "температур", "осад", "ветер", "курс", "цен", "стоим", "новост", "распис", "событ", "статус", "доступен", "работает", "запущен", "срок") || approximateToken(tokens, "погод", 2)
|
observedStateCue := containsStemInTokens(tokens, "погод", "температур", "осад", "ветер", "курс", "цен", "стоим", "новост", "распис", "событ", "статус", "доступен", "работает", "запущен", "срок") || approximateToken(tokens, "погод", 2)
|
||||||
placeSearchCue := containsStemInTokens(tokens, "ресторан", "кафе", "отел", "магаз", "мест", "ближ", "адрес", "организац", "бренд", "товар", "артикул", "продавец", "маркетплейс", "wildberries", "wb")
|
placeSearchCue := containsStemInTokens(tokens, "ресторан", "кафе", "отел", "магаз", "мест", "ближ", "адрес", "организац", "бренд", "товар", "артикул", "продавец", "маркетплейс", "wildberries", "wb")
|
||||||
travelSearchCue := containsStemInTokens(tokens, "билет", "рейс", "самолет", "самолёт", "вылет", "поезд", "автобус", "перелет", "перелёт", "отправлен", "прибыт", "расстоян", "километр", "добрат", "маршрут")
|
travelSearchCue := travelCue(tokens) || containsStemInTokens(tokens, "отправлен", "прибыт", "расстоян", "километр", "добрат", "маршрут")
|
||||||
timeDifferenceCue := containsStemInTokens(tokens, "разниц") && containsStemInTokens(tokens, "времен", "час")
|
timeDifferenceCue := containsStemInTokens(tokens, "разниц") && containsStemInTokens(tokens, "времен", "час")
|
||||||
return currentCue || observedStateCue || placeSearchCue || travelSearchCue || timeDifferenceCue
|
return currentCue || observedStateCue || placeSearchCue || travelSearchCue || timeDifferenceCue
|
||||||
}
|
}
|
||||||
@@ -622,13 +622,33 @@ func sourceDependentQuestion(primary, secondary interaction.SpeechAct, tokens []
|
|||||||
// source-dependent concepts such as weather.
|
// source-dependent concepts such as weather.
|
||||||
func approximateToken(tokens []string, target string, maxDistance int) bool {
|
func approximateToken(tokens []string, target string, maxDistance int) bool {
|
||||||
for _, token := range tokens {
|
for _, token := range tokens {
|
||||||
if editDistance([]rune(token), []rune(target)) <= maxDistance {
|
if nearToken(token, target, maxDistance) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func nearToken(token, target string, maxDistance int) bool {
|
||||||
|
if editDistance([]rune(token), []rune(target)) <= maxDistance {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if maxDistance < 1 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
left, right := []rune(token), []rune(target)
|
||||||
|
if len(left) != len(right) || len(left) < 2 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for index := range left {
|
||||||
|
if left[index] == right[index] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return index+1 < len(left) && left[index] == right[index+1] && left[index+1] == right[index] && string(left[index+2:]) == string(right[index+2:])
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func editDistance(left, right []rune) int {
|
func editDistance(left, right []rune) int {
|
||||||
previous := make([]int, len(right)+1)
|
previous := make([]int, len(right)+1)
|
||||||
for index := range previous {
|
for index := range previous {
|
||||||
|
|||||||
@@ -50,9 +50,11 @@ func TestNewHumanUtteranceClassifiesReminderAndCapabilityConnectionAsDirective(t
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestPlaneRequestReceivesTravelResearchCapability(t *testing.T) {
|
func TestPlaneRequestReceivesTravelResearchCapability(t *testing.T) {
|
||||||
candidate := BuildDeterministicCandidate("найди ближайший самолет до Казани", "", 100)
|
for _, message := range []string{"найди ближайший самолет до Казани", "найди сомалет до Казани"} {
|
||||||
if !containsToken(candidate.CapabilityHints, "WEB_RESEARCH") {
|
candidate := BuildDeterministicCandidate(message, "", 100)
|
||||||
t.Fatalf("plane request did not select web research: %+v", candidate)
|
if !containsToken(candidate.CapabilityHints, "WEB_RESEARCH") {
|
||||||
|
t.Fatalf("plane request did not select web research for %q: %+v", message, candidate)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -85,6 +85,15 @@ func TestLocalSearchClarification(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTicketSearchDestinationUsesRequestDestination(t *testing.T) {
|
||||||
|
if got := TicketSearchDestination("найди билеты до Ялты сегодня"); got != "Ялты" {
|
||||||
|
t.Fatalf("ticket destination = %q", got)
|
||||||
|
}
|
||||||
|
if got := TicketSearchDestination("найди билеты"); got != "" {
|
||||||
|
t.Fatalf("destination invented without one: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestContinueLocalSearch(t *testing.T) {
|
func TestContinueLocalSearch(t *testing.T) {
|
||||||
history := []interaction.HumanUtterance{{Content: "Найди ближайший ресторан"}}
|
history := []interaction.HumanUtterance{{Content: "Найди ближайший ресторан"}}
|
||||||
if got := ContinueLocalSearch("в Сочи", history); got != "Найди ближайший ресторан в Сочи" {
|
if got := ContinueLocalSearch("в Сочи", history); got != "Найди ближайший ресторан в Сочи" {
|
||||||
@@ -217,6 +226,24 @@ func TestNearestPlaneUsesTravelContextAndCurrentDay(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTravelResearchQueryUsesKnownOriginForTrainSchedule(t *testing.T) {
|
||||||
|
now := time.Date(2026, time.August, 26, 9, 0, 0, 0, time.UTC)
|
||||||
|
history := []interaction.HumanUtterance{{Content: "я сейчас в Москве"}}
|
||||||
|
got := TravelResearchQuery("найди поезд до Петербурга", history, now)
|
||||||
|
want := "расписание поездов из Москве в Петербурга время отправления сегодня 26.08.2026"
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("train schedule query lost route context or primary outcome: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTravelResearchQueryNormalizesNearUnambiguousTravelTypo(t *testing.T) {
|
||||||
|
history := []interaction.HumanUtterance{{Content: "я сейчас в Москве"}}
|
||||||
|
got := TravelResearchQuery("найди сомалет до Казани", history, time.Time{})
|
||||||
|
if !strings.Contains(got, "самолёт") || !strings.Contains(got, "пункт отправления: Москве") {
|
||||||
|
t.Fatalf("travel typo was not normalized with remembered route context: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestIndependentRequestPartsKeepsCoordinatedEntitiesTogether(t *testing.T) {
|
func TestIndependentRequestPartsKeepsCoordinatedEntitiesTogether(t *testing.T) {
|
||||||
if got := IndependentRequestParts("какая разница во времени между Москвой и Шанхаем?"); len(got) != 1 {
|
if got := IndependentRequestParts("какая разница во времени между Москвой и Шанхаем?"); len(got) != 1 {
|
||||||
t.Fatalf("coordinated entities became independent requests: %#v", got)
|
t.Fatalf("coordinated entities became independent requests: %#v", got)
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
// TravelSearchQuery carries the implicit current-day meaning of a nearest
|
// TravelSearchQuery carries the implicit current-day meaning of a nearest
|
||||||
// flight request into the research adapter.
|
// flight request into the research adapter.
|
||||||
func TravelSearchQuery(message string, now time.Time) string {
|
func TravelSearchQuery(message string, now time.Time) string {
|
||||||
cleaned := strings.TrimSpace(StripAssistantVocative(message))
|
cleaned := normalizedTravelSearchText(message)
|
||||||
tokens := semanticTokens(cleaned)
|
tokens := semanticTokens(cleaned)
|
||||||
if !travelCue(tokens) || !containsStemInTokens(tokens, "ближ") || isTravelDateSpecified(tokens) {
|
if !travelCue(tokens) || !containsStemInTokens(tokens, "ближ") || isTravelDateSpecified(tokens) {
|
||||||
return cleaned
|
return cleaned
|
||||||
@@ -21,6 +21,25 @@ func TravelSearchQuery(message string, now time.Time) string {
|
|||||||
return cleaned + " сегодня " + now.Format("02.01.2006")
|
return cleaned + " сегодня " + now.Format("02.01.2006")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// normalizedTravelSearchText corrects only a near-unambiguous typo in a
|
||||||
|
// capability word before an external query. The original utterance is kept by
|
||||||
|
// Conversation; this is a replaceable search-skill normalization, not a fact
|
||||||
|
// about a user, city or provider.
|
||||||
|
func normalizedTravelSearchText(message string) string {
|
||||||
|
tokens := semanticTokens(StripAssistantVocative(message))
|
||||||
|
changed := false
|
||||||
|
for index, token := range tokens {
|
||||||
|
if nearToken(token, "самолет", 2) || nearToken(token, "самолёт", 2) {
|
||||||
|
tokens[index] = "самолёт"
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !changed {
|
||||||
|
return strings.TrimSpace(StripAssistantVocative(message))
|
||||||
|
}
|
||||||
|
return strings.Join(tokens, " ")
|
||||||
|
}
|
||||||
|
|
||||||
// TravelResearchQuery keeps route and distance questions tied to a known
|
// TravelResearchQuery keeps route and distance questions tied to a known
|
||||||
// origin before they reach a generic web search. The history is semantic
|
// origin before they reach a generic web search. The history is semantic
|
||||||
// context, not a list of example-specific answers.
|
// context, not a list of example-specific answers.
|
||||||
@@ -46,6 +65,12 @@ func TravelResearchQuery(message string, history []interaction.HumanUtterance, n
|
|||||||
if origin != "" && !containsStemInTokens(tokens, "из", "откуда", "от") {
|
if origin != "" && !containsStemInTokens(tokens, "из", "откуда", "от") {
|
||||||
query += " отправление из " + origin
|
query += " отправление из " + origin
|
||||||
}
|
}
|
||||||
|
} else if trainScheduleRequest(tokens) {
|
||||||
|
origin := travelContextOrigin(history)
|
||||||
|
destination := travelContextDestinationFromTokens(tokens)
|
||||||
|
if origin != "" && destination != "" {
|
||||||
|
return trainScheduleResearchQuery(origin, destination, now, containsStemInTokens(tokens, "ближ"))
|
||||||
|
}
|
||||||
} else if travelCue(tokens) && !containsStemInTokens(tokens, "из", "откуда", "от") {
|
} else if travelCue(tokens) && !containsStemInTokens(tokens, "из", "откуда", "от") {
|
||||||
origin := travelContextOrigin(history)
|
origin := travelContextOrigin(history)
|
||||||
destination := travelContextDestinationFromTokens(tokens)
|
destination := travelContextDestinationFromTokens(tokens)
|
||||||
@@ -61,6 +86,21 @@ func TravelResearchQuery(message string, history []interaction.HumanUtterance, n
|
|||||||
return query
|
return query
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// trainScheduleResearchQuery formulates an observed schedule request from the
|
||||||
|
// user's route and remembered origin. It contains no city, provider or answer
|
||||||
|
// catalogue: actual departure data remains evidence from the selected source.
|
||||||
|
func trainScheduleResearchQuery(origin, destination string, now time.Time, nearest bool) string {
|
||||||
|
prefix := "расписание поездов"
|
||||||
|
if nearest {
|
||||||
|
prefix = "ближайшие поезда"
|
||||||
|
}
|
||||||
|
query := prefix + " из " + origin + " в " + destination + " время отправления"
|
||||||
|
if !now.IsZero() {
|
||||||
|
query += " сегодня " + now.Format("02.01.2006")
|
||||||
|
}
|
||||||
|
return query
|
||||||
|
}
|
||||||
|
|
||||||
// nearestAirTravelSearchQuery is a capability-local search formulation, not a
|
// nearestAirTravelSearchQuery is a capability-local search formulation, not a
|
||||||
// provider or place lookup. It removes conversational imperatives while
|
// provider or place lookup. It removes conversational imperatives while
|
||||||
// preserving the two user-derived route endpoints and the implicit current-day
|
// preserving the two user-derived route endpoints and the implicit current-day
|
||||||
@@ -236,6 +276,16 @@ func ContinueTravelDate(message string, history []interaction.HumanUtterance) st
|
|||||||
return strings.TrimSpace(latest + " " + current)
|
return strings.TrimSpace(latest + " " + current)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TicketSearchDestination extracts the destination from a ticket request
|
||||||
|
// without assigning any city or travel-provider meaning in core code.
|
||||||
|
func TicketSearchDestination(message string) string {
|
||||||
|
tokens := semanticTokens(StripAssistantVocative(message))
|
||||||
|
if !containsStemInTokens(tokens, "билет") {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return travelContextDestinationFromTokens(tokens)
|
||||||
|
}
|
||||||
|
|
||||||
// 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 {
|
||||||
@@ -388,7 +438,12 @@ func capitalizeWord(value string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func travelCue(tokens []string) bool {
|
func travelCue(tokens []string) bool {
|
||||||
return containsStemInTokens(tokens, "билет", "рейс", "самолет", "самолёт", "вылет", "поезд", "автобус", "перелет", "перелёт")
|
return containsStemInTokens(tokens, "билет", "рейс", "самолет", "самолёт", "вылет", "поезд", "автобус", "перелет", "перелёт") || approximateToken(tokens, "самолет", 2) || approximateToken(tokens, "самолёт", 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
func trainScheduleRequest(tokens []string) bool {
|
||||||
|
return containsStemInTokens(tokens, "поезд") &&
|
||||||
|
(containsStemInTokens(tokens, "найд", "ближ", "расписан", "отправ", "прибуд", "едет", "едут") || len(tokens) > 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func nearestAirTravelRequest(tokens []string) bool {
|
func nearestAirTravelRequest(tokens []string) bool {
|
||||||
|
|||||||
Reference in New Issue
Block a user