File size: 33,341 Bytes
95422b8
8a7f07f
7522fcc
95422b8
8a7f07f
95422b8
 
 
 
 
 
 
 
 
 
 
 
c915e07
 
 
36fcb1c
 
b233ee2
57bb7fa
de2bf69
7ca0d65
 
 
 
de2bf69
5052b34
95422b8
8a7f07f
95422b8
 
ecb75f4
c915e07
 
95422b8
8a7f07f
 
95422b8
 
 
 
 
7522fcc
fef6f3e
c915e07
 
 
 
 
 
 
 
 
b554423
 
2e0f6d4
 
 
 
 
 
 
 
 
 
c915e07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35d9025
 
 
 
 
 
 
 
 
 
 
53f5338
35d9025
 
6f8f77a
bc66a28
35d9025
 
 
 
 
 
 
 
 
 
bc66a28
35d9025
dbb8125
 
2e0f6d4
8fccf21
 
2e0f6d4
7ca0d65
 
 
 
 
 
 
 
 
 
8fccf21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e0f6d4
dbb8125
7ca0d65
2e0f6d4
 
7ca0d65
 
 
 
 
 
 
6613278
b220464
 
 
 
053c8b7
b220464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e0f6d4
b220464
347d713
a95565e
b220464
 
 
53f5338
b220464
53f5338
b220464
 
 
53f5338
b220464
7ca0d65
b220464
 
 
a95565e
 
 
53f5338
b220464
8a7f07f
 
 
 
 
7ca0d65
cd6d88e
 
8a7f07f
 
cd6d88e
 
0188f7c
f5b0da4
 
95422b8
 
cd6d88e
5052b34
0188f7c
8a7f07f
cd6d88e
 
8a7f07f
 
 
e964295
0188f7c
8a7f07f
95422b8
5052b34
cd6d88e
 
8a7f07f
5052b34
8a7f07f
7ca0d65
f5b0da4
2e0f6d4
0188f7c
f5b0da4
8a7f07f
7ca0d65
8a7f07f
 
7ca0d65
 
95422b8
7ca0d65
8a7f07f
7ca0d65
 
 
 
 
8a7f07f
 
 
0188f7c
95422b8
 
 
 
 
 
 
 
 
 
 
 
 
 
7ca0d65
 
 
 
2e0f6d4
7ca0d65
 
 
2e0f6d4
7ca0d65
 
 
 
2e0f6d4
7ca0d65
 
 
2e0f6d4
7ca0d65
 
 
2e0f6d4
7ca0d65
2e0f6d4
 
7ca0d65
 
 
 
 
 
2e0f6d4
7ca0d65
 
 
 
 
 
 
 
 
2e0f6d4
 
7ca0d65
 
 
2e0f6d4
7ca0d65
2e0f6d4
7ca0d65
2e0f6d4
7ca0d65
 
2e0f6d4
7ca0d65
 
 
 
 
 
 
2e0f6d4
7ca0d65
 
 
 
 
 
 
 
b1c7d76
4ad9d00
95422b8
 
 
 
 
 
 
 
 
7ca0d65
95422b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0188f7c
7522fcc
 
fef6f3e
95422b8
 
 
 
0188f7c
95422b8
b554423
c1ecd7d
b554423
 
3f89215
 
 
 
 
 
 
c915e07
3f89215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4256e65
3f89215
 
 
 
 
 
 
 
 
 
 
79bdd61
89cd4f0
3f89215
 
 
 
 
 
 
 
 
 
 
c915e07
3f89215
 
 
89cd4f0
3f89215
 
 
ecbb8f8
3f89215
 
 
ecbb8f8
c915e07
3f89215
 
053c8b7
3f89215
 
d7b3c8f
3f89215
 
6fcf6f6
a981823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c915e07
8783629
d06694f
610c2e7
ecb75f4
95422b8
7ca0d65
 
 
95422b8
7ca0d65
 
 
 
 
 
 
a981823
7ca0d65
 
 
2e0f6d4
7ca0d65
 
 
 
 
 
 
 
 
2e0f6d4
7ca0d65
 
 
 
2e0f6d4
7ca0d65
 
2e0f6d4
7ca0d65
2e0f6d4
 
 
7ca0d65
 
 
fef6f3e
7ca0d65
 
 
 
 
 
 
 
 
 
2e0f6d4
3b0b2cb
2e0f6d4
 
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
import logging
import os
import streamlit as st
from dotenv import load_dotenv
import openai
from langchain_openai import ChatOpenAI
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.agents import tool, AgentExecutor
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser
from langchain.agents.format_scratchpad.openai_tools import format_to_openai_tool_messages
from langchain_core.messages import AIMessage, HumanMessage
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import CharacterTextSplitter
import serpapi
import requests
import streamlit.components.v1 as components
import smtplib
from email.mime.multipart import MIMEMultipart
from datetime import datetime
import pandas as pd
import re
import random
from bs4 import BeautifulSoup
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from markdownify import markdownify

# Initialize logging and load environment variables
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
load_dotenv()




# Define and validate API keys
openai_api_key = os.getenv("OPENAI_API_KEY")
serper_api_key = os.getenv("SERPER_API_KEY")

if not openai_api_key or not serper_api_key:
    logger.error("API keys are not set properly.")
    raise ValueError("API keys for OpenAI and SERPER must be set in the .env file.")

openai.api_key = openai_api_key


st.markdown("""
    <style>
    .custom-image img {
        width: 100px;  /* Set the width to make the image smaller */
        height: auto;  /* Keep the aspect ratio */
    }
    </style>
    """, unsafe_allow_html=True)
if "chat_started" not in st.session_state:
    st.session_state["chat_started"] = False
if 'previous_trust_tip' not in st.session_state:
    st.session_state.previous_trust_tip = None
if 'previous_suggestion' not in st.session_state:
    st.session_state.previous_suggestion = None

if 'used_trust_tips' not in st.session_state:
    st.session_state.used_trust_tips = set()
if 'used_suggestions' not in st.session_state:
    st.session_state.used_suggestions = set()
    
def copy_to_clipboard(text):
    """Creates a button to copy text to clipboard."""
    escaped_text = text.replace('\n', '\\n').replace('"', '\\"')
    copy_icon_html = f"""
    <style>
    .copy-container {{
        position: relative;
        margin-top: 10px;
        padding-bottom: 30px; /* Space for the button */
        font-size: 0; /* Hide extra space */
    }}
    .copy-button {{
        background: none;
        border: none;
        color: #808080; /* Grey color */
        cursor: pointer;
        font-size: 18px; /* Adjust icon size */
        position: absolute;
        bottom: 0;
        right: 0;
    }}
    .copy-button:hover {{
        color: #606060; /* Darker grey on hover */
    }}
    .copy-message {{
        font-size: 12px;
        color: #4CAF50;
        margin-left: 10px;
        display: none;
    }}
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <div class="copy-container">
        <button class="copy-button" onclick="copyToClipboard()">
            <i class="fas fa-copy"></i>
        </button>
        <span class="copy-message" id="copy_message">Copied!</span>
    </div>
    
    <script>
    function copyToClipboard() {{
        var textArea = document.createElement("textarea");
        textArea.value = "{escaped_text}";
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand("copy");
        document.body.removeChild(textArea);
        
        var copyMessage = document.getElementById("copy_message");
        copyMessage.style.display = "inline";
        setTimeout(function() {{
            copyMessage.style.display = "none";
        }}, 2000);
    }}
    </script>
    """
    components.html(copy_icon_html, height=60)


def send_feedback_via_email(name, email, feedback):
    """Sends an email with feedback details."""
    smtp_server = 'smtp.office365.com'  
    smtp_port = 465  # Typically 587 for TLS, 465 for SSL
    smtp_user = os.getenv("EMAIL_ADDRESS") 
    smtp_password = os.getenv("Password")   

    msg = MIMEMultipart()
    msg['From'] = smtp_user
    msg['To'] = "wajahat698@gmail.com"
    msg['Subject'] = 'Feedback Received'
    
    body = f"Feedback received from {name}:\n\n{feedback}"
    msg.attach(MIMEText(body, 'plain'))

    try:
        with smtplib.SMTP(smtp_server, smtp_port, timeout=10) as server:
            server.set_debuglevel(1)  # Enable debug output for troubleshooting
            server.starttls()  
            server.login(smtp_user, smtp_password)
            server.sendmail(smtp_user, email, msg.as_string())
            st.success("Feedback sent via email successfully!")
    except smtplib.SMTPConnectError:
        st.error("Failed to connect to the SMTP server. Check server settings and network connectivity.")
    except smtplib.SMTPAuthenticationError:
        st.error("Authentication failed. Check email and password.")
    except Exception as e:
        st.error(f"Error sending email: {e}")



def clean_text(text):
    text = text.replace('\\n', '\n')

    # Remove all HTML tags, including nested structures
    text = re.sub(r'<[^>]*>', '', text)
    # Remove any remaining < or > characters
    text = text.replace('<', '').replace('>', '')
    text = re.sub(r'<[^>]+>', '', text)
    text = re.sub(r'(\d+)\s*(B|M|T|billion|million|trillion)', lambda m: f"{m.group(1)} {m.group(2)}", text)    
    text = re.sub(r'(\d)\s*([a-zA-Z])', r'\1 \2', text)  # Fix numbers next to letters
    text = re.sub(r'(\d+)\s+([a-zA-Z])', r'\1 \2', text)  # Fix broken numbers and words
    text = re.sub(r'<span class="(mathnormal|mord)">.*?</span>', '', text, flags=re.DOTALL)

    # Split the text into paragraphs
    paragraphs = text.split('\n\n')
    
    cleaned_paragraphs = []
    for paragraph in paragraphs:
        lines = paragraph.split('\n')
        cleaned_lines = []
        for line in lines:
            # Preserve bold formatting for headings
            if line.strip().startswith('**') and line.strip().endswith('**'):
                cleaned_line = line.strip()
            else:
                # Remove asterisks, special characters, and fix merged text
                cleaned_line = re.sub(r'\*|\−|\∗', '', line)
                cleaned_line = re.sub(r'([a-z])([A-Z])', r'\1 \2', cleaned_line)
            
            # Handle bullet points
            if cleaned_line.strip().startswith('-'):
                cleaned_line = '\n' + cleaned_line.strip()
            
            # Remove extra spaces
            cleaned_line = re.sub(r'\s+', ' ', cleaned_line).strip()
            cleaned_lines.append(cleaned_line)
        
        # Join the lines within each paragraph
        cleaned_paragraph = '\n'.join(cleaned_lines)
        cleaned_paragraphs.append(cleaned_paragraph)
    
    # Join the paragraphs back together
    cleaned_text = '\n\n'.join(para for para in cleaned_paragraphs if para)
    return cleaned_text
    


  

def get_trust_tip_and_suggestion():
    trust_tip = random.choice(trust_tips)
    suggestion = random.choice(suggestions)
    return trust_tip, suggestion



def side():        
    with st.sidebar.form(key='feedback_form'):
    
        st.image( "Trust Logic_Wheel_RGB_Standard.png")
        st.header("Let's create something great.")
        st.markdown("Our minds assess trust through Six Buckets of Trust® and determine their importance and order in a given situation. We then evaluate why we can or can’t trust someone in these Buckets. Trustifier.ai®, trained on 20 years of TrustLogic® application, helps you identify reasons why your audience can trust you in each Bucket and create trust-optimised solutions. It’s copy AI with substance.")
        st.markdown("""
                    <style>
                        .stability { color: rgb(7, 55, 99); font-size: 24px; font-weight: bold; }
                        .development { color: rgb(241, 194, 50); font-size: 24px; font-weight: bold; }
                        .relationship { color: rgb(204, 0, 0); font-size: 24px; font-weight: bold; }
                        .benefit { color: rgb(56, 118, 29); font-size: 24px; font-weight: bold; }
                        .vision { color: rgb(255, 153, 0); font-size: 24px; font-weight: bold; }
                        .competence { color: rgb(111, 168, 220); font-size: 24px; font-weight: bold; }
                    </style>
    
                    <h3 class="stability">Stability Trust:</h3>
                    <p>Why can I trust you to have built a strong and stable foundation?</p>
    
                    <h3 class="development">Development Trust:</h3>
                    <p>Why can I trust you to develop well in the future?</p>
    
                    <h3 class="relationship">Relationship Trust:</h3>
                    <p>What appealing relationship qualities can I trust you for?</p>
    
                    <h3 class="benefit">Benefit Trust:</h3>
                    <p>What benefits can I trust you for?</p>
    
                    <h3 class="vision">Vision Trust:</h3>
                    <p>What Vision and Values can I trust you for?</p>
    
                    <h3 class="competence">Competence Trust:</h3>
                    <p>What competencies can I trust you for?</p>
                    """, unsafe_allow_html=True)
        st.markdown("For detailed descriptions, visit [Academy](https://www.trustifier.ai)")
    
        
    
    
    
        feedback_name = st.text_input("Name")
        feedback_email_input = st.text_input("Email")
        feedback_text = st.text_area("Feedback")

        # Submit button within the form
        submit_button = st.form_submit_button("Submit Feedback")
        if submit_button:
            if feedback_name and feedback_email_input and feedback_text:
                with st.spinner('Sending email'):
                    send_feedback_via_email(feedback_name, feedback_email_input, feedback_text)
                    st.success("Thank you for your feedback!")
            else:
                st.error("Please fill in all fields.")




side()
# Load knowledge base
def load_knowledge_base():
    try:
        loader = TextLoader("./data_source/time_to_rethink_trust_book.md")
        documents = loader.load()
        text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
        docs = text_splitter.split_documents(documents)
        return docs
    except Exception as e:
        logger.error(f"Error loading knowledge base: {e}")
        raise e

knowledge_base = load_knowledge_base()

# Initialize embeddings and FAISS index
embeddings = OpenAIEmbeddings()
db = FAISS.from_documents(knowledge_base, embeddings)

# Define search functions
def search_knowledge_base(query):
    try:
        output = db.similarity_search(query)
        return output
    except Exception as e:
        logger.error(f"Error searching knowledge base: {e}")
        return ["Error occurred during knowledge base search"]
    
def google_search(query):
    try:
        search_client = serpapi.Client(api_key=serper_api_key)
        results = search_client.search({"engine": "google", "q": query})
        snippets = [result["snippet"] for result in results.get("organic_results", [])]
        return snippets
    except Exception as e:
        logger.error(f"Error in Google search: {e}")
        return ["Error occurred during Google search"]
        


# RAG response function
def rag_response(query):
    try:
        # Directly search for the exact term in the knowledge base
        retrieved_docs = search_knowledge_base(query)
        context = "\n".join(doc.page_content for doc in retrieved_docs)
        
        # Prepare the prompt with the retrieved context
        prompt = f"Context:\n{context}\n\nQuestion: {query}\nAnswer:"
        llm = ChatOpenAI(model="gpt-4o", temperature=0.3, api_key=openai_api_key)
        response = llm.invoke(prompt)
        
        # Replace terms in the final output as per your restrictions
        response_content = response.content
        
        return response_content
    except Exception as e:
        logger.error(f"Error generating RAG response: {e}")
        return "Error occurred during RAG response generation"

# Define tools
@tool
def knowledge_base_tool(query: str):
    """Query the knowledge base and retrieve a response."""
    return rag_response(query)

@tool
def google_search_tool(query: str):
    """Perform a Google search using the SERPER API."""
    return google_search(query)

tools = [knowledge_base_tool, google_search_tool]

# Create the prompt template
prompt_message = f"""
You are an expert copywriter specializing in creating high-quality marketing content that integrates TrustBuilders® into various content formats. Your goal is to produce compelling, factual, and well-structured material that adheres to the following guidelines and based on knowledge base:
**GENERAL  INSTRUCTIONS:**
- **Consistency:** Maintain a uniform format across all content types.
- **Tone:** Use an active, engaging, and direct tone. Avoid flowery language and things like 'in the realm','beacon of hope'etc. Avoid complex or overly elaborate language.
- **No Conclusions:** Do not include conclusions in your responses.
- **Specificity:** Include relevant names, numbers like $dollars and years, programs, strategies, places, awards, actions.
- **Formatting:** Avoid using HTML tags such as `<span>`, `<i>`, or others, except for the registered trademark symbol (®). Ensure that numerical values are properly formatted with spaces (e.g., 750 billion to 1 trillion). Do not use bold, italics, or other text styling for numbers.
- **Trademark Usage:** Only use the registered trademark symbol (®) with these brands: TrustLogic, TrustBuilder/TrustBuilders, Six Buckets of Trust, TrustifierAI. Do not use (®) with other brands.
**CONTENT TYPES AND FORMATS:**
1. **Annual Reports or Articles:**
   - Guidelines: Look in knowledge base for guiding principles for generation of marketing copy before generating response.
   - **Introduction:** Start with "Here is a draft of your [Annual Report/Article]. Feel free to suggest further refinements."
   - **Trademark Usage:** Only use the registered trademark symbol (®) with these brands: TrustLogic, TrustBuilder/TrustBuilders, Six Buckets of Trust, TrustifierAI. Do not use (®) with other brands.
   - **Structure:** 
     - **Headline:** This will contain the Principles.The headline should not mention TrustBuilders® or any trust buckets directly.
     - **Content:**
         - One main heading followed by 3-4 detailed paragraphs  summarizing key content (without source links included and without any headings).
         - **Perspective:** Write as if you are part of the organization (using "we"), emphasizing togetherness and collective effort.
     - **Sub-Headings (After Summary):**
       1. **List of TrustBuilders® used :** Strictly return list of  relevant trust builders used with facts and figures  with embedded URL source links everytime.
       2. **Heuristics Used:** Provide 3-5 heuristics from the following list that are relevant to the content. Ensure to integrate them in a way that highlights their relevance to the content:Social Proof, Scarcity, Authority, Reciprocity, Consistency, Liking, Anchoring, Contrast, Urgency, Simplicity, Storytelling, Emotion, Framing, Loss Aversion, Recency, Frequency, Congruence, Availability, Commitment, Halo Effect, Ingroup Bias, Reciprocal Concessions (Door-in-the-Face), Priming, Cognitive Ease, Affect Heuristic, Endowment Effect, Decoy Effect, Foot-in-the-Door, Pacing, Zeigarnik Effect.
       3. **Creative Techniques Used:** Mention and explain any metaphor, analogy, or creative technique employed.
   - **Word Count:** Strictly follow word count instruction if given in user prompt. Main [Content] must meet the specified word count.Do not include the sub-heading sections in the word count limit.
   
2. **Social Media Posts:**
   - **Format:** Create engaging posts with relevant hashtags.
   - **Intro Line:** Start with "Here is a draft of your social media post. Feel free to suggest further refinements."
   - **Content:** Ensure the post is concise, impactful, and designed to engage the audience.
   - **Additional Requirements:** Avoid mentioning trust buckets as hashtags or in the post copy. Ensure source links and trust builders are not included in the post text.
   - **List of TrustBuilders® used :** Provide a list of relevant TrustBuilders used with facts and figures and embedded URL source links.
    - **Word Count:** Strictly follow word count instruction if given in user prompt  . Main [body] must meet the specified word count. 
3. **Sales Conversations or Ad Copy:**
   - **Format:** Create a structured conversation or ad copy with clear messaging.
   - **Intro Line:** Start with "Here is a draft of your [Sales Conversation/Ad Copy]. Feel free to suggest further refinements."
   - **Content:** Include persuasive elements with integrated TrustBuilders®.
   - **List of TrustBuilders® used :** Provide a list of relevant TrustBuilders used with facts and figures and embedded URL source links.
   
4. **Emails, Newsletters, Direct Marketing Letters:**
   - **Format:** Structure properly as an email or letter without any sub-headings.
   - **Intro Line:** Start with "Here is a draft of your [Email/Newsletter/Letter]. Feel free to suggest further refinements."
   - **Content:** Focus on clear, concise messaging with a call to action where appropriate. Do-not include source links here or any links.
   - **Subject:** Give proper subject for emails.
   - **Additional Requirements:** Ensure that trust builders are not mentioned in the email or letter body unless specifically required. Do-not include source links.
   -  **Sub-Headings (At bottom):**
       1. **List of TrustBuilders® used :** Provide List of  relevant trust builders used with facts and figures and with embedded source links.
       2. **Heuristics Used:** Provide 3-5 heuristics names only from the following list that are relevant to the content :Social Proof, Scarcity, Authority, Reciprocity, Consistency, Liking, Anchoring, Contrast, Urgency, Simplicity, Storytelling, Emotion, Framing, Loss Aversion, Recency, Frequency, Congruence, Availability, Commitment, Halo Effect, Ingroup Bias, Reciprocal Concessions (Door-in-the-Face), Priming, Cognitive Ease, Affect Heuristic, Endowment Effect, Decoy Effect, Foot-in-the-Door, Pacing, Zeigarnik Effect.
       3. **Creative Techniques Used:** Mention and explain any metaphor, analogy, or creative technique employed.
   - **Word Count:** Strictly follow word count instruction if given in user prompt . Main body [Content] must meet the specified word count. Do not include the sub-heading sections in the word count limit.
5. **TRUST-BASED QUERIES:**
  - When a query specifically seeks proof points or content related to trust builders or trust buckets, follow these  guidelines:
  - **TrustBuilder® Integration:** Find and list a minimum of 15 Trust Builders points directly followed by relevant source links.
  - **Intro Line:** Start with "Here are some [Bucket name] TrustBuilders®. Let me know if you want to refine the results or find more."
  - **TrustBuilders® Formatting :** Strictly categorize TrustBuilders® correctly into the following sections:
      - ### Organization:** List details about the organization. do-not mention any heading within points.
      - ### People:** List individuals associated with the TrustBuilder®. do-not mention any heading within points.
      - ### Offers/Services:** Detail the offers or services provided. do-not mention any heading within points.
  - **Style and Structure:**
    - Write in bullet points under each heading.
    - Each point should not contain any sub-headings.
    - Give source links with each point.
    - Maintain consistent format.
    - No conclusions at the end of content unless specifically requested.
    - **Trust Bucket Focus:** Do not mix trust buckets; keep responses focused on the requested area.
    - *Refer to the knowledge base for Guiding Principles.*
**GENERAL QUERIES:**
- For general content like blogs or reports always refer knowledge base first, focus on the overall flow and structure without explicitly mentioning trust metrics unless requested.
"""
    
   
    
    

prompt_template = ChatPromptTemplate.from_messages([
    ("system", prompt_message),
    MessagesPlaceholder(variable_name="chat_history"),
    ("user", "{input}"),
    MessagesPlaceholder(variable_name="agent_scratchpad"),
])

# Create Langchain Agent
llm = ChatOpenAI(model="gpt-4o", temperature=0.6)
llm_with_tools = llm.bind_tools(tools)

# Define the agent pipeline
agent = (
    {
        "input": lambda x: x["input"],
        "agent_scratchpad": lambda x: format_to_openai_tool_messages(x["intermediate_steps"]),
        "chat_history": lambda x: x["chat_history"],
    }
    | prompt_template
    | llm_with_tools
    | OpenAIToolsAgentOutputParser()
)

# Instantiate an AgentExecutor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# Streamlit app

# Initialize chat history
if 'chat_history' not in st.session_state:
    st.session_state.chat_history = []

# Display chat history
for message in st.session_state.chat_history:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

# Chat input
if not st.session_state.get("chat_started", False):


    st.markdown("""
    <script>
    document.addEventListener('DOMContentLoaded', (event) => {
        const svgs = document.querySelectorAll('svg');
        svgs.forEach(svg => {
            if (svg.getAttribute('xmlns') === 'http://www.w3.org/2000/svg' && svg.getAttribute('width') === '18' && svg.getAttribute('height') === '18') {
                svg.style.display = 'none';
            }
        });
    });
    </script>
    <style>
    /* Hide all <a> elements inside elements with block-container and st-emotion-cache-1eo1tir ea3mdgi5 classes */
    .block-container.st-emotion-cache-1eo1tir.ea3mdgi5 a {
        display: none !important;
    }
    /* Ensure links in the sidebar are visible and underlined */
    .stSidebar a {
        display: inline !important;
        text-decoration: underline !important;
        color: inherit !important;
    }
    /* Additional styles */
    .section-container {
        display: flex;
        justify-content: center;
        align-items: stretch;
        flex-wrap: wrap;
        gap: 4px;
    }
    
    .section {
        flex: 1;
        min-width: 150px;
        max-width: 90px;
        min-height: 150px;
        border: 1px solid #afafaf;
        border-radius: 10px;
        padding: 5px;
        background-color: transparent;
        margin: 3px;
        text-align: center;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        box-sizing: border-box;
        font-size: 12px;
        transition: background-color 0.3s ease;
    }
    .section h2 {
        color: #afafaf;
        font-size: 14px;
        margin-bottom: 8px;
        border-bottom: 1px solid #afafaf;
        padding-bottom: 4px;
        text-align: center; /* Center headings */
    }
    .section p {
        color: #afafaf;
        font-size: 11px;
        margin: 5px 0;
        line-height: 1.4;
    }
    @media (max-width: 100px) {
        .section {
            min-width: 90%;
            max-width: 90%;
        }
    }
    </style>
    
    <h1 style="text-align: center; background: #528186; -webkit-background-clip: text; color: transparent;">How can I help you today?</h1>
    <div class="section-container">
        <div class="section">
            <h2>Find</h2>
            <p>Discover all your great TrustBuilders®. <br> Example: Find Development Trust Builders® for Food for the Hungry
        </div>
        <div class="section">
            <h2>Create</h2>
            <p>Generate trust-optimised solutions : <br>Example: Find Food for the Hungry development TrustBuilders®. Then use them to write a 200-word annual report article. Enthusiastic tone.</p>
        </div>
        <div class="section">
            <h2>Trust-optimise</h2>
            <p>Paste your LinkedIn profile, EDM or blog and ask Trustifier.ai® to improve it using specific Trust Buckets® and add your specific TrustBuilders® as examples.</p>
        </div>
    </div>
    <div style="height: 50px;"></div> <!-- Adds a gap of 50px after the section containers -->
    """, unsafe_allow_html=True)
  

trust_tips = [
    "What I don’t know I can’t trust you for. Make sure you know all your great TrustBuilders® and use them over time.",
    "The more specific, the more trustworthy each TrustBuilder® is.",
    "For TrustBuilders®, think about each Trust Bucket® and in each one organization, product, and key individuals.",
    "You are infinitely trustworthy. Organization, products, and your people. In each Trust Bucket® and past, present, and future.",
    "Some TrustBuilders® are enduring (we have over 3 million clients), others changing (we are ranked No. 1 for 8 years/9 years), and yet others short-lived (we will present at XYZ conference next month).",
    "Not all Trust Buckets® are equally important all the time. Think about which ones are most important right now and how to fill them (with TrustAnalyser® you know).",
    "In social media, structure posts over time to focus on different Trust Buckets® and themes within them.",
    "Try focusing your idea on specific Trust Buckets® or a mix of them.",
    "Within each Trust Bucket®, ask for examples across different themes like employee programs, IT, R&D.",
    "To create more and different trust, ask trustifier.ai to combine seemingly unconnected aspects like 'I played in bands all my youth. What does this add to my competence as a lawyer?'",
    "With every little bit more trust, your opportunity doubles. It's about using trustifier.ai to help you nudge trust up ever so slightly in everything you do.",
    "Being honest is not enough. You can be honest with one aspect and destroy trust and build a lot of trust with another. Define what that is.",
    "The more I trust you, the more likely I am to recommend you. And that's much easier with specifics.",
    "What others don’t say they are not trusted for - but you can claim that trust.",
    "Building more trust is a service to your audience. It's so valuable to us, as humans, that we reflect that value right away in our behaviors.",
    "In your audience journey, you can use TrustAnalyser® to know precisely which Trust Buckets® and TrustBuilders® are most effective at each stage of the journey.",
    "Try structuring a document. Like % use of each Trust Bucket® and different orders in the document.",
    "In longer documents like proposals, think about the chapter structure and which Trust Buckets® and TrustBuilders® you want to focus on when.",
    "Building Trust doesn’t take a long time. Trust is built and destroyed every second, with every word, action, and impression. That's why it's so important to build more trust all the time.",
    "There is no prize for the second most trusted. To get the most business, support, and recognition, you have to be the most trusted.",
    "With most clients, we know they don’t know 90% of their available TrustBuilders®. Knowing them increases internal trust - and that can be carried to the outside.",
    "Our client data always shows that, after price, trust is the key decision factor (and price is a part of benefit and relationship trust).",
    "Our client data shows that customer value increases 9x times from Trust Neutral to High Trust. A good reason for internal discussions.",
    "Our client's data shows that high trust customers are consistently far more valuable than just trusting ones.",
    "Trust determines up to 85% of your NPS. No wonder, because the more I trust you, the more likely I am to recommend you.",
    "Trust determines up to 75% of your loyalty. Think about it yourself. It's intuitive.",
    "Trust determines up to 87% of your reputation. Effectively, they are one and the same.",
    "Trust determines up to 85% of your employee engagement. But what is it that they want to trust you for?",
    "Don't just ask 'what your audience needs to trust for'. That just keeps you at low, hygiene trust levels. Ask what they 'would love to trust for'. That's what gets you to High Trust."
]

suggestions = [
    "Try digging deeper into a specific TrustBuilder®.",
    "Ask just for organization, product, or a person's TrustBuilders® for a specific Trust Bucket®.",
    "Some TrustBuilders® can fill more than one Trust Bucket®. We call these PowerBuilders. TrustAnalyser® reveals them for you.",
    "Building trust is storytelling. trustifier.ai connects Trust Buckets® and TrustBuilders® for you. But you can push it more to connect specific Trust Buckets® and TrustBuilders®.",
    "Describe your audience and ask trustifier.ai to choose the most relevant Trust Buckets®, TrustBuilders®, and tonality (TrustAnalyser® can do this precisely for you).",
    "Ask trustifier.ai to find TrustBuilders® for yourself. Then correct and add a few for your focus Trust Buckets® - and generate a profile or CV.",
    "LinkedIn Profiles are at their most powerful if they are regularly updated and focused on your objectives. Rewrite it every 2-3 months using different Trust Buckets®.",
    "Share more of your TrustBuilders® with others and get them to help you build your trust.",
    "Build a trust strategy. Ask trustifier.ai to find all your TrustBuilders® in the Trust Buckets® and then create a trust-building program for a specific person/audience over 8 weeks focusing on different Trust Buckets® that build on one another over time. Then refine and develop by channel ideas.",
    "Brief your own TrustBuilders® and ask trustifier.ai to tell you which Trust Buckets® they're likely to fill (some can fill more than one).",
    "Have some fun. Ask trustifier.ai to write a 200-word speech to investors using all Trust Buckets®, but leading and ending with Development Trust. Use [BRAND], product, and personal CEO [NAME] TrustBuilders®.",
    "Ask why TrustLogic® can be trusted in each Trust Bucket®.",
    "Ask what's behind TrustLogic®."
]



prompt = st.chat_input("")
if prompt :
    
        st.session_state["chat_started"] = True
        # Add user message to chat history
        st.session_state.chat_history.append({"role": "user", "content": prompt})
        
        # Display user message
        with st.chat_message("user"):
            st.markdown(prompt)
    
        # Generate AI response
        with st.chat_message("assistant"):
            full_response = ""
            
            try:
                # Generate response using the agent executor
                output = agent_executor.invoke({
                            "input": f"{prompt} .Strictly follow words (write more than the mentioned words in case of article or news letter) and already mention instructions.Handle problematic text (Usually it is related to numbers, figures and text nearby )clean it up make spaced  so that it is readable and properly formatted for display in a web application. Avoid any unusual line breaks or formatting issues. Always provide sources links with trust builders. Find right trust builders, do not mix please. ",
    
                    "chat_history": st.session_state.chat_history
                })
                full_response = output["output"]
                #full_response= replace_terms(full_response)

                cleaned_text = clean_text(full_response)
                cleaned_text = re.sub(r'<[^>]*>', '', cleaned_text)


                
                #cleaned_text = re.sub(r'</span>', '', cleaned_text) 
                #cleaned_text = re.sub(r'<span[^>]*>', '', cleaned_text)
                # Display the response
                
                trust_tip, suggestion = get_trust_tip_and_suggestion()

                #combined_text = f"{cleaned_text}\n\n---\n\n**Trust Tip**: {trust_tip}\n\n**Suggestion**: {suggestion}"
                combined_text = f"{cleaned_text}\n\n---\n\n**Trust Tip**: {trust_tip}\n\n**Suggestion**: {suggestion}"

                st.markdown(combined_text,unsafe_allow_html=True)
                
                #seprtor= st.markdown("---")  # Add a separator
                #t_tip= st.markdown(f"**Trust Tip**: {trust_tip}")
                #s_sug- st.markdown(f"**Suggestion**: {suggestion}")

    
    
    
    
    
            except Exception as e:
                logger.error(f"Error generating response: {e}")
                full_response = "I apologize, but an error occurred while generating the response. Please try again."
                st.write(full_response)
    
        # Add AI response to chat history 

        st.session_state.chat_history.append({"role": "assistant", "content": cleaned_text})
        copy_to_clipboard(cleaned_text)