Spaces:
Runtime error
Runtime error
Delete confluence_integration_example.py
Browse files
confluence_integration_example.py
DELETED
|
@@ -1,320 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Quick Start: Fraud Assistant with Confluence Integration
|
| 3 |
-
|
| 4 |
-
This example shows minimal changes needed to add Confluence document search
|
| 5 |
-
to your existing fraud explainability assistant.
|
| 6 |
-
|
| 7 |
-
Installation:
|
| 8 |
-
pip install -r requirements-with-confluence.txt
|
| 9 |
-
|
| 10 |
-
Setup:
|
| 11 |
-
1. Copy .env.example to .env
|
| 12 |
-
2. Edit .env with your Confluence credentials
|
| 13 |
-
3. See CONFLUENCE_SETUP_GUIDE.md for detailed instructions
|
| 14 |
-
|
| 15 |
-
Environment Variables (.env):
|
| 16 |
-
CONFLUENCE_URL=https://yourcompany.atlassian.net
|
| 17 |
-
CONFLUENCE_EMAIL=your-email@company.com
|
| 18 |
-
CONFLUENCE_API_TOKEN=your_api_token
|
| 19 |
-
EMBEDDING_PROVIDER=huggingface
|
| 20 |
-
"""
|
| 21 |
-
|
| 22 |
-
import os
|
| 23 |
-
import warnings
|
| 24 |
-
from typing import Optional
|
| 25 |
-
|
| 26 |
-
# Suppress ResourceWarning for cleaner output
|
| 27 |
-
warnings.filterwarnings("ignore", category=ResourceWarning)
|
| 28 |
-
os.environ["PYTHONWARNINGS"] = "ignore::ResourceWarning"
|
| 29 |
-
|
| 30 |
-
# Load environment variables from .env file
|
| 31 |
-
try:
|
| 32 |
-
from dotenv import load_dotenv
|
| 33 |
-
load_dotenv() # Load .env file if it exists
|
| 34 |
-
except ImportError:
|
| 35 |
-
print("⚠ Warning: python-dotenv not installed. Install with: pip install python-dotenv")
|
| 36 |
-
print(" Environment variables must be set manually.")
|
| 37 |
-
|
| 38 |
-
import gradio as gr
|
| 39 |
-
from strands import Agent
|
| 40 |
-
from strands.models.openai import OpenAIModel
|
| 41 |
-
|
| 42 |
-
# Import confluence-ingestor
|
| 43 |
-
from confluence_ingestor import ConfluenceRAG
|
| 44 |
-
from confluence_ingestor.adapters.strands import (
|
| 45 |
-
create_confluence_search_tool,
|
| 46 |
-
create_confluence_loader_tool,
|
| 47 |
-
)
|
| 48 |
-
|
| 49 |
-
# Import your existing fraud tools
|
| 50 |
-
from app import (
|
| 51 |
-
get_application_summary,
|
| 52 |
-
explain_fraud_score,
|
| 53 |
-
compare_to_population,
|
| 54 |
-
check_fair_lending_flags,
|
| 55 |
-
get_identity_network,
|
| 56 |
-
get_model_performance,
|
| 57 |
-
SYSTEM_PROMPT as ORIGINAL_PROMPT,
|
| 58 |
-
)
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
# =============================================================================
|
| 62 |
-
# STEP 1: Initialize Confluence RAG
|
| 63 |
-
# =============================================================================
|
| 64 |
-
|
| 65 |
-
_confluence_rag: Optional[ConfluenceRAG] = None
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
def init_confluence():
|
| 69 |
-
"""Initialize Confluence RAG (runs once at startup)."""
|
| 70 |
-
global _confluence_rag
|
| 71 |
-
|
| 72 |
-
if _confluence_rag is None:
|
| 73 |
-
print("🔧 Initializing Confluence integration...")
|
| 74 |
-
|
| 75 |
-
# Check if required environment variables are set
|
| 76 |
-
required_vars = ["CONFLUENCE_URL", "CONFLUENCE_EMAIL", "CONFLUENCE_API_TOKEN"]
|
| 77 |
-
missing_vars = [var for var in required_vars if not os.getenv(var)]
|
| 78 |
-
|
| 79 |
-
if missing_vars:
|
| 80 |
-
print(f"\n❌ ERROR: Missing required environment variables: {', '.join(missing_vars)}")
|
| 81 |
-
print("\n📝 Setup Instructions:")
|
| 82 |
-
print(" 1. Copy .env.example to .env:")
|
| 83 |
-
print(" cp .env.example .env")
|
| 84 |
-
print(" 2. Edit .env with your Confluence credentials")
|
| 85 |
-
print(" 3. See CONFLUENCE_SETUP_GUIDE.md for detailed setup instructions")
|
| 86 |
-
print("\n⚠ App will run WITHOUT Confluence integration.\n")
|
| 87 |
-
raise ValueError(f"Missing Confluence credentials: {', '.join(missing_vars)}")
|
| 88 |
-
|
| 89 |
-
# Create RAG pipeline with free local embeddings
|
| 90 |
-
_confluence_rag = ConfluenceRAG.from_env(
|
| 91 |
-
embedding_provider="huggingface", # Free, runs locally
|
| 92 |
-
vector_store_type="chroma",
|
| 93 |
-
)
|
| 94 |
-
|
| 95 |
-
# Ingest your Confluence spaces (runs once, then cached)
|
| 96 |
-
spaces = {
|
| 97 |
-
"fraud-model-governance": 100, # Model docs, validation reports
|
| 98 |
-
"compliance-policies": 50, # Fair lending, ECOA policies
|
| 99 |
-
"fraud-investigation-playbooks": 75, # Investigation procedures
|
| 100 |
-
}
|
| 101 |
-
|
| 102 |
-
for space_key, max_pages in spaces.items():
|
| 103 |
-
try:
|
| 104 |
-
stats = _confluence_rag.ingest_space(
|
| 105 |
-
space_key, max_pages=max_pages, force=False
|
| 106 |
-
)
|
| 107 |
-
|
| 108 |
-
if stats.get("skipped"):
|
| 109 |
-
print(f" ✓ {space_key}: {stats['reason']}")
|
| 110 |
-
else:
|
| 111 |
-
print(f" ✓ {space_key}: {stats['pages']} pages indexed")
|
| 112 |
-
|
| 113 |
-
except Exception as e:
|
| 114 |
-
print(f" ⚠ {space_key}: Failed - {e}")
|
| 115 |
-
|
| 116 |
-
print("✅ Confluence integration ready!")
|
| 117 |
-
|
| 118 |
-
return _confluence_rag
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
# =============================================================================
|
| 122 |
-
# STEP 2: Enhanced System Prompt
|
| 123 |
-
# =============================================================================
|
| 124 |
-
|
| 125 |
-
ENHANCED_PROMPT = """
|
| 126 |
-
You are a Fraud Model Explainability Assistant for a major financial services company.
|
| 127 |
-
Your role is to help fraud analysts, data scientists, and executives understand
|
| 128 |
-
fraud model decisions and their implications.
|
| 129 |
-
|
| 130 |
-
You have access to tools that can:
|
| 131 |
-
1. Retrieve application summaries and fraud scores
|
| 132 |
-
2. Explain why applications received specific fraud scores (SHAP-style explanations)
|
| 133 |
-
3. Compare applications to approved/denied populations statistically
|
| 134 |
-
4. Check for fair lending compliance concerns
|
| 135 |
-
5. Analyze identity networks and linkages
|
| 136 |
-
6. Show model performance metrics
|
| 137 |
-
7. **Search company Confluence documentation** for policies, procedures, and guidelines
|
| 138 |
-
|
| 139 |
-
When answering questions:
|
| 140 |
-
- Be precise and data-driven
|
| 141 |
-
- Highlight the most important risk factors first
|
| 142 |
-
- Explain technical concepts in business terms when speaking to executives
|
| 143 |
-
- **Use Confluence search to augment responses with company-specific policies**
|
| 144 |
-
- **Cite specific Confluence pages when referencing procedures**
|
| 145 |
-
- **For compliance questions, ALWAYS search for relevant policy documentation**
|
| 146 |
-
- **For model governance questions, reference actual validation reports when available**
|
| 147 |
-
- Always mention fair lending implications when relevant
|
| 148 |
-
- Provide actionable insights, not just data
|
| 149 |
-
|
| 150 |
-
For flagged applications, structure your response as:
|
| 151 |
-
1. Quick summary (score, decision, risk level)
|
| 152 |
-
2. Top contributing factors
|
| 153 |
-
3. How unusual this is compared to the population
|
| 154 |
-
4. Any compliance considerations (with policy references from Confluence)
|
| 155 |
-
5. Recommended next steps
|
| 156 |
-
|
| 157 |
-
Remember: Your explanations may be used in regulatory examinations and audits,
|
| 158 |
-
so be accurate and thorough. When citing company policies, always reference the
|
| 159 |
-
source Confluence page.
|
| 160 |
-
""".strip()
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
# =============================================================================
|
| 164 |
-
# STEP 3: Create Agent with Confluence
|
| 165 |
-
# =============================================================================
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
def create_enhanced_agent():
|
| 169 |
-
"""Create fraud agent with Confluence integration."""
|
| 170 |
-
openai_api_key = os.environ.get("OPENAI_API_KEY")
|
| 171 |
-
|
| 172 |
-
# Initialize Confluence
|
| 173 |
-
try:
|
| 174 |
-
rag = init_confluence()
|
| 175 |
-
|
| 176 |
-
# Create Confluence tools
|
| 177 |
-
search_confluence = create_confluence_search_tool(rag=rag, k=5)
|
| 178 |
-
load_confluence_page = create_confluence_loader_tool(max_pages=3)
|
| 179 |
-
|
| 180 |
-
# Add Confluence to existing tools
|
| 181 |
-
tools = [
|
| 182 |
-
get_application_summary,
|
| 183 |
-
explain_fraud_score,
|
| 184 |
-
compare_to_population,
|
| 185 |
-
check_fair_lending_flags,
|
| 186 |
-
get_identity_network,
|
| 187 |
-
get_model_performance,
|
| 188 |
-
search_confluence, # NEW: Confluence semantic search
|
| 189 |
-
load_confluence_page, # NEW: Confluence page loader
|
| 190 |
-
]
|
| 191 |
-
|
| 192 |
-
system_prompt = ENHANCED_PROMPT
|
| 193 |
-
|
| 194 |
-
except Exception as e:
|
| 195 |
-
print(f"⚠ Confluence disabled: {e}")
|
| 196 |
-
|
| 197 |
-
# Fall back to original tools if Confluence fails
|
| 198 |
-
tools = [
|
| 199 |
-
get_application_summary,
|
| 200 |
-
explain_fraud_score,
|
| 201 |
-
compare_to_population,
|
| 202 |
-
check_fair_lending_flags,
|
| 203 |
-
get_identity_network,
|
| 204 |
-
get_model_performance,
|
| 205 |
-
]
|
| 206 |
-
|
| 207 |
-
system_prompt = ORIGINAL_PROMPT
|
| 208 |
-
|
| 209 |
-
# Create agent
|
| 210 |
-
if openai_api_key:
|
| 211 |
-
model = OpenAIModel(
|
| 212 |
-
client_args={"api_key": openai_api_key},
|
| 213 |
-
model_id="gpt-4o",
|
| 214 |
-
params={"temperature": 0.1, "max_tokens": 2048},
|
| 215 |
-
)
|
| 216 |
-
return Agent(model=model, system_prompt=system_prompt, tools=tools)
|
| 217 |
-
else:
|
| 218 |
-
# Default to Bedrock
|
| 219 |
-
return Agent(system_prompt=system_prompt, tools=tools)
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
def query_enhanced(question: str) -> str:
|
| 223 |
-
"""Process question with Confluence-enhanced agent."""
|
| 224 |
-
try:
|
| 225 |
-
agent = create_enhanced_agent()
|
| 226 |
-
result = agent(question)
|
| 227 |
-
return str(result)
|
| 228 |
-
except Exception as e:
|
| 229 |
-
return f"Error: {str(e)}"
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
# =============================================================================
|
| 233 |
-
# STEP 4: Gradio Interface (Same as Original)
|
| 234 |
-
# =============================================================================
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
def process_question(question: str) -> str:
|
| 238 |
-
"""Wrapper for Gradio."""
|
| 239 |
-
return query_enhanced(question)
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
# Create interface
|
| 243 |
-
with gr.Blocks(title="Fraud Model Explainability Assistant") as iface:
|
| 244 |
-
gr.Markdown(
|
| 245 |
-
"""
|
| 246 |
-
# 🔍 Fraud Model Explainability Assistant
|
| 247 |
-
|
| 248 |
-
Enhanced with **Confluence Knowledge Base** integration.
|
| 249 |
-
|
| 250 |
-
**New Capabilities:**
|
| 251 |
-
- Search company Confluence documentation
|
| 252 |
-
- Retrieve policies, procedures, and guidelines
|
| 253 |
-
- Cite specific Confluence pages in responses
|
| 254 |
-
|
| 255 |
-
**Example Questions:**
|
| 256 |
-
- "What does our fair lending policy say about synthetic ID detection?"
|
| 257 |
-
- "Find the model validation report for XGBoost v3.2"
|
| 258 |
-
- "What are the procedures for escalating high-risk applications?"
|
| 259 |
-
"""
|
| 260 |
-
)
|
| 261 |
-
|
| 262 |
-
with gr.Row():
|
| 263 |
-
with gr.Column(scale=2):
|
| 264 |
-
question_input = gr.Textbox(
|
| 265 |
-
label="Ask a Question",
|
| 266 |
-
placeholder="e.g., What does our fair lending policy say about phone type features?",
|
| 267 |
-
lines=3,
|
| 268 |
-
)
|
| 269 |
-
submit_btn = gr.Button("🔍 Analyze", variant="primary")
|
| 270 |
-
|
| 271 |
-
with gr.Row():
|
| 272 |
-
output = gr.Textbox(label="Analysis Results", lines=25)
|
| 273 |
-
|
| 274 |
-
gr.Markdown("### 💡 Example Questions")
|
| 275 |
-
|
| 276 |
-
examples = gr.Examples(
|
| 277 |
-
examples=[
|
| 278 |
-
["Why was application APP-78432 flagged as high risk?"],
|
| 279 |
-
["Explain the fraud score for APP-12345 and compare it to approved applications"],
|
| 280 |
-
["Check fair lending compliance for APP-55555 and cite relevant policies"],
|
| 281 |
-
["Show me the identity network analysis for APP-78432"],
|
| 282 |
-
["What's the current model performance for the Retail Card portfolio?"],
|
| 283 |
-
["What does our fair lending policy say about synthetic ID detection?"],
|
| 284 |
-
["Find the model validation report for XGBoost v3.2"],
|
| 285 |
-
["What are the procedures for escalating high-risk applications?"],
|
| 286 |
-
["I need to present APP-99999 to the CCO. Give me a complete risk summary with compliance review and policy references."],
|
| 287 |
-
],
|
| 288 |
-
inputs=question_input,
|
| 289 |
-
)
|
| 290 |
-
|
| 291 |
-
submit_btn.click(fn=process_question, inputs=question_input, outputs=output)
|
| 292 |
-
question_input.submit(fn=process_question, inputs=question_input, outputs=output)
|
| 293 |
-
|
| 294 |
-
gr.Markdown(
|
| 295 |
-
"""
|
| 296 |
-
---
|
| 297 |
-
*Powered by Strands Agents + Confluence Integration*
|
| 298 |
-
|
| 299 |
-
**Setup Instructions:**
|
| 300 |
-
1. Install: `pip install confluence-ingestor[strands,huggingface,chroma]`
|
| 301 |
-
2. Configure .env with Confluence credentials
|
| 302 |
-
3. Run: `python confluence_integration_example.py`
|
| 303 |
-
"""
|
| 304 |
-
)
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
# =============================================================================
|
| 308 |
-
# MAIN
|
| 309 |
-
# =============================================================================
|
| 310 |
-
|
| 311 |
-
if __name__ == "__main__":
|
| 312 |
-
# Pre-initialize Confluence (optional, speeds up first query)
|
| 313 |
-
try:
|
| 314 |
-
init_confluence()
|
| 315 |
-
except Exception as e:
|
| 316 |
-
print(f"Warning: Confluence initialization failed: {e}")
|
| 317 |
-
print("App will run without Confluence integration.")
|
| 318 |
-
|
| 319 |
-
# Launch Gradio UI
|
| 320 |
-
iface.launch(ssr_mode=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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