logger.error(f"Error applying rules to match: {str(e)}")
# Fail safe: flag for review if rule processing fails
ifmatch.tax_analysisisNone:
match.tax_analysis={}
match.tax_analysis["flag_for_review"]=True
match.tax_analysis["auto_approve"]=False
match.tax_analysis["rule_reasons"]=[
f"Rule evaluation error: {str(e)}"
]
returnmatches
def_evaluate_rules_for_match(
self,match:Match,rules:List[Dict]
)->Dict[str,any]:
"""
Use LLM to evaluate all rules for a single match.
Returns:
{
"flag_for_review": bool,
"auto_approve": bool,
"rules_applied": List[str],
"reasons": List[str]
}
"""
# Build context about the match
match_context=self._build_match_context(match)
# Build rules context
rules_context=self._build_rules_context(rules)
# Create prompt for LLM
prompt=f"""You are a financial matching rules engine. Analyze the following receipt-to-transaction match and apply the specified rules.
MATCH DETAILS:
{match_context}
RULES TO APPLY:
{rules_context}
INSTRUCTIONS:
1. Evaluate each rule's condition against the match details
2. If a rule's condition is TRUE, apply the action:
- If action is "flag_for_review" or "review" → set flag_for_review = true
- If action is "auto_approve" or "approve" → set auto_approve = true
- For other actions, determine if they imply review or approval
3. If BOTH flag_for_review and auto_approve are triggered, flag_for_review takes priority
4. If NO rules match, set both to false (default behavior)
IMPORTANT BUILT-IN RULE:
- If receipt currency differs from transaction currency → ALWAYS set flag_for_review = true
Return ONLY a valid JSON object with this exact format:
{{
"flag_for_review": boolean,
"auto_approve": boolean,
"rules_applied": ["list of rule conditions that matched"],
"reasons": ["list of reasons for the decisions"]
}}
"""
try:
# Call LLM
response=self.client.chat.completions.create(
model=self.model,
messages=[
{
"role":"system",
"content":"You are a financial rules evaluation assistant. You analyze transaction matches and apply business rules. Always respond with valid JSON only.",