Files

85 lines
2.8 KiB
Go
Raw Permalink Normal View History

2026-08-21 00:57:23 +08:00
package aiagent
import (
"context"
"errors"
"net/http"
"code.tczkiot.com/wlw/ai-agent/contract"
"code.tczkiot.com/wlw/ai-agent/identity"
"code.tczkiot.com/wlw/ai-agent/internal/ai"
"code.tczkiot.com/wlw/ai-agent/internal/bootstrap"
"code.tczkiot.com/wlw/ai-agent/internal/models"
"code.tczkiot.com/wlw/ai-agent/internal/pkg/httpx"
"code.tczkiot.com/wlw/ai-agent/internal/services"
"code.tczkiot.com/wlw/ai-agent/internal/services/storage"
"gorm.io/gorm"
)
type Options struct {
Database *gorm.DB
TablePrefix string
LoadSettings func(ctx context.Context, prefix string) (map[string]string, error)
QuerySubjects identity.QuerySubjectsFunc
Authorize identity.AuthorizeFunc
ResponseWriter contract.ResponseWriter
FileStorage contract.FileStorage
BusinessReadTools []contract.BusinessReadTool
BusinessActionTools []contract.BusinessActionTool
CustomerQuickActions []contract.CustomerQuickAction
PlatformAI contract.PlatformAIProvider
}
// SyncSchema explicitly creates or updates AI Agent tables. It is intended
// for the host application's maintenance command and is never called by New.
func SyncSchema(database *gorm.DB, tablePrefix string) error {
if tablePrefix == "" {
tablePrefix = "ai_"
}
moduleDB, err := bootstrap.ScopedDatabase(database, tablePrefix)
if err != nil {
return err
}
return moduleDB.AutoMigrate(models.Models...)
}
// New initializes the customer-service business module. Authentication and
// authorization must already have been completed by the host system.
func New(options Options) (http.Handler, error) {
if options.Database == nil {
return nil, errors.New("ai-agent: Database is required")
}
if options.LoadSettings == nil {
return nil, errors.New("ai-agent: LoadSettings is required")
}
if options.QuerySubjects == nil {
2026-08-21 00:57:23 +08:00
return nil, errors.New("ai-agent: QuerySubjects is required")
}
if options.Authorize == nil {
2026-08-21 00:57:23 +08:00
return nil, errors.New("ai-agent: Authorize is required")
}
if options.TablePrefix == "" {
options.TablePrefix = "ai_"
}
services.SetQuerySubjects(options.QuerySubjects)
services.SetAuthorize(options.Authorize)
services.SetPlatformAIProvider(options.PlatformAI)
ai.SetPlatformAIProvider(options.PlatformAI)
if err := services.SetBusinessReadTools(options.BusinessReadTools); err != nil {
return nil, err
}
if err := services.SetBusinessActionTools(options.BusinessActionTools); err != nil {
return nil, err
}
if err := services.SetCustomerQuickActions(options.CustomerQuickActions); err != nil {
return nil, err
}
storage.SetHostStorage(options.FileStorage)
if err := bootstrap.InitModule(options.Database, options.TablePrefix, options.LoadSettings); err != nil {
return nil, err
}
httpx.SetResponseWriter(options.ResponseWriter)
return bootstrap.NewServer()
}