Files
archie/modules/governance/models_api.go
T

288 lines
10 KiB
Go

package governance
import (
"context"
json "encoding/json/v2"
"errors"
"fmt"
"net/http"
"slices"
"strings"
"github.com/danielgtaylor/huma/v2"
"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 {
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"`
// APIKeyCredential names the credential whose token authenticates the
// provider. Only the name is ever returned.
APIKeyCredential string `json:"api_key_credential,omitempty"`
}
// 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.Provider == "" {
return Model{}, errors.New("a provider is required")
}
if req.Model == "" {
return Model{}, errors.New("a model is required")
}
p, ok, err := m.store.Provider(ctx, m.orgID, req.Provider)
if err != nil {
return Model{}, err
}
if !ok {
return Model{}, fmt.Errorf("no provider named %q", req.Provider)
}
return Model{
Provider: p.Name, Model: req.Model,
Class: p.Class, BaseURL: p.BaseURL, APIKeyCredential: p.APIKeyCredential,
}, 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[map[string]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")
}
out := make(map[string]ModelProvider, len(rows))
for _, p := range rows {
out[p.Name] = ModelProvider{Name: p.Name, Class: p.Class, BaseURL: p.BaseURL, APIKeyCredential: p.APIKeyCredential}
}
return httpapi.OK(out), nil
}
func (m *Module) putModelProvider(ctx context.Context, in *struct {
Name string `path:"name" doc:"Lowercase letters, digits, dots, underscores or hyphens"`
Body ModelProvider
},
) (*httpapi.Reply[ModelProvider], error) {
p, err := endpoint(in.Name, in.Body.Class, in.Body.BaseURL, in.Body.APIKeyCredential)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
p.OrgID = m.orgID
if err := m.store.PutProvider(ctx, p); err != nil {
m.log.ErrorContext(ctx, "put model provider", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the model provider")
}
return httpapi.OK(ModelProvider{
Name: p.Name, Class: p.Class, BaseURL: p.BaseURL, APIKeyCredential: p.APIKeyCredential,
}), nil
}
func (m *Module) deleteModelProvider(ctx context.Context, in *struct {
Name string `path:"name"`
},
) (*struct{}, error) {
users, err := m.store.AliasesUsingProvider(ctx, m.orgID, in.Name)
if err != nil {
m.log.ErrorContext(ctx, "read the aliases that use a provider", "provider", in.Name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't check the aliases that use "+in.Name)
}
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 %s is used by aliases: %s", in.Name, strings.Join(aliases, ", ")))
}
found, err := m.store.DeleteProvider(ctx, m.orgID, in.Name)
if err != nil {
m.log.ErrorContext(ctx, "delete model provider", "provider", in.Name, "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't delete "+in.Name)
}
if !found {
return nil, huma.NewError(http.StatusNotFound, "no provider named "+in.Name)
}
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: "put-model-provider", Method: http.MethodPut, Path: "/api/settings/model-providers/{name}",
Summary: "Save a model provider", 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/{name}",
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)
}