Files

737 lines
28 KiB
Go

// Package governance owns an organisation's settings. So far that is the
// agent model: the provider class, base URL and model every agent loop uses.
// Nothing an event or a tool result says can change where a model request
// goes, because the client is built only from these settings.
package governance
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
"net/http"
"net/url"
"regexp"
"sync/atomic"
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/internal/platform/prompts"
"github.com/samcharles93/archie-core/modules/governance/internal/store"
)
// ErrNoAgentModel means the organisation hasn't chosen its agent model. There
// is no built-in default.
var ErrNoAgentModel = errors.New("no agent model is set for the organisation")
const (
roleAgent = "agent"
agentAliasPrefix = "agent:"
)
var agentAliasPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,62}$`)
// providerName is the shape of a provider name.
var providerName = regexp.MustCompile(`^[a-z0-9][a-z0-9_.-]{0,62}$`)
// ValidateAgentModelAlias accepts an empty alias for the default model.
func ValidateAgentModelAlias(alias string) error {
if alias != "" && !agentAliasPattern.MatchString(alias) {
return fmt.Errorf("invalid agent model alias %q: use 1-63 letters, digits, dots, underscores or hyphens, starting with a letter or digit", alias)
}
return nil
}
func agentModelRole(alias string) string {
if alias == "" || alias == "default" {
return roleAgent
}
return agentAliasPrefix + alias
}
// DefaultApprovalDeadline is how long an approval request waits for an answer
// when the organisation hasn't set one.
const DefaultApprovalDeadline = 24 * time.Hour
// DefaultProposeAutonomyAfter is how many approvals in a row earn a proposal to
// loosen an action type when the organisation hasn't set one.
const DefaultProposeAutonomyAfter = 3
// maxProposeAutonomyAfter bounds the count: past it an action type could never
// earn an autonomy proposal.
const maxProposeAutonomyAfter = 100
// DefaultRecurrenceThreshold is how many incidents with one cause on one target
// it takes to propose a root-cause fix when the organisation hasn't set one.
const DefaultRecurrenceThreshold = 5
// The bounds on the recurrence threshold. One incident is no pattern; past a
// hundred the history Archie keeps per target can't confirm it.
const (
minRecurrenceThreshold = 2
maxRecurrenceThreshold = 100
)
// DefaultAttemptsPerRun is how many steps an agent may take in one run when the
// organisation hasn't set one.
const DefaultAttemptsPerRun = 20
// The bounds on attempts per run. An agent needs a few steps to look anything
// up; past two hundred a run is looping.
const (
minAttemptsPerRun = 2
maxAttemptsPerRun = 200
)
// The defaults and bounds on the action budgets.
const (
DefaultActionsPerRun = 10
DefaultActionsPerDay = 100
maxActionBudget = 10000
)
// The bounds on an approval deadline. Below a minute nobody could answer; past
// a month the request outlives the incident it was raised for.
const (
minApprovalDeadline = time.Minute
maxApprovalDeadline = 30 * 24 * time.Hour
)
// Settings is what the organisation decides about how Archie acts.
type Settings struct {
// ApprovalDeadline is how long an approval request waits for an answer
// before the run gives up on it.
ApprovalDeadline time.Duration
// ProposeAutonomyAfter is how many approvals in a row, since an action type
// was last tightened, earn a proposal to loosen it by one level.
ProposeAutonomyAfter int
// Frozen holds every action that changes something at propose and wait,
// without changing any class's level.
Frozen bool
// RecurrenceThreshold is how many incidents with the same cause on one
// target it takes, whatever their outcomes, to propose a root-cause fix.
RecurrenceThreshold int
// AttemptsPerRun is how many steps an agent may take in one run.
AttemptsPerRun int
// DefaultOwner is the id of the member who answers for what has no other
// owner, or empty.
DefaultOwner string
// Escalation is the members an unanswered request moves through, in order,
// each with how long the request waits on them.
Escalation []Step
// Timing is when changing actions may run without asking.
Timing Timing
// ActionsPerRun and ActionsPerDay are how many actions one run, and the
// organisation in a day, may take before a changing action waits for approval.
ActionsPerRun int
ActionsPerDay int
}
// Step is one stop on the escalation path: a member and how long an unanswered
// request waits on them before it moves to the next.
type Step struct {
// Account is the id of the member the request is passed to.
Account string
Deadline time.Duration
}
// stepRow is a step as stored.
type stepRow struct {
Account string `json:"account"`
DeadlineMS int64 `json:"deadline_ms"`
}
// stepRequest is a step as the API shows and sets it. Its deadline travels as
// a Go duration string, like the approval deadline.
type stepRequest struct {
Account string `json:"account"`
Deadline string `json:"deadline"`
}
// settingsRequest is the settings as the API shows and sets them. A duration
// travels as a Go duration string ("24h"), the same form every other duration
// in the config takes.
type settingsRequest struct {
ApprovalDeadline string `json:"approval_deadline"`
ProposeAutonomyAfter int `json:"propose_autonomy_after"`
Frozen bool `json:"frozen"`
RecurrenceThreshold int `json:"recurrence_threshold"`
AttemptsPerRun int `json:"attempts_per_run"`
DefaultOwner string `json:"default_owner"`
Escalation []stepRequest `json:"escalation"`
Timing Timing `json:"timing"`
ActionsPerRun int `json:"actions_per_run"`
ActionsPerDay int `json:"actions_per_day"`
}
func (s Settings) request() settingsRequest {
return settingsRequest{
ApprovalDeadline: s.ApprovalDeadline.String(), ProposeAutonomyAfter: s.ProposeAutonomyAfter, Frozen: s.Frozen,
RecurrenceThreshold: s.RecurrenceThreshold, AttemptsPerRun: s.AttemptsPerRun,
DefaultOwner: s.DefaultOwner, Escalation: stepRequests(s.Escalation),
Timing: s.Timing, ActionsPerRun: s.ActionsPerRun, ActionsPerDay: s.ActionsPerDay,
}
}
func stepRequests(steps []Step) []stepRequest {
out := make([]stepRequest, 0, len(steps))
for _, st := range steps {
out = append(out, stepRequest{Account: st.Account, Deadline: st.Deadline.String()})
}
return out
}
// stepsOf reads the steps of a request, each with a deadline inside the range
// an answer can be given in.
func stepsOf(req []stepRequest) ([]Step, error) {
out := make([]Step, 0, len(req))
for _, r := range req {
d, err := time.ParseDuration(r.Deadline)
if err != nil {
return nil, errors.New("each escalation deadline is a duration, such as 4h")
}
out = append(out, Step{Account: r.Account, Deadline: d})
}
return out, nil
}
// Model is the model chosen for a role.
type Model struct {
// ProviderID is the endpoint the model is called on, and Model is its name
// there.
ProviderID uuid.UUID `json:"provider_id" format:"uuid" doc:"The provider the model is called on"`
Model string `json:"model" doc:"The model's name on the provider"`
// Provider, Class, BaseURL, APIKeyCredentialID and APIKeyCredential are
// read from the provider. The dashboard shows the credential's name, never
// its token.
Provider string `json:"provider,omitempty" readOnly:"true"`
Class string `json:"class,omitempty" readOnly:"true"`
BaseURL string `json:"base_url,omitempty" readOnly:"true"`
APIKeyCredentialID *uuid.UUID `json:"api_key_credential_id,omitempty" format:"uuid" readOnly:"true"`
APIKeyCredential string `json:"api_key_credential,omitempty" readOnly:"true"`
}
// Credentials resolves a credential's token and display name by id. It is the
// connectors module's sealed store, so governance never holds a secret.
type Credentials interface {
BearerTokenByID(ctx context.Context, id uuid.UUID) (string, error)
BearerCredentialName(ctx context.Context, id uuid.UUID) (string, bool, error)
BearerCredentialNames(ctx context.Context) (map[uuid.UUID]string, error)
}
// orgScopeCtx confines credential lookups to the organisation itself with no
// person attached, so an organisation's model provider can never reach a
// person-scoped credential or another organisation's credential.
func (m *Module) orgScopeCtx(ctx context.Context) context.Context {
return WithOrg(WithoutPrincipal(ctx), DefaultOrgID)
}
// AgentProvider builds the chat client for model, resolving the credential it
// names whenever a run rebuilds the client.
func (m *Module) AgentProvider(ctx context.Context, model Model) (chat.Provider, chat.ModelInfo, error) {
return m.provider(ctx, model)
}
// provider builds the chat client for model, resolving its credential when it
// names one.
func (m *Module) provider(ctx context.Context, model Model) (chat.Provider, chat.ModelInfo, error) {
auth := runtime.AuthConfig{Type: runtime.AuthTypeNone}
if model.APIKeyCredentialID != nil && *model.APIKeyCredentialID != uuid.Nil {
if m.credentials == nil {
return nil, chat.ModelInfo{}, errors.New("no credential store is configured")
}
key, err := m.credentials.BearerTokenByID(m.orgScopeCtx(ctx), *model.APIKeyCredentialID)
if err != nil {
return nil, chat.ModelInfo{}, fmt.Errorf("agent model credential %s: %w", *model.APIKeyCredentialID, err)
}
auth = runtime.AuthConfig{Type: runtime.AuthTypeAPIKey, APIKey: key}
}
rt := runtime.NewRuntime(runtime.Config{Providers: map[string]runtime.ProviderConfig{
roleAgent: {ID: roleAgent, Class: model.Class, BaseURL: model.BaseURL, Auth: auth},
}})
ref := roleAgent + "/" + model.Model
provider, _, err := rt.ChatProvider(ctx, ref)
if err != nil {
return nil, chat.ModelInfo{}, fmt.Errorf("agent model %s: %w", ref, err)
}
info, err := rt.ChatModelInfo(ref)
if err != nil {
return nil, chat.ModelInfo{}, fmt.Errorf("agent model %s: %w", ref, err)
}
return provider, info, nil
}
// Module serves one organisation's settings.
type Module struct {
orgID string
store *store.Store
log *slog.Logger
credentials Credentials
authorizer atomic.Pointer[Authorizer]
oidc *oidcLogin
setup *SetupSignal
channels ChannelLinks
}
// NewModule returns the governance module for orgID. The ai-sdk provider
// classes must already be registered.
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module {
return &Module{orgID: orgID, store: store.New(db), log: log, oidc: &oidcLogin{}, setup: NewSetupSignal()}
}
// UseCredentials gives the module the sealed store a model's key reference
// resolves through.
func (m *Module) UseCredentials(c Credentials) { m.credentials = c }
// UseAuthorizer gives the module the live policy chain that administrative
// writes are checked against.
func (m *Module) UseAuthorizer(a Authorizer) { m.authorizer.Store(&a) }
// authz returns the policy chain, or nil before UseAuthorizer.
func (m *Module) authz() Authorizer {
if a := m.authorizer.Load(); a != nil {
return *a
}
return nil
}
// AgentModel returns the organisation's agent model.
func (m *Module) AgentModel(ctx context.Context) (Model, error) {
return m.AgentModelForAlias(ctx, "")
}
// AgentModelForAlias resolves a model without falling back for unknown aliases.
func (m *Module) AgentModelForAlias(ctx context.Context, alias string) (Model, error) {
if err := ValidateAgentModelAlias(alias); err != nil {
return Model{}, err
}
key := agentModelRole(alias)
role, ok, err := m.store.ModelRole(ctx, m.orgID, key)
if err != nil {
return Model{}, err
}
if !ok {
if key != roleAgent {
return Model{}, fmt.Errorf("agent model alias %q: %w", alias, ErrNoAgentModel)
}
return Model{}, ErrNoAgentModel
}
return Model{
ProviderID: role.ProviderID, Provider: role.Provider, Model: role.Model,
Class: role.Class, BaseURL: role.BaseURL,
APIKeyCredentialID: credentialIDPtr(role.APIKeyCredentialID),
APIKeyCredential: m.credentialName(ctx, role.APIKeyCredentialID),
}, nil
}
// Settings returns the organisation's settings, with a default for every one it
// hasn't set.
func (m *Module) Settings(ctx context.Context) (Settings, error) {
row, ok, err := m.store.Settings(ctx, m.orgID)
if err != nil {
return Settings{}, err
}
if !ok {
return Settings{
ApprovalDeadline: DefaultApprovalDeadline, ProposeAutonomyAfter: DefaultProposeAutonomyAfter,
RecurrenceThreshold: DefaultRecurrenceThreshold, AttemptsPerRun: DefaultAttemptsPerRun,
Escalation: []Step{}, Timing: Timing{}.normalised(),
ActionsPerRun: DefaultActionsPerRun, ActionsPerDay: DefaultActionsPerDay,
}, nil
}
var rows []stepRow
if err := json.Unmarshal(jsontext.Value(row.Escalation), &rows); err != nil {
return Settings{}, fmt.Errorf("read escalation path: %w", err)
}
escalation := make([]Step, 0, len(rows))
for _, r := range rows {
escalation = append(escalation, Step{Account: r.Account, Deadline: time.Duration(r.DeadlineMS) * time.Millisecond})
}
var timing Timing
if err := json.Unmarshal(jsontext.Value(row.Timing), &timing); err != nil {
return Settings{}, fmt.Errorf("read timing: %w", err)
}
return Settings{
Timing: timing.normalised(), ActionsPerRun: row.ActionsPerRun, ActionsPerDay: row.ActionsPerDay,
ApprovalDeadline: time.Duration(row.ApprovalDeadlineMS) * time.Millisecond,
ProposeAutonomyAfter: row.ProposeAutonomyAfter,
Frozen: row.Frozen,
RecurrenceThreshold: row.RecurrenceThreshold,
AttemptsPerRun: row.AttemptsPerRun,
DefaultOwner: row.DefaultOwner,
Escalation: escalation,
}, nil
}
// ProposeAutonomyAfter is how many approvals in a row earn a proposal to loosen
// an action type.
func (m *Module) ProposeAutonomyAfter(ctx context.Context) (int, error) {
set, err := m.Settings(ctx)
if err != nil {
return 0, err
}
return set.ProposeAutonomyAfter, nil
}
// Frozen reports whether the organisation has frozen its actions.
func (m *Module) Frozen(ctx context.Context) (bool, error) {
set, err := m.Settings(ctx)
if err != nil {
return false, err
}
return set.Frozen, nil
}
// RecurrenceThreshold is how many incidents with one cause on one target it
// takes to propose a root-cause fix.
func (m *Module) RecurrenceThreshold(ctx context.Context) (int, error) {
set, err := m.Settings(ctx)
if err != nil {
return 0, err
}
return set.RecurrenceThreshold, nil
}
// AttemptsPerRun is how many steps an agent may take in one run.
func (m *Module) AttemptsPerRun(ctx context.Context) (int, error) {
set, err := m.Settings(ctx)
if err != nil {
return 0, err
}
return set.AttemptsPerRun, nil
}
// ApprovalDeadline is how long an approval request waits for an answer.
func (m *Module) ApprovalDeadline(ctx context.Context) (time.Duration, error) {
set, err := m.Settings(ctx)
if err != nil {
return 0, err
}
return set.ApprovalDeadline, nil
}
// Register adds the settings API: organisation settings and the agent model.
func (m *Module) Register(api huma.API) {
tags := []string{"Governance"}
httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{
OperationID: "get-settings", Method: http.MethodGet, Path: "/api/settings",
Summary: "Get the organisation settings", Tags: tags,
}, m.getSettings)
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "put-settings", Method: http.MethodPut, Path: "/api/settings",
Summary: "Change the organisation settings", Tags: tags,
}, m.putSettings)
httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{
OperationID: "list-agent-models", Method: http.MethodGet, Path: "/api/settings/agent-models",
Summary: "List agent models by alias", Tags: tags,
}, m.listAgentModels)
httpapi.Register(api, httpapi.AdminAuthorized(ActionRead, KindSettings), huma.Operation{
OperationID: "get-agent-model", Method: http.MethodGet, Path: "/api/settings/agent-model",
Summary: "Get the agent model", Tags: tags,
}, m.getAgentModel)
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "put-agent-model", Method: http.MethodPut, Path: "/api/settings/agent-model",
Summary: "Set the agent model", Tags: tags,
}, m.putAgentModel)
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "delete-agent-model", Method: http.MethodDelete, Path: "/api/settings/agent-model",
Summary: "Delete an agent model", Tags: tags, DefaultStatus: http.StatusNoContent,
}, m.deleteAgentModel)
httpapi.Register(api, httpapi.AdminAuthorized(ActionUpdate, KindSettings), huma.Operation{
OperationID: "test-agent-model", Method: http.MethodPost, Path: "/api/settings/agent-model/test",
Summary: "Ask a model one question before saving it", Tags: tags,
}, m.testAgentModel)
m.registerModels(api)
m.registerInstructions(api)
}
func (m *Module) getSettings(ctx context.Context, _ *struct{}) (*httpapi.Reply[settingsRequest], error) {
set, err := m.Settings(ctx)
if err != nil {
m.log.ErrorContext(ctx, "read settings", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the settings")
}
return httpapi.OK(set.request()), nil
}
func (m *Module) putSettings(ctx context.Context, in *struct{ Body settingsRequest }) (*httpapi.Reply[settingsRequest], error) {
req := in.Body
deadline, err := time.ParseDuration(req.ApprovalDeadline)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, "approval deadline is a duration, such as 24h")
}
steps, err := stepsOf(req.Escalation)
if err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
set := Settings{
ApprovalDeadline: deadline, ProposeAutonomyAfter: req.ProposeAutonomyAfter, Frozen: req.Frozen,
RecurrenceThreshold: req.RecurrenceThreshold, AttemptsPerRun: req.AttemptsPerRun,
DefaultOwner: req.DefaultOwner, Escalation: steps,
Timing: req.Timing.normalised(), ActionsPerRun: req.ActionsPerRun, ActionsPerDay: req.ActionsPerDay,
}
if err := set.validate(); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
members, err := m.memberNames(ctx)
if err != nil {
m.log.ErrorContext(ctx, "read members", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the settings")
}
if err := set.knows(members); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
rows := make([]stepRow, 0, len(set.Escalation))
for _, st := range set.Escalation {
rows = append(rows, stepRow{Account: st.Account, DeadlineMS: st.Deadline.Milliseconds()})
}
escalation, err := json.Marshal(rows)
if err != nil {
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the settings")
}
timing, err := json.Marshal(set.Timing)
if err != nil {
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the settings")
}
if err := m.store.PutSettings(ctx, store.Settings{
OrgID: m.orgID, ApprovalDeadlineMS: set.ApprovalDeadline.Milliseconds(),
ProposeAutonomyAfter: set.ProposeAutonomyAfter, Frozen: set.Frozen, RecurrenceThreshold: set.RecurrenceThreshold,
AttemptsPerRun: set.AttemptsPerRun, DefaultOwner: set.DefaultOwner, Escalation: string(escalation),
Timing: string(timing), ActionsPerRun: set.ActionsPerRun, ActionsPerDay: set.ActionsPerDay,
}); err != nil {
m.log.ErrorContext(ctx, "put settings", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the settings")
}
return httpapi.OK(set.request()), nil
}
// validate keeps a deadline inside the range an answer can be given in, the
// count of approvals an autonomy proposal needs inside the range an action
// type can earn, and the
// recurrence threshold inside the range that means a pattern.
func (s Settings) validate() error {
if s.RecurrenceThreshold < minRecurrenceThreshold || s.RecurrenceThreshold > maxRecurrenceThreshold {
return fmt.Errorf("recurrence threshold must be between %d and %d", minRecurrenceThreshold, maxRecurrenceThreshold)
}
if s.ApprovalDeadline < minApprovalDeadline || s.ApprovalDeadline > maxApprovalDeadline {
return fmt.Errorf("approval deadline must be between %s and %s", minApprovalDeadline, maxApprovalDeadline)
}
if s.ProposeAutonomyAfter < 1 || s.ProposeAutonomyAfter > maxProposeAutonomyAfter {
return fmt.Errorf("propose autonomy after must be between 1 and %d approvals", maxProposeAutonomyAfter)
}
if s.AttemptsPerRun < minAttemptsPerRun || s.AttemptsPerRun > maxAttemptsPerRun {
return fmt.Errorf("attempts per run must be between %d and %d", minAttemptsPerRun, maxAttemptsPerRun)
}
if err := validDeadlines(s.Escalation); err != nil {
return err
}
if s.ActionsPerRun < 1 || s.ActionsPerRun > maxActionBudget || s.ActionsPerDay < s.ActionsPerRun || s.ActionsPerDay > maxActionBudget {
return fmt.Errorf("actions per run must be at least 1, and actions per day at least that and at most %d", maxActionBudget)
}
return s.Timing.validate()
}
// validDeadlines keeps each escalation step's deadline inside the range the
// approval deadline takes.
func validDeadlines(path []Step) error {
for _, st := range path {
if st.Deadline < minApprovalDeadline || st.Deadline > maxApprovalDeadline {
return fmt.Errorf("each escalation deadline must be between %s and %s", minApprovalDeadline, maxApprovalDeadline)
}
}
return nil
}
// knows checks that the default owner and every account on the escalation
// path is one of members, and that no one is on the path twice.
func (s Settings) knows(members map[string]string) error {
if _, ok := members[s.DefaultOwner]; s.DefaultOwner != "" && !ok {
return errors.New("the default owner must be a member")
}
seen := map[string]bool{}
for _, st := range s.Escalation {
if _, ok := members[st.Account]; !ok {
return errors.New("everyone on the escalation path must be a member")
}
if seen[st.Account] {
return errors.New("a member can be on the escalation path once")
}
seen[st.Account] = true
}
return nil
}
// memberNames returns the display name of each person who holds an org-wide
// membership, by account id. Agents and service accounts never answer.
func (m *Module) memberNames(ctx context.Context) (map[string]string, error) {
members, err := m.ListMembers(ctx, DefaultOrgID)
if err != nil {
return nil, err
}
out := make(map[string]string, len(members))
for _, member := range members {
if member.Kind == KindUser && member.WorkspaceID == "" {
out[string(member.IdentityID)] = member.DisplayName
}
}
return out, nil
}
func (m *Module) listAgentModels(ctx context.Context, _ *struct{}) (*httpapi.Reply[map[string]Model], error) {
rows, err := m.store.AgentModelRoles(ctx, m.orgID)
if err != nil {
m.log.ErrorContext(ctx, "list agent models", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't list agent models")
}
var credNames map[uuid.UUID]string
for _, row := range rows {
if row.APIKeyCredentialID.Valid {
credNames = m.credentialNames(ctx)
break
}
}
out := make(map[string]Model, len(rows))
for _, row := range rows {
out[aliasOf(row.Role)] = Model{
ProviderID: row.ProviderID, Provider: row.Provider, Model: row.Model,
Class: row.Class, BaseURL: row.BaseURL,
APIKeyCredentialID: credentialIDPtr(row.APIKeyCredentialID),
APIKeyCredential: credNames[row.APIKeyCredentialID.UUID],
}
}
return httpapi.OK(out), nil
}
type agentModelAlias struct {
Alias string `query:"alias" doc:"Agent model alias; omit for the default model"`
}
func (m *Module) getAgentModel(ctx context.Context, in *agentModelAlias) (*httpapi.Reply[Model], error) {
if err := ValidateAgentModelAlias(in.Alias); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
model, err := m.AgentModelForAlias(ctx, in.Alias)
switch {
case errors.Is(err, ErrNoAgentModel):
return nil, huma.NewError(http.StatusNotFound, err.Error())
case err != nil:
m.log.ErrorContext(ctx, "read agent model", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the agent model")
default:
return httpapi.OK(model), nil
}
}
type agentModelInput struct {
Alias string `query:"alias" doc:"Agent model alias; omit for the default model"`
Body Model
}
// putAgentModel stores the provider and model an alias names.
func (m *Module) putAgentModel(ctx context.Context, in *agentModelInput) (*httpapi.Reply[Model], error) {
if err := ValidateAgentModelAlias(in.Alias); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
model, err := m.modelOf(ctx, in.Body)
if err != nil {
return nil, err
}
if err := m.store.PutModelRole(ctx, store.ModelRole{
OrgID: m.orgID, Role: agentModelRole(in.Alias), ProviderID: model.ProviderID, Model: model.Model,
}); err != nil {
if errors.Is(err, store.ErrNoProvider) {
return nil, huma.NewError(http.StatusBadRequest, fmt.Sprintf("no provider with id %s", model.ProviderID))
}
m.log.ErrorContext(ctx, "put agent model", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the agent model")
}
return httpapi.OK(model), nil
}
func (m *Module) deleteAgentModel(ctx context.Context, in *agentModelAlias) (*struct{}, error) {
if err := ValidateAgentModelAlias(in.Alias); err != nil {
return nil, huma.NewError(http.StatusBadRequest, err.Error())
}
found, err := m.store.DeleteModelRole(ctx, m.orgID, agentModelRole(in.Alias))
if err != nil {
m.log.ErrorContext(ctx, "delete agent model", "error", err)
return nil, huma.NewError(http.StatusInternalServerError, "couldn't delete the agent model")
}
if !found {
return nil, huma.NewError(http.StatusNotFound, "no such agent model")
}
return nil, nil
}
// modelAnswer is a test call's answer.
type modelAnswer struct {
Model string `json:"model"`
Answer string `json:"answer"`
}
// testTimeout bounds a test call, so a slow endpoint answers the operator with
// a failure instead of holding the request open.
const testTimeout = 60 * time.Second
// testAgentModel asks the model one question and reports its answer, so the
// operator knows the endpoint, model and key work before saving them.
func (m *Module) testAgentModel(ctx context.Context, in *struct{ Body Model }) (*httpapi.Reply[modelAnswer], error) {
model, err := m.modelOf(ctx, in.Body)
if err != nil {
return nil, err
}
provider, _, err := m.provider(ctx, model)
if err != nil {
return nil, huma.NewError(http.StatusInternalServerError, err.Error())
}
ctx, cancel := context.WithTimeout(ctx, testTimeout)
defer cancel()
resp, err := provider.Chat(ctx, chat.Request{
Model: model.Model,
Messages: []chat.Message{{Role: chat.RoleUser, Content: prompts.ModelProbe()}},
MaxTokens: 32,
})
if err != nil {
return nil, huma.NewError(http.StatusBadGateway, err.Error())
}
return httpapi.OK(modelAnswer{Model: model.Model, Answer: resp.Content}), nil
}
// endpoint checks a provider's class and endpoint and returns it with the
// class's default base URL filled in.
func endpoint(name, class, baseURL string, credentialID *uuid.UUID) (store.Provider, error) {
if !providerName.MatchString(name) {
return store.Provider{}, errors.New("a provider name is lowercase letters, digits, dots, underscores or hyphens")
}
if _, ok := runtime.GetClass(class); !ok {
return store.Provider{}, fmt.Errorf("unknown provider class %q", class)
}
if baseURL == "" {
base, ok := runtime.DefaultBaseURL(class)
if !ok {
return store.Provider{}, fmt.Errorf("provider class %q has no default base URL; give one", class)
}
baseURL = base
}
u, err := url.Parse(baseURL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return store.Provider{}, fmt.Errorf("base URL %q must be an http or https URL", baseURL)
}
var credID uuid.NullUUID
if credentialID != nil {
if *credentialID == uuid.Nil {
return store.Provider{}, errors.New("a credential id is a non-zero UUID")
}
credID = uuid.NullUUID{UUID: *credentialID, Valid: true}
}
return store.Provider{Name: name, Class: class, BaseURL: baseURL, APIKeyCredentialID: credID}, nil
}