chrisjcc commited on
Commit
3fdc736
·
1 Parent(s): 1334d7e

Delete confluence_integration_example_2.py

Browse files
Files changed (1) hide show
  1. confluence_integration_example_2.py +0 -414
confluence_integration_example_2.py DELETED
@@ -1,414 +0,0 @@
1
- """
2
- Phase 2: Enhanced Confluence Integration with Space Filtering and Caching
3
-
4
- This example builds on confluence_integration_example.py with:
5
- - Specialized search tools for different Confluence spaces
6
- - Smart tool selection based on query type
7
- - Caching for improved performance
8
-
9
- Prerequisites:
10
- - Complete Phase 1 (confluence_integration_example.py)
11
- - Install: pip install -r requirements-with-confluence.txt
12
- - Configure .env with Confluence credentials
13
- """
14
-
15
- import os
16
- import warnings
17
- from functools import lru_cache
18
- from typing import Optional
19
-
20
- # Suppress ResourceWarning for cleaner output
21
- warnings.filterwarnings("ignore", category=ResourceWarning)
22
- os.environ["PYTHONWARNINGS"] = "ignore::ResourceWarning"
23
-
24
- # Load environment variables from .env file
25
- try:
26
- from dotenv import load_dotenv
27
- load_dotenv()
28
- except ImportError:
29
- print("⚠ Warning: python-dotenv not installed. Install with: pip install python-dotenv")
30
- print(" Environment variables must be set manually.")
31
-
32
- import gradio as gr
33
- from strands import Agent
34
- from strands.models.openai import OpenAIModel
35
-
36
- # Import confluence-ingestor
37
- from confluence_ingestor import ConfluenceRAG
38
- from confluence_ingestor.adapters.strands import (
39
- create_confluence_search_tool,
40
- create_confluence_loader_tool,
41
- )
42
-
43
- # Import your existing fraud tools
44
- from app import (
45
- get_application_summary,
46
- explain_fraud_score,
47
- compare_to_population,
48
- check_fair_lending_flags,
49
- get_identity_network,
50
- get_model_performance,
51
- SYSTEM_PROMPT as ORIGINAL_PROMPT,
52
- )
53
-
54
-
55
- # =============================================================================
56
- # STEP 1: Initialize Confluence RAG (Same as Phase 1)
57
- # =============================================================================
58
-
59
- _confluence_rag: Optional[ConfluenceRAG] = None
60
-
61
-
62
- def init_confluence():
63
- """Initialize Confluence RAG (runs once at startup)."""
64
- global _confluence_rag
65
-
66
- if _confluence_rag is None:
67
- print("🔧 Initializing Confluence integration...")
68
-
69
- # Check if required environment variables are set
70
- required_vars = ["CONFLUENCE_URL", "CONFLUENCE_EMAIL", "CONFLUENCE_API_TOKEN"]
71
- missing_vars = [var for var in required_vars if not os.getenv(var)]
72
-
73
- if missing_vars:
74
- print(f"\n❌ ERROR: Missing required environment variables: {', '.join(missing_vars)}")
75
- print("\n📝 Setup Instructions:")
76
- print(" 1. Copy .env.example to .env:")
77
- print(" cp .env.example .env")
78
- print(" 2. Edit .env with your Confluence credentials")
79
- print(" 3. See CONFLUENCE_SETUP_GUIDE.md for detailed setup instructions")
80
- print("\n⚠ App will run WITHOUT Confluence integration.\n")
81
- raise ValueError(f"Missing Confluence credentials: {', '.join(missing_vars)}")
82
-
83
- # Create RAG pipeline with free local embeddings
84
- _confluence_rag = ConfluenceRAG.from_env(
85
- embedding_provider="huggingface", # Free, runs locally
86
- vector_store_type="chroma",
87
- )
88
-
89
- # Ingest your Confluence spaces (runs once, then cached)
90
- spaces = {
91
- "fraud-model-governance": 100, # Model docs, validation reports
92
- "compliance-policies": 50, # Fair lending, ECOA policies
93
- "fraud-investigation-playbooks": 75, # Investigation procedures
94
- }
95
-
96
- for space_key, max_pages in spaces.items():
97
- try:
98
- stats = _confluence_rag.ingest_space(
99
- space_key, max_pages=max_pages, force=False
100
- )
101
-
102
- if stats.get("skipped"):
103
- print(f" ✓ {space_key}: {stats['reason']}")
104
- else:
105
- print(f" ✓ {space_key}: {stats['pages']} pages indexed")
106
-
107
- except Exception as e:
108
- print(f" ⚠ {space_key}: Failed - {e}")
109
-
110
- print("✅ Confluence integration ready!")
111
-
112
- return _confluence_rag
113
-
114
-
115
- # =============================================================================
116
- # PHASE 2 ENHANCEMENT 1: Space-Filtered Search Tools
117
- # =============================================================================
118
-
119
- def create_specialized_search_tools(rag: ConfluenceRAG) -> dict:
120
- """Create specialized search tools for different Confluence spaces.
121
-
122
- This allows the agent to search specific spaces for targeted results,
123
- improving relevance and response time.
124
-
125
- Returns:
126
- Dictionary of specialized search tools
127
- """
128
- return {
129
- "search_compliance": create_confluence_search_tool(
130
- rag=rag,
131
- k=3, # Fewer results for focused searches
132
- space_filter="compliance-policies"
133
- ),
134
- "search_model_governance": create_confluence_search_tool(
135
- rag=rag,
136
- k=3,
137
- space_filter="fraud-model-governance"
138
- ),
139
- "search_investigation": create_confluence_search_tool(
140
- rag=rag,
141
- k=3,
142
- space_filter="fraud-investigation-playbooks"
143
- ),
144
- "search_all": create_confluence_search_tool(
145
- rag=rag,
146
- k=5, # More results for general searches
147
- space_filter=None
148
- ),
149
- }
150
-
151
-
152
- # =============================================================================
153
- # PHASE 2 ENHANCEMENT 2: Caching Layer
154
- # =============================================================================
155
-
156
- @lru_cache(maxsize=100)
157
- def cached_confluence_search(query: str, space_filter: Optional[str] = None) -> str:
158
- """Cached Confluence search for frequently asked questions.
159
-
160
- Args:
161
- query: Search query
162
- space_filter: Optional space key filter
163
-
164
- Returns:
165
- Formatted search results
166
- """
167
- rag = init_confluence()
168
- results = rag.search(query, k=5, space_filter=space_filter)
169
-
170
- if not results:
171
- return "No relevant documents found in Confluence."
172
-
173
- # Format results
174
- output = [f"Found {len(results)} relevant documents from Confluence:\n"]
175
-
176
- for i, result in enumerate(results, 1):
177
- output.append(f"\n{i}. {result.title}")
178
- output.append(f" Space: {result.space_key}")
179
- output.append(f" Relevance Score: {result.score:.4f}")
180
- output.append(f" Source: {result.source}")
181
-
182
- # Truncate content for readability
183
- content = (
184
- result.content[:300] + "..."
185
- if len(result.content) > 300
186
- else result.content
187
- )
188
- output.append(f" Content: {content}")
189
-
190
- return "\n".join(output)
191
-
192
-
193
- # =============================================================================
194
- # STEP 2: Enhanced System Prompt with Smart Tool Selection
195
- # =============================================================================
196
-
197
- ENHANCED_PROMPT_PHASE2 = """
198
- You are a Fraud Model Explainability Assistant for a major financial services company.
199
- Your role is to help fraud analysts, data scientists, and executives understand
200
- fraud model decisions and their implications.
201
-
202
- You have access to tools that can:
203
- 1. Retrieve application summaries and fraud scores
204
- 2. Explain why applications received specific fraud scores (SHAP-style explanations)
205
- 3. Compare applications to approved/denied populations statistically
206
- 4. Check for fair lending compliance concerns
207
- 5. Analyze identity networks and linkages
208
- 6. Show model performance metrics
209
- 7. **Search company Confluence documentation** with specialized tools:
210
- - search_compliance: Search compliance policies and fair lending documentation
211
- - search_model_governance: Search model validation reports and SR 11-7 docs
212
- - search_investigation: Search fraud investigation playbooks and procedures
213
- - search_all: Search all Confluence spaces
214
-
215
- SMART TOOL SELECTION GUIDELINES:
216
- - For fair lending questions → Use search_compliance FIRST
217
- - For model documentation questions → Use search_model_governance FIRST
218
- - For investigation procedures → Use search_investigation FIRST
219
- - For general or multi-topic questions → Use search_all
220
-
221
- When answering questions:
222
- - Be precise and data-driven
223
- - Highlight the most important risk factors first
224
- - Explain technical concepts in business terms when speaking to executives
225
- - **Use the most specific Confluence search tool for the question type**
226
- - **Cite specific Confluence pages when referencing procedures**
227
- - **For compliance questions, ALWAYS search for relevant policy documentation**
228
- - **For model governance questions, reference actual validation reports when available**
229
- - Always mention fair lending implications when relevant
230
- - Provide actionable insights, not just data
231
-
232
- For flagged applications, structure your response as:
233
- 1. Quick summary (score, decision, risk level)
234
- 2. Top contributing factors
235
- 3. How unusual this is compared to the population
236
- 4. Any compliance considerations (with policy references from Confluence)
237
- 5. Recommended next steps
238
-
239
- Remember: Your explanations may be used in regulatory examinations and audits,
240
- so be accurate and thorough. When citing company policies, always reference the
241
- source Confluence page.
242
- """.strip()
243
-
244
-
245
- # =============================================================================
246
- # STEP 3: Create Agent with Phase 2 Enhancements
247
- # =============================================================================
248
-
249
- def create_enhanced_agent_phase2():
250
- """Create fraud agent with Phase 2 Confluence enhancements.
251
-
252
- Phase 2 features:
253
- - Specialized search tools for different Confluence spaces
254
- - Caching for improved performance
255
- - Smart tool selection guidance in system prompt
256
- """
257
- openai_api_key = os.environ.get("OPENAI_API_KEY")
258
-
259
- # Initialize Confluence
260
- try:
261
- rag = init_confluence()
262
-
263
- # Create specialized search tools
264
- specialized_tools = create_specialized_search_tools(rag)
265
-
266
- # Create loader tool
267
- load_confluence_page = create_confluence_loader_tool(max_pages=3)
268
-
269
- # Add all tools (fraud + specialized Confluence)
270
- tools = [
271
- get_application_summary,
272
- explain_fraud_score,
273
- compare_to_population,
274
- check_fair_lending_flags,
275
- get_identity_network,
276
- get_model_performance,
277
- specialized_tools["search_compliance"], # NEW: Compliance-specific search
278
- specialized_tools["search_model_governance"], # NEW: Model governance search
279
- specialized_tools["search_investigation"], # NEW: Investigation playbook search
280
- specialized_tools["search_all"], # NEW: General Confluence search
281
- load_confluence_page, # Confluence page loader
282
- ]
283
-
284
- system_prompt = ENHANCED_PROMPT_PHASE2
285
-
286
- except Exception as e:
287
- print(f"⚠ Confluence disabled: {e}")
288
-
289
- # Fall back to original tools if Confluence fails
290
- tools = [
291
- get_application_summary,
292
- explain_fraud_score,
293
- compare_to_population,
294
- check_fair_lending_flags,
295
- get_identity_network,
296
- get_model_performance,
297
- ]
298
-
299
- system_prompt = ORIGINAL_PROMPT
300
-
301
- # Create agent
302
- if openai_api_key:
303
- model = OpenAIModel(
304
- client_args={"api_key": openai_api_key},
305
- model_id="gpt-4o",
306
- params={"temperature": 0.1, "max_tokens": 2048},
307
- )
308
- return Agent(model=model, system_prompt=system_prompt, tools=tools)
309
- else:
310
- # Default to Bedrock
311
- return Agent(system_prompt=system_prompt, tools=tools)
312
-
313
-
314
- def query_enhanced(question: str) -> str:
315
- """Process question with Phase 2 enhanced agent."""
316
- try:
317
- agent = create_enhanced_agent_phase2()
318
- result = agent(question)
319
- return str(result)
320
- except Exception as e:
321
- return f"Error: {str(e)}"
322
-
323
-
324
- # =============================================================================
325
- # STEP 4: Gradio Interface
326
- # =============================================================================
327
-
328
- def process_question(question: str) -> str:
329
- """Wrapper for Gradio."""
330
- return query_enhanced(question)
331
-
332
-
333
- # Create interface
334
- with gr.Blocks(title="Fraud Model Explainability Assistant - Phase 2") as iface:
335
- gr.Markdown(
336
- """
337
- # 🔍 Fraud Model Explainability Assistant (Phase 2)
338
-
339
- Enhanced with **specialized Confluence search tools** and **performance caching**.
340
-
341
- **Phase 2 Enhancements:**
342
- - **Space-filtered search**: Targeted searches in compliance, model governance, and investigation spaces
343
- - **Smart tool selection**: Agent automatically chooses the best search tool for each question
344
- - **Performance caching**: Frequently asked questions return instantly
345
-
346
- **Example Questions:**
347
- - "What does our fair lending policy say about synthetic ID detection?" (→ search_compliance)
348
- - "Find the model validation report for XGBoost v3.2" (→ search_model_governance)
349
- - "What are the procedures for escalating high-risk applications?" (→ search_investigation)
350
- """
351
- )
352
-
353
- with gr.Row():
354
- with gr.Column(scale=2):
355
- question_input = gr.Textbox(
356
- label="Ask a Question",
357
- placeholder="e.g., What does our fair lending policy say about phone type features?",
358
- lines=3,
359
- )
360
- submit_btn = gr.Button("🔍 Analyze", variant="primary")
361
-
362
- with gr.Row():
363
- output = gr.Textbox(label="Analysis Results", lines=25)
364
-
365
- gr.Markdown("### 💡 Example Questions")
366
-
367
- examples = gr.Examples(
368
- examples=[
369
- ["Why was application APP-78432 flagged as high risk?"],
370
- ["Explain the fraud score for APP-12345 and compare it to approved applications"],
371
- ["Check fair lending compliance for APP-55555 and cite relevant policies"],
372
- ["Show me the identity network analysis for APP-78432"],
373
- ["What's the current model performance for the Retail Card portfolio?"],
374
- ["What does our fair lending policy say about synthetic ID detection?"],
375
- ["Find the model validation report for XGBoost v3.2"],
376
- ["What are the procedures for escalating high-risk applications?"],
377
- ["I need to present APP-99999 to the CCO. Give me a complete risk summary with compliance review and policy references."],
378
- ],
379
- inputs=question_input,
380
- )
381
-
382
- submit_btn.click(fn=process_question, inputs=question_input, outputs=output)
383
- question_input.submit(fn=process_question, inputs=question_input, outputs=output)
384
-
385
- gr.Markdown(
386
- """
387
- ---
388
- *Powered by Strands Agents + Confluence Integration (Phase 2)*
389
-
390
- **Phase 2 Features:**
391
- - ✅ Specialized search tools for compliance, model governance, and investigations
392
- - ✅ LRU caching for frequently asked questions
393
- - ✅ Smart tool selection guidance
394
-
395
- **Next Steps:**
396
- - See `confluence_integration_phase3.py` for monitoring, logging, and scheduled updates
397
- """
398
- )
399
-
400
-
401
- # =============================================================================
402
- # MAIN
403
- # =============================================================================
404
-
405
- if __name__ == "__main__":
406
- # Pre-initialize Confluence (optional, speeds up first query)
407
- try:
408
- init_confluence()
409
- except Exception as e:
410
- print(f"Warning: Confluence initialization failed: {e}")
411
- print("App will run without Confluence integration.")
412
-
413
- # Launch Gradio UI
414
- iface.launch(ssr_mode=False)