litellm.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /*
  2. Copyright 2026 LocoStack.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package reconciler
  14. import (
  15. "context"
  16. "crypto/rand"
  17. "crypto/sha256"
  18. "encoding/hex"
  19. "fmt"
  20. "maps"
  21. "github.com/LocoStack/loco-operator/api/v1alpha1"
  22. "github.com/LocoStack/loco-operator/pkg/templates/litellm"
  23. "go.yaml.in/yaml/v2"
  24. corev1 "k8s.io/api/core/v1"
  25. apierrors "k8s.io/apimachinery/pkg/api/errors"
  26. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. "k8s.io/apimachinery/pkg/runtime"
  28. "sigs.k8s.io/controller-runtime/pkg/client"
  29. "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
  30. )
  31. type LiteLLMReconciler struct {
  32. *DefaultComponentReconciler
  33. client client.Client
  34. scheme *runtime.Scheme
  35. stack *v1alpha1.Stack
  36. component *v1alpha1.Component
  37. }
  38. func NewLiteLLMReconciler(client client.Client, scheme *runtime.Scheme, stack *v1alpha1.Stack, component *v1alpha1.Component) *LiteLLMReconciler {
  39. return &LiteLLMReconciler{
  40. DefaultComponentReconciler: NewDefaultComponentReconciler(client, scheme, stack, component),
  41. client: client,
  42. scheme: scheme,
  43. stack: stack,
  44. component: component,
  45. }
  46. }
  47. func (r *LiteLLMReconciler) ReconcileComponent(ctx context.Context, tmpl *v1alpha1.Template, variables map[string]string) ([]client.Object, error) {
  48. if err := r.ReconcileKey(ctx, "litellm", litellm.LITELLM_AUTH_SECRET_KEY, generateKey); err != nil {
  49. return nil, fmt.Errorf("Failed to reconcile LiteLLM master key: %w", err)
  50. }
  51. deps := make([]client.Object, 0)
  52. emList := make([]*v1alpha1.ExternalModel, 0)
  53. mmList := make([]*v1alpha1.ManagedModel, 0)
  54. for _, dep := range r.component.Spec.Dependencies {
  55. switch dep.Kind {
  56. case "ExternalModel":
  57. em := &v1alpha1.ExternalModel{}
  58. if err := r.client.Get(ctx, client.ObjectKey{Name: dep.Name, Namespace: dep.Namespace}, em); err != nil {
  59. return nil, fmt.Errorf("Failed to get ExternalModel %s/%s: %w", dep.Namespace, dep.Name, err)
  60. }
  61. emList = append(emList, em)
  62. deps = append(deps, em)
  63. case "ManagedModel":
  64. mm := &v1alpha1.ManagedModel{}
  65. if err := r.client.Get(ctx, client.ObjectKey{Name: dep.Name, Namespace: dep.Namespace}, mm); err != nil {
  66. return nil, fmt.Errorf("Failed to get ManagedModel %s/%s: %w", dep.Namespace, dep.Name, err)
  67. }
  68. mmList = append(mmList, mm)
  69. deps = append(deps, mm)
  70. }
  71. }
  72. configHash, err := r.reconcileConfigMap(ctx, emList, mmList)
  73. if err != nil {
  74. return nil, fmt.Errorf("Failed to reconcile LiteLLM config: %w", err)
  75. }
  76. authSpecs := make(map[string]map[string]*v1alpha1.AuthSpec)
  77. for _, em := range emList {
  78. if em.Spec.Auth != nil {
  79. if _, ok := authSpecs["ExternalModel"]; !ok {
  80. authSpecs["ExternalModel"] = make(map[string]*v1alpha1.AuthSpec)
  81. }
  82. authSpecs["ExternalModel"][em.Name] = em.Spec.Auth
  83. }
  84. }
  85. credentialsHash, err := r.credentialsHash(ctx, authSpecs)
  86. if err != nil {
  87. return nil, fmt.Errorf("Failed to hash LiteLLM credentials: %w", err)
  88. }
  89. injectSecrets(tmpl, authSpecs)
  90. if tmpl.Metadata.Annotations == nil {
  91. tmpl.Metadata.Annotations = make(map[string]string)
  92. }
  93. // the credential values reach the Pod as env vars, which are snapshotted when it
  94. // starts, so the rendered config alone does not decide whether the gateway is current:
  95. // a key rotated in place has to roll it out as well
  96. h := sha256.Sum256([]byte(configHash + credentialsHash))
  97. maps.Copy(tmpl.Metadata.Annotations, map[string]string{
  98. "locostack.com/configHash": hex.EncodeToString(h[:]),
  99. })
  100. if _, err := r.DefaultComponentReconciler.ReconcileComponent(ctx, tmpl, variables); err != nil {
  101. return nil, err
  102. }
  103. return deps, nil
  104. }
  105. func (r *LiteLLMReconciler) reconcileConfigMap(ctx context.Context, emList []*v1alpha1.ExternalModel, mmList []*v1alpha1.ManagedModel) (string, error) {
  106. var o11yComp *v1alpha1.Component
  107. if r.stack.Spec.Observability != nil && r.stack.Spec.Observability.Enabled {
  108. o11yComp = &v1alpha1.Component{}
  109. if err := r.client.Get(ctx, client.ObjectKey{Name: fmt.Sprintf("observability-%s", r.stack.Name), Namespace: r.stack.Namespace}, o11yComp); err != nil {
  110. return "", fmt.Errorf("Failed to get Observability component: %w", err)
  111. }
  112. }
  113. configBuilder := litellm.LiteLLMConfigBuilder{
  114. MasterKeyEnvName: litellm.LITELLM_MASTER_KEY_ENV_NAME,
  115. Stack: r.stack,
  116. ObservabilityComponent: o11yComp,
  117. ExternalModels: emList,
  118. ManagedModels: mmList,
  119. }
  120. config, err := configBuilder.BuildLiteLLMConfig()
  121. if err != nil {
  122. return "", fmt.Errorf("Failed to build LiteLLM config: %w", err)
  123. }
  124. configData, err := yaml.Marshal(config)
  125. if err != nil {
  126. return "", fmt.Errorf("Failed to marshal LiteLLM config: %w", err)
  127. }
  128. configDataStr := string(configData)
  129. h := sha256.Sum256([]byte(configDataStr))
  130. configHash := hex.EncodeToString(h[:])
  131. cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: r.ResourceName("config"), Namespace: r.component.GetNamespace()}}
  132. if _, err := controllerutil.CreateOrUpdate(ctx, r.client, cm, func() error {
  133. if cm.Labels == nil {
  134. cm.Labels = map[string]string{}
  135. }
  136. maps.Copy(cm.Labels, r.ResourceLabels())
  137. if cm.Annotations == nil {
  138. cm.Annotations = make(map[string]string)
  139. }
  140. cm.Annotations["hash"] = configHash
  141. cm.Data = map[string]string{litellm.LITELLM_CONFIG_KEY: configDataStr}
  142. return controllerutil.SetControllerReference(r.component, cm, r.scheme)
  143. }); err != nil {
  144. return "", err
  145. }
  146. return configHash, nil
  147. }
  148. // credentialsHash digests the credential values that the gateway Pod reads from Secrets,
  149. // keyed by the dependency and Secret key they belong to. A Secret or key that does not
  150. // resolve hashes as empty rather than failing the reconcile: the rest of the config still
  151. // has to be written, and it is the dependency's own CredentialsResolved condition that
  152. // reports the dangling reference.
  153. func (r *LiteLLMReconciler) credentialsHash(ctx context.Context, authSpecs map[string]map[string]*v1alpha1.AuthSpec) (string, error) {
  154. h := sha256.New()
  155. for _, kind := range sortedKeys(authSpecs) {
  156. for _, name := range sortedKeys(authSpecs[kind]) {
  157. for _, ref := range AuthSecretRefs(authSpecs[kind][name]) {
  158. secret := &corev1.Secret{}
  159. if err := r.client.Get(ctx, client.ObjectKey{Name: ref.Name, Namespace: r.component.GetNamespace()}, secret); err != nil && !apierrors.IsNotFound(err) {
  160. return "", fmt.Errorf("Failed to get Secret %s: %w", ref.Name, err)
  161. }
  162. _, _ = fmt.Fprintf(h, "%s/%s/%s/%s=%s\n", kind, name, ref.Name, ref.Key, secret.Data[ref.Key])
  163. }
  164. }
  165. }
  166. return hex.EncodeToString(h.Sum(nil)), nil
  167. }
  168. func generateKey() (string, error) {
  169. b := make([]byte, 24)
  170. if _, err := rand.Read(b); err != nil {
  171. return "", err
  172. }
  173. return "sk-" + hex.EncodeToString(b), nil
  174. }
  175. func injectSecrets(tmpl *v1alpha1.Template, authSpecs map[string]map[string]*v1alpha1.AuthSpec) {
  176. envVars := []corev1.EnvVar{}
  177. for _, kind := range sortedKeys(authSpecs) {
  178. kindAuthSpecs := authSpecs[kind]
  179. for _, name := range sortedKeys(kindAuthSpecs) {
  180. auth := kindAuthSpecs[name]
  181. var refName string
  182. var refKey string
  183. if auth.APIKey != nil {
  184. refName = auth.APIKey.SecretRef.Name
  185. refKey = auth.APIKey.SecretRef.Key
  186. } else if auth.BearerToken != nil {
  187. refName = auth.BearerToken.Name
  188. refKey = auth.BearerToken.Key
  189. }
  190. if refName != "" && refKey != "" {
  191. envVars = append(envVars, corev1.EnvVar{
  192. Name: litellm.AuthEnvVarName(kind, name),
  193. ValueFrom: &corev1.EnvVarSource{
  194. SecretKeyRef: &corev1.SecretKeySelector{
  195. LocalObjectReference: corev1.LocalObjectReference{Name: refName},
  196. Key: refKey,
  197. },
  198. },
  199. })
  200. }
  201. if auth.Headers != nil {
  202. for _, header := range auth.Headers {
  203. if header.ValueFrom.SecretKeyRef != nil {
  204. envVars = append(envVars, corev1.EnvVar{
  205. Name: litellm.AuthEnvVarName(kind, name+"_"+header.Name),
  206. ValueFrom: &corev1.EnvVarSource{
  207. SecretKeyRef: &corev1.SecretKeySelector{
  208. LocalObjectReference: header.ValueFrom.SecretKeyRef.LocalObjectReference,
  209. Key: header.ValueFrom.SecretKeyRef.Key,
  210. },
  211. },
  212. })
  213. }
  214. }
  215. }
  216. }
  217. }
  218. tmpl.Spec.Runtime.Env = append(tmpl.Spec.Runtime.Env, envVars...)
  219. }