MCPcopy Index your code
hub / github.com/mudler/LocalAI / CreateAgentForUser

Method CreateAgentForUser

core/services/agentpool/agent_pool.go:864–891  ·  view source on GitHub ↗

CreateAgentForUser creates an agent namespaced to a user. When auth is enabled and the agent config has no API key, a new user API key is auto-generated so the agent can authenticate against LocalAI's own API.

(userID string, config *state.AgentConfig)

Source from the content-addressed store, hash-verified

862// When auth is enabled and the agent config has no API key, a new user API key
863// is auto-generated so the agent can authenticate against LocalAI's own API.
864func (s *AgentPoolService) CreateAgentForUser(userID string, config *state.AgentConfig) error {
865 if err := ValidateAgentName(config.Name); err != nil {
866 return err
867 }
868
869 // Auto-generate a user API key when auth is active and none is specified
870 if s.users.authDB != nil && userID != "" && config.APIKey == "" {
871 plaintext, _, err := auth.CreateAPIKey(s.users.authDB, userID, "agent:"+config.Name, "user", s.appConfig.Auth.APIKeyHMACSecret, nil)
872 if err != nil {
873 return fmt.Errorf("failed to create API key for agent: %w", err)
874 }
875 config.APIKey = plaintext
876 xlog.Info("Auto-generated API key for agent", "agent", config.Name, "user", userID)
877 }
878
879 if err := s.configBackend.SaveConfig(userID, config); err != nil {
880 return err
881 }
882
883 // Auto-create collection when knowledge base or long-term memory is enabled
884 if config.EnableKnowledgeBase || config.LongTermMemory {
885 if err := s.ensureCollectionForUser(userID, config.Name); err != nil {
886 xlog.Warn("Failed to auto-create collection for agent", "agent", config.Name, "error", err)
887 }
888 }
889
890 return nil
891}
892
893// GetAgentForUser returns the agent for a user.
894// Returns nil in distributed mode where agents don't run in-process.

Callers 1

CreateAgentEndpointFunction · 0.80

Calls 4

CreateAPIKeyFunction · 0.92
ValidateAgentNameFunction · 0.85
SaveConfigMethod · 0.65

Tested by

no test coverage detected