Explain returns an AI-generated explanation of why Enforce returned a particular result. It calls the configured OpenAI-compatible API to generate a natural language explanation.
(rvals ...interface{})
| 71 | // Explain returns an AI-generated explanation of why Enforce returned a particular result. |
| 72 | // It calls the configured OpenAI-compatible API to generate a natural language explanation. |
| 73 | func (e *Enforcer) Explain(rvals ...interface{}) (string, error) { |
| 74 | if e.aiConfig.Endpoint == "" { |
| 75 | return "", errors.New("AI config not set, use SetAIConfig first") |
| 76 | } |
| 77 | |
| 78 | // Get enforcement result and matched rules |
| 79 | result, matchedRules, err := e.EnforceEx(rvals...) |
| 80 | if err != nil { |
| 81 | return "", fmt.Errorf("failed to enforce: %w", err) |
| 82 | } |
| 83 | |
| 84 | // Build context for AI |
| 85 | explainContext := e.buildExplainContext(rvals, result, matchedRules) |
| 86 | |
| 87 | // Call AI API |
| 88 | explanation, err := e.callAIAPI(explainContext) |
| 89 | if err != nil { |
| 90 | return "", fmt.Errorf("failed to get AI explanation: %w", err) |
| 91 | } |
| 92 | |
| 93 | return explanation, nil |
| 94 | } |
| 95 | |
| 96 | // buildExplainContext builds the context string for AI explanation. |
| 97 | func (e *Enforcer) buildExplainContext(rvals []interface{}, result bool, matchedRules []string) string { |