-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathengine.go
More file actions
281 lines (242 loc) · 8.66 KB
/
engine.go
File metadata and controls
281 lines (242 loc) · 8.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package analysisengine
import (
"bytes"
"context"
"embed"
"fmt"
"html/template"
"io/fs"
"os"
"path/filepath"
"time"
"github.com/gomarkdown/markdown"
mdhtml "github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser"
"github.com/openshift/osde2e/internal/analysisengine"
"github.com/openshift/osde2e/internal/llm"
"github.com/openshift/osde2e/internal/llm/tools"
"github.com/openshift/osde2e/internal/prompts"
"github.com/openshift/osde2e/internal/reporter"
krknAggregator "github.com/openshift/osde2e/pkg/krknai/aggregator"
"gopkg.in/yaml.v3"
)
//go:embed prompts/*
var krknPrompts embed.FS
const (
analysisDirName = "llm-analysis"
summaryFileName = "summary.yaml"
krknAIPromptTemplate = "krknai"
htmlTemplatePath = "prompts/report.html"
)
// Config holds configuration for the krkn-ai analysis engine.
type Config struct {
analysisengine.BaseConfig
TopScenariosCount int // Number of top scenarios to include (default: 10)
ReportFormat string // "json" (default), "markdown", or "html"
}
// Engine analyzes krkn-ai chaos test results using LLM.
type Engine struct {
config *Config
aggregator *krknAggregator.KrknAIAggregator
promptStore *prompts.PromptStore
llmClient llm.LLMClient
reporterRegistry *reporter.ReporterRegistry
}
// New creates a new krkn-ai analysis engine.
func New(ctx context.Context, config *Config) (*Engine, error) {
if config.ArtifactsDir == "" {
return nil, fmt.Errorf("results directory is required")
}
if config.APIKey == "" {
return nil, fmt.Errorf("GEMINI_API_KEY is required for krkn-ai analysis")
}
// Create krkn-ai specific aggregator
agg := krknAggregator.NewKrknAIAggregator(ctx)
if config.TopScenariosCount > 0 {
agg.WithTopScenariosCount(config.TopScenariosCount)
}
promptStore, err := prompts.NewPromptStore(prompts.DefaultTemplates())
if err != nil {
return nil, fmt.Errorf("failed to initialize prompt store: %w", err)
}
localFS, err := fs.Sub(krknPrompts, "prompts")
if err != nil {
return nil, fmt.Errorf("failed to load krkn-ai prompt templates: %w", err)
}
if err := promptStore.RegisterTemplates(localFS); err != nil {
return nil, fmt.Errorf("failed to register krkn-ai prompt templates: %w", err)
}
client, err := llm.NewGeminiClient(ctx, config.APIKey)
if err != nil {
return nil, fmt.Errorf("failed to initialize LLM client: %w", err)
}
// Initialize reporter registry
reporterRegistry := reporter.NewReporterRegistry()
reporterRegistry.Register(reporter.NewSlackReporter())
return &Engine{
config: config,
aggregator: agg,
promptStore: promptStore,
llmClient: client,
reporterRegistry: reporterRegistry,
}, nil
}
// WithClusterInfo sets cluster metadata on the aggregator for inclusion in collected data.
func (e *Engine) WithClusterInfo(info *krknAggregator.ClusterInfo) *Engine {
e.aggregator.WithClusterInfo(info)
return e
}
// Run executes the krkn-ai analysis workflow.
func (e *Engine) Run(ctx context.Context) (*analysisengine.Result, error) {
// Collect krkn-ai results
data, err := e.aggregator.Collect(ctx, e.config.ArtifactsDir)
if err != nil {
return nil, fmt.Errorf("failed to collect krkn-ai results: %w", err)
}
// Create tool registry with log artifacts for read_file tool
toolRegistry := tools.NewRegistry(data.LogArtifacts)
// Prepare template variables from collected data
vars := map[string]any{
"Summary": data.Summary,
"TopScenarios": data.TopScenarios,
"FailedScenarios": data.FailedScenarios,
"HealthCheckReport": data.HealthCheckReport,
"LogArtifacts": data.LogArtifacts,
"ConfigSummary": data.ConfigSummary,
}
if data.ClusterInfo != nil {
vars["ClusterInfo"] = data.ClusterInfo
}
// Render prompt using prompt store
userPrompt, llmConfig, err := e.promptStore.RenderPrompt(krknAIPromptTemplate, vars)
if err != nil {
return nil, fmt.Errorf("failed to render prompt: %w", err)
}
// Apply LLM config overrides
if e.config.LLMConfig != nil {
if e.config.LLMConfig.Temperature != nil {
llmConfig.Temperature = e.config.LLMConfig.Temperature
}
if e.config.LLMConfig.MaxTokens != nil {
llmConfig.MaxTokens = e.config.LLMConfig.MaxTokens
}
if e.config.LLMConfig.TopP != nil {
llmConfig.TopP = e.config.LLMConfig.TopP
}
}
// Run LLM analysis
result, err := e.llmClient.Analyze(ctx, userPrompt, llmConfig, toolRegistry)
if err != nil {
return nil, fmt.Errorf("LLM analysis failed: %w", err)
}
content := result.Content
if e.config.ReportFormat == "html" {
var err error
content, err = markdownToHTML(content)
if err != nil {
return nil, fmt.Errorf("failed to convert markdown to HTML: %w", err)
}
}
// Build analysis result
analysisResult := &analysisengine.Result{
Status: "completed",
Content: content,
Prompt: userPrompt,
Metadata: map[string]any{
"analysis_type": "krknai",
"total_scenarios": data.Summary.TotalScenarioCount,
"successful_scenarios": data.Summary.SuccessfulScenarioCount,
"failed_scenarios": data.Summary.FailedScenarioCount,
"generations": data.Summary.Generations,
"max_fitness_score": data.Summary.MaxFitnessScore,
"artifacts_examined": func() (count int) {
for _, tc := range result.ToolCalls {
if tc.Name == "read_file" {
count++
}
}
return count
}(),
"tool_calls": len(result.ToolCalls),
},
}
// Write summary to results directory
if err := e.writeSummary(analysisResult, data); err != nil {
return nil, fmt.Errorf("failed to write analysis summary: %w", err)
}
// Send notifications if configured
if e.config.NotificationConfig != nil && e.config.NotificationConfig.Enabled {
e.sendNotifications(ctx, analysisResult)
}
return analysisResult, nil
}
// writeSummary writes the analysis result to a YAML summary file.
func (e *Engine) writeSummary(result *analysisengine.Result, data *krknAggregator.KrknAIData) error {
analysisDir := filepath.Join(e.config.ArtifactsDir, analysisDirName)
if err := os.MkdirAll(analysisDir, 0o755); err != nil {
return fmt.Errorf("failed to create analysis directory: %w", err)
}
summary := map[string]any{
"timestamp": time.Now().Format(time.RFC3339),
"analysis_type": "krknai",
"cluster_info": data.ClusterInfo,
"run_summary": map[string]any{
"total_scenarios": data.Summary.TotalScenarioCount,
"successful_scenarios": data.Summary.SuccessfulScenarioCount,
"failed_scenarios": data.Summary.FailedScenarioCount,
"generations": data.Summary.Generations,
"max_fitness_score": data.Summary.MaxFitnessScore,
"avg_fitness_score": data.Summary.AvgFitnessScore,
"scenario_types": data.Summary.ScenarioTypes,
},
"top_scenarios": data.TopScenarios,
"failed_scenarios": data.FailedScenarios,
"status": result.Status,
"prompt": result.Prompt,
"response": result.Content,
"metadata": result.Metadata,
"error": result.Error,
}
yamlData, err := yaml.Marshal(summary)
if err != nil {
return fmt.Errorf("failed to marshal summary to YAML: %w", err)
}
summaryPath := filepath.Join(analysisDir, summaryFileName)
if err := os.WriteFile(summaryPath, yamlData, 0o644); err != nil {
return fmt.Errorf("failed to write summary file: %w", err)
}
return nil
}
func markdownToHTML(content string) (string, error) {
htmlTmplBytes, err := krknPrompts.ReadFile(htmlTemplatePath)
if err != nil {
return "", fmt.Errorf("failed to read HTML template: %w", err)
}
tmpl, err := template.New("report").Parse(string(htmlTmplBytes))
if err != nil {
return "", fmt.Errorf("failed to parse HTML template: %w", err)
}
p := parser.NewWithExtensions(parser.CommonExtensions | parser.AutoHeadingIDs)
renderer := mdhtml.NewRenderer(mdhtml.RendererOptions{Flags: mdhtml.CommonFlags | mdhtml.HrefTargetBlank})
body := markdown.ToHTML([]byte(content), p, renderer)
var buf bytes.Buffer
if err := tmpl.Execute(&buf, struct{ Body template.HTML }{Body: template.HTML(body)}); err != nil {
return "", fmt.Errorf("failed to execute HTML template: %w", err)
}
return buf.String(), nil
}
// sendNotifications sends analysis results to configured reporters.
func (e *Engine) sendNotifications(ctx context.Context, result *analysisengine.Result) {
reporterResult := &reporter.AnalysisResult{
Status: result.Status,
Content: result.Content,
Metadata: result.Metadata,
Error: result.Error,
Prompt: result.Prompt,
}
for _, reporterConfig := range e.config.NotificationConfig.Reporters {
if err := e.reporterRegistry.SendNotification(ctx, reporterResult, &reporterConfig); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to send notification via %s: %v\n", reporterConfig.Type, err)
}
}
}