DEV-000062 human intent project context
This commit is contained in:
@@ -99,13 +99,13 @@ func NewHumanUtterance(conversation interaction.Conversation, request interactio
|
||||
func ClassifySpeechAct(message string, corrects interaction.HumanUtteranceID) interaction.SpeechAct {
|
||||
lower := strings.ToLower(strings.TrimSpace(message))
|
||||
switch {
|
||||
case corrects != "" || strings.Contains(lower, "исправ") || strings.Contains(lower, "не так"):
|
||||
case corrects != "" || strings.Contains(lower, "исправ") || strings.Contains(lower, "не так") || strings.HasPrefix(lower, "нет,"):
|
||||
return interaction.SpeechActCorrection
|
||||
case strings.Contains(lower, "?") || strings.HasPrefix(lower, "что ") || strings.HasPrefix(lower, "как ") || strings.HasPrefix(lower, "почему ") || strings.HasPrefix(lower, "кто "):
|
||||
return interaction.SpeechActQuestion
|
||||
case strings.Contains(lower, "проверь") || strings.Contains(lower, "исслед") || strings.Contains(lower, "разбер"):
|
||||
return interaction.SpeechActRequestToInvestigate
|
||||
case strings.Contains(lower, "сделай") || strings.Contains(lower, "запусти") || strings.Contains(lower, "создай") || strings.Contains(lower, "настрой"):
|
||||
case strings.Contains(lower, "сделай") || strings.Contains(lower, "запусти") || strings.Contains(lower, "создай") || strings.Contains(lower, "настрой") || strings.Contains(lower, "добавь") || strings.Contains(lower, "измени") || strings.Contains(lower, "поменяй") || strings.Contains(lower, "используй") || strings.Contains(lower, "удали") || strings.Contains(lower, "удалить"):
|
||||
return interaction.SpeechActDirective
|
||||
case strings.HasPrefix(lower, "я решил") || strings.Contains(lower, "решение"):
|
||||
return interaction.SpeechActDecision
|
||||
@@ -113,9 +113,9 @@ func ClassifySpeechAct(message string, corrects interaction.HumanUtteranceID) in
|
||||
return interaction.SpeechActPreference
|
||||
case strings.HasPrefix(lower, "думаю") || strings.Contains(lower, "гипотез"):
|
||||
return interaction.SpeechActHypothesis
|
||||
case strings.Contains(lower, "да") || strings.Contains(lower, "подтверж"):
|
||||
case lower == "да" || strings.HasPrefix(lower, "да,") || strings.Contains(lower, "подтверж"):
|
||||
return interaction.SpeechActConfirmation
|
||||
case strings.Contains(lower, "нет") || strings.Contains(lower, "отмен"):
|
||||
case lower == "нет" || strings.HasPrefix(lower, "нет,") || strings.Contains(lower, "отмен"):
|
||||
return interaction.SpeechActRejection
|
||||
case strings.Contains(lower, "привет") || strings.Contains(lower, "здравств"):
|
||||
return interaction.SpeechActConversational
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/epistemics"
|
||||
"git.cin.su/m/Assistant/contracts/interaction"
|
||||
"git.cin.su/m/Assistant/contracts/situation"
|
||||
"git.cin.su/m/Assistant/platform/ids"
|
||||
)
|
||||
|
||||
type SemanticResult struct {
|
||||
Interpretation interaction.UtteranceInterpretation
|
||||
Projects []interaction.ProjectReference
|
||||
Relations []interaction.InteractionRelation
|
||||
ActiveFocus *situation.ActiveProjectFocus
|
||||
Reply string
|
||||
NeedsCognition bool
|
||||
}
|
||||
|
||||
func InterpretUtterance(utterance interaction.HumanUtterance, projects []situation.ProjectDescriptor, previousFocus *situation.ActiveProjectFocus, now time.Time) (SemanticResult, error) {
|
||||
act := ClassifySpeechAct(utterance.Content, utterance.CorrectsUtteranceID)
|
||||
interpretationID, err := ids.New()
|
||||
if err != nil {
|
||||
return SemanticResult{}, err
|
||||
}
|
||||
millis := now.UnixMilli()
|
||||
result := SemanticResult{
|
||||
Interpretation: interaction.UtteranceInterpretation{
|
||||
ID: interaction.InterpretationID(interpretationID),
|
||||
UtteranceID: utterance.ID,
|
||||
SpeechAct: act,
|
||||
ConfidenceMillis: confidenceFor(act),
|
||||
Source: "deterministic-v1",
|
||||
AssertionVerification: string(epistemics.VerificationUnverified),
|
||||
RequestedOutcome: requestedOutcome(utterance.Content, act),
|
||||
Clarification: interaction.ClarificationNotRequired,
|
||||
RecordedAtUnixMillis: millis,
|
||||
},
|
||||
NeedsCognition: NeedsCognition(act),
|
||||
}
|
||||
explicitFocus := explicitProjectFocus(utterance.Content, projects)
|
||||
projectRefs, err := projectReferences(utterance, projects, explicitFocus, previousFocus, millis)
|
||||
if err != nil {
|
||||
return SemanticResult{}, err
|
||||
}
|
||||
result.Projects = projectRefs
|
||||
if explicitFocus != nil {
|
||||
result.ActiveFocus = &situation.ActiveProjectFocus{
|
||||
ActorID: utterance.ActorID,
|
||||
PrincipalID: utterance.PrincipalID,
|
||||
ProjectID: explicitFocus.ProjectID,
|
||||
ProjectDisplayName: explicitFocus.ProjectDisplayName,
|
||||
Provenance: situation.ProjectResolutionExplicit,
|
||||
ConfidenceMillis: explicitFocus.ConfidenceMillis,
|
||||
SourceUtteranceID: string(utterance.ID),
|
||||
UpdatedAtUnixMillis: millis,
|
||||
}
|
||||
}
|
||||
if isAmbiguousDestructive(act, utterance.Content, result.Projects) {
|
||||
result.Interpretation.Clarification = interaction.ClarificationRequired
|
||||
result.Reply = "Уточните проект и цель: это потенциально разрушительное изменение, а текущая ссылка недостаточно надёжна."
|
||||
return result, nil
|
||||
}
|
||||
if act == interaction.SpeechActCorrection {
|
||||
relations, err := correctionRelations(utterance, millis)
|
||||
if err != nil {
|
||||
return SemanticResult{}, err
|
||||
}
|
||||
result.Relations = append(result.Relations, relations...)
|
||||
}
|
||||
result.Reply = semanticReply(utterance.Content, result, previousFocus)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func explicitProjectFocus(message string, projects []situation.ProjectDescriptor) *interaction.ProjectReference {
|
||||
lower := strings.ToLower(message)
|
||||
if !(strings.Contains(lower, "работаем с") || strings.Contains(lower, "вернемся к") || strings.Contains(lower, "вернёмся к") || strings.HasPrefix(strings.TrimSpace(lower), "теперь ")) {
|
||||
return nil
|
||||
}
|
||||
for _, project := range projects {
|
||||
for _, alias := range projectAliases(project) {
|
||||
if strings.Contains(lower, alias) {
|
||||
return &interaction.ProjectReference{ProjectID: project.ID, ProjectDisplayName: project.DisplayName, Provenance: situation.ProjectResolutionExplicit, ConfidenceMillis: 980}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func projectReferences(utterance interaction.HumanUtterance, projects []situation.ProjectDescriptor, explicit *interaction.ProjectReference, previousFocus *situation.ActiveProjectFocus, millis int64) ([]interaction.ProjectReference, error) {
|
||||
if explicit != nil {
|
||||
ref, err := newProjectReference(utterance.ID, explicit.ProjectID, explicit.ProjectDisplayName, interaction.ProjectRolePrimary, explicit.Provenance, explicit.ConfidenceMillis, millis)
|
||||
return []interaction.ProjectReference{ref}, err
|
||||
}
|
||||
lower := strings.ToLower(utterance.Content)
|
||||
var refs []interaction.ProjectReference
|
||||
for _, project := range projects {
|
||||
for _, alias := range projectAliases(project) {
|
||||
if strings.Contains(lower, alias) {
|
||||
role := projectRoleForAlias(lower, alias)
|
||||
ref, err := newProjectReference(utterance.ID, project.ID, project.DisplayName, role, situation.ProjectResolutionEntityReference, 850, millis)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
refs = append(refs, ref)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(refs) == 0 && previousFocus != nil && strings.Contains(lower, "туда") {
|
||||
ref, err := newProjectReference(utterance.ID, previousFocus.ProjectID, previousFocus.ProjectDisplayName, interaction.ProjectRolePrimary, situation.ProjectResolutionInheritedFocus, 700, millis)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
refs = append(refs, ref)
|
||||
}
|
||||
if len(refs) > 1 {
|
||||
hasPrimary := false
|
||||
for _, ref := range refs {
|
||||
hasPrimary = hasPrimary || ref.Role == interaction.ProjectRolePrimary
|
||||
}
|
||||
if !hasPrimary {
|
||||
refs[len(refs)-1].Role = interaction.ProjectRolePrimary
|
||||
}
|
||||
}
|
||||
return refs, nil
|
||||
}
|
||||
|
||||
func projectRoleForAlias(lower string, alias string) interaction.ProjectReferenceRole {
|
||||
aliasIndex := strings.Index(lower, alias)
|
||||
if aliasIndex < 0 {
|
||||
return interaction.ProjectRoleRelated
|
||||
}
|
||||
before := strings.TrimSpace(lower[:aliasIndex])
|
||||
afterStart := aliasIndex + len(alias)
|
||||
after := ""
|
||||
if afterStart < len(lower) {
|
||||
after = strings.TrimSpace(lower[afterStart:])
|
||||
}
|
||||
if strings.Contains(before, "как") || strings.Contains(before, "посмотри") || strings.Contains(after, "как источник") {
|
||||
return interaction.ProjectRoleReferenceSource
|
||||
}
|
||||
targetMarkers := []string{"сделай", "добавь", "измени", "поменяй", "перенеси", "используй", "настрой", "в "}
|
||||
for _, marker := range targetMarkers {
|
||||
if strings.Contains(before, marker) {
|
||||
return interaction.ProjectRolePrimary
|
||||
}
|
||||
}
|
||||
return interaction.ProjectRoleRelated
|
||||
}
|
||||
|
||||
func newProjectReference(utteranceID interaction.HumanUtteranceID, projectID situation.ProjectID, display string, role interaction.ProjectReferenceRole, provenance situation.ProjectResolutionProvenance, confidence int64, millis int64) (interaction.ProjectReference, error) {
|
||||
id, err := ids.New()
|
||||
if err != nil {
|
||||
return interaction.ProjectReference{}, err
|
||||
}
|
||||
return interaction.ProjectReference{ID: interaction.ProjectReferenceID(id), UtteranceID: utteranceID, ProjectID: projectID, ProjectDisplayName: display, Role: role, Provenance: provenance, ConfidenceMillis: confidence, RecordedAtUnixMillis: millis}, nil
|
||||
}
|
||||
|
||||
func projectAliases(project situation.ProjectDescriptor) []string {
|
||||
values := []string{strings.ToLower(project.DisplayName), strings.ToLower(string(project.ID))}
|
||||
for _, alias := range project.Aliases {
|
||||
values = append(values, strings.ToLower(string(alias)))
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func correctionRelations(utterance interaction.HumanUtterance, millis int64) ([]interaction.InteractionRelation, error) {
|
||||
if utterance.CorrectsUtteranceID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
id, err := ids.New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []interaction.InteractionRelation{{ID: interaction.InteractionRelationID(id), FromUtteranceID: utterance.ID, ToUtteranceID: utterance.CorrectsUtteranceID, Kind: interaction.RelationSupersedes, RecordedAtUnixMillis: millis}}, nil
|
||||
}
|
||||
|
||||
func confidenceFor(act interaction.SpeechAct) int64 {
|
||||
if act == interaction.SpeechActUnknown {
|
||||
return 300
|
||||
}
|
||||
return 800
|
||||
}
|
||||
|
||||
func requestedOutcome(message string, act interaction.SpeechAct) string {
|
||||
if act == interaction.SpeechActDirective || act == interaction.SpeechActDecision || act == interaction.SpeechActRequestToInvestigate {
|
||||
return strings.TrimSpace(message)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func inheritedFocusAllowed(act interaction.SpeechAct, message string) bool {
|
||||
return strings.Contains(strings.ToLower(message), "туда") && act != interaction.SpeechActUnknown
|
||||
}
|
||||
|
||||
func isAmbiguousDestructive(act interaction.SpeechAct, message string, projects []interaction.ProjectReference) bool {
|
||||
lower := strings.ToLower(message)
|
||||
destructive := strings.Contains(lower, "удали") || strings.Contains(lower, "снеси") || strings.Contains(lower, "удалить")
|
||||
if !destructive || act != interaction.SpeechActDirective {
|
||||
return false
|
||||
}
|
||||
if len(projects) == 0 {
|
||||
return true
|
||||
}
|
||||
return projects[0].Provenance == situation.ProjectResolutionInheritedFocus || projects[0].Provenance == situation.ProjectResolutionInferred
|
||||
}
|
||||
|
||||
func semanticReply(message string, result SemanticResult, previousFocus *situation.ActiveProjectFocus) string {
|
||||
if result.ActiveFocus != nil {
|
||||
return "Фокус переключён: " + result.ActiveFocus.ProjectDisplayName + "."
|
||||
}
|
||||
switch result.Interpretation.SpeechAct {
|
||||
case interaction.SpeechActAssertion:
|
||||
return "Записал как утверждение человека. Это пока не проверенный факт."
|
||||
case interaction.SpeechActDirective:
|
||||
return "Записал просьбу как намерение пользователя. Ничего не выполнено без отдельного подтверждённого действия."
|
||||
case interaction.SpeechActDecision:
|
||||
return "Записал это как явное решение пользователя для дальнейшей обработки."
|
||||
case interaction.SpeechActCorrection:
|
||||
return "Исправление записано новым сообщением; прежняя история сохранена."
|
||||
case interaction.SpeechActQuestion:
|
||||
lower := strings.ToLower(message)
|
||||
if previousFocus != nil && (strings.Contains(lower, "сейчас") || strings.Contains(lower, "что мы") || strings.Contains(lower, "делаем")) {
|
||||
return "Сейчас в фокусе: " + previousFocus.ProjectDisplayName + "."
|
||||
}
|
||||
}
|
||||
return FallbackText(result.Interpretation.SpeechAct)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"git.cin.su/m/Assistant/contracts/interaction"
|
||||
"git.cin.su/m/Assistant/contracts/situation"
|
||||
)
|
||||
|
||||
func TestInterpretUtteranceRecordsExplicitProjectFocus(t *testing.T) {
|
||||
result := interpretForTest(t, "Сейчас работаем с УПО.", nil, "")
|
||||
if result.ActiveFocus == nil || result.ActiveFocus.ProjectID != "upo" {
|
||||
t.Fatalf("expected explicit UPO focus, got %#v", result.ActiveFocus)
|
||||
}
|
||||
if result.Interpretation.SpeechAct != interaction.SpeechActAssertion {
|
||||
t.Fatalf("expected assertion, got %s", result.Interpretation.SpeechAct)
|
||||
}
|
||||
if result.Projects[0].Provenance != situation.ProjectResolutionExplicit {
|
||||
t.Fatalf("expected explicit provenance, got %#v", result.Projects)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpretUtteranceAssertionIsNotVerifiedFact(t *testing.T) {
|
||||
result := interpretForTest(t, "На сервере сейчас свободно 300 ГБ.", nil, "")
|
||||
if result.Interpretation.SpeechAct != interaction.SpeechActAssertion {
|
||||
t.Fatalf("expected assertion, got %s", result.Interpretation.SpeechAct)
|
||||
}
|
||||
if result.Interpretation.AssertionVerification != "UNVERIFIED" || !strings.Contains(result.Reply, "не проверенный факт") {
|
||||
t.Fatalf("expected unverified human assertion, got %#v reply=%q", result.Interpretation, result.Reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpretUtteranceDirectiveRecordsOutcomeWithoutExecution(t *testing.T) {
|
||||
result := interpretForTest(t, "Поменяй базу на УПО1.", activeFocus("upo", "УПО"), "")
|
||||
if result.Interpretation.SpeechAct != interaction.SpeechActDirective {
|
||||
t.Fatalf("expected directive, got %s", result.Interpretation.SpeechAct)
|
||||
}
|
||||
if result.Interpretation.RequestedOutcome == "" || !strings.Contains(result.Reply, "Ничего не выполнено") {
|
||||
t.Fatalf("expected non-executed requested outcome, got %#v reply=%q", result.Interpretation, result.Reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpretUtteranceCorrectionIsAppendOnlySupersedes(t *testing.T) {
|
||||
result := interpretForTest(t, "Нет, используй УПО2.", activeFocus("upo", "УПО"), "utterance-previous")
|
||||
if result.Interpretation.SpeechAct != interaction.SpeechActCorrection {
|
||||
t.Fatalf("expected correction, got %s", result.Interpretation.SpeechAct)
|
||||
}
|
||||
if len(result.Relations) != 1 || result.Relations[0].Kind != interaction.RelationSupersedes || result.Relations[0].ToUtteranceID != "utterance-previous" {
|
||||
t.Fatalf("expected supersedes relation, got %#v", result.Relations)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpretUtteranceQuestionAboutCurrentWorkUsesFocus(t *testing.T) {
|
||||
result := interpretForTest(t, "Что мы сейчас делаем?", activeFocus("assistant", "Assistant"), "")
|
||||
if result.Interpretation.SpeechAct != interaction.SpeechActQuestion {
|
||||
t.Fatalf("expected question, got %s", result.Interpretation.SpeechAct)
|
||||
}
|
||||
if !strings.Contains(result.Reply, "Assistant") {
|
||||
t.Fatalf("expected focus-aware reply, got %q", result.Reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpretUtteranceInheritedFocusForThere(t *testing.T) {
|
||||
result := interpretForTest(t, "Добавь туда новую настройку.", activeFocus("assistant", "Assistant"), "")
|
||||
if len(result.Projects) != 1 || result.Projects[0].ProjectID != "assistant" || result.Projects[0].Provenance != situation.ProjectResolutionInheritedFocus {
|
||||
t.Fatalf("expected inherited Assistant focus, got %#v", result.Projects)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpretUtteranceMultiProjectReferenceRoles(t *testing.T) {
|
||||
result := interpretForTest(t, "Посмотри, как это сделано в Assistant, и сделай аналогично в УПО.", nil, "")
|
||||
if len(result.Projects) != 2 {
|
||||
t.Fatalf("expected two project references, got %#v", result.Projects)
|
||||
}
|
||||
roles := map[situation.ProjectID]interaction.ProjectReferenceRole{}
|
||||
for _, ref := range result.Projects {
|
||||
roles[ref.ProjectID] = ref.Role
|
||||
}
|
||||
if roles["assistant"] != interaction.ProjectRoleReferenceSource || roles["upo"] != interaction.ProjectRolePrimary {
|
||||
t.Fatalf("unexpected roles: %#v", roles)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterpretUtteranceAmbiguousDestructiveRequiresClarification(t *testing.T) {
|
||||
result := interpretForTest(t, "Удали туда старую базу.", activeFocus("assistant", "Assistant"), "")
|
||||
if result.Interpretation.Clarification != interaction.ClarificationRequired {
|
||||
t.Fatalf("expected clarification, got %#v", result.Interpretation)
|
||||
}
|
||||
if result.NeedsCognition {
|
||||
t.Fatalf("ambiguous destructive directive must not require cognition")
|
||||
}
|
||||
}
|
||||
|
||||
func interpretForTest(t *testing.T, message string, previous *situation.ActiveProjectFocus, corrects interaction.HumanUtteranceID) SemanticResult {
|
||||
t.Helper()
|
||||
conversation := interaction.Conversation{ID: "conversation-1", ActorID: "actor-1", PrincipalID: "principal-1", Channel: interaction.ChannelWebChat, State: interaction.ConversationOpen}
|
||||
utterance, _, _, err := NewHumanUtterance(conversation, interaction.ChatMessageRequest{Message: message, CorrectsUtteranceID: corrects}, time.Unix(100, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := InterpretUtterance(utterance, projectRegistryForTest(), previous, time.Unix(100, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func projectRegistryForTest() []situation.ProjectDescriptor {
|
||||
return []situation.ProjectDescriptor{
|
||||
{ID: "assistant", DisplayName: "Assistant", Aliases: []situation.ProjectAlias{"assistant", "ассистент", "домовой"}},
|
||||
{ID: "upo", DisplayName: "УПО", Aliases: []situation.ProjectAlias{"упо", "upo"}},
|
||||
}
|
||||
}
|
||||
|
||||
func activeFocus(projectID situation.ProjectID, displayName string) *situation.ActiveProjectFocus {
|
||||
return &situation.ActiveProjectFocus{
|
||||
ActorID: identity.ActorID("actor-1"),
|
||||
PrincipalID: identity.PrincipalID("principal-1"),
|
||||
ProjectID: projectID,
|
||||
ProjectDisplayName: displayName,
|
||||
Provenance: situation.ProjectResolutionExplicit,
|
||||
ConfidenceMillis: 980,
|
||||
SourceUtteranceID: "utterance-focus",
|
||||
UpdatedAtUnixMillis: time.Unix(90, 0).UnixMilli(),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user