Files
archie/modules/governance/models_api.go
T

417 lines
15 KiB
Go

package governance
import (
"context"
json "encoding/json/v2"
"errors"
"fmt"
"net/http"
"slices"
"strings"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/modules/governance/internal/store"
)
// ErrModelNotAllowed means the organisation's model policy doesn't allow the
// alias where it was named.
var ErrModelNotAllowed = errors.New("the organisation's model policy doesn't allow this alias")
// ModelProvider is an endpoint models are called on.
type ModelProvider struct {
ID uuid.UUID `json:"id"`
Name string `json:"name" doc:"Lowercase letters, digits, dots, underscores or hyphens"`
Class string `json:"class" doc:"A provider class from the model classes catalogue"`
// BaseURL is the endpoint; empty uses the class's default.
BaseURL string `json:"base_url,omitempty"`
// APIKeyCredentialID references the credential whose token authenticates
// the provider. APIKeyCredential is its display name, read from connectors.
APIKeyCredentialID *uuid.UUID `json:"api_key_credential_id,omitempty" format:"uuid"`
APIKeyCredential string `json:"api_key_credential,omitempty" readOnly:"true"`
}
// modelProviderInput is a provider as the API creates or updates it.
type modelProviderInput struct {
Name string `json:"name" doc:"Lowercase letters, digits, dots, underscores or hyphens"`
Class string `json:"class" doc:"A provider class from the model classes catalogue"`
BaseURL string `json:"base_url,omitempty" doc:"The endpoint; empty uses the class's default"`
APIKeyCredentialID *uuid.UUID `json:"api_key_credential_id,omitempty" format:"uuid" doc:"The bearer credential whose token authenticates the provider"`
}
func credentialIDPtr(id uuid.NullUUID) *uuid.UUID {
if !id.Valid {
return nil
}
v := id.UUID
return &v
}
func (m *Module) credentialName(ctx context.Context, id uuid.NullUUID) string {
if !id.Valid || m.credentials == nil {
return ""
}
name, ok, err := m.credentials.BearerCredentialName(m.orgScopeCtx(ctx), id.UUID)
if err != nil {
m.log.WarnContext(ctx, "read credential name", "credential_id", id.UUID, "error", err)
return ""
}
if !ok {
return ""
}
return name
}
func (m *Module) credentialNames(ctx context.Context) map[uuid.UUID]string {
if m.credentials == nil {
return nil
}
names, err := m.credentials.BearerCredentialNames(m.orgScopeCtx(ctx))
if err != nil {
m.log.WarnContext(ctx, "list credential names", "error", err)
return nil
}
return names
}
func (m *Module) checkCredential(ctx context.Context, id uuid.NullUUID) (string, error) {
if !id.Valid {
return "", nil
}
if m.credentials == nil {
return "", huma.NewError(http.StatusInternalServerError, "no credential store is configured")
}
name, ok, err := m.credentials.BearerCredentialName(m.orgScopeCtx(ctx), id.UUID)
if err != nil {
m.log.ErrorContext(ctx, "check credential", "credential_id", id.UUID, "error", err)
return "", huma.NewError(http.StatusInternalServerError, "couldn't check the credential")
}
if !ok {
return "", huma.NewError(http.StatusBadRequest, "no accessible bearer credential with that id")
}
return name, nil
}
func providerView(p store.Provider, credName string) ModelProvider {
return ModelProvider{
ID: p.ID, Name: p.Name, Class: p.Class, BaseURL: p.BaseURL,
APIKeyCredentialID: credentialIDPtr(p.APIKeyCredentialID),
APIKeyCredential: credName,
}
}
// ModelClass is one provider class the runtime can build.
type ModelClass struct {
Class string `json:"class"`
// DefaultBaseURL is where the class calls when a provider gives none.
DefaultBaseURL string `json:"default_base_url,omitempty"`
}
// ModelPolicy is which aliases workflows and chat may name. A nil list lets
// any alias through.
type ModelPolicy struct {
WorkflowAliases []string `json:"workflow_aliases" doc:"Aliases workflows may name; null lets them use any"`
ChatAliases []string `json:"chat_aliases" doc:"Aliases chat may use; null lets it use any"`
}
// modelOf returns the model a request names with its provider's endpoint.
func (m *Module) modelOf(ctx context.Context, req Model) (Model, error) {
if req.ProviderID == uuid.Nil {
return Model{}, huma.NewError(http.StatusBadRequest, "a provider is required")
}
if req.Model == "" {
return Model{}, huma.NewError(http.StatusBadRequest, "a model is required")
}
p, ok, err := m.store.ProviderByID(ctx, m.orgID, req.ProviderID)
if err != nil {
m.log.ErrorContext(ctx, "read model provider", "provider_id", req.ProviderID, "error", err)
return Model{}, huma.NewError(http.StatusInternalServerError, "couldn't read the model provider")
}
if !ok {
return Model{}, huma.NewError(http.StatusBadRequest, fmt.Sprintf("no provider with id %s", req.ProviderID))
}
return Model{
ProviderID: p.ID, Provider: p.Name, Model: req.Model,
Class: p.Class, BaseURL: p.BaseURL,
APIKeyCredentialID: credentialIDPtr(p.APIKeyCredentialID),
APIKeyCredential: m.credentialName(ctx, p.APIKeyCredentialID),
}, nil
}
// ModelPolicy returns the organisation's model policy.
func (m *Module) ModelPolicy(ctx context.Context) (ModelPolicy, error) {
row, ok, err := m.store.Policy(ctx, m.orgID)
if err != nil {
return ModelPolicy{}, err
}
if !ok {
return ModelPolicy{}, nil
}
workflow, err := aliasesOf(row.WorkflowAliases)
if err != nil {
return ModelPolicy{}, err
}
chat, err := aliasesOf(row.ChatAliases)
if err != nil {
return ModelPolicy{}, err
}
return ModelPolicy{WorkflowAliases: workflow, ChatAliases: chat}, nil
}
// WorkflowModelForAlias resolves a model a workflow named, refusing one the
// organisation's policy doesn't allow.
func (m *Module) WorkflowModelForAlias(ctx context.Context, alias string) (Model, error) {
policy, err := m.ModelPolicy(ctx)
if err != nil {
return Model{}, err
}
if err := allowedAlias(policy.WorkflowAliases, alias); err != nil {
return Model{}, err
}
return m.AgentModelForAlias(ctx, alias)
}
// ChatModelForAlias resolves the model chat may use, refusing one the
// organisation's policy doesn't allow.
func (m *Module) ChatModelForAlias(ctx context.Context, alias string) (Model, error) {
policy, err := m.ModelPolicy(ctx)
if err != nil {
return Model{}, err
}
if err := allowedAlias(policy.ChatAliases, alias); err != nil {
return Model{}, err
}
return m.AgentModelForAlias(ctx, alias)
}
func allowedAlias(allowed []string, alias string) error {
if allowed == nil {
return nil
}
name := alias
if name == "" {
name = "default"
}
if !slices.Contains(allowed, name) {
return fmt.Errorf("model alias %q: %w", name, ErrModelNotAllowed)
}
return nil
}
func aliasesOf(raw []byte) ([]string, error) {
if raw == nil {
return nil, nil
}
var out []string
if err := json.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("model policy: %w", err)
}
return out, nil
}
func marshalAliases(aliases []string) ([]byte, error) {
if aliases == nil {
return nil, nil
}
return json.Marshal(aliases)
}
func (m *Module) listModelProviders(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]ModelProvider], error) {
rows, err := m.store.Providers(ctx, m.orgID)
if err != nil {
m.log.ErrorContext(ctx, "list model providers", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't list model providers")
}
var credNames map[uuid.UUID]string
for _, p := range rows {
if p.APIKeyCredentialID.Valid {
credNames = m.credentialNames(ctx)
break
}
}
out := make([]ModelProvider, 0, len(rows))
for _, p := range rows {
out = append(out, providerView(p, credNames[p.APIKeyCredentialID.UUID]))
}
return httpapi.OK(out), nil
}
func (m *Module) createModelProvider(ctx context.Context, in *struct {
Body modelProviderInput
},
) (*httpapi.Reply[ModelProvider], error) {
p, err := endpoint(in.Body.Name, in.Body.Class, in.Body.BaseURL, in.Body.APIKeyCredentialID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
credName, err := m.checkCredential(ctx, p.APIKeyCredentialID)
if err != nil {
return nil, err
}
p.ID = uuid.New()
p.OrgID = m.orgID
if err := m.store.CreateProvider(ctx, p); err != nil {
if errors.Is(err, store.ErrProviderNameTaken) {
return nil, huma.NewError(http.StatusConflict, "another model provider has that name")
}
m.log.ErrorContext(ctx, "create model provider", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the model provider")
}
return httpapi.OK(providerView(p, credName)), nil
}
func (m *Module) putModelProvider(ctx context.Context, in *struct {
ID string `path:"id" format:"uuid"`
Body modelProviderInput
},
) (*httpapi.Reply[ModelProvider], error) {
id, err := uuid.Parse(in.ID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, "a provider id is a UUID")
}
p, err := endpoint(in.Body.Name, in.Body.Class, in.Body.BaseURL, in.Body.APIKeyCredentialID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
credName, err := m.checkCredential(ctx, p.APIKeyCredentialID)
if err != nil {
return nil, err
}
p.ID = id
p.OrgID = m.orgID
switch err := m.store.UpdateProvider(ctx, p); {
case errors.Is(err, store.ErrNoProvider):
return nil, huma.NewError(http.StatusNotFound, "no such model provider")
case errors.Is(err, store.ErrProviderNameTaken):
return nil, huma.NewError(http.StatusConflict, "another model provider has that name")
case err != nil:
m.log.ErrorContext(ctx, "update model provider", "provider_id", id, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the model provider")
}
return httpapi.OK(providerView(p, credName)), nil
}
func (m *Module) deleteModelProvider(ctx context.Context, in *struct {
ID string `path:"id" format:"uuid"`
},
) (*struct{}, error) {
id, err := uuid.Parse(in.ID)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, "a provider id is a UUID")
}
users, err := m.store.AliasesUsingProvider(ctx, m.orgID, id)
if err != nil {
m.log.ErrorContext(ctx, "read the aliases that use a provider", "provider_id", id, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't check the aliases that use this provider")
}
if len(users) > 0 {
aliases := make([]string, 0, len(users))
for _, role := range users {
aliases = append(aliases, aliasOf(role))
}
return nil, huma.NewError(http.StatusConflict,
fmt.Sprintf("provider is used by aliases: %s", strings.Join(aliases, ", ")))
}
found, err := m.store.DeleteProvider(ctx, m.orgID, id)
if err != nil {
if errors.Is(err, store.ErrProviderInUse) {
return nil, huma.NewError(http.StatusConflict, "provider is still used by an alias")
}
m.log.ErrorContext(ctx, "delete model provider", "provider_id", id, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't delete the model provider")
}
if !found {
return nil, huma.NewError(http.StatusNotFound, "no such model provider")
}
return nil, nil
}
func listModelClasses(context.Context, *struct{}) (*httpapi.Reply[[]ModelClass], error) {
names := slices.Clone(runtime.ClassNames())
slices.Sort(names)
names = slices.Compact(names)
out := make([]ModelClass, 0, len(names))
for _, name := range names {
base, _ := runtime.DefaultBaseURL(name)
out = append(out, ModelClass{Class: name, DefaultBaseURL: base})
}
return httpapi.OK(out), nil
}
func (m *Module) getModelPolicy(ctx context.Context, _ *struct{}) (*httpapi.Reply[ModelPolicy], error) {
policy, err := m.ModelPolicy(ctx)
if err != nil {
m.log.ErrorContext(ctx, "read the model policy", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the model policy")
}
return httpapi.OK(policy), nil
}
func (m *Module) putModelPolicy(ctx context.Context, in *struct{ Body ModelPolicy }) (*httpapi.Reply[ModelPolicy], error) {
for _, aliases := range [][]string{in.Body.WorkflowAliases, in.Body.ChatAliases} {
for _, alias := range aliases {
if err := ValidateAgentModelAlias(alias); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
}
}
workflow, err := marshalAliases(in.Body.WorkflowAliases)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
chat, err := marshalAliases(in.Body.ChatAliases)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
if err := m.store.PutPolicy(ctx, store.ModelPolicy{
OrgID: m.orgID, WorkflowAliases: workflow, ChatAliases: chat,
}); err != nil {
m.log.ErrorContext(ctx, "put the model policy", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the model policy")
}
return httpapi.OK(in.Body), nil
}
// aliasOf returns the dashboard's name for a stored role.
func aliasOf(role string) string {
if role == roleAgent {
return "default"
}
return strings.TrimPrefix(role, agentAliasPrefix)
}
func (m *Module) registerModels(api huma.API) {
tags := []string{"Governance"}
httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{
OperationID: "list-model-providers", Method: http.MethodGet, Path: "/api/settings/model-providers",
Summary: "List model providers", Tags: tags,
}, m.listModelProviders)
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "create-model-provider", Method: http.MethodPost, Path: "/api/settings/model-providers",
Summary: "Create a model provider", Tags: tags, DefaultStatus: http.StatusCreated,
}, m.createModelProvider)
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "put-model-provider", Method: http.MethodPut, Path: "/api/settings/model-providers/{id}",
Summary: "Save a model provider, including its name; aliases refer to it by id and are unchanged", Tags: tags,
}, m.putModelProvider)
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "delete-model-provider", Method: http.MethodDelete, Path: "/api/settings/model-providers/{id}",
Summary: "Delete a model provider no alias uses", Tags: tags, DefaultStatus: http.StatusNoContent,
}, m.deleteModelProvider)
httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{
OperationID: "list-model-classes", Method: http.MethodGet, Path: "/api/settings/model-classes",
Summary: "List the provider classes the runtime can build", Tags: tags,
}, listModelClasses)
httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{
OperationID: "get-model-policy", Method: http.MethodGet, Path: "/api/settings/model-policy",
Summary: "Get which aliases workflows and chat may use", Tags: tags,
}, m.getModelPolicy)
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "put-model-policy", Method: http.MethodPut, Path: "/api/settings/model-policy",
Summary: "Set which aliases workflows and chat may use", Tags: tags,
}, m.putModelPolicy)
}