Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
101f8beadb | ||
|
|
b16925b386 | ||
|
|
be5a146cca | ||
|
|
094fdcc51e | ||
|
|
307ad4a587 | ||
|
|
e867ba3c93 | ||
|
|
c3027c5901 | ||
|
|
30bf2d6e67 | ||
|
|
7fcab3bf31 | ||
|
|
eca8475e29 | ||
|
|
b340d46cdd | ||
|
|
ac721216ea | ||
|
|
e314d02212 | ||
|
|
6394e45bf2 | ||
|
|
ba5cc60c15 | ||
|
|
a0fed9956c | ||
|
|
58e9c97d76 | ||
|
|
ba154e4ec2 | ||
|
|
c4d7795280 | ||
|
|
25323d4ac1 | ||
|
|
15133cd0fc | ||
|
|
813554dc80 | ||
|
|
bd8980bc3c | ||
|
|
62a3713e1e | ||
|
|
1fb03de7be | ||
|
|
fa92a10eb7 | ||
|
|
bf20f247eb | ||
|
|
560b51e2f6 |
@@ -122,10 +122,10 @@ type compatibleChatResponse struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *OpenAICompatibleLocalAdapter) Advise(ctx context.Context, request cognitive.AdvisoryRequest) (cognitive.AdvisoryResponse, error) {
|
func (a *OpenAICompatibleLocalAdapter) Advise(ctx context.Context, request cognitive.AdvisoryRequest) (cognitive.AdvisoryResponse, error) {
|
||||||
if err := ValidateAdvisoryRequest(request); err != nil || request.ProviderModelID == "" || len(request.Context) != 0 {
|
if err := ValidateAdvisoryRequest(request); err != nil || request.ProviderModelID == "" {
|
||||||
return cognitive.AdvisoryResponse{}, ErrInvalidAdvisory
|
return cognitive.AdvisoryResponse{}, ErrInvalidAdvisory
|
||||||
}
|
}
|
||||||
payload := compatibleChatRequest{Model: string(request.ProviderModelID), Messages: []compatibleMessage{{Role: "system", Content: "Provide non-canonical advisory text only. Never claim that an action occurred."}, {Role: "user", Content: request.Message}}, Temperature: 0, Stream: false, MaxTokens: request.MaxOutputBytes / 4, ChatTemplateKwargs: compatibleTemplateKwargs{EnableThinking: false}}
|
payload := compatibleChatRequest{Model: string(request.ProviderModelID), Messages: []compatibleMessage{{Role: "system", Content: "Ты отвечаешь от имени Домового — локального помощника пользователя. Не называй себя именем модели, поставщиком или внутренним runtime. Если спрашивают имя, ответь: «Меня зовут Домовой». Понимай смысл сообщения и помогай довести цель до полезного результата. Отвечай только некатегоричным текстом совета; не утверждай, что внешнее действие уже выполнено."}, {Role: "user", Content: localAdvisoryMessage(request)}}, Temperature: 0, Stream: false, MaxTokens: request.MaxOutputBytes / 4, ChatTemplateKwargs: compatibleTemplateKwargs{EnableThinking: false}}
|
||||||
var result compatibleChatResponse
|
var result compatibleChatResponse
|
||||||
status, err := a.requestJSON(ctx, http.MethodPost, "/chat/completions", payload, &result)
|
status, err := a.requestJSON(ctx, http.MethodPost, "/chat/completions", payload, &result)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -151,6 +151,19 @@ func (a *OpenAICompatibleLocalAdapter) Advise(ctx context.Context, request cogni
|
|||||||
return response, nil
|
return response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func localAdvisoryMessage(request cognitive.AdvisoryRequest) string {
|
||||||
|
if len(request.Context) == 0 {
|
||||||
|
return request.Message
|
||||||
|
}
|
||||||
|
var builder strings.Builder
|
||||||
|
builder.WriteString(request.Message)
|
||||||
|
builder.WriteString("\n\nRelevant local context:\n")
|
||||||
|
for _, excerpt := range request.Context {
|
||||||
|
fmt.Fprintf(&builder, "- [%s/%s] %s\n", excerpt.SourceKind, excerpt.SourceID, excerpt.Text)
|
||||||
|
}
|
||||||
|
return builder.String()
|
||||||
|
}
|
||||||
|
|
||||||
func (a *OpenAICompatibleLocalAdapter) requestJSON(ctx context.Context, method, path string, input, output any) (int, error) {
|
func (a *OpenAICompatibleLocalAdapter) requestJSON(ctx context.Context, method, path string, input, output any) (int, error) {
|
||||||
var body io.Reader
|
var body io.Reader
|
||||||
if input != nil {
|
if input != nil {
|
||||||
|
|||||||
@@ -92,3 +92,32 @@ func TestOpenAICompatibleLocalAdapterDisablesTemplateThinkingForBoundedAdvisory(
|
|||||||
t.Fatal("expected bounded advisory to disable template thinking")
|
t.Fatal("expected bounded advisory to disable template thinking")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestOpenAICompatibleLocalAdapterPassesLocalContextToAdvisory(t *testing.T) {
|
||||||
|
transport := &captureRoundTripper{}
|
||||||
|
adapter, err := NewOpenAICompatibleLocalAdapter("http://gateway/v1", transport)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err = adapter.Advise(context.Background(), cognitive.AdvisoryRequest{
|
||||||
|
Version: cognitive.CreatorAdvisoryV1, RequestID: "request-context", ActorID: "actor", PrincipalID: "principal", ScopeID: "scope",
|
||||||
|
Message: "Продолжи разговор", Locale: "ru-RU", MaxOutputBytes: 256, ProviderBindingID: "binding-1", ProviderBindingRevision: 1,
|
||||||
|
ProviderInstanceID: "provider-1", ModelDescriptorID: "model-1", ProviderModelID: capability.ProviderModelID("local-model"),
|
||||||
|
Context: []cognitive.ContextExcerpt{{ID: "focus", SourceKind: "situation", SourceID: "focus-1", Revision: 1, Sensitivity: cognitive.SensitivityPrivateAllowed, Text: "Активный проект: Домовой"}},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var payload struct {
|
||||||
|
Messages []struct {
|
||||||
|
Role string `json:"role"`
|
||||||
|
Content string `json:"content"`
|
||||||
|
} `json:"messages"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(transport.body, &payload); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(payload.Messages) != 2 || !strings.Contains(payload.Messages[1].Content, "Активный проект: Домовой") {
|
||||||
|
t.Fatalf("local context was not passed to advisory: %+v", payload.Messages)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -36,19 +36,52 @@ var searchStopTerms = map[string]struct{}{
|
|||||||
// cities, weather terms, entities or model names: the complete semantic query
|
// cities, weather terms, entities or model names: the complete semantic query
|
||||||
// comes from the interpretation layer.
|
// comes from the interpretation layer.
|
||||||
type SearchConnector struct {
|
type SearchConnector struct {
|
||||||
Client *http.Client
|
Client *http.Client
|
||||||
EndpointTemplate string
|
EndpointTemplate string
|
||||||
AllowedHosts map[string]struct{}
|
AllowedHosts map[string]struct{}
|
||||||
MaxBytes int64
|
FallbackEndpoints []SearchEndpoint
|
||||||
MaxResults int
|
MaxBytes int64
|
||||||
|
MaxResults int
|
||||||
|
}
|
||||||
|
|
||||||
|
// SearchEndpoint is an independently allowlisted web-search route. The
|
||||||
|
// connector tries routes in order and stops at the first relevant evidence.
|
||||||
|
// This is a source-recovery policy, not a question-type classifier.
|
||||||
|
type SearchEndpoint struct {
|
||||||
|
Template string
|
||||||
|
AllowedHosts map[string]struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c SearchConnector) Collect(ctx context.Context, request epistemics.WebSearchRequest, nowUnixMillis int64) ([]epistemics.ResearchCandidate, error) {
|
func (c SearchConnector) Collect(ctx context.Context, request epistemics.WebSearchRequest, nowUnixMillis int64) ([]epistemics.ResearchCandidate, error) {
|
||||||
if request.Plan.Validate() != nil || strings.TrimSpace(request.Query) == "" || nowUnixMillis < 1 || !strings.Contains(c.EndpointTemplate, "%s") {
|
if request.Plan.Validate() != nil || strings.TrimSpace(request.Query) == "" || nowUnixMillis < 1 || !strings.Contains(c.EndpointTemplate, "%s") {
|
||||||
return nil, ErrSearchRejected
|
return nil, ErrSearchRejected
|
||||||
}
|
}
|
||||||
endpoint, err := url.Parse(strings.Replace(c.EndpointTemplate, "%s", url.QueryEscape(strings.TrimSpace(request.Query)), 1))
|
endpoints := make([]SearchEndpoint, 0, 1+len(c.FallbackEndpoints))
|
||||||
if err != nil || endpoint.Scheme != "https" || endpoint.Host == "" || !c.allowedHost(strings.ToLower(endpoint.Hostname())) {
|
endpoints = append(endpoints, SearchEndpoint{Template: c.EndpointTemplate, AllowedHosts: c.AllowedHosts})
|
||||||
|
endpoints = append(endpoints, c.FallbackEndpoints...)
|
||||||
|
var lastErr error
|
||||||
|
for _, candidateEndpoint := range endpoints {
|
||||||
|
results, err := c.collectEndpoint(ctx, candidateEndpoint, request, nowUnixMillis)
|
||||||
|
if err != nil {
|
||||||
|
lastErr = err
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(results) > 0 {
|
||||||
|
return results, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if lastErr != nil {
|
||||||
|
return nil, lastErr
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c SearchConnector) collectEndpoint(ctx context.Context, configured SearchEndpoint, request epistemics.WebSearchRequest, nowUnixMillis int64) ([]epistemics.ResearchCandidate, error) {
|
||||||
|
if !strings.Contains(configured.Template, "%s") {
|
||||||
|
return nil, ErrSearchRejected
|
||||||
|
}
|
||||||
|
endpoint, err := url.Parse(strings.Replace(configured.Template, "%s", url.QueryEscape(strings.TrimSpace(request.Query)), 1))
|
||||||
|
if err != nil || endpoint.Scheme != "https" || endpoint.Host == "" || !allowedHost(configured.AllowedHosts, strings.ToLower(endpoint.Hostname())) {
|
||||||
return nil, ErrSearchRejected
|
return nil, ErrSearchRejected
|
||||||
}
|
}
|
||||||
client := c.Client
|
client := c.Client
|
||||||
@@ -63,6 +96,10 @@ func (c SearchConnector) Collect(ctx context.Context, request epistemics.WebSear
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, ErrSearchRejected
|
return nil, ErrSearchRejected
|
||||||
}
|
}
|
||||||
|
// Search providers commonly return a consent/challenge shell to the
|
||||||
|
// default Go client. A neutral browser identification improves the same
|
||||||
|
// generic evidence path for every query without selecting by topic.
|
||||||
|
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; DomovoyResearch/1.0)")
|
||||||
response, err := client.Do(req)
|
response, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -138,7 +175,7 @@ func searchStatementRelatesToQuery(query, statement string) bool {
|
|||||||
return usable == 0
|
return usable == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c SearchConnector) allowedHost(host string) bool { _, ok := c.AllowedHosts[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 {
|
||||||
return 3
|
return 3
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package research
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.cin.su/m/Assistant/contracts/epistemics"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSearchConnectorFallsBackToAnotherAllowedSource(t *testing.T) {
|
||||||
|
primary := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, _ = w.Write([]byte(`<html><body>no usable results</body></html>`))
|
||||||
|
}))
|
||||||
|
defer primary.Close()
|
||||||
|
fallback := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
_, _ = w.Write([]byte(`<a class="result__a" href="https://example.test">Казань: текущая температура 18 °C</a><a class="result__snippet">Наблюдается переменная облачность.</a>`))
|
||||||
|
}))
|
||||||
|
defer fallback.Close()
|
||||||
|
client := fallback.Client()
|
||||||
|
client.Transport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} // test servers only
|
||||||
|
request := epistemics.WebSearchRequest{Plan: epistemics.ResearchPlan{ID: "plan:test", Question: "какая погода в Казани", SourceClasses: []string{"web-search"}, FreshnessPolicy: string(epistemics.FreshnessCurrent)}, PropositionKey: "question:test", Query: "какая погода в Казани"}
|
||||||
|
connector := SearchConnector{
|
||||||
|
Client: client,
|
||||||
|
EndpointTemplate: primary.URL + "?q=%s",
|
||||||
|
AllowedHosts: map[string]struct{}{strings.TrimPrefix(primary.URL, "https://"): {}},
|
||||||
|
FallbackEndpoints: []SearchEndpoint{{
|
||||||
|
Template: fallback.URL + "?q=%s",
|
||||||
|
AllowedHosts: map[string]struct{}{strings.TrimPrefix(fallback.URL, "https://"): {}},
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
// The allowlist is hostname-only; test servers include an ephemeral port.
|
||||||
|
connector.AllowedHosts = map[string]struct{}{strings.Split(strings.TrimPrefix(primary.URL, "https://"), ":")[0]: {}}
|
||||||
|
connector.FallbackEndpoints[0].AllowedHosts = map[string]struct{}{strings.Split(strings.TrimPrefix(fallback.URL, "https://"), ":")[0]: {}}
|
||||||
|
results, err := connector.Collect(context.Background(), request, 1)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(results) != 1 || !strings.Contains(results[0].Statement, "18") {
|
||||||
|
t.Fatalf("fallback evidence = %#v", results)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.cin.su/m/Assistant/contracts/capability"
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
@@ -31,35 +32,16 @@ type fleetStatusResponse struct {
|
|||||||
func fleetReadinessHandler(client *http.Client, preferred capability.FleetTier, endpoints []fleetEndpoint) http.Handler {
|
func fleetReadinessHandler(client *http.Client, preferred capability.FleetTier, endpoints []fleetEndpoint) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
members := make([]capability.FleetMember, 0, len(endpoints))
|
members := make([]capability.FleetMember, 0, len(endpoints))
|
||||||
for _, endpoint := range endpoints {
|
members = make([]capability.FleetMember, len(endpoints))
|
||||||
member := capability.FleetMember{ProviderInstanceID: capability.ProviderInstanceID(endpoint.ProviderID), ModelDescriptorID: capability.ModelDescriptorID(endpoint.ModelID), Tier: endpoint.Tier, Reason: "NOT_CONFIGURED"}
|
var waitGroup sync.WaitGroup
|
||||||
if strings.TrimSpace(endpoint.URL) == "" {
|
for index, endpoint := range endpoints {
|
||||||
members = append(members, member)
|
waitGroup.Add(1)
|
||||||
continue
|
go func(index int, endpoint fleetEndpoint) {
|
||||||
}
|
defer waitGroup.Done()
|
||||||
request, err := http.NewRequestWithContext(r.Context(), http.MethodGet, endpoint.URL, nil)
|
members[index] = probeFleetEndpoint(r.Context(), client, endpoint)
|
||||||
if err == nil {
|
}(index, endpoint)
|
||||||
for name, value := range endpoint.Headers {
|
|
||||||
request.Header.Set(name, value)
|
|
||||||
}
|
|
||||||
probeClient := endpoint.Client
|
|
||||||
if probeClient == nil {
|
|
||||||
probeClient = client
|
|
||||||
}
|
|
||||||
response, requestErr := probeClient.Do(request)
|
|
||||||
if requestErr == nil {
|
|
||||||
response.Body.Close()
|
|
||||||
if response.StatusCode >= 200 && response.StatusCode < 300 {
|
|
||||||
member.Ready, member.Reason = true, "AVAILABLE"
|
|
||||||
} else {
|
|
||||||
member.Reason = fmt.Sprintf("status=%s", response.Status)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
member.Reason = requestErr.Error()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
members = append(members, member)
|
|
||||||
}
|
}
|
||||||
|
waitGroup.Wait()
|
||||||
readiness, err := fleetdomain.BuildFleetReadiness(time.Now().UnixMilli(), members)
|
readiness, err := fleetdomain.BuildFleetReadiness(time.Now().UnixMilli(), members)
|
||||||
response := fleetStatusResponse{Readiness: readiness, Preferred: preferred}
|
response := fleetStatusResponse{Readiness: readiness, Preferred: preferred}
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -76,4 +58,37 @@ func fleetReadinessHandler(client *http.Client, preferred capability.FleetTier,
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func probeFleetEndpoint(parent context.Context, fallbackClient *http.Client, endpoint fleetEndpoint) capability.FleetMember {
|
||||||
|
member := capability.FleetMember{ProviderInstanceID: capability.ProviderInstanceID(endpoint.ProviderID), ModelDescriptorID: capability.ModelDescriptorID(endpoint.ModelID), Tier: endpoint.Tier, Reason: "NOT_CONFIGURED"}
|
||||||
|
if strings.TrimSpace(endpoint.URL) == "" {
|
||||||
|
return member
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(parent, 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.URL, nil)
|
||||||
|
if err != nil {
|
||||||
|
member.Reason = err.Error()
|
||||||
|
return member
|
||||||
|
}
|
||||||
|
for name, value := range endpoint.Headers {
|
||||||
|
request.Header.Set(name, value)
|
||||||
|
}
|
||||||
|
probeClient := endpoint.Client
|
||||||
|
if probeClient == nil {
|
||||||
|
probeClient = fallbackClient
|
||||||
|
}
|
||||||
|
response, requestErr := probeClient.Do(request)
|
||||||
|
if requestErr != nil {
|
||||||
|
member.Reason = requestErr.Error()
|
||||||
|
return member
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode >= 200 && response.StatusCode < 300 {
|
||||||
|
member.Ready, member.Reason = true, "AVAILABLE"
|
||||||
|
} else {
|
||||||
|
member.Reason = fmt.Sprintf("status=%s", response.Status)
|
||||||
|
}
|
||||||
|
return member
|
||||||
|
}
|
||||||
|
|
||||||
func fleetContext(ctx context.Context) context.Context { return ctx }
|
func fleetContext(ctx context.Context) context.Context { return ctx }
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"git.cin.su/m/Assistant/contracts/capability"
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
)
|
)
|
||||||
@@ -26,6 +27,29 @@ func TestFleetReadinessSelectsBestAvailablePrimaryTierBeforeLifeboat(t *testing.
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestFleetReadinessDoesNotWaitForSlowMembersSerially(t *testing.T) {
|
||||||
|
slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
time.Sleep(150 * time.Millisecond)
|
||||||
|
w.WriteHeader(http.StatusServiceUnavailable)
|
||||||
|
}))
|
||||||
|
defer slow.Close()
|
||||||
|
fast := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }))
|
||||||
|
defer fast.Close()
|
||||||
|
handler := fleetReadinessHandler(fast.Client(), capability.FleetTierFast, []fleetEndpoint{
|
||||||
|
{ProviderID: "slow", ModelID: "slow-model", Tier: capability.FleetTierMedium, URL: slow.URL},
|
||||||
|
{ProviderID: "lifeboat", ModelID: "lifeboat-model", Tier: capability.FleetTierLifeboat, URL: fast.URL},
|
||||||
|
})
|
||||||
|
started := time.Now()
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/v1/fleet/readiness", nil))
|
||||||
|
if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), `"selected_tier":"LIFEBOAT"`) {
|
||||||
|
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||||
|
}
|
||||||
|
if elapsed := time.Since(started); elapsed >= 300*time.Millisecond {
|
||||||
|
t.Fatalf("fleet readiness was serialized: elapsed=%s", elapsed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestFleetReadinessSendsConfiguredProviderHeaders(t *testing.T) {
|
func TestFleetReadinessSendsConfiguredProviderHeaders(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.Header.Get("Authorization") != "Bearer fleet-key" {
|
if r.Header.Get("Authorization") != "Bearer fleet-key" {
|
||||||
|
|||||||
@@ -126,7 +126,9 @@ func main() {
|
|||||||
}
|
}
|
||||||
cpuEndpoint := strings.TrimRight(envOr("LOCAL_CPU_PROVIDER_URL", "http://docker.cin.su:18082/v1"), "/") + "/models"
|
cpuEndpoint := strings.TrimRight(envOr("LOCAL_CPU_PROVIDER_URL", "http://docker.cin.su:18082/v1"), "/") + "/models"
|
||||||
cpuHealthProbe := health.OptionalHTTPProbeWithHeaders(cpuReadinessClient, cpuEndpoint, cpuFleetHeaders)
|
cpuHealthProbe := health.OptionalHTTPProbeWithHeaders(cpuReadinessClient, cpuEndpoint, cpuFleetHeaders)
|
||||||
cpuHealthProbe.Timeout = 10 * time.Second
|
// Opportunistic providers must not hide a ready local lifeboat. Keep their
|
||||||
|
// readiness budget short; their detailed fleet state is reported separately.
|
||||||
|
cpuHealthProbe.Timeout = 2 * time.Second
|
||||||
mediumEndpoint := ""
|
mediumEndpoint := ""
|
||||||
mediumHeaders := map[string]string{}
|
mediumHeaders := map[string]string{}
|
||||||
mediumHealthProbe := health.Probe{}
|
mediumHealthProbe := health.Probe{}
|
||||||
@@ -136,7 +138,7 @@ func main() {
|
|||||||
mediumHeaders["Authorization"] = "Bearer " + mediumAPIKey
|
mediumHeaders["Authorization"] = "Bearer " + mediumAPIKey
|
||||||
}
|
}
|
||||||
mediumHealthProbe = health.OptionalHTTPProbeWithHeaders(mediumReadinessClient, mediumEndpoint, mediumHeaders)
|
mediumHealthProbe = health.OptionalHTTPProbeWithHeaders(mediumReadinessClient, mediumEndpoint, mediumHeaders)
|
||||||
mediumHealthProbe.Timeout = 10 * time.Second
|
mediumHealthProbe.Timeout = 2 * time.Second
|
||||||
}
|
}
|
||||||
readinessProbes := []health.Probe{
|
readinessProbes := []health.Probe{
|
||||||
health.HTTPProbe(readinessClient, strings.TrimRight(envOr("CORE_RUNTIME_URL", "http://core-runtime:8080"), "/")+"/healthz"),
|
health.HTTPProbe(readinessClient, strings.TrimRight(envOr("CORE_RUNTIME_URL", "http://core-runtime:8080"), "/")+"/healthz"),
|
||||||
@@ -149,7 +151,7 @@ func main() {
|
|||||||
if gpuConfigured {
|
if gpuConfigured {
|
||||||
gpuHeaders := map[string]string{"Authorization": "Bearer " + gpuKey}
|
gpuHeaders := map[string]string{"Authorization": "Bearer " + gpuKey}
|
||||||
gpuProbe := health.OptionalHTTPProbeWithHeaders(readinessClient, strings.TrimRight(gpuURL, "/")+"/models", gpuHeaders)
|
gpuProbe := health.OptionalHTTPProbeWithHeaders(readinessClient, strings.TrimRight(gpuURL, "/")+"/models", gpuHeaders)
|
||||||
gpuProbe.Timeout = 10 * time.Second
|
gpuProbe.Timeout = 2 * time.Second
|
||||||
readinessProbes = append(readinessProbes, gpuProbe)
|
readinessProbes = append(readinessProbes, gpuProbe)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sort"
|
||||||
|
|
||||||
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
|
interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
type chatRouteKind string
|
||||||
|
|
||||||
|
const (
|
||||||
|
chatRouteResearch chatRouteKind = "RESEARCH"
|
||||||
|
chatRouteConversation chatRouteKind = "CONVERSATION"
|
||||||
|
chatRouteAction chatRouteKind = "ACTION"
|
||||||
|
chatRouteAgent chatRouteKind = "AGENT"
|
||||||
|
)
|
||||||
|
|
||||||
|
type chatRoute struct {
|
||||||
|
Kind chatRouteKind
|
||||||
|
Capability capability.CapabilityKind
|
||||||
|
Profile string
|
||||||
|
Order int
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildChatRoutePlan creates one bounded route per meaning-bearing capability.
|
||||||
|
// A failed research route must not suppress the local conversational route or
|
||||||
|
// an unrelated action route.
|
||||||
|
func buildChatRoutePlan(result interactiondomain.SemanticResult) []chatRoute {
|
||||||
|
seen := make(map[capability.CapabilityKind]struct{})
|
||||||
|
routes := make([]chatRoute, 0, len(result.CapabilityHints)+1)
|
||||||
|
add := func(kind chatRouteKind, capabilityKind capability.CapabilityKind, profile string, order int) {
|
||||||
|
if capabilityKind != "" {
|
||||||
|
if _, exists := seen[capabilityKind]; exists {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[capabilityKind] = struct{}{}
|
||||||
|
}
|
||||||
|
routes = append(routes, chatRoute{Kind: kind, Capability: capabilityKind, Profile: profile, Order: order})
|
||||||
|
}
|
||||||
|
for _, hint := range result.CapabilityHints {
|
||||||
|
switch capability.CapabilityKind(hint) {
|
||||||
|
case capability.CapabilityKindWebResearch:
|
||||||
|
add(chatRouteResearch, capability.CapabilityKindWebResearch, "truth-research-v1", 10)
|
||||||
|
case capability.CapabilityKindCognitiveReasoning, capability.CapabilityKindVerifyFact:
|
||||||
|
add(chatRouteConversation, capability.CapabilityKind(hint), "local-reasoning-v1", 20)
|
||||||
|
case capability.CapabilityKindScheduleReminder:
|
||||||
|
add(chatRouteAction, capability.CapabilityKindScheduleReminder, "continuity-reminder-v1", 30)
|
||||||
|
case capability.CapabilityKindModifyCode, capability.CapabilityKindRunTests, capability.CapabilityKindInspectProject:
|
||||||
|
add(chatRouteAgent, capability.CapabilityKind(hint), "software-agent-v1", 40)
|
||||||
|
case capability.CapabilityKindSendEmail, capability.CapabilityKindReadEmail:
|
||||||
|
add(chatRouteAgent, capability.CapabilityKind(hint), "communication-agent-v1", 50)
|
||||||
|
case capability.CapabilityKindReadDatabase, capability.CapabilityKindQueryLogs:
|
||||||
|
add(chatRouteAgent, capability.CapabilityKind(hint), "diagnostics-agent-v1", 60)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if result.NeedsCognition || len(routes) == 0 {
|
||||||
|
add(chatRouteConversation, capability.CapabilityKindCognitiveReasoning, "local-reasoning-v1", 20)
|
||||||
|
}
|
||||||
|
sort.SliceStable(routes, func(i, j int) bool { return routes[i].Order < routes[j].Order })
|
||||||
|
return routes
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasChatRoute(routes []chatRoute, kind chatRouteKind) bool {
|
||||||
|
for _, route := range routes {
|
||||||
|
if route.Kind == kind {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
|
interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBuildChatRoutePlanPreservesMultipleMeaningfulRoutes(t *testing.T) {
|
||||||
|
planned := buildChatRoutePlan(interactiondomain.SemanticResult{
|
||||||
|
NeedsCognition: true,
|
||||||
|
CapabilityHints: []string{"WEB_RESEARCH", "MODIFY_CODE", "RUN_TESTS", "SCHEDULE_REMINDER"},
|
||||||
|
})
|
||||||
|
if len(planned) != 5 {
|
||||||
|
t.Fatalf("expected five deduplicated routes, got %+v", planned)
|
||||||
|
}
|
||||||
|
want := []struct {
|
||||||
|
kind chatRouteKind
|
||||||
|
profile string
|
||||||
|
cap capability.CapabilityKind
|
||||||
|
}{
|
||||||
|
{chatRouteResearch, "truth-research-v1", capability.CapabilityKindWebResearch},
|
||||||
|
{chatRouteConversation, "local-reasoning-v1", capability.CapabilityKindCognitiveReasoning},
|
||||||
|
{chatRouteAction, "continuity-reminder-v1", capability.CapabilityKindScheduleReminder},
|
||||||
|
{chatRouteAgent, "software-agent-v1", capability.CapabilityKindModifyCode},
|
||||||
|
{chatRouteAgent, "software-agent-v1", capability.CapabilityKindRunTests},
|
||||||
|
}
|
||||||
|
for index, expected := range want {
|
||||||
|
if planned[index].Kind != expected.kind || planned[index].Profile != expected.profile || planned[index].Capability != expected.cap {
|
||||||
|
t.Fatalf("route %d = %+v, want %+v", index, planned[index], expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildChatRoutePlanAlwaysKeepsLocalConversationRoute(t *testing.T) {
|
||||||
|
planned := buildChatRoutePlan(interactiondomain.SemanticResult{NeedsCognition: true})
|
||||||
|
if len(planned) != 1 || planned[0].Kind != chatRouteConversation || planned[0].Profile != "local-reasoning-v1" {
|
||||||
|
t.Fatalf("unexpected local route: %+v", planned)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,8 +5,10 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"hash/fnv"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"time"
|
||||||
|
|
||||||
"git.cin.su/m/Assistant/contracts/authority"
|
"git.cin.su/m/Assistant/contracts/authority"
|
||||||
"git.cin.su/m/Assistant/contracts/capability"
|
"git.cin.su/m/Assistant/contracts/capability"
|
||||||
@@ -61,12 +63,59 @@ func (c cognitiveInterpretationClient) Interpret(ctx context.Context, request co
|
|||||||
}
|
}
|
||||||
|
|
||||||
func shouldRequestBroaderInterpretation(result interactiondomain.SemanticResult) bool {
|
func shouldRequestBroaderInterpretation(result interactiondomain.SemanticResult) bool {
|
||||||
switch result.Interpretation.Applicability {
|
return shouldRequestSemanticInterpretation(result)
|
||||||
case interaction.SemanticNeedsBroaderInterpret, interaction.SemanticLowConfidence, interaction.SemanticMixedIntent:
|
}
|
||||||
return true
|
|
||||||
default:
|
// shouldRequestSemanticInterpretation keeps the deterministic layer as a
|
||||||
|
// fast reflex, not as the meaning authority. Questions, requests, directives,
|
||||||
|
// mixed signals and capability-bearing messages go through cognitive
|
||||||
|
// interpretation; only stable low-risk conversational/assertive reflexes may
|
||||||
|
// answer without it.
|
||||||
|
func shouldRequestSemanticInterpretation(result interactiondomain.SemanticResult) bool {
|
||||||
|
if result.Interpretation.Clarification == interaction.ClarificationRequired {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
// Structured, read-only information intents already have a semantic owner
|
||||||
|
// in core-runtime. Sending them through the slower advisory interpretation
|
||||||
|
// path only adds latency and can make a healthy runtime look unavailable.
|
||||||
|
if result.InformationRequestKind != "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if result.NeedsCognition || len(result.CapabilityHints) > 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if result.Interpretation.Applicability != interaction.SemanticApplicable {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
switch result.Interpretation.SpeechAct {
|
||||||
|
case interaction.SpeechActConversational, interaction.SpeechActConfirmation, interaction.SpeechActRejection:
|
||||||
|
return false
|
||||||
|
case interaction.SpeechActAssertion:
|
||||||
|
return result.Interpretation.ConfidenceMillis < 850
|
||||||
|
default:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
deterministicReflexAuditInterval = 10 * time.Minute
|
||||||
|
deterministicReflexAuditSample = uint32(16)
|
||||||
|
)
|
||||||
|
|
||||||
|
// shouldAuditDeterministicReflex samples stable reflexes in a time bucket.
|
||||||
|
// This is observability, not a correctness gate: a failed audit leaves the
|
||||||
|
// reflex usable, while a successful disagreement can replace it with the
|
||||||
|
// cognitive candidate and becomes durable evidence through the normal
|
||||||
|
// candidate store.
|
||||||
|
func shouldAuditDeterministicReflex(result interactiondomain.SemanticResult, utteranceID string, now time.Time) bool {
|
||||||
|
if shouldRequestSemanticInterpretation(result) || utteranceID == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
bucket := now.Unix() / int64(deterministicReflexAuditInterval/time.Second)
|
||||||
|
hash := fnv.New32a()
|
||||||
|
_, _ = hash.Write([]byte(utteranceID))
|
||||||
|
_, _ = hash.Write([]byte(fmt.Sprintf(":%d", bucket)))
|
||||||
|
return hash.Sum32()%deterministicReflexAuditSample == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func isSimpleLocalQuestion(result interactiondomain.SemanticResult) bool {
|
func isSimpleLocalQuestion(result interactiondomain.SemanticResult) bool {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"git.cin.su/m/Assistant/contracts/interaction"
|
"git.cin.su/m/Assistant/contracts/interaction"
|
||||||
interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain"
|
interactiondomain "git.cin.su/m/Assistant/modules/interaction/domain"
|
||||||
@@ -34,3 +35,42 @@ func TestOperationalQuestionStillUsesStrictInterpretation(t *testing.T) {
|
|||||||
t.Fatal("operational question must retain strict interpretation routing")
|
t.Fatal("operational question must retain strict interpretation routing")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestStructuredInventoryUsesDirectReadOnlySemanticRoute(t *testing.T) {
|
||||||
|
result := interactiondomain.SemanticResult{
|
||||||
|
Interpretation: interaction.UtteranceInterpretation{
|
||||||
|
SpeechAct: interaction.SpeechActDirective,
|
||||||
|
Applicability: interaction.SemanticApplicable,
|
||||||
|
ConfidenceMillis: 980,
|
||||||
|
},
|
||||||
|
InformationRequestKind: interaction.InformationRequestCognitiveModelInventory,
|
||||||
|
}
|
||||||
|
if shouldRequestSemanticInterpretation(result) {
|
||||||
|
t.Fatal("structured model inventory must use the direct read-only semantic route")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStableReflexIsPeriodicallySampledForDrift(t *testing.T) {
|
||||||
|
result := interactiondomain.SemanticResult{Interpretation: interaction.UtteranceInterpretation{
|
||||||
|
SpeechAct: interaction.SpeechActConversational, Applicability: interaction.SemanticApplicable,
|
||||||
|
}}
|
||||||
|
found := false
|
||||||
|
for minute := 0; minute < 160; minute++ {
|
||||||
|
if shouldAuditDeterministicReflex(result, "utterance-drift-probe", time.Unix(int64(minute)*60, 0)) {
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatal("stable reflex was never sampled during the audit window")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMeaningfulSignalsAreNotReflexOnly(t *testing.T) {
|
||||||
|
for _, act := range []interaction.SpeechAct{interaction.SpeechActQuestion, interaction.SpeechActRequestToInvestigate, interaction.SpeechActDirective} {
|
||||||
|
result := interactiondomain.SemanticResult{Interpretation: interaction.UtteranceInterpretation{SpeechAct: act, Applicability: interaction.SemanticApplicable}}
|
||||||
|
if !shouldRequestSemanticInterpretation(result) {
|
||||||
|
t.Fatalf("%s must prefer cognitive interpretation", act)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -512,9 +512,12 @@ func main() {
|
|||||||
http.Error(w, "interpret chat message", http.StatusServiceUnavailable)
|
http.Error(w, "interpret chat message", http.StatusServiceUnavailable)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
routePlan := buildChatRoutePlan(semantic)
|
||||||
cognitiveAttempted := false
|
cognitiveAttempted := false
|
||||||
cognitiveAvailable := true
|
cognitiveAvailable := true
|
||||||
if shouldRequestBroaderInterpretation(semantic) {
|
semanticInterpretationRequested := shouldRequestSemanticInterpretation(semantic)
|
||||||
|
semanticReflexAudit := shouldAuditDeterministicReflex(semantic, string(utterance.ID), now)
|
||||||
|
if semanticInterpretationRequested || semanticReflexAudit {
|
||||||
cognitiveAttempted = true
|
cognitiveAttempted = true
|
||||||
projectNames := make([]string, 0, len(semantic.Projects))
|
projectNames := make([]string, 0, len(semantic.Projects))
|
||||||
for _, ref := range semantic.Projects {
|
for _, ref := range semantic.Projects {
|
||||||
@@ -623,13 +626,17 @@ func main() {
|
|||||||
needsCognition = false
|
needsCognition = false
|
||||||
}
|
}
|
||||||
researchBacked := false
|
researchBacked := false
|
||||||
if hasCapabilityHint(semantic.CapabilityHints, "WEB_RESEARCH") && 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 {
|
||||||
result, researchErr := researchClient.SearchWeb(r.Context(), epistemics.WebSearchRequest{
|
researchCtx, cancelResearch := context.WithTimeout(r.Context(), 8*time.Second)
|
||||||
|
result, researchErr := researchClient.SearchWeb(researchCtx, epistemics.WebSearchRequest{
|
||||||
Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID("plan:" + planID), Question: utterance.Content, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"},
|
Plan: epistemics.ResearchPlan{ID: epistemics.ResearchPlanID("plan:" + planID), Question: utterance.Content, SourceClasses: []string{"web-search"}, FreshnessPolicy: "current"},
|
||||||
PropositionKey: "question:" + string(utterance.ID), Query: utterance.Content,
|
PropositionKey: "question:" + string(utterance.ID), Query: utterance.Content,
|
||||||
})
|
})
|
||||||
|
cancelResearch()
|
||||||
planningReply, researchBacked = renderResearchReply(result, researchErr)
|
planningReply, researchBacked = renderResearchReply(result, researchErr)
|
||||||
|
// A failed source must not turn the complete conversation into a
|
||||||
|
// runtime failure or invite an unsupported local guess for a fact.
|
||||||
needsCognition = false
|
needsCognition = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -158,14 +158,21 @@ func TestChatMessageDoesNotExposeUnverifiedQuestionAsFact(t *testing.T) {
|
|||||||
_ = json.NewEncoder(w).Encode(identity.CreatorSession{ActorID: "actor-1", PrincipalID: "principal-1"})
|
_ = json.NewEncoder(w).Encode(identity.CreatorSession{ActorID: "actor-1", PrincipalID: "principal-1"})
|
||||||
case r.Method == http.MethodPost && r.URL.Path == "/v1/creator/chat/messages":
|
case r.Method == http.MethodPost && r.URL.Path == "/v1/creator/chat/messages":
|
||||||
w.WriteHeader(http.StatusCreated)
|
w.WriteHeader(http.StatusCreated)
|
||||||
_ = json.NewEncoder(w).Encode(interaction.ChatMessageResponse{ConversationID: "conversation-1", UtteranceID: "utterance-1", SpeechAct: interaction.SpeechActQuestion, NeedsCognition: true, FallbackText: "небезопасная модельная догадка"})
|
_ = json.NewEncoder(w).Encode(interaction.ChatMessageResponse{ConversationID: "conversation-1", UtteranceID: "utterance-1", SpeechAct: interaction.SpeechActQuestion, NeedsCognition: true, CapabilityHints: []capability.CapabilityKind{capability.CapabilityKindWebResearch}, FallbackText: "небезопасная модельная догадка"})
|
||||||
default:
|
default:
|
||||||
t.Fatalf("unexpected core route %s %s", r.Method, r.URL.Path)
|
t.Fatalf("unexpected core route %s %s", r.Method, r.URL.Path)
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
defer core.Close()
|
defer core.Close()
|
||||||
cognitiveRuntime := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
cognitiveRuntime := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
t.Fatalf("unverified question must not reach advisory: %s %s", r.Method, r.URL.Path)
|
if r.Method != http.MethodPost || r.URL.Path != "/v1/advisories" {
|
||||||
|
t.Fatalf("unexpected cognitive route: %s %s", r.Method, r.URL.Path)
|
||||||
|
}
|
||||||
|
var request cognitive.GatewayAdvisoryRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(cognitive.GatewayAdvisoryResponse{Version: cognitive.CreatorAdvisoryV1, RequestID: request.RequestID, AdvisoryText: "Я продолжаю искать проверяемый ответ через доступный источник.", FinishReason: cognitive.FinishCompleted})
|
||||||
}))
|
}))
|
||||||
defer cognitiveRuntime.Close()
|
defer cognitiveRuntime.Close()
|
||||||
handler, err := newHandler(core.URL, "http://continuity", "http://commit", core.Client(), cognitiveRuntime.URL)
|
handler, err := newHandler(core.URL, "http://continuity", "http://commit", core.Client(), cognitiveRuntime.URL)
|
||||||
@@ -184,8 +191,53 @@ func TestChatMessageDoesNotExposeUnverifiedQuestionAsFact(t *testing.T) {
|
|||||||
if err := json.NewDecoder(recorder.Body).Decode(&response); err != nil {
|
if err := json.NewDecoder(recorder.Body).Decode(&response); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if response.Cognition != "verification_required" || strings.Contains(response.ReplyText, "небезопасная") || !strings.Contains(response.ReplyText, "не буду придумывать") {
|
if response.Cognition != string(cognitive.FinishCompleted) || strings.Contains(response.ReplyText, "небезопасная") || !strings.Contains(response.ReplyText, "продолжаю искать") {
|
||||||
t.Fatalf("unexpected truth-first response: %#v", response)
|
t.Fatalf("unexpected research recovery response: %#v", response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChatMessageUsesLocalAdvisoryForOrdinaryConversationalQuestion(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"})
|
||||||
|
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) {
|
||||||
|
if r.URL.Path != "/v1/advisories" {
|
||||||
|
t.Fatalf("unexpected cognitive path %s", r.URL.Path)
|
||||||
|
}
|
||||||
|
var request cognitive.GatewayAdvisoryRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(cognitive.GatewayAdvisoryResponse{Version: cognitive.CreatorAdvisoryV1, RequestID: request.RequestID, AdvisoryText: "Я рядом. Давай поговорим.", FinishReason: cognitive.FinishCompleted})
|
||||||
|
}))
|
||||||
|
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)
|
||||||
|
if recorder.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected status 200, got %d body=%s", recorder.Code, recorder.Body.String())
|
||||||
|
}
|
||||||
|
var response browserChatResponse
|
||||||
|
if err := json.NewDecoder(recorder.Body).Decode(&response); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if response.ReplyText != "Я рядом. Давай поговорим." || response.Cognition != string(cognitive.FinishCompleted) {
|
||||||
|
t.Fatalf("unexpected conversational response: %#v", response)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,11 @@ func main() {
|
|||||||
envOr("CORE_RUNTIME_URL", "http://core-runtime:8080"),
|
envOr("CORE_RUNTIME_URL", "http://core-runtime:8080"),
|
||||||
envOr("CONTINUITY_RUNTIME_URL", "http://continuity-runtime:8081"),
|
envOr("CONTINUITY_RUNTIME_URL", "http://continuity-runtime:8081"),
|
||||||
envOr("COMMIT_RUNTIME_URL", "http://commit-runtime:8082"),
|
envOr("COMMIT_RUNTIME_URL", "http://commit-runtime:8082"),
|
||||||
&http.Client{Timeout: 10 * time.Second},
|
// Core chat may spend several seconds on semantic interpretation and
|
||||||
|
// local cognition. Keep the browser gateway alive long enough to return
|
||||||
|
// the completed response instead of converting a successful core 201
|
||||||
|
// into a misleading 502.
|
||||||
|
&http.Client{Timeout: 30 * time.Second},
|
||||||
envOr("COGNITIVE_RUNTIME_URL", "http://cognitive-worker:8083"),
|
envOr("COGNITIVE_RUNTIME_URL", "http://cognitive-worker:8083"),
|
||||||
envOr("AGENT_WORKER_URL", "http://agent-worker:8090"),
|
envOr("AGENT_WORKER_URL", "http://agent-worker:8090"),
|
||||||
)
|
)
|
||||||
|
|||||||
+20
-18
@@ -468,11 +468,7 @@ func (g *gateway) handleChatMessage(w http.ResponseWriter, r *http.Request) {
|
|||||||
saved.NeedsCognition = false
|
saved.NeedsCognition = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if saved.SpeechAct == interaction.SpeechActQuestion && saved.InformationRequestKind == "" && !saved.ResearchBacked && !saved.WorkPlanned && saved.Clarification != interaction.ClarificationRequired && !asksAttention(browserRequest.Message) {
|
if saved.NeedsCognition && !saved.WorkPlanned && saved.Clarification != interaction.ClarificationRequired {
|
||||||
reply = truthfulVerificationRequiredReply()
|
|
||||||
cognition = "verification_required"
|
|
||||||
saved.NeedsCognition = false
|
|
||||||
} else if saved.NeedsCognition && !saved.WorkPlanned && saved.Clarification != interaction.ClarificationRequired {
|
|
||||||
cognition = "unavailable"
|
cognition = "unavailable"
|
||||||
requestID, idErr := ids.New()
|
requestID, idErr := ids.New()
|
||||||
if idErr == nil {
|
if idErr == nil {
|
||||||
@@ -514,18 +510,19 @@ func (g *gateway) handleChatMessage(w http.ResponseWriter, r *http.Request) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func truthfulVerificationRequiredReply() string {
|
|
||||||
return "Я не могу сейчас подтвердить этот факт по проверенному источнику, поэтому не буду придумывать ответ. Для проверки используйте официальный сайт соответствующей службы или надёжный сервис с текущими данными; когда подключён research-маршрут, Домовой сможет проверить это сам."
|
|
||||||
}
|
|
||||||
|
|
||||||
func localChatContext(saved interaction.ChatMessageResponse) []cognitive.ContextExcerpt {
|
func localChatContext(saved interaction.ChatMessageResponse) []cognitive.ContextExcerpt {
|
||||||
if strings.TrimSpace(saved.ActiveProjectName) == "" {
|
candidates := []cognitive.ContextCandidate{{
|
||||||
return []cognitive.ContextExcerpt{}
|
Excerpt: cognitive.ContextExcerpt{
|
||||||
}
|
ID: "assistant-identity",
|
||||||
bundle, err := cognitive.CompileContext(cognitive.ContextCompileInput{
|
SourceKind: "assistant-identity-policy",
|
||||||
DataPolicy: capability.DataPolicyLocalOnly,
|
SourceID: "domovoy",
|
||||||
MaxBytes: 2048,
|
Sensitivity: cognitive.SensitivityPublic,
|
||||||
Candidates: []cognitive.ContextCandidate{{
|
Text: "Ты — Домовой, локальный помощник пользователя. Отвечай от имени Домового. Не называй себя Qwen, Alibaba Cloud, поставщиком модели или внутренним runtime. Если спрашивают имя, скажи: «Меня зовут Домовой». Твоя задача — понять смысл запроса, найти путь к цели и довести помощь до полезного конечного результата; не ограничивайся пересказом отказа модели.",
|
||||||
|
},
|
||||||
|
Relevance: 100,
|
||||||
|
}}
|
||||||
|
if strings.TrimSpace(saved.ActiveProjectName) != "" {
|
||||||
|
candidates = append(candidates, cognitive.ContextCandidate{
|
||||||
Excerpt: cognitive.ContextExcerpt{
|
Excerpt: cognitive.ContextExcerpt{
|
||||||
ID: cognitive.ContextExcerptID("active-project-focus"),
|
ID: cognitive.ContextExcerptID("active-project-focus"),
|
||||||
SourceKind: "situation-active-project",
|
SourceKind: "situation-active-project",
|
||||||
@@ -533,8 +530,13 @@ func localChatContext(saved interaction.ChatMessageResponse) []cognitive.Context
|
|||||||
Sensitivity: cognitive.SensitivityPrivateAllowed,
|
Sensitivity: cognitive.SensitivityPrivateAllowed,
|
||||||
Text: "Текущий проект: " + strings.TrimSpace(saved.ActiveProjectName),
|
Text: "Текущий проект: " + strings.TrimSpace(saved.ActiveProjectName),
|
||||||
},
|
},
|
||||||
Relevance: 100,
|
Relevance: 90,
|
||||||
}},
|
})
|
||||||
|
}
|
||||||
|
bundle, err := cognitive.CompileContext(cognitive.ContextCompileInput{
|
||||||
|
DataPolicy: capability.DataPolicyLocalOnly,
|
||||||
|
MaxBytes: 2048,
|
||||||
|
Candidates: candidates,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return []cognitive.ContextExcerpt{}
|
return []cognitive.ContextExcerpt{}
|
||||||
|
|||||||
@@ -13,13 +13,13 @@ import (
|
|||||||
"git.cin.su/m/Assistant/contracts/interaction"
|
"git.cin.su/m/Assistant/contracts/interaction"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestLocalChatContextUsesOnlyActiveProject(t *testing.T) {
|
func TestLocalChatContextIncludesDomovoyIdentityAndOptionalActiveProject(t *testing.T) {
|
||||||
context := localChatContext(interaction.ChatMessageResponse{ActiveProjectName: "Домовой"})
|
context := localChatContext(interaction.ChatMessageResponse{ActiveProjectName: "Домовой"})
|
||||||
if len(context) != 1 || context[0].SourceKind != "situation-active-project" || context[0].Text != "Текущий проект: Домовой" {
|
if len(context) != 2 || context[0].SourceID != "domovoy" || !strings.Contains(context[0].Text, "Ты — Домовой") || context[1].Text != "Текущий проект: Домовой" {
|
||||||
t.Fatalf("unexpected local context: %#v", context)
|
t.Fatalf("unexpected local context: %#v", context)
|
||||||
}
|
}
|
||||||
if empty := localChatContext(interaction.ChatMessageResponse{}); len(empty) != 0 {
|
if empty := localChatContext(interaction.ChatMessageResponse{}); len(empty) != 1 || empty[0].SourceID != "domovoy" {
|
||||||
t.Fatalf("expected empty context without active project: %#v", empty)
|
t.Fatalf("identity context must remain available without active project: %#v", empty)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -89,7 +89,16 @@ func main() {
|
|||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
_ = json.NewEncoder(w).Encode(result)
|
_ = json.NewEncoder(w).Encode(result)
|
||||||
})
|
})
|
||||||
searchConnector := researchadapter.SearchConnector{EndpointTemplate: os.Getenv("RESEARCH_SEARCH_URL_TEMPLATE"), AllowedHosts: allowedHosts(os.Getenv("RESEARCH_SEARCH_ALLOWED_HOSTS")), Client: &http.Client{Timeout: 8 * time.Second}, MaxResults: 3}
|
searchConnector := researchadapter.SearchConnector{
|
||||||
|
EndpointTemplate: os.Getenv("RESEARCH_SEARCH_URL_TEMPLATE"),
|
||||||
|
AllowedHosts: allowedHosts(os.Getenv("RESEARCH_SEARCH_ALLOWED_HOSTS")),
|
||||||
|
FallbackEndpoints: []researchadapter.SearchEndpoint{{
|
||||||
|
Template: "https://html.duckduckgo.com/html/?q=%s",
|
||||||
|
AllowedHosts: map[string]struct{}{"html.duckduckgo.com": {}},
|
||||||
|
}},
|
||||||
|
Client: &http.Client{Timeout: 8 * time.Second},
|
||||||
|
MaxResults: 3,
|
||||||
|
}
|
||||||
mux.HandleFunc("POST /v1/research/web/search", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("POST /v1/research/web/search", func(w http.ResponseWriter, r *http.Request) {
|
||||||
var request epistemics.WebSearchRequest
|
var request epistemics.WebSearchRequest
|
||||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&request); err != nil {
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&request); err != nil {
|
||||||
|
|||||||
@@ -102,8 +102,11 @@ services:
|
|||||||
LISTEN_ADDR: ":8083"
|
LISTEN_ADDR: ":8083"
|
||||||
CORE_RUNTIME_URL: http://core-runtime:8080
|
CORE_RUNTIME_URL: http://core-runtime:8080
|
||||||
LOCAL_CPU_PROVIDER_URL: http://docker.cin.su:18082/v1
|
LOCAL_CPU_PROVIDER_URL: http://docker.cin.su:18082/v1
|
||||||
|
LOCAL_MEDIUM_PROVIDER_URL: ${LOCAL_MEDIUM_PROVIDER_URL:-http://docker.cin.su:18082/v1}
|
||||||
|
LOCAL_MEDIUM_PROVIDER_TIMEOUT: ${LOCAL_MEDIUM_PROVIDER_TIMEOUT:-120s}
|
||||||
LOCAL_LIFEBOAT_PROVIDER_URL: ${LOCAL_LIFEBOAT_PROVIDER_URL:-}
|
LOCAL_LIFEBOAT_PROVIDER_URL: ${LOCAL_LIFEBOAT_PROVIDER_URL:-}
|
||||||
LOCAL_GPU_PROVIDER_URL: http://192.168.220.91:11434
|
LOCAL_GPU_PROVIDER_URL: http://192.168.220.91:11434
|
||||||
|
COGNITIVE_ALLOW_CANARY: "true"
|
||||||
COGNITIVE_OWNER_PRINCIPAL_ID: domovoy-creator-principal
|
COGNITIVE_OWNER_PRINCIPAL_ID: domovoy-creator-principal
|
||||||
ports: ["19083:8083"]
|
ports: ["19083:8083"]
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"task_file": "dev/tasks/DEV-000291-mobile-acceptance-evidence.json",
|
"task_file": "dev/tasks/DEV-000292-development-mode-runtime-access.json",
|
||||||
"task_id": "DEV-000291",
|
"task_id": "DEV-000292",
|
||||||
"task_revision": 1
|
"task_revision": 1
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
{
|
||||||
|
"task_id": "DEV-000292",
|
||||||
|
"task_revision": 1,
|
||||||
|
"architecture_revision": "ADR-0018",
|
||||||
|
"base_repo_revision": "HEAD",
|
||||||
|
"risk_tier": "E",
|
||||||
|
"intent": "Provide an explicitly isolated development/test runtime profile for Domovoy so local model, speech, image, OCR, Docker and diagnostic paths are usable without changing production behavior.",
|
||||||
|
"requirement_ids": ["isolated development runtime", "local multimodal model access", "development diagnostics"],
|
||||||
|
"allowed_change_scope": {
|
||||||
|
"modules": ["interaction", "core-runtime", "cognitive-worker", "creator-web", "deployment", "development-governance"],
|
||||||
|
"paths": [
|
||||||
|
"cmd/cognitive-worker/**",
|
||||||
|
"cmd/core-runtime/**",
|
||||||
|
"cmd/creator-web/**",
|
||||||
|
"cmd/research-runtime/**",
|
||||||
|
"adapters/models/**",
|
||||||
|
"adapters/research/**",
|
||||||
|
"contracts/cognitive/**",
|
||||||
|
"modules/interaction/domain/**",
|
||||||
|
"deploy/docker-compose.dev.yml",
|
||||||
|
"dev/ACTIVE_TASK.json",
|
||||||
|
"dev/tasks/DEV-000292-development-mode-runtime-access.json",
|
||||||
|
"docs/evidence/**",
|
||||||
|
"docs/PROJECT_STATUS.md"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"forbidden_change_scope": {
|
||||||
|
"paths": ["architecture/**", "security/**", "database/**", "deploy/docker-compose.prod.yml", "LLM-local/**"]
|
||||||
|
},
|
||||||
|
"allowed_architecture_delta": {
|
||||||
|
"new_cross_module_dependencies": 0,
|
||||||
|
"new_canonical_owners": 0,
|
||||||
|
"new_privileges": 1,
|
||||||
|
"new_third_party_dependencies": 0,
|
||||||
|
"new_database_owner_roles": 0
|
||||||
|
},
|
||||||
|
"contracts": {
|
||||||
|
"consume": ["existing cognitive gateway", "existing local model HTTP APIs", "existing dev compose network"],
|
||||||
|
"may_change": ["dev-only modality and diagnostic wiring; no production contract change"]
|
||||||
|
},
|
||||||
|
"semantic_owner": "development-governance owns the isolated dev profile; cognitive-worker owns model capability routing",
|
||||||
|
"canonical_state": ["existing dev databases and Docker volumes only"],
|
||||||
|
"state_transitions": ["production-only restriction -> explicit dev-only capability switch"],
|
||||||
|
"side_effects_and_privileges": ["dev network and Docker diagnostics only", "no production credentials", "no secret logging", "no production external mutation"],
|
||||||
|
"persistence_and_migrations": ["dev volumes only; no production migration"],
|
||||||
|
"failure_retry_restart": ["dev services remain independently restartable", "unsupported modality stays explicitly unavailable"],
|
||||||
|
"assumptions": ["the developer starts the profile separately from production", "test credentials are disposable and never reused in production"],
|
||||||
|
"acceptance_scenarios": ["dev profile starts independently", "text, speech, image and OCR routes are discoverable or report a precise unavailable state", "diagnostic endpoints are reachable inside the dev network", "meaningful chat requests prefer cognitive interpretation over token reflexes", "stable reflexes are sampled periodically for cognitive drift and a disagreement is observable as a cognitive candidate", "production compose remains unchanged", "no secret value appears in source or logs"],
|
||||||
|
"required_tests": ["go test ./...", "go vet ./...", "go run ./cmd/devctl preflight -active dev/ACTIVE_TASK.json", "go run ./cmd/devctl check-diff -active dev/ACTIVE_TASK.json", "go run ./cmd/devctl check-architecture", "go run ./cmd/devctl independent", "docker compose -f deploy/docker-compose.dev.yml config", "git diff --check", "dev runtime health smoke"],
|
||||||
|
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT", "BLOCKED_BY_MISSING_CAPABILITY"]
|
||||||
|
}
|
||||||
@@ -215,7 +215,7 @@ func semanticScores(tokens []string, hasQuestionMark bool, explicitCorrection bo
|
|||||||
conversationWords := []string{"привет", "здравствуйте", "спасибо", "ку", "здравствуй"}
|
conversationWords := []string{"привет", "здравствуйте", "спасибо", "ку", "здравствуй"}
|
||||||
investigateStems := []string{"разбер", "проверь", "проанализ", "исслед", "выясн", "подум", "понят", "посмотри"}
|
investigateStems := []string{"разбер", "проверь", "проанализ", "исслед", "выясн", "подум", "понят", "посмотри"}
|
||||||
directiveStems := []string{"сдел", "запуст", "созд", "настро", "добав", "измени", "помен", "использ", "удал", "напом", "подключ", "исправ", "обрати", "спрос", "посчитай", "рассчитай", "ответь"}
|
directiveStems := []string{"сдел", "запуст", "созд", "настро", "добав", "измени", "помен", "использ", "удал", "напом", "подключ", "исправ", "обрати", "спрос", "посчитай", "рассчитай", "ответь"}
|
||||||
explanatoryRequestStems := []string{"расска", "раска", "объяс", "опиш", "покаж", "подскаж"}
|
explanatoryRequestStems := []string{"расска", "раска", "объяс", "опиш", "покаж", "подскаж", "сообщ"}
|
||||||
preferenceStems := []string{"предпоч", "хочу", "лучше", "не используй"}
|
preferenceStems := []string{"предпоч", "хочу", "лучше", "не используй"}
|
||||||
hypothesisStems := []string{"думаю", "кажется", "гипотез", "похоже"}
|
hypothesisStems := []string{"думаю", "кажется", "гипотез", "похоже"}
|
||||||
decisionStems := []string{"решил", "решение", "выбираю"}
|
decisionStems := []string{"решил", "решение", "выбираю"}
|
||||||
@@ -471,7 +471,7 @@ func informationRequestKind(message string, candidate interaction.SemanticCandid
|
|||||||
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, "настро"))
|
||||||
inventoryRequest := inquiry || containsStemInTokens(tokens, "напиш", "покаж", "перечисл")
|
inventoryRequest := inquiry || containsStemInTokens(tokens, "напиш", "покаж", "перечисл", "сообщ", "вывед", "предостав")
|
||||||
if cognitiveSubject && inventoryRequest && inventoryCue {
|
if cognitiveSubject && inventoryRequest && inventoryCue {
|
||||||
return interaction.InformationRequestCognitiveModelInventory
|
return interaction.InformationRequestCognitiveModelInventory
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -121,6 +121,8 @@ func TestInformationRequestsAreClassifiedOnceByInteraction(t *testing.T) {
|
|||||||
{"что ты умеешь?", interaction.InformationRequestCapabilityInventory},
|
{"что ты умеешь?", interaction.InformationRequestCapabilityInventory},
|
||||||
{"проверь состояние локального канала", interaction.InformationRequestCognitiveChannelStatus},
|
{"проверь состояние локального канала", interaction.InformationRequestCognitiveChannelStatus},
|
||||||
{"нет связи с ИИ, восстанови канал", interaction.InformationRequestCognitiveRecovery},
|
{"нет связи с ИИ, восстанови канал", interaction.InformationRequestCognitiveRecovery},
|
||||||
|
{"сообщии список моделей", interaction.InformationRequestCognitiveModelInventory},
|
||||||
|
{"сообщите список подключённых моделей", interaction.InformationRequestCognitiveModelInventory},
|
||||||
}
|
}
|
||||||
for _, test := range cases {
|
for _, test := range cases {
|
||||||
result, err := InterpretUtterance(interaction.HumanUtterance{Content: test.message}, nil, nil, time.Unix(10, 0))
|
result, err := InterpretUtterance(interaction.HumanUtterance{Content: test.message}, nil, nil, time.Unix(10, 0))
|
||||||
|
|||||||
Reference in New Issue
Block a user