AI Analysis

Sentinel includes an optional AI-powered analysis system that brings intelligent threat interpretation to your security data. By integrating with leading LLM providers — Anthropic Claude, OpenAI, or Google Gemini — Sentinel can generate plain-English explanations of threat events, assess the risk level of threat actors, summarize your daily security posture, answer natural language questions about your data, and even recommend new WAF rules based on recent attack patterns.

AI analysis is entirely optional. When not configured, all AI endpoints gracefully return a message indicating that AI is not set up, and the dashboard shows setup instructions instead of analysis results. No API calls are made to any external service unless you explicitly provide a provider and API key.

Optional Feature

AI analysis requires a valid API key from one of the supported providers. Sentinel works perfectly without it — all core security features (WAF, rate limiting, anomaly detection, threat intelligence, alerting) operate independently of AI. Think of it as an intelligence layer on top of your existing security data.

Supported Providers

Sentinel supports three AI providers out of the box. Each provider uses a sensible default model, but you can override it with any model the provider supports.

ProviderConstantDefault ModelDescription
Claudesentinel.Claudeclaude-sonnet-4-20250514Anthropic Claude. Excellent at nuanced security analysis and structured reasoning.
OpenAIsentinel.OpenAIgpt-4oOpenAI GPT. Strong general-purpose analysis with broad security knowledge.
Geminisentinel.Geminigemini-2.0-flashGoogle Gemini. Fast and cost-effective for high-volume analysis workloads.

Configuration

AI analysis is configured through the AI field on the main sentinel.Config struct. This field is a pointer (*AIConfig), so setting it to nil (or simply omitting it) disables all AI features.

AIConfig

FieldTypeRequiredDescription
ProviderAIProviderYesWhich AI provider to use: sentinel.Claude, sentinel.OpenAI, or sentinel.Gemini.
APIKeystringYesYour API key for the chosen provider. Keep this secret — use environment variables in production.
ModelstringNoOptional model override. When empty, the default model for the chosen provider is used (see table above).
DailySummaryboolNoWhen true, enables automatic daily summary generation.
core/config.gogo
1// AIConfig configures optional AI-powered analysis.
2type AIConfig struct {
3 Provider AIProvider `json:"provider"`
4 APIKey string `json:"api_key"`
5 Model string `json:"model,omitempty"`
6 DailySummary bool `json:"daily_summary,omitempty"`
7}
8
9// AIProvider specifies which AI provider to use.
10type AIProvider string
11
12const (
13 Claude AIProvider = "claude"
14 OpenAI AIProvider = "openai"
15 Gemini AIProvider = "gemini"
16)

Basic Configuration (Claude)

main.gogo
1sentinel.Mount(r, nil, sentinel.Config{
2 WAF: sentinel.WAFConfig{
3 Enabled: true,
4 Mode: sentinel.ModeBlock,
5 },
6 AI: &sentinel.AIConfig{
7 Provider: sentinel.Claude,
8 APIKey: os.Getenv("ANTHROPIC_API_KEY"),
9 },
10})

OpenAI Configuration

main.gogo
1AI: &sentinel.AIConfig{
2 Provider: sentinel.OpenAI,
3 APIKey: os.Getenv("OPENAI_API_KEY"),
4}

Gemini Configuration

main.gogo
1AI: &sentinel.AIConfig{
2 Provider: sentinel.Gemini,
3 APIKey: os.Getenv("GEMINI_API_KEY"),
4}

Custom Model Override

If you want to use a specific model version instead of the default, set the Model field:

1AI: &sentinel.AIConfig{
2 Provider: sentinel.OpenAI,
3 APIKey: os.Getenv("OPENAI_API_KEY"),
4 Model: "gpt-4-turbo", // Override the default gpt-4o
5}

Protect Your API Key

Never hardcode API keys in your source code. Use environment variables or a secrets manager. The examples above use os.Getenv() to load the key from the environment at runtime.

AI Capabilities

Sentinel provides five distinct AI-powered analysis features. Each one is accessible via the dashboard UI and the REST API.

1. Threat Analysis

Generate a detailed, plain-English analysis of a specific threat event. The AI examines the threat type, severity, payload, targeted route, and the associated actor profile to produce an explanation of what happened, why it matters, and what you should do about it.

Response FieldTypeDescription
summarystringA concise one-line summary of the threat.
explanationstringA detailed explanation of the attack technique and its implications.
severity_assessmentstringThe AI assessment of how severe this threat is in context.
succeededboolWhether the AI believes the attack succeeded.
recommendations[]stringActionable recommendations for mitigating or preventing this threat.
threat_categorystringThe broad category the AI assigns to this threat.
confidenceintThe AI confidence score (0-100) in its analysis.

2. Actor Assessment

Generate a risk assessment of a threat actor based on their IP address, behavioral history, and recent events. The AI evaluates the actor's intent, sophistication level, and overall risk to your application.

Response FieldTypeDescription
summarystringA concise overview of the actor and their behavior.
intentstringThe AI assessment of the actor's likely intent (e.g., reconnaissance, exploitation, data exfiltration).
sophisticationstringThe estimated skill level of the actor (e.g., script kiddie, intermediate, advanced).
risk_levelstringOverall risk rating for this actor.
recommendations[]stringSuggested actions to take regarding this actor.
related_groups[]stringKnown threat groups or campaigns the actor's behavior may be associated with.

3. Daily Summary

Generate an AI-powered summary of the last 24 hours of security events. This provides a high-level overview of your security posture, highlights the most significant threats, identifies trends, and offers strategic recommendations.

Response FieldTypeDescription
summarystringA narrative overview of the day's security events.
highlights[]stringKey events and milestones from the past 24 hours.
top_threats[]stringThe most significant threats observed during the period.
trend_analysisstringAnalysis of how threat patterns are evolving.
recommendations[]stringStrategic recommendations based on observed patterns.
overall_statusstringA brief assessment of overall security health.

4. Natural Language Query

Ask questions about your security data in plain English. The AI receives context about your recent threats, top actors, threat statistics, and security score, then answers your question using that live data.

Example Queriesjson
{ "query": "What are the most common attack types this week?" }
{ "query": "Is the IP 203.0.113.50 a serious threat?" }
{ "query": "Should I be worried about the spike in XSS attempts?" }
{ "query": "Summarize the threats targeting my /api/auth endpoint" }
Response FieldTypeDescription
answerstringThe AI answer to your question, grounded in your actual security data.
sources[]stringReferences to the data sources used to answer the question.
suggestions[]stringFollow-up questions or actions the AI suggests.

5. WAF Recommendations

The AI analyzes recent threat events and suggests new WAF rules to improve your defenses. Each recommendation includes a rule ID, name, regex pattern, severity, the request components it should apply to, and the reasoning behind the suggestion.

Response FieldTypeDescription
rule_idstringA suggested unique ID for the rule.
namestringHuman-readable name for the recommended rule.
patternstringThe regex pattern to match against requests.
severitystringSuggested severity level for matches.
reasonstringExplanation of why this rule is recommended based on observed patterns.
applies_to[]stringWhich request components to inspect (e.g., path, query, headers, body).

Review Before Applying

AI-generated WAF rules are suggestions, not automatic deployments. Always review the recommended patterns carefully and test them in ModeLog before enabling them in production. The AI may occasionally suggest overly broad patterns that could cause false positives.

API Endpoints

All AI endpoints are protected by dashboard authentication (JWT). They are available under the /sentinel/api/ai prefix by default.

MethodEndpointDescription
POST/ai/analyze-threat/:idAnalyze a specific threat event by its ID.
GET/ai/analyze-actor/:ipGenerate a risk assessment for a threat actor by IP address.
GET/ai/daily-summaryGenerate an AI summary of the last 24 hours of security events.
POST/ai/queryAsk a natural language question about your security data.
GET/ai/waf-recommendationsGet AI-suggested WAF rules based on recent threats.

Analyze Threat

# Analyze a specific threat event
curl -X POST http://localhost:8080/sentinel/api/ai/analyze-threat/te-abc123 \
-H "Authorization: Bearer <token>"

Analyze Actor

# Get risk assessment for a threat actor
curl http://localhost:8080/sentinel/api/ai/analyze-actor/203.0.113.50 \
-H "Authorization: Bearer <token>"

Daily Summary

# Generate AI daily security summary
curl http://localhost:8080/sentinel/api/ai/daily-summary \
-H "Authorization: Bearer <token>"

Natural Language Query

# Ask a question about your security data
curl -X POST http://localhost:8080/sentinel/api/ai/query \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{"query": "What are the most targeted endpoints this week?"}'

WAF Recommendations

# Get AI-suggested WAF rules
curl http://localhost:8080/sentinel/api/ai/waf-recommendations \
-H "Authorization: Bearer <token>"

Response Caching

To minimize API costs and improve response times, Sentinel wraps every AI provider with a CachedProvider. The caching layer intercepts requests and returns cached responses when available, falling back to the real provider only when the cache misses or expires.

FeatureCache KeyCached?
Threat Analysisthreat:<threat_id>Yes
Actor Assessmentactor:<ip_address>Yes
Daily Summarydaily:<YYYY-MM-DD>Yes
Natural Language QueryN/ANo — each query is unique
WAF Recommendationswaf-rec:<YYYY-MM-DD>Yes

The default cache TTL is 1 hour. After the TTL expires, the next request for the same key triggers a fresh AI call. Natural language queries are never cached because each query is unique and users expect real-time answers.

ai/provider.gogo
1// CachedProvider wraps a Provider with response caching.
2type CachedProvider struct {
3 provider Provider
4 cache map[string]*cacheEntry
5 mu sync.RWMutex
6 ttl time.Duration
7}
8
9// NewCachedProvider creates a caching wrapper around any Provider.
10func NewCachedProvider(provider Provider, ttl time.Duration) *CachedProvider {
11 if ttl == 0 {
12 ttl = 1 * time.Hour // Default TTL
13 }
14 return &CachedProvider{
15 provider: provider,
16 cache: make(map[string]*cacheEntry),
17 ttl: ttl,
18 }
19}

Cost Optimization

The caching layer significantly reduces API costs. Analyzing the same threat event multiple times (e.g., when multiple team members view the same event in the dashboard) only incurs one API call. Daily summaries and WAF recommendations are cached for the entire day, so repeated views are instant and free.

Graceful Degradation

When AI is not configured (the AI field is nil or the API key is empty), Sentinel degrades gracefully rather than failing. All AI endpoints remain available but return a clear message indicating that AI is not set up.

API Response When AI Is Not Configured

Responsejson
{
"data": null,
"message": "AI not configured"
}

This consistent response format means your frontend or API consumers can check for the message field and display appropriate UI — such as a setup prompt or a feature explanation — without error handling.

ai/provider.gogo
1// NewProvider creates the appropriate Provider based on configuration.
2// Returns nil if AI is not configured.
3func NewProvider(config *AIConfig) Provider {
4 if config == nil || config.APIKey == "" {
5 return nil
6 }
7 // ... create provider based on config.Provider
8}

Dashboard Behavior

When AI is not configured, the dashboard AI Insights page detects the "AI not configured" response and displays setup instructions instead of analysis results. This guides users through enabling the feature without showing error states.

No Breaking Changes

You can safely enable or disable AI at any time by adding or removing the AI config pointer. No other part of the system depends on AI being available. The WAF, rate limiter, anomaly detection, alerting, and all other features continue to operate normally regardless of AI configuration.

Dashboard — AI Insights

The Sentinel dashboard includes a dedicated AI Insights page that provides a visual interface for all five AI capabilities. Access it at http://localhost:8080/sentinel/ui and navigate to the AI Insights section.

  • Threat Analysis — Click the "Analyze with AI" button on any threat event detail page to generate an in-depth analysis. The result includes the summary, explanation, severity assessment, confidence score, and actionable recommendations.
  • Actor Assessment — From any threat actor profile page, trigger an AI risk assessment. The result shows the actor's likely intent, sophistication level, overall risk rating, and recommended actions.
  • Daily Summary — The AI Insights page features a daily summary section that provides a narrative overview of the last 24 hours, including highlights, top threats, trend analysis, and strategic recommendations.
  • Natural Language Query — A chat-like interface where you can type questions about your security data in plain English and receive AI-generated answers grounded in your live data.
  • WAF Recommendations — A dedicated section that displays AI-suggested WAF rules with their patterns, severity levels, and the reasoning behind each recommendation. Review and apply them directly from the dashboard.

Testing Without an API Key

You can run Sentinel with the AI feature unconfigured and everything works normally. The system gracefully handles the absence of an API key at every level:

  1. Provider creationai.NewProvider(nil) returns nil when the config is nil or the API key is empty. No provider is instantiated, no external connections are attempted.
  2. API handlers — Every AI handler checks if aiProvider is nil before proceeding. If it is, the handler returns an HTTP 200 with {"data": null, "message": "AI not configured"}.
  3. Dashboard — The frontend checks the API response and shows setup instructions rather than error messages when AI is not available.
main.gogo
1// AI is completely optional — just omit the AI field
2sentinel.Mount(r, nil, sentinel.Config{
3 WAF: sentinel.WAFConfig{
4 Enabled: true,
5 Mode: sentinel.ModeBlock,
6 },
7 // AI: nil — not configured, all AI endpoints return gracefully
8})

Safe to Explore

You can explore the AI Insights page in the dashboard even without an API key. The page loads normally and shows helpful information about what each feature does, along with configuration instructions. This makes it easy to evaluate the feature before committing to an API provider.

Full Configuration Example

The following example enables the WAF, alerting, and AI analysis with Claude. The AI system will analyze threats, assess actors, generate daily summaries, answer queries, and recommend WAF rules — all powered by Claude.

main.gogo
1package main
2
3import (
4 "os"
5
6 sentinel "github.com/MUKE-coder/sentinel"
7 "github.com/gin-gonic/gin"
8)
9
10func main() {
11 r := gin.Default()
12
13 sentinel.Mount(r, nil, sentinel.Config{
14 Dashboard: sentinel.DashboardConfig{
15 Username: "admin",
16 Password: "s3cur3-p4ss!",
17 SecretKey: "my-jwt-secret-change-in-production",
18 },
19
20 WAF: sentinel.WAFConfig{
21 Enabled: true,
22 Mode: sentinel.ModeBlock,
23 },
24
25 Alerts: sentinel.AlertConfig{
26 MinSeverity: sentinel.SeverityHigh,
27 Slack: &sentinel.SlackConfig{
28 WebhookURL: os.Getenv("SLACK_WEBHOOK_URL"),
29 },
30 },
31
32 // Enable AI analysis with Claude
33 AI: &sentinel.AIConfig{
34 Provider: sentinel.Claude,
35 APIKey: os.Getenv("ANTHROPIC_API_KEY"),
36 // Model defaults to claude-sonnet-4-20250514
37 },
38 })
39
40 r.GET("/api/data", func(c *gin.Context) {
41 c.JSON(200, gin.H{"status": "ok"})
42 })
43
44 r.Run(":8080")
45}

Next Steps

  • WAF — Configure the detection rules that generate threat events for AI analysis
  • Threat Intelligence — Enrich threat actor profiles that feed into AI assessments
  • Alerting — Get notified when high-severity threats are detected
  • Anomaly Detection — Add behavioral analysis that complements AI insights
  • Dashboard — Explore the AI Insights page and other dashboard features

Built with by JB