File size: 17,751 Bytes
d4e1ed9
 
9abd2f2
 
a03b5fc
e21cbb5
efa9970
 
 
d4e1ed9
 
 
 
ba203d2
d4e1ed9
efa9970
b9938e6
efa9970
 
 
 
2405040
e21cbb5
 
 
 
 
 
2405040
e21cbb5
2405040
e21cbb5
 
 
2405040
e21cbb5
 
 
 
 
 
2405040
 
 
e21cbb5
 
efa9970
148668c
efa9970
148668c
 
 
 
 
efa9970
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21cbb5
 
a03b5fc
e21cbb5
 
 
a03b5fc
2405040
e21cbb5
 
bca9833
2405040
 
 
e21cbb5
 
 
 
bca9833
e21cbb5
 
 
 
2405040
 
 
 
 
 
 
 
 
 
bca9833
2405040
bca9833
e21cbb5
 
 
 
bca9833
e21cbb5
 
 
 
bca9833
e21cbb5
 
 
 
bca9833
2405040
bca9833
 
 
 
e21cbb5
bca9833
2405040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21cbb5
2405040
 
 
 
 
e21cbb5
2405040
a03b5fc
e21cbb5
d4e1ed9
 
 
 
 
 
 
 
 
efa9970
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2405040
e21cbb5
 
a03b5fc
3908e5f
e21cbb5
 
 
 
 
 
 
2405040
 
 
e21cbb5
 
2405040
 
e21cbb5
2405040
 
e21cbb5
2405040
 
 
 
 
3908e5f
 
ff62d4f
e21cbb5
d4e1ed9
 
ff62d4f
d4e1ed9
ff62d4f
 
 
d4e1ed9
e21cbb5
cde7d1a
e21cbb5
9abd2f2
e21cbb5
5f0033b
a03b5fc
e21cbb5
a03b5fc
 
 
 
 
 
 
 
e21cbb5
 
a03b5fc
e21cbb5
 
 
a03b5fc
e21cbb5
 
a03b5fc
3908e5f
e21cbb5
 
a03b5fc
 
e21cbb5
 
 
a03b5fc
e21cbb5
a03b5fc
 
 
e21cbb5
 
 
 
 
 
a03b5fc
e21cbb5
 
a03b5fc
 
3908e5f
e21cbb5
cde7d1a
a03b5fc
e21cbb5
 
d4e1ed9
d881a0d
dc0fedf
 
d881a0d
 
dc0fedf
d881a0d
dc0fedf
 
 
 
d881a0d
 
 
dc0fedf
 
 
d881a0d
 
 
 
 
dc0fedf
 
 
d881a0d
 
 
dc0fedf
 
 
d881a0d
 
 
 
dc0fedf
 
e21cbb5
 
dc0fedf
 
e21cbb5
 
 
 
 
d881a0d
 
e21cbb5
 
 
 
 
dc0fedf
 
e21cbb5
d881a0d
e21cbb5
d881a0d
 
e21cbb5
 
dc0fedf
9abd2f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efa9970
 
 
 
 
 
 
 
 
 
 
 
dc0fedf
 
d4e1ed9
 
 
efa9970
 
d4e1ed9
dc0fedf
 
 
d881a0d
 
 
 
 
 
 
 
 
 
 
e56e479
d881a0d
 
 
 
 
 
 
 
 
 
 
 
e56e479
d881a0d
dc0fedf
d881a0d
 
 
dc0fedf
 
d4e1ed9
a10cd56
d18bd01
4a08cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30f47d5
 
 
a10cd56
 
e21cbb5
 
d4e1ed9
 
 
e21cbb5
d4e1ed9
 
 
 
 
 
2615e7f
efa9970
 
 
d4e1ed9
 
1ec4295
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import gradio as gr
from huggingface_hub import InferenceClient
import time
import html
import re
import traceback
import datetime
import threading
from collections import defaultdict

"""
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
"""
client = InferenceClient("PlantWisdom/Data_Management")

# Rate limiting settings
MAX_REQUESTS_PER_DAY = 100  # Maximum number of requests per IP per day (set to 1 for testing)
ip_request_counters = defaultdict(int)  # Tracks request count per IP
ip_last_reset = {}  # Tracks when counters were last reset for each IP
rate_limit_lock = threading.Lock()  # Lock for thread-safe counter access

# Expanded comprehensive patterns to filter out thinking and meta-commentary
THINKING_PATTERNS = [
    r"Okay, so I('m| am) (trying to|going to|attempting to)",
    r"I need to figure out",
    r"I'll start by",
    r"Let me try to",
    r"I'm trying to understand",
    r"First, I (know|think) that",
    r"I'll need to look into",
    r"I'm not entirely (sure|clear)",
    r"I believe this is",
    r"I imagine it involves",
    r"I think I understand",
    r"From what I (know|remember)",
    r"Let me think about",
    r"From my understanding",
    r"As I understand it",
    r"To answer this question",
    r"To address this",
    r"I'll approach this by",
    r"I think it's (important|worth) (to note|noting)",
    r"I (think|believe|wonder|should|also wonder|recall)",
    r"I also (think|believe|wonder|should|recall)",
]

def get_client_ip():
    """Get the client's IP address from the request context"""
    try:
        # Try to get IP from Gradio's request context
        import contextvars
        request_context = contextvars.ContextVar("request").get()
        if hasattr(request_context, "client") and request_context.client:
            return request_context.client.host
    except:
        pass
    
    # Fallback if we can't get a real IP
    return "127.0.0.1"

def check_rate_limit():
    """Check if the current IP has exceeded its daily limit"""
    current_ip = get_client_ip()
    current_date = datetime.datetime.now().date()
    
    with rate_limit_lock:
        # Reset counter if it's a new day
        if current_ip in ip_last_reset and ip_last_reset[current_ip] != current_date:
            ip_request_counters[current_ip] = 0
        
        # Update last reset date
        ip_last_reset[current_ip] = current_date
        
        # Check if limit is exceeded
        if ip_request_counters[current_ip] >= MAX_REQUESTS_PER_DAY:
            return False
        
        # Increment counter
        ip_request_counters[current_ip] += 1
        return True

def process_final_response(response_text):
    """Comprehensive processing of the final response to ensure quality"""
    
    # Early return if response is too short
    if len(response_text) < 50:
        return response_text
    
    # 1. Remove thinking patterns more aggressively
    for pattern in THINKING_PATTERNS:
        response_text = re.sub(pattern, "", response_text, flags=re.IGNORECASE)
    
    # Remove first person references completely
    response_text = re.sub(r"\b(I|me|my|mine|myself)\b", "", response_text, flags=re.IGNORECASE)
    
    # 2. Split into paragraphs
    paragraphs = [p.strip() for p in response_text.split('\n\n') if p.strip()]
    
    # 3. Filter meaningless paragraphs
    filtered_paragraphs = []
    for para in paragraphs:
        # Skip too short paragraphs or those that are just meta-commentary
        if len(para) < 20 or re.search(r"^(In summary|To summarize|In conclusion)", para, re.IGNORECASE):
            continue
        
        # Skip paragraphs with thinking patterns
        skip = False
        for pattern in THINKING_PATTERNS:
            if re.search(pattern, para, re.IGNORECASE):
                skip = True
                break
        
        if not skip:
            filtered_paragraphs.append(para)
    
    # 4. Remove duplicates and similar paragraphs with stricter threshold
    unique_paragraphs = []
    for current in filtered_paragraphs:
        # Clean for comparison
        clean_current = re.sub(r'[^\w\s]', '', current.lower())
        words_current = set(clean_current.split())
        
        is_duplicate = False
        for existing in unique_paragraphs:
            clean_existing = re.sub(r'[^\w\s]', '', existing.lower())
            words_existing = set(clean_existing.split())
            
            if len(words_current) > 3 and len(words_existing) > 3:  # Ignore very short paragraphs
                # Calculate word overlap as similarity measure
                overlap = len(words_current.intersection(words_existing))
                similarity = overlap / min(len(words_current), len(words_existing))
                
                if similarity > 0.5:  # 50% threshold for similarity (stricter)
                    is_duplicate = True
                    break
        
        if not is_duplicate:
            unique_paragraphs.append(current)
    
    # 5. Structure the response based on detected content
    title = ""
    if "retention policies" in response_text.lower() and "retention labels" in response_text.lower():
        title = "# Retention Policies vs. Retention Labels in Microsoft 365"
    elif "onedrive" in response_text.lower() and "sharepoint" in response_text.lower():
        title = "# Key Differences Between OneDrive for Business and SharePoint Online"
    else:
        # Extract a title from the content
        first_para = unique_paragraphs[0] if unique_paragraphs else ""
        first_sentence = first_para.split('.')[0] if first_para else ""
        if len(first_sentence) > 10:
            title = f"# {first_sentence}"
        else:
            title = "# Microsoft 365 Information Management"
    
    # Build structured content with max 2-3 paragraphs
    final_paras = []
    if unique_paragraphs:
        # Limit to just 2-3 most relevant paragraphs
        final_paras = unique_paragraphs[:min(3, len(unique_paragraphs))]
        
        # Add a "Use cases" section if we have 3+ paragraphs
        if len(unique_paragraphs) > 2:
            final_text = f"{title}\n\n{final_paras[0]}\n\n{final_paras[1]}\n\n## Key Considerations\n\n{final_paras[2]}"
        else:
            final_text = f"{title}\n\n" + "\n\n".join(final_paras)
    else:
        final_text = f"{title}\n\nNo content available."
    
    return final_text.strip()

def respond(
    message,
    history: list[tuple[str, str]],
    system_message,
    max_tokens,
    temperature,
    top_p,
):
    # Check rate limit before processing the request
    if not check_rate_limit():
        current_ip = get_client_ip()
        next_reset = (datetime.datetime.now() + datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0)
        hours_until_reset = int((next_reset - datetime.datetime.now()).total_seconds() / 3600)
        
        limit_message = f"""
<div class="rate-limit-warning">
    <h3>Daily Request Limit Reached</h3>
    <p>You've reached the maximum of {MAX_REQUESTS_PER_DAY} requests allowed per day.</p>
    <p>Your limit will reset in approximately {hours_until_reset} hours (at midnight your local time).</p>
    <p>Please try again tomorrow. Thank you for your understanding!</p>
</div>
"""
        yield limit_message
        return
    
    # Create a more effective system prompt with stronger instructions
    enhanced_system_message = f"""You are an expert in Microsoft 365 services including SharePoint, OneDrive, Teams, and the Microsoft 365 compliance ecosystem.

{system_message}

FORMAT YOUR RESPONSE USING:
- Clear, direct language
- Markdown formatting with headings and bullet points
- Concise, factual information
- Specific technical details where appropriate

CRITICAL RESPONSE REQUIREMENTS:
1. Start IMMEDIATELY with the answer - NO preamble or self-reference
2. NEVER use first person (I, me, my) under any circumstances
3. NEVER reveal your thought process - just state facts
4. Be AUTHORITATIVE and PRECISE
5. Present EACH KEY POINT EXACTLY ONCE
6. Focus on GOVERNANCE & TECHNICAL details
7. Keep total response under 1500 characters
8. Use 2-3 paragraphs maximum
9. Provide concrete recommendations
10. Write as if from an official Microsoft technical document

If comparing two services or features:
- Begin with clear definitions of both
- Focus on FUNCTIONAL differences
- List KEY SCENARIOS for each
- End with GOVERNANCE implications"""

    messages = [{"role": "system", "content": enhanced_system_message}]

    # Add history and current message
    for val in history:
        if val[0]:
            messages.append({"role": "user", "content": val[0]})
        if val[1]:
            messages.append({"role": "assistant", "content": val[1]})

    messages.append({"role": "user", "content": message})

    # Initialize state variables
    full_response = ""
    thinking_steps = []
    start_time = time.time()
    generation_complete = False
    
    try:
        # Generate response
        for message in client.chat_completion(
            messages,
            max_tokens=max_tokens,
            stream=True,
            temperature=temperature,
            top_p=top_p,
        ):
            token = message.choices[0].delta.content
            
            # Skip empty tokens
            if not token:
                # Check for completion
                if message.choices[0].finish_reason == "stop":
                    generation_complete = True
                continue
            
            # Append token to response
            full_response += token
            
            # Store thinking step snapshot every 250 chars
            if len(full_response) % 250 == 0:
                thinking_steps.append(full_response)
                
            # Format and display response
            thinking_html = ""
            if thinking_steps:
                thinking_html = '<div class="thinking-wrapper"><details><summary>Show thinking process</summary><div class="thinking-steps">'
                for i, step in enumerate(thinking_steps):
                    safe_step = html.escape(step)
                    thinking_html += f'<div class="thinking-step">Step {i+1}: {safe_step}</div>'
                thinking_html += '</div></details></div>'
            
            # Yield the response
            yield f"{thinking_html}{full_response}"
        
        # Check if we need to post-process the response
        processed_response = process_final_response(full_response)
        
        # If the processing made significant changes, show both versions
        if len(processed_response) < len(full_response) * 0.8 or len(processed_response) > 100:
            thinking_html = '<div class="thinking-wrapper"><details><summary>Show original response</summary><div class="thinking-steps">'
            thinking_html += f'<div class="thinking-step">{html.escape(full_response)}</div>'
            thinking_html += '</div></details></div>'
            yield f"{thinking_html}{processed_response}"
            
    except Exception as e:
        error_msg = f"I apologize, but I encountered an error while generating a response. Error details: {str(e)}"
        yield error_msg

# Custom CSS for Plant Wisdom.AI styling
custom_css = """
.gradio-container {
    font-family: 'Source Sans Pro', 'Helvetica Neue', Arial, sans-serif;
    max-width: 1000px;
    margin: 0 auto;
    background-color: #ffffff;
}

.contain {
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 6px rgba(0,0,0,0.05);
    padding: 20px;
}

.message {
    padding: 16px 20px;
    border-radius: 12px;
    margin: 12px 0;
    font-size: 16px;
    line-height: 1.5;
}

.message.user {
    background-color: #f5f7fa;
    margin-left: 15%;
    border: 1px solid #e8eef7;
}

.message.assistant {
    background-color: #f0f7f0;
    margin-right: 15%;
    border: 1px solid #e0ede0;
    color: #2c3338;
}

.message.assistant p {
    margin-bottom: 12px;
}

.message.assistant h1 {
    font-size: 1.4em;
    margin-top: 0;
    margin-bottom: 16px;
    color: #2e7d32;
}

.message.assistant h2 {
    font-size: 1.2em;
    margin-top: 16px;
    margin-bottom: 12px;
    color: #2e7d32;
}

.message.assistant ul, .message.assistant ol {
    margin: 12px 0;
    padding-left: 24px;
}

.message.assistant li {
    margin-bottom: 6px;
}

.thinking-wrapper {
    margin-bottom: 12px;
}

details {
    background-color: #f8faf8;
    border: 1px solid #e0ede0;
    border-radius: 8px;
    padding: 8px;
    margin-bottom: 16px;
}

summary {
    cursor: pointer;
    color: #2e7d32;
    font-weight: 500;
    padding: 4px 8px;
}

summary:hover {
    background-color: rgba(46,125,50,0.1);
    border-radius: 4px;
}

.thinking-steps {
    margin-top: 8px;
    padding: 8px;
    border-top: 1px solid #e0ede0;
    max-height: 200px;
    overflow-y: auto;
}

.thinking-step {
    padding: 4px 8px;
    font-size: 14px;
    color: #666;
    border-bottom: 1px dashed #eee;
}

.thinking-step:last-child {
    border-bottom: none;
}

/* Rate limit warning styling */
.rate-limit-warning {
    background-color: #fff3cd;
    color: #856404;
    border: 1px solid #ffeeba;
    border-radius: 8px;
    padding: 16px;
    margin: 16px 0;
    text-align: center;
    font-weight: 500;
}
"""

"""
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
"""
# Main chat interface
chat_interface = gr.ChatInterface(
    respond,
    title="AI Data Management Expert",
    description="Hello! I am your Data Management Expert, specialized in Microsoft 365. I'm here to help you with guidance on Data Management procedures. How can I assist you today?",
    theme=gr.themes.Base(
        primary_hue=gr.themes.Color(
            c50="#f3f7f3",
            c100="#e0ede0",
            c200="#b5d4b5",
            c300="#8abb8a",
            c400="#5fa25f",
            c500="#2e7d32",
            c600="#1b5e20",
            c700="#154a19",
            c800="#0e3511",
            c900="#082108",
            c950="#041104"
        ),
        secondary_hue=gr.themes.Color(
            c50="#f3f7f3",
            c100="#e0ede0",
            c200="#b5d4b5",
            c300="#8abb8a",
            c400="#5fa25f",
            c500="#2e7d32",
            c600="#1b5e20",
            c700="#154a19",
            c800="#0e3511",
            c900="#082108",
            c950="#041104"
        ),
        neutral_hue="slate",
        spacing_size="lg",
        radius_size="lg",
        font=["Source Sans Pro", "Helvetica Neue", "Arial", "sans-serif"],
    ),
    css=custom_css,
    additional_inputs=[
        gr.Textbox(
            value="""You are a specialized AI assistant made by Plant Wisdom.AI with deep knowledge of Microsoft 365 services—including SharePoint Online, OneDrive, Teams, Exchange, and the Microsoft Purview (Compliance) ecosystem—as well as general records management and data governance best practices.

Your primary objectives are:

Provide accurate, detailed, and practical answers about:

Microsoft 365's features, capabilities, and architecture.

Document and records management (e.g., retention labels, policies, disposition reviews).

Compliance and information governance (e.g., data loss prevention, eDiscovery, retention schedules).

SharePoint Online configuration, site management, and usage best practices.

Integration points across Microsoft 365 (Teams, Outlook, Power Platform, etc.).

Address user questions in a clear, direct manner without simply directing them to official documentation. Instead, share concise explanations and relevant examples.

When applicable, highlight best practices, common pitfalls, and recommended solutions based on real-world usage.

If you are not certain about an answer or lack enough context, say so clearly rather than guess.

Tone and Style:

Strive for clarity and helpfulness; avoid excessive jargon.

Avoid generic references like "refer to the documentation." Instead, explain or paraphrase relevant information whenever possible.

Cite Microsoft's recommended or well-known practices when beneficial, but do so in your own words.

Keep responses concise yet sufficiently detailed.

Additional Guidelines:

Where necessary, provide step-by-step instructions for configurations or troubleshooting.

Distinguish between official Microsoft 365 functionalities and custom solutions or third-party tools.

If the user's request includes advanced or niche scenarios, do your best to provide an overview, while acknowledging any areas that may require deeper research.

Maintain professionalism in all responses; be polite, solution-focused, and proactive.

Follow any privacy or ethical guidelines, and do not disclose personally identifiable information about real people.

IMPORTANT: If a question has been asked before in the conversation, acknowledge this and either refer back to the previous answer or provide additional context. Do not simply repeat the same answer verbatim.""",
            label="System message"
        ),
        gr.Slider(minimum=1, maximum=2048, value=1000, step=1, label="Max new tokens"),
        gr.Slider(minimum=0.1, maximum=2.0, value=0.35, step=0.05, label="Temperature"),
        gr.Slider(
            minimum=0.1,
            maximum=1.0,
            value=0.6,
            step=0.05,
            label="Top-p (nucleus sampling)",
        ),
    ],
)

# Create Gradio Blocks app with chat interface
with gr.Blocks(theme=gr.themes.Base()) as demo:
    # Main chat interface
    chat_interface.render()

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0")