feat: answer model inventory from capability registry
This commit is contained in:
@@ -394,6 +394,11 @@ func main() {
|
||||
}
|
||||
needsCognition = false
|
||||
}
|
||||
if isModelInventoryQuestion(utterance.Content) {
|
||||
candidates, inventoryErr := capabilityRepository.LoadCognitiveCandidates(r.Context(), capability.CapabilityID("creator-advisory"), session.PrincipalID)
|
||||
planningReply = humanCognitiveModelInventory(candidates, inventoryErr)
|
||||
needsCognition = false
|
||||
}
|
||||
if isCognitiveChannelQuestion(utterance.Content) {
|
||||
health, healthErr := capabilityRepository.LoadHealth(r.Context(), capability.CapabilityID("cognitive-proposal"))
|
||||
planningReply = humanCognitiveChannelReply(utterance.Content, health, healthErr)
|
||||
@@ -1153,6 +1158,90 @@ func isCapabilityQuestion(message string) bool {
|
||||
return strings.Contains(lower, "что ты умеешь") || strings.Contains(lower, "что умеешь") || strings.Contains(lower, "какие возможности")
|
||||
}
|
||||
|
||||
func isModelInventoryQuestion(message string) bool {
|
||||
lower := strings.ToLower(strings.TrimSpace(message))
|
||||
if lower == "" {
|
||||
return false
|
||||
}
|
||||
asksAboutModels := strings.Contains(lower, "модел") || strings.Contains(lower, "ии") && (strings.Contains(lower, "внешн") || strings.Contains(lower, "настро") || strings.Contains(lower, "подключ"))
|
||||
asksForInventory := strings.Contains(lower, "какие") || strings.Contains(lower, "какая") || strings.Contains(lower, "список") || strings.Contains(lower, "доступ") || strings.Contains(lower, "настро")
|
||||
return asksAboutModels && asksForInventory
|
||||
}
|
||||
|
||||
func humanCognitiveModelInventory(candidates []capability.ResolvedCognitiveBinding, inventoryErr error) string {
|
||||
if inventoryErr != nil {
|
||||
return "Я не смогла прочитать реестр подключённых моделей. Встроенный канал Домового остаётся доступен; настройки можно проверить повторно после восстановления реестра. Ключи и пароли не выводятся в чат."
|
||||
}
|
||||
if len(candidates) == 0 {
|
||||
return "В реестре пока нет подтверждённых подключённых моделей. Встроенный локальный канал Домового доступен всегда; внешние модели добавляются через настройки подключения. Ключи и пароли в чат не выводятся."
|
||||
}
|
||||
lines := make([]string, 0, len(candidates)+1)
|
||||
lines = append(lines, "Подключённые модели из реестра:")
|
||||
for _, candidate := range candidates {
|
||||
modelName := string(candidate.Model.ProviderModelID)
|
||||
if modelName == "" {
|
||||
modelName = "имя модели не подтверждено"
|
||||
}
|
||||
status := cognitiveInventoryStatus(candidate)
|
||||
pricing := cognitiveInventoryPricing(candidate.Provider)
|
||||
details := []string{status, "тип " + string(candidate.Provider.Kind), "политика " + string(candidate.Binding.DataPolicy)}
|
||||
if pricing != "" {
|
||||
details = append(details, pricing)
|
||||
}
|
||||
if candidate.Provider.AuthMode != "" && candidate.Provider.AuthMode != capability.AuthNone {
|
||||
details = append(details, "доступ "+humanAuthMode(candidate.Provider.AuthMode))
|
||||
}
|
||||
lines = append(lines, "- "+modelName+" ("+strings.Join(details, "; ")+")")
|
||||
}
|
||||
lines = append(lines, "Секреты, ключи и пароли намеренно не показываются.")
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func cognitiveInventoryStatus(candidate capability.ResolvedCognitiveBinding) string {
|
||||
if candidate.Provider.Health == capability.HealthAvailable && candidate.Model.Health == capability.HealthAvailable {
|
||||
if candidate.Binding.Activation == capability.ActivationActive {
|
||||
return "активна"
|
||||
}
|
||||
return "доступна, не активирована для автоматического выбора"
|
||||
}
|
||||
if candidate.Provider.Health == capability.HealthDegraded || candidate.Model.Health == capability.HealthDegraded {
|
||||
return "работает с ограничениями"
|
||||
}
|
||||
return "недоступна или не подтверждена"
|
||||
}
|
||||
|
||||
func cognitiveInventoryPricing(provider capability.ProviderInstance) string {
|
||||
switch provider.BillingMode {
|
||||
case capability.BillingFree:
|
||||
return "бесплатная"
|
||||
case capability.BillingPerInput:
|
||||
return "платная: стоимость входа указана в реестре"
|
||||
case capability.BillingPerOutput:
|
||||
return "платная: стоимость выхода указана в реестре"
|
||||
case capability.BillingPerRequest:
|
||||
return "платная: стоимость запроса указана в реестре"
|
||||
default:
|
||||
return "стоимость не подтверждена"
|
||||
}
|
||||
}
|
||||
|
||||
func humanAuthMode(mode capability.AuthMode) string {
|
||||
switch mode {
|
||||
case capability.AuthKey:
|
||||
return "API-ключ"
|
||||
case capability.AuthBearer:
|
||||
return "Bearer-токен"
|
||||
case capability.AuthUsernamePassword:
|
||||
return "логин и пароль"
|
||||
case capability.AuthOAuth:
|
||||
return "OAuth"
|
||||
case capability.AuthSecretFile:
|
||||
return "защищённый файл секрета"
|
||||
default:
|
||||
return "защищённый способ"
|
||||
}
|
||||
}
|
||||
|
||||
func isCognitiveChannelQuestion(message string) bool {
|
||||
lower := strings.ToLower(message)
|
||||
markers := []string{"локальн", "модель", "когнитивн", "канал мышления", "проверь канал", "настройк"}
|
||||
|
||||
@@ -49,6 +49,26 @@ func TestCognitiveDegradedReplyKeepsDomovoyAlive(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelInventoryQuestionUsesReadOnlyFastPath(t *testing.T) {
|
||||
for _, message := range []string{"какие модели доступны?", "напиши список настроек ИИ", "какие есть подключения ИИ"} {
|
||||
if !isModelInventoryQuestion(message) {
|
||||
t.Fatalf("message %q was not recognized as model inventory question", message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHumanCognitiveModelInventoryDoesNotExposeSecrets(t *testing.T) {
|
||||
cost := int64(25)
|
||||
text := humanCognitiveModelInventory([]capability.ResolvedCognitiveBinding{{
|
||||
Binding: capability.CognitiveBinding{DataPolicy: capability.DataPolicyExternalMessageOnly, Activation: capability.ActivationActive},
|
||||
Provider: capability.ProviderInstance{Kind: "openai-compatible-chat-v1", CredentialRef: "secret-ref", AuthMode: capability.AuthKey, BillingMode: capability.BillingPerRequest, RequestCostMicros: &cost, Health: capability.HealthAvailable},
|
||||
Model: capability.ModelDescriptor{ProviderModelID: "example-model", Health: capability.HealthAvailable},
|
||||
}}, nil)
|
||||
if strings.Contains(text, "secret-ref") || strings.Contains(text, "25") || !strings.Contains(text, "example-model") || !strings.Contains(text, "API-ключ") {
|
||||
t.Fatalf("unsafe or incomplete inventory: %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatorSessionHandlerAcceptsConfiguredCredentials(t *testing.T) {
|
||||
handler := creatorSessionHandler("recovery", "m", "password", []byte("01234567890123456789012345678901"), func() time.Time { return time.Unix(1000, 0) })
|
||||
request := httptest.NewRequest(http.MethodPost, "/v1/creator/sessions", strings.NewReader(`{"username":"m","password":"password"}`))
|
||||
|
||||
Reference in New Issue
Block a user