Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions admin/server/alerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,8 @@ func (s *Server) yamlForManagedAlert(opts *adminv1.AlertOptions, ownerUserID, em
return nil, err
}
// Notification options
// An AI alert's check fails when the analysis can't determine whether its condition holds, so its owner hears about errors.
res.OnError = opts.Resolver == "ai"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With on_error enabled, a cannot_determine reason goes through SendAlertStatus as ExecutionError. That branch puts the analyst’s text straight into Slack markup, so angle-bracketed text can turn into a link or mention. Could we use slackTextEscaper.Replace(s.ExecutionError) for ErrorMessage, like the alert-triggered branch does for Reason? Slack’s escaping rules

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 14c91f5: the error branch now escapes ExecutionError with slackTextEscaper, for every alert, and the Slack notifier test covers it.

res.Renotify = opts.Renotify
res.RenotifyAfter = opts.RenotifyAfterSeconds
res.Notify.RowsLimit = opts.NotifyRowsLimit
Expand Down Expand Up @@ -828,6 +830,7 @@ type alertYAML struct {
IncludeHeader bool `yaml:"include_header"`
Limit uint64 `yaml:"limit,omitempty"`
} `yaml:"export,omitempty"` // Omitted unless attaching, so runtimes that predate it can parse the YAML
OnError bool `yaml:"on_error,omitempty"`
Renotify bool `yaml:"renotify"`
RenotifyAfter uint32 `yaml:"renotify_after"`
Notify struct {
Expand Down
32 changes: 32 additions & 0 deletions admin/server/alerts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
adminv1 "github.com/rilldata/rill/proto/gen/rill/admin/v1"
runtimev1 "github.com/rilldata/rill/proto/gen/rill/runtime/v1"
"github.com/rilldata/rill/runtime"
"github.com/rilldata/rill/runtime/parser"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/structpb"
"gopkg.in/yaml.v3"
Expand Down Expand Up @@ -219,3 +220,34 @@ func TestYAMLForAlertNotifyRowsLimit(t *testing.T) {
opts.NotifyRowsLimit = 10
}
}

// TestYAMLForManagedAIAlertNotifiesOnError checks that AI alerts notify on errors,
// since a check fails when the analysis can't determine whether the condition holds.
func TestYAMLForManagedAIAlertNotifiesOnError(t *testing.T) {
s := &Server{}
props, err := structpb.NewStruct(map[string]any{"prompt": "Revenue dropped", "explore": "e1"})
require.NoError(t, err)
opts := &adminv1.AlertOptions{
DisplayName: "Alert",
MetricsViewName: "mv1",
RefreshCron: "0 9 * * *",
Resolver: "ai",
ResolverProperties: props,
EmailRecipients: []string{"user_1@example.com"},
}
parse := func() *parser.AlertYAML {
data, err := s.yamlForManagedAlert(opts, "owner", "", "", nil)
require.NoError(t, err)
res := &parser.AlertYAML{}
require.NoError(t, yaml.Unmarshal(data, res))
return res
}
onError := parse().OnError
require.NotNil(t, onError)
require.True(t, *onError)

// Other alerts keep the parser's default, which doesn't notify on errors
opts.Resolver, opts.ResolverProperties = "", nil
opts.QueryName, opts.QueryArgsJson = "MetricsViewAggregation", `{"metrics_view":"mv1"}`
require.Nil(t, parse().OnError)
}
28 changes: 26 additions & 2 deletions docs/docs/reference/project-files/alerts.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,11 @@ _[oneOf]_ - Data source for the alert _(required)_

- **`union`** - _[array of object]_ - List of resolver definitions whose results are combined into a single result set. _(required)_

- **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports.
- **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports and alerts.

- **`ai`** - _[object]_ - AI resolver configuration for generating automated insights _(required)_

- **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used.
- **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. Required for alerts, where it is the condition that the analysis checks.

- **`time_range`** - _[object]_ - Time range for the analysis period. Use either a Rill time expression or fixed start and end timestamps.

Expand Down Expand Up @@ -264,3 +264,27 @@ notify:
channels:
- '#rill-cloud-alerts'
```

```yaml
# Example: To send an email when an AI analysis finds that a condition written in words holds
type: alert
display_name: Weekly revenue drop
# AI alerts must run on a cron schedule of at most once an hour, and can't set `refresh.every`, `refresh.ref_update` or `intervals`.
refresh:
cron: 0 9 * * *
time_zone: America/New_York
# AI alerts must set the Rill Cloud user whose access and AI session the analysis runs with.
for:
user_id: <user-id>
# The prompt is the condition; the alert fails, and notifies, when the analysis finds that it holds.
data:
ai:
prompt: Revenue dropped by more than 10% compared with the previous 7 days
explore: sales_explore
time_range:
expression: 7D as of latest/D+1D # the last 7 days with data
notify:
email:
recipients:
- jane@example.com
```
8 changes: 4 additions & 4 deletions docs/docs/reference/project-files/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,11 +178,11 @@ _[oneOf]_ - Refers to the explicitly defined state of your model, cannot be used

- **`union`** - _[array of object]_ - List of resolver definitions whose results are combined into a single result set. _(required)_

- **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports.
- **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports and alerts.

- **`ai`** - _[object]_ - AI resolver configuration for generating automated insights _(required)_

- **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used.
- **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. Required for alerts, where it is the condition that the analysis checks.

- **`time_range`** - _[object]_ - Time range for the analysis period. Use either a Rill time expression or fixed start and end timestamps.

Expand Down Expand Up @@ -272,11 +272,11 @@ _[oneOf]_ - Refers to how your data is partitioned; cannot be used with state. (

- **`union`** - _[array of object]_ - List of resolver definitions whose results are combined into a single result set. _(required)_

- **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports.
- **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports and alerts.

- **`ai`** - _[object]_ - AI resolver configuration for generating automated insights _(required)_

- **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used.
- **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. Required for alerts, where it is the condition that the analysis checks.

- **`time_range`** - _[object]_ - Time range for the analysis period. Use either a Rill time expression or fixed start and end timestamps.

Expand Down
4 changes: 2 additions & 2 deletions docs/docs/reference/project-files/reports.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,11 @@ Supports ai resolvers only as of now.

- **`union`** - _[array of object]_ - List of resolver definitions whose results are combined into a single result set. _(required)_

- **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports.
- **option 7** - _[object]_ - Uses AI to generate insights and analysis from metrics data. Only available for reports and alerts.

- **`ai`** - _[object]_ - AI resolver configuration for generating automated insights _(required)_

- **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used.
- **`prompt`** - _[string]_ - Custom prompt to guide the AI analysis. If not provided, a default analysis prompt is used. Required for alerts, where it is the condition that the analysis checks.

- **`time_range`** - _[object]_ - Time range for the analysis period. Use either a Rill time expression or fixed start and end timestamps.

Expand Down
57 changes: 56 additions & 1 deletion runtime/ai/analyst_agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ type AnalystAgentArgs struct {
ComparisonTimeEnd time.Time `json:"comparison_time_end" yaml:"comparison_time_end" jsonschema:"Optional comparison period end time."`
DisableCharts bool `json:"disable_charts" yaml:"disable_charts" jsonschema:"Flag indicating whether to disable chart creation in the analysis."`
IsReport bool `json:"is_report" yaml:"is_report" jsonschema:"Flag indicating this is an automated report."`
IsAlert bool `json:"is_alert" yaml:"is_alert" jsonschema:"Flag indicating this checks an AI alert's condition, which is the prompt. The result then includes a verdict."`
}

func (a *AnalystAgentArgs) ToLLM() *aiv1.ContentBlock {
Expand All @@ -55,8 +56,19 @@ func (a *AnalystAgentArgs) ToLLM() *aiv1.ContentBlock {

type AnalystAgentResult struct {
Response string `json:"response"`
// AlertOutcome is the verdict on an AI alert's condition (see AnalystAgentArgs.IsAlert).
AlertOutcome AlertOutcome `json:"alert_outcome,omitempty"`
}

// AlertOutcome is the analyst's verdict on whether an AI alert's condition holds.
type AlertOutcome string

const (
AlertOutcomeMet AlertOutcome = "met"
AlertOutcomeNotMet AlertOutcome = "not_met"
AlertOutcomeCannotDetermine AlertOutcome = "cannot_determine"
)

func (r *AnalystAgentResult) ToLLM() *aiv1.ContentBlock {
return &aiv1.ContentBlock{
BlockType: &aiv1.ContentBlock_Text{
Expand Down Expand Up @@ -253,9 +265,42 @@ func (t *AnalystAgent) Handler(ctx context.Context, args *AnalystAgentArgs) (*An
return nil, err
}

// An AI alert's analysis ends with a verdict on its condition.
// The verdict is a separate call without tools, since some providers (e.g. Gemini) reject requests that combine tools with an output schema.
if args.IsAlert {
outcome, err := alertOutcome(ctx, s, args.Prompt, response)
if err != nil {
return nil, err
}
return &AnalystAgentResult{Response: response, AlertOutcome: outcome}, nil
}

return &AnalystAgentResult{Response: response}, nil
}

// alertOutcome classifies the analysis of an AI alert's condition as met, not met, or not answerable from the data.
func alertOutcome(ctx context.Context, s *Session, condition, analysis string) (AlertOutcome, error) {
var verdict struct {
Outcome AlertOutcome `json:"outcome" jsonschema:"One of \"met\", \"not_met\" or \"cannot_determine\"."`
}
err := s.Complete(ctx, "Alert verdict", &verdict, &CompleteOptions{
Messages: []*aiv1.CompletionMessage{
NewTextCompletionMessage(RoleSystem, `You read an analysis that checked whether an alert's condition holds, and give the analysis's verdict.
The outcome is "met" if the analysis shows that the condition holds, "not_met" if it shows that the condition does not hold,
and "cannot_determine" if the analysis could not tell, for example because the data has no measure or dimension that the condition refers to.`),
NewTextCompletionMessage(RoleUser, fmt.Sprintf("The alert's condition:\n%s\n\nThe analysis:\n%s", condition, analysis)),
},
})
if err != nil {
return "", fmt.Errorf("failed to get a verdict on the alert's condition: %w", err)
}
switch verdict.Outcome {
case AlertOutcomeMet, AlertOutcomeNotMet, AlertOutcomeCannotDetermine:
return verdict.Outcome, nil
}
return "", fmt.Errorf("invalid verdict on the alert's condition: %q", verdict.Outcome)
}

func (t *AnalystAgent) systemPrompt(ctx context.Context) (string, error) {
instr, err := instructions.Load("analysis.md", instructions.Options{Memory: GetSession(ctx).MemoryEnabled()})
if err != nil {
Expand Down Expand Up @@ -307,6 +352,7 @@ func (t *AnalystAgent) userPrompt(ctx context.Context, metricsViewNames []string
"measures": strings.Join(measuresQuoted, ", "),
"forked": session.Forked(),
"is_report": args.IsReport,
"is_alert": args.IsAlert,
"now": time.Now(),
"max_query_limit": instanceCfg.AIMaxQueryLimit,
"external_servers": session.ExternalServerPromptData(ctx, "analyst"),
Expand Down Expand Up @@ -349,9 +395,18 @@ You are operating in an automated scheduled insight report mode where you will c
{{ if .is_prompt }}The user has provided a custom prompt for this scheduled insight report. Tailor your analysis to address this prompt specifically.{{ end }}
{{ end }}

{{ if .is_alert }}
You are checking the condition of an automated alert, without additional user input.
The condition is the user's request at the end of this message: a statement about the data that either holds or does not.
Query the data to decide whether it holds. Do not ask questions, since nobody will answer them.
If the data can't tell whether the condition holds, for example because it refers to a measure or dimension that doesn't exist, say so instead of guessing.
Relative expressions in the condition, such as "this month", "today" or "compared with the previous period", refer to {{ if (and .time_start .time_end) }}the time range start={{.time_start}}, end={{.time_end}}{{ else }}the latest data available{{ end }}, not to today's date.
Begin your final response with a summary wrapped in <summary></summary> tags: one to three plain sentences that say whether the condition holds and give the figures it rests on, without citation links.
{{ end }}

{{ if .explore }}
Your goal is to analyze the contents of the dashboard "{{ .explore }}", which is powered by the metrics view(s) {{ .metrics_views }}.
{{ if not .is_report }}The user is actively viewing this dashboard, and it's what they refer to if they use expressions like "this dashboard", "the current view", etc. {{ end }}
{{ if not (or .is_report .is_alert) }}The user is actively viewing this dashboard, and it's what they refer to if they use expressions like "this dashboard", "the current view", etc. {{ end }}
The metrics view's definition and time range of available data has been provided in your tool calls.

Here is an overview of the settings applied to the dashboard:
Expand Down
126 changes: 126 additions & 0 deletions runtime/ai/analyst_alert_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package ai_test

import (
"testing"

"github.com/google/jsonschema-go/jsonschema"
aiv1 "github.com/rilldata/rill/proto/gen/rill/ai/v1"
"github.com/rilldata/rill/runtime/ai"
"github.com/rilldata/rill/runtime/drivers"
"github.com/rilldata/rill/runtime/testruntime"
"github.com/stretchr/testify/require"
)

func TestAnalystAlert(t *testing.T) {
alertArgs := &ai.RouterAgentArgs{
Prompt: "There are orders from Denmark",
Agent: ai.AnalystAgentName,
AnalystAgentArgs: &ai.AnalystAgentArgs{IsAlert: true},
}
analysis := "<summary>Denmark has orders.</summary> Orders come from Denmark."

cases := []struct {
verdict string
want ai.AlertOutcome
wantErr string
}{
{verdict: `{"outcome": "met"}`, want: ai.AlertOutcomeMet},
{verdict: `{"outcome": "not_met"}`, want: ai.AlertOutcomeNotMet},
{verdict: `{"outcome": "cannot_determine"}`, want: ai.AlertOutcomeCannotDetermine},
{verdict: `{"outcome": "maybe"}`, wantErr: "invalid verdict"},
{verdict: `The condition holds.`, wantErr: "verdict"},
}
for _, tc := range cases {
t.Run(tc.verdict, func(t *testing.T) {
var schemas []*jsonschema.Schema
recordSchema := func(turn turnFunc) turnFunc {
return func(opts *drivers.CompleteOptions) *aiv1.CompletionMessage {
schemas = append(schemas, opts.OutputSchema)
return turn(opts)
}
}
script := &scriptedAIService{turns: []turnFunc{recordSchema(textTurn(analysis)), recordSchema(textTurn(tc.verdict))}}
s := newSkillReferencesSession(t, script)

var res *ai.RouterAgentResult
_, err := s.CallTool(t.Context(), ai.RoleUser, ai.RouterAgentName, &res, alertArgs)
if tc.wantErr != "" {
require.ErrorContains(t, err, tc.wantErr)
return
}
require.NoError(t, err)
require.Equal(t, tc.want, res.AlertOutcome)
require.Equal(t, analysis, res.Response)

// The analysis runs with tools and the verdict with an output schema, in separate requests,
// since some providers reject a request that combines them.
require.Len(t, schemas, 2)
require.Contains(t, script.tools[0], ai.QueryMetricsViewName)
require.Nil(t, schemas[0])
require.Empty(t, script.tools[1])
require.Contains(t, schemas[1].Properties, "outcome")
// The verdict is given on the analysis
require.Contains(t, script.inputs[1][len(script.inputs[1])-1].Content[0].GetText(), analysis)
})
}
}

func TestAnalystAlertEval(t *testing.T) {
// Eight weeks of daily revenue for three countries.
// Revenue is around 100 a day for every country, except Spain, which drops to around 30 a day in the last week.
rt, instanceID := testruntime.NewInstanceWithOptions(t, testruntime.InstanceOptions{
AIConnector: "openai",
Files: map[string]string{
"models/orders.yaml": `
type: model
materialize: true
sql: |
SELECT
d::TIMESTAMP AS event_time,
c AS country,
CASE WHEN c = 'Spain' AND d >= DATE '2025-10-19' THEN 30 ELSE 100 END + (hash(d::DATE, c) % 7)::INTEGER AS revenue
FROM range(DATE '2025-08-31', DATE '2025-10-26', INTERVAL 1 DAY) AS t(d), (VALUES ('Spain'), ('France'), ('Germany')) AS countries(c)
`,
"metrics/orders.yaml": `
type: metrics_view
model: orders
timeseries: event_time
dimensions:
- column: country
measures:
- name: revenue
expression: SUM(revenue)
`,
"explores/orders.yaml": `
type: explore
metrics_view: orders
`,
},
})
testruntime.RequireReconcileState(t, rt, instanceID, 3, 0, 0)

cases := []struct {
condition string
want ai.AlertOutcome
}{
{"Revenue in Spain dropped sharply in the last week compared with the previous weeks", ai.AlertOutcomeMet},
{"Spain is the country with the lowest revenue in the last week", ai.AlertOutcomeMet},
{"Revenue in France dropped sharply in the last week compared with the previous weeks", ai.AlertOutcomeNotMet},
{"There are orders from Italy", ai.AlertOutcomeNotMet},
// The data has no profit
{"The profit margin in Spain fell below 10% in the last week", ai.AlertOutcomeCannotDetermine},
}
for _, tc := range cases {
t.Run(tc.condition, func(t *testing.T) {
s := newEval(t, rt, instanceID)
var res *ai.RouterAgentResult
_, err := s.CallTool(t.Context(), ai.RoleUser, ai.RouterAgentName, &res, &ai.RouterAgentArgs{
Prompt: tc.condition,
Agent: ai.AnalystAgentName,
AnalystAgentArgs: &ai.AnalystAgentArgs{Explore: "orders", IsAlert: true},
})
require.NoError(t, err)
require.Equal(t, tc.want, res.AlertOutcome, res.Response)
})
}
}
4 changes: 3 additions & 1 deletion runtime/ai/router_agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ type RouterAgentArgs struct {
type RouterAgentResult struct {
Response string `json:"response"`
Agent string `json:"agent"`
// AlertOutcome is the analyst's verdict when it checked an AI alert's condition.
AlertOutcome AlertOutcome `json:"alert_outcome,omitempty"`
}

func (t *RouterAgent) Spec() *mcp.Tool {
Expand Down Expand Up @@ -169,7 +171,7 @@ func (t *RouterAgent) Handler(ctx context.Context, args *RouterAgentArgs) (*Rout
if err != nil {
return nil, mapAgentErr(err)
}
return &RouterAgentResult{Response: res.Response, Agent: args.Agent}, nil
return &RouterAgentResult{Response: res.Response, Agent: args.Agent, AlertOutcome: res.AlertOutcome}, nil

case DeveloperAgentName:
developerAgentArgs := args.DeveloperAgentArgs
Expand Down
1 change: 1 addition & 0 deletions runtime/drivers/notifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type AlertStatus struct {
FailColumns []string // Column names of FailRows, in the order of the alert query's result
FailRows [][]string // Display values of the rows that matched the alert criteria; it has at most the alert's rows limit
FailRowsTruncated bool // True if more rows matched the alert criteria than FailRows contains
Reason string // The AI analysis's reason when an AI alert fires; it's shown instead of the fail rows
ExecutionError string
OpenLink string
EditLink string
Expand Down
Loading
Loading