/* Copyright 2026. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controller import ( "context" _ "embed" // Required for go:embed directives in this package "fmt" common_helper "github.com/openstack-k8s-operators/lib-common/modules/common/helper" apiv1beta1 "github.com/openstack-k8s-operators/lightspeed-operator/api/v1beta1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/yaml" ) // systemPrompt - system prompt tailored to the needs of OpenStack Lightspeed. // //go:embed assets/system_prompt.txt var systemPrompt string // getSystemPrompt returns the OpenStackLightspeed system prompt func getSystemPrompt() string { return systemPrompt } // lcoreProvider represents an LLM provider configuration. type lcoreProvider struct { Name string URL string Type string CredentialsSecret string Models []lcoreModel AzureDeploymentName string APIVersion string WatsonProjectID string } // lcoreModel represents a model configuration. type lcoreModel struct { Name string MaxTokensForResponse int } func modelProviderName(modelName string) string { return fmt.Sprintf("provider-%s", modelName) } // buildProviders creates lcore providers from an OpenStackLightspeed instance. func buildProviders(instance *apiv1beta1.OpenStackLightspeed) []lcoreProvider { providers := make([]lcoreProvider, 0, len(instance.Spec.Models)) for _, model := range instance.Spec.Models { providers = append(providers, lcoreProvider{ Name: modelProviderName(model.Name), URL: model.LLMEndpoint, Type: model.LLMEndpointType, CredentialsSecret: model.LLMCredentials, Models: []lcoreModel{ { Name: model.ModelName, MaxTokensForResponse: model.MaxTokensForResponse, }, }, AzureDeploymentName: model.LLMDeploymentName, APIVersion: model.LLMAPIVersion, WatsonProjectID: model.LLMProjectID, }) } return providers } func buildLCoreServiceConfig(_ *common_helper.Helper, _ *apiv1beta1.OpenStackLightspeed) map[string]interface{} { return map[string]interface{}{ "host": "0.0.0.0", "port": OpenStackLightspeedAppServerContainerPort, "auth_enabled": true, "workers": 1, "color_log": false, "access_log": true, "tls_config": map[string]interface{}{ "tls_certificate_path": OpenStackLightspeedTLSCertPath, "tls_key_path": OpenStackLightspeedTLSKeyPath, }, } } func buildLCoreOGXConfig() map[string]interface{} { ogxConfig := map[string]interface{}{ "use_as_library_client": false, "url": fmt.Sprintf("http://localhost:%d", OGXContainerPort), } return ogxConfig } func buildLCoreUserDataCollectionConfig(_ *common_helper.Helper, instance *apiv1beta1.OpenStackLightspeed) map[string]interface{} { feedbackEnabled := isDataverseExporterFeedbackEnabled(instance) transcriptsEnabled := isDataverseExporterTranscriptsEnabled(instance) return map[string]interface{}{ "feedback_enabled": feedbackEnabled, "feedback_storage": LCoreUserDataMountPath + "/feedback", "transcripts_enabled": transcriptsEnabled, "transcripts_storage": LCoreUserDataMountPath + "/transcripts", } } func buildLCoreAuthenticationConfig(_ *common_helper.Helper, _ *apiv1beta1.OpenStackLightspeed) map[string]interface{} { return map[string]interface{}{ "module": "k8s", "skip_for_health_probes": true, } } func buildLCoreInferenceConfig(_ *common_helper.Helper, instance *apiv1beta1.OpenStackLightspeed) map[string]interface{} { return map[string]interface{}{ "default_provider": modelProviderName(instance.Spec.DefaultModel), "default_model": instance.Spec.DefaultModel, } } // buildLCoreDatabaseConfig configures persistent database storage (PostgreSQL) func buildLCoreDatabaseConfig(h *common_helper.Helper, _ *apiv1beta1.OpenStackLightspeed) map[string]interface{} { return map[string]interface{}{ // #nosec G101 -- values are env-var substitution placeholders, not hardcoded credentials "postgres": map[string]interface{}{ "host": PostgresServiceName + "." + h.GetBeforeObject().GetNamespace() + ".svc", "port": PostgresServicePort, "db": PostgresLightspeedStackDbName, "user": "${env.POSTGRESQL_USER}", "ssl_mode": PostgresDefaultSSLMode, "gss_encmode": "disable", "ca_cert_path": CABundleMountPath, // Environment variable substitution via ogx.core.stack.replace_env_vars "password": "${env.POSTGRESQL_PASSWORD}", // Separate schema for LCore to avoid conflicts with App Server "namespace": "lcore", }, } } // buildLCoreCustomizationConfig configures the system prompt. func buildLCoreCustomizationConfig() map[string]interface{} { return map[string]interface{}{ "system_prompt": getSystemPrompt(), // Prevent users from overriding via API "disable_query_system_prompt": true, } } // buildLCoreConversationCacheConfig configures chat history caching (PostgreSQL) func buildLCoreConversationCacheConfig(h *common_helper.Helper, _ *apiv1beta1.OpenStackLightspeed) map[string]interface{} { return map[string]interface{}{ "type": "postgres", // #nosec G101 -- values are env-var substitution placeholders, not hardcoded credentials "postgres": map[string]interface{}{ "host": PostgresServiceName + "." + h.GetBeforeObject().GetNamespace() + ".svc", "port": PostgresServicePort, "db": PostgresLightspeedStackDbName, "user": "${env.POSTGRESQL_USER}", "password": "${env.POSTGRESQL_PASSWORD}", "ssl_mode": PostgresDefaultSSLMode, "gss_encmode": "disable", "ca_cert_path": CABundleMountPath, "namespace": "conversation_cache", }, } } // quotaLimiterTypeMapping maps CRD-facing limiter types to the literal values // matched exactly by lightspeed-stack's QuotaLimiterFactory. var quotaLimiterTypeMapping = map[string]string{ "userLimiter": "user_limiter", "clusterLimiter": "cluster_limiter", } // buildLCoreQuotaHandlersConfig configures quota enforcement (limiters, scheduler, // token history), backed by the operator-managed database instance. Returns nil // when no limiters are configured, keeping quota enforcement opt-in. func buildLCoreQuotaHandlersConfig(h *common_helper.Helper, instance *apiv1beta1.OpenStackLightspeed) map[string]interface{} { quotas := instance.Spec.Quotas if quotas == nil || len(quotas.Limiters) == 0 { return nil } limiters := make([]interface{}, 0, len(quotas.Limiters)) for _, limiter := range quotas.Limiters { limiters = append(limiters, map[string]interface{}{ "name": limiter.Name, "type": quotaLimiterTypeMapping[limiter.Type], "initial_quota": limiter.InitialQuota, "quota_increase": limiter.QuotaIncrease, "period": limiter.Period, }) } scheduler := &apiv1beta1.QuotaSchedulerSpec{Period: 5, DatabaseReconnectionCount: 10, DatabaseReconnectionDelay: 1} if quotas.Scheduler != nil { scheduler = quotas.Scheduler } return map[string]interface{}{ "postgres": map[string]interface{}{ "host": PostgresServiceName + "." + h.GetBeforeObject().GetNamespace() + ".svc", "port": PostgresServicePort, "db": PostgresLightspeedStackDbName, "user": "${env.POSTGRESQL_USER}", // #nosec G101 - This is only a placeholder. "password": "${env.POSTGRESQL_PASSWORD}", // #nosec G101 - This is only a placeholder. "ssl_mode": PostgresDefaultSSLMode, "gss_encmode": "disable", "ca_cert_path": CABundleMountPath, "namespace": "quota_handlers", }, "limiters": limiters, "scheduler": map[string]interface{}{ "period": scheduler.Period, "database_reconnection_count": scheduler.DatabaseReconnectionCount, "database_reconnection_delay": scheduler.DatabaseReconnectionDelay, }, "enable_token_history": quotas.EnableTokenHistory, } } // isDataCollectionEnabled returns true if at least one of feedback or transcripts is enabled. func isDataCollectionEnabled(instance *apiv1beta1.OpenStackLightspeed) bool { return isDataverseExporterFeedbackEnabled(instance) || isDataverseExporterTranscriptsEnabled(instance) } func isDataverseExporterFeedbackEnabled(instance *apiv1beta1.OpenStackLightspeed) bool { if instance.Spec.DataverseExporter == nil || instance.Spec.DataverseExporter.Feedback == nil || instance.Spec.DataverseExporter.Feedback.Enabled == nil { return true } return *instance.Spec.DataverseExporter.Feedback.Enabled } func isDataverseExporterTranscriptsEnabled(instance *apiv1beta1.OpenStackLightspeed) bool { if instance.Spec.DataverseExporter == nil || instance.Spec.DataverseExporter.Transcripts == nil { return false } return instance.Spec.DataverseExporter.Transcripts.Enabled } func dataverseExporterLogLevel(instance *apiv1beta1.OpenStackLightspeed) string { if instance.Spec.DataverseExporter == nil { return "" } return instance.Spec.DataverseExporter.LogLevel } // buildExporterConfigMap creates the ConfigMap for the dataverse exporter sidecar. func buildExporterConfigMap(h *common_helper.Helper, _ *apiv1beta1.OpenStackLightspeed) *corev1.ConfigMap { exporterConfig := fmt.Sprintf(`service_id: "%s" ingress_server_url: "https://console.redhat.com/api/ingress/v1/upload" allowed_subdirs: - feedback - transcripts - config_status collection_interval: 300 cleanup_after_send: true ingress_connection_timeout: 30 `, ServiceIDRHOSO) return &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: ExporterConfigCmName, Namespace: h.GetBeforeObject().GetNamespace(), Labels: generateAppServerSelectorLabels(), }, Data: map[string]string{ ExporterConfigFilename: exporterConfig, }, } } func buildOKPConfig(ctx context.Context, h *common_helper.Helper, instance *apiv1beta1.OpenStackLightspeed) map[string]interface{} { offline := true if instance.Spec.OKP != nil && instance.Spec.OKP.Offline != nil { offline = *instance.Spec.OKP.Offline } return map[string]interface{}{ "rhokp_url": "${env.RH_SERVER_OKP}", "offline": offline, "chunk_filter_query": getOKPChunkFilterQuery(ctx, h, instance), } } // buildLCoreRetrievalConfig builds the rag.retrieval section. // OKP is always exposed via the file-search tool; empty inline.sources is // filled by vector-database-config-build with BYOK vector store IDs. func buildLCoreRetrievalConfig(_ *apiv1beta1.OpenStackLightspeed) map[string]interface{} { return map[string]interface{}{ "inline": map[string]interface{}{ "sources": []interface{}{}, }, "tool": map[string]interface{}{ "sources": []interface{}{"okp"}, }, } } // buildLCoreRAGConfig builds the rag section of the lightspeed-stack config. func buildLCoreRAGConfig(ctx context.Context, h *common_helper.Helper, instance *apiv1beta1.OpenStackLightspeed) map[string]interface{} { return map[string]interface{}{ "byok": map[string]interface{}{ "stores": []interface{}{}, }, "retrieval": buildLCoreRetrievalConfig(instance), "okp": buildOKPConfig(ctx, h, instance), } } // buildLCoreConfigYAML assembles the complete Lightspeed Core Service configuration and converts to YAML. // NOTE: tools approval features are disabled for OpenStack Lightspeed. func buildLCoreConfigYAML(ctx context.Context, h *common_helper.Helper, instance *apiv1beta1.OpenStackLightspeed) (string, error) { // Build the complete config as a map config := map[string]interface{}{ "name": "Lightspeed Core Service (LCS)", "service": buildLCoreServiceConfig(h, instance), "ogx": buildLCoreOGXConfig(), "user_data_collection": buildLCoreUserDataCollectionConfig(h, instance), "authentication": buildLCoreAuthenticationConfig(h, instance), "inference": buildLCoreInferenceConfig(h, instance), "database": buildLCoreDatabaseConfig(h, instance), "customization": buildLCoreCustomizationConfig(), "conversation_cache": buildLCoreConversationCacheConfig(h, instance), "rag": buildLCoreRAGConfig(ctx, h, instance), } if quotaHandlers := buildLCoreQuotaHandlersConfig(h, instance); quotaHandlers != nil { config["quota_handlers"] = quotaHandlers } if instance.Spec.LCore != nil && instance.Spec.LCore.CustomServiceConfig != "" { var customConfig map[string]interface{} if err := yaml.UnmarshalStrict([]byte(instance.Spec.LCore.CustomServiceConfig), &customConfig); err != nil { return "", fmt.Errorf("failed to parse spec.lcore.customServiceConfig as a YAML mapping: %w", err) } mergeLCoreConfig(config, customConfig) } // Convert to YAML yamlBytes, err := yaml.Marshal(config) if err != nil { return "", fmt.Errorf("failed to marshal LCore config to YAML: %w", err) } return string(yamlBytes), nil } // mergeLCoreConfig recursively merges mappings, replacing other values with overrides. func mergeLCoreConfig(config, overrides map[string]interface{}) { for key, value := range overrides { if customMap, ok := value.(map[string]interface{}); ok { if generatedMap, ok := config[key].(map[string]interface{}); ok { mergeLCoreConfig(generatedMap, customMap) continue } } config[key] = value } }