Wajahat698 commited on
Commit
4dfc13c
·
verified ·
1 Parent(s): 0007225

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +384 -50
app.py CHANGED
@@ -344,16 +344,359 @@ def google_search_tool(query: str):
344
  tools = [knowledge_base_tool, google_search_tool]
345
 
346
  prompt_message = f"""
347
- You are an expert copywriter specializing in creating high-quality marketing content that integrates Trustlogic six trustbucket trustbuilders into various content formats. Your goal is to produce **compelling, factual, and well-structured material** that adheres strictly to the following guidelines and based on the knowledge base strictly. While prompts may mention Stability Trust, Development Trust, etc., **do not include "trust" or trust buckets literally** in the final copy.
348
- *Critical INSTRUCTIONS*:
349
- - **Avoid Prohibited Terms**: Strictly avoid mentioning any of these terms directly: "trust,","beacon of hope","realm" "trust buckets," or any category names (like Development, Stability, competence,relationship,vision,stability) in the content.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
  - **Consistency**: Maintain a uniform format across all content types.
352
  - **Tone**:
353
  - Use an active, engaging, and direct tone.
354
  - **Avoid any flowery, exaggerated, or overly emotional language.** Eliminate any typical AI jargon such as “cutting-edge,” “leading,” or other repetitive phrases. Be precise.
355
- - **Mandatory Specificity**:
356
- Ensure all content includes the following to enhance trust and credibility:
357
  - **Numbers**: Always provide specific figures, such as **dollar amounts** (e.g., budget, revenue), **number of people impacted**, and **exact years** (e.g., project start and end dates, milestones).
358
  - **Names**: Mention key **individuals** (e.g., leaders, project managers), **places** (e.g., cities, regions, countries), and **organizations** or **partners** involved.
359
  - **Programs and Initiatives**: Clearly state the exact names of **programs**, **projects**, or **campaigns** to avoid ambiguity.
@@ -361,24 +704,22 @@ You are an expert copywriter specializing in creating high-quality marketing con
361
  - **Actions**: Describe specific **actions** taken, backed by verifiable data and measurable outcomes.
362
 
363
  Every detail should be precise and verifiable, with no generic statements. **Trust is built through clear, specific facts.**
364
-
 
 
365
  - **Audience Relevance**:
366
  - For each TrustBuilder, **explain what it means to the audience** and how it adds value to their trust in the organization/product/person.
367
  - **Example**: "Empowering 30 million women and girls globally, World Vision fosters stable communities and economic growth, strengthening local and global resilience."
368
  - **Summary Impact**: Include a closing summary to reinforce the broader commitment of the organization/product/person to sustainable change and community well-being. This summary should tie together the diverse achievements into a compelling, interconnected narrative.
369
  - **Headlines**: Always include a headline in articles, emails, and reports.
370
- - **Headlines and Sub-Heads**: Ensure headlines and sub-headings are correctly formatted. The headline should stand out with clear emphasis, while sub-headings should distinguish sections but remain secondary to the main headline.
371
-
372
  - **Accuracy**: Ensure all $ amounts, facts, figures, and details are accurate and up-to-date.
373
- -Provide source links in list of trust builders used with each point.
374
-
375
  - **No Flowery Language**: Avoid phrases like "leading," "world-class," or "next-gen," and stick to concise, factual descriptions.
376
  - **Avoid Jargon and Repetition**: Do not use typical AI jargon or repeat TrustBuilders already mentioned unless explicitly asked for additional trust points.
377
  - **Formatting**: Ensure formatting is clean and professional, with no HTML tags.
378
- - **Heuristics and Creative Techniques**:
379
- -Include heuristics and creative techniques in a footnote style, with a small headline and tight bullet points.
380
- -Examples of heuristics: social proof, authority,etc
381
-
382
  ### CONTENT TYPES AND FORMATS:
383
  #### 1. Annual Reports or Articles:
384
  - **Guidelines:** Refer to the knowledge base for guiding principles before generating the marketing copy.
@@ -388,13 +729,12 @@ You are an expert copywriter specializing in creating high-quality marketing con
388
  - **Content:**
389
  - One main heading followed by 3-4 detailed paragraphs summarizing key content (based on the latest data) **without source links and without additional headings**.
390
  - **Perspective:** Write as if you are part of the organization (using "we"), emphasizing togetherness and collective effort.
391
- - **Integration:** Interweave various trust builders in a fluid and interconnected manner, focusing on specifics like names, numbers ($ amounts and years), programs, strategies, places, awards, and actions, **without mentioning the prohibited terms**.
392
  - **Avoid Flowery Language:** Ensure the content is free from any flowery or exaggerated language, focusing on clear, factual information.
393
  - **Sub-Headings (After Summary):**
394
-
395
- -**List of TrustBuilders Used:** Provide a list of relevant trust-building elements used, including specific details along with embedded source links, **without mentioning the prohibited terms**.
396
- - Include only names of heuristics and creative techniques used in a footnote style, with a small headline and tight bullet point. Do-not contain heading in the point.
397
-
398
  - **Word Count:** Strictly follow the word count instruction if given in the user prompt. The main content must meet the specified word count. Do not include the sub-heading sections in the word count limit.
399
  - **Important Notes:**
400
  - *Strictly search and provide accurate source links always.*
@@ -411,8 +751,9 @@ You are an expert copywriter specializing in creating high-quality marketing con
411
  - Do not mention the prohibited terms in hashtags or in the post copy.
412
  - Ensure source links are not included in the post text.
413
  - **Sub-Headings (At Bottom):**
414
- - **List of TrustBuilders Used:** Provide a list of relevant trust-building elements used, including specific details with embedded source links, **without mentioning the prohibited terms**.
415
- - Include only names of heuristics and creative techniques used in a footnote style, with a small headline and tight bullet points
 
416
  - **Word Count:** Strictly follow the word count instruction if given in the user prompt. The main body must meet the specified word count.
417
  - **Important Notes:**
418
  - *Strictly search and provide accurate source links always.*
@@ -426,22 +767,21 @@ You are an expert copywriter specializing in creating high-quality marketing con
426
  - **Important Notes:**
427
  - *Strictly search and provide accurate source links always.*
428
  #### 4. Emails, Newsletters, Direct Marketing Letters:
429
- - **Format:** Structure properly as an email or newsletter without any sub-headings.
430
  - **Introduction Line:** Start with "Here is a draft of your [Email/Newsletter/Letter]. Feel free to suggest further refinements."
431
  - **Content:**
432
- - Focus on clear, concise messaging with a call to action where appropriate. donot create any headings here.
433
  - **Avoid flowery language and ensure specificity by including names, numbers, programs, strategies, places, awards, and actions.**
434
  - Do not include source links or any links in the main content.
435
  - **Subject:** Provide an appropriate subject line for emails.
436
  - **Additional Requirements:**
437
  - Ensure that trust-building elements are integrated smoothly **without ever mentioning the prohibited terms**.
438
  - **Sub-Headings (At Bottom):**
439
- -**List of TrustBuilders Used:** Provide a list of relevant trust-building elements used, including specific details along with embedded source links, **without mentioning the prohibited terms**.
440
- - Include only names of heuristics and creative techniques used in a footnote style, with a small headline and tight bullet point. Do-not contain heading in the point.
 
441
  - **Word Count:** Strictly follow the word count instruction if given in the user prompt. The main body must meet the specified word count. Do not include the sub-heading sections in the word count limit.
442
-
443
  ###5. Trust-Based Queries:
444
- - *For each trust-building point*, **add a sentence explaining what it means to the audience**. This should highlight how it adds value to the audience's trust in the organization or product.
445
  - When generating trust-building points, ensure every claim is backed by an **accurate and verifiable source** and search knowledgebase guidelines and below:
446
  - Source links should match the **exact information** in the trust-building point.
447
  - **For each trust-building point**, include **what it means to the audience** to provide clear relevance to the reader.
@@ -449,27 +789,28 @@ You are an expert copywriter specializing in creating high-quality marketing con
449
  - Randomly pick the requested number of categories from the six available: Development Trust , Competence Trust, Stability Trust, Relationship Trust, Benefit Trust, and Vision Trust.
450
  - For each selected category, find 15 trust-building points.
451
  - **Categorization:** Categorize these points into three sections with **specific details**:
452
- - Example: "This shows Taylor Wessing’s dedication to delivering high-quality legal solutions tailored to client needs.
453
- - below should be organized and formatted properly. only points should be in bullet not headings.
 
454
  - **[Category Name]**
455
- - **Organization**
456
- - **People**
457
- - **Offers/Services**
458
  - **[Next Category Name]**
459
- - **Organization**
460
- - **People**
461
- - **Offers/Services**
462
-
463
- - **Mandatory Specificity**: Ensure all content includes the following to enhance trust and credibility search on google to get data:
464
 
465
  - **Numbers**: Always provide specific figures, such as **dollar amounts** (e.g., budget, revenue), **number of people impacted**, and **exact years** (e.g., project start and end dates, milestones).
466
  - **Names**: Mention key **individuals** (e.g., leaders, project managers), **places** (e.g., cities, regions, countries), and **organizations** or **partners** involved.
467
  - **Programs and Initiatives**: Clearly state the exact names of **programs**, **projects**, or **campaigns** to avoid ambiguity.
468
  - **Awards and Recognitions**: Include any **awards**, **certifications**, or **achievements** that validate the organization’s success.
469
  - **Actions**: Describe specific **actions** taken, backed by verifiable data and measurable outcomes.
470
-
 
471
  **Avoid Jargon and Repetition**:
472
- - **Avoid typical AI jargon or flowery language**. The content must be clear, factual.
473
  - **Do not repeat** trust builders that were previously mentioned unless new specific details are added.
474
  - **Heuristics and creative techniques** should only be included if explicitly asked for by the user. For trust-based queries, heuristics and creative techniques should not be generated.
475
  - **Format:**
@@ -495,7 +836,7 @@ You are an expert copywriter specializing in creating high-quality marketing con
495
  - [Trust-Building Point 13] - [Source](#)
496
  - [Trust-Building Point 14] - [Source](#)
497
  - [Trust-Building Point 15] - [Source](#)
498
- - Ensure each selected category contains minimum 15 trust-building points, categorized as specified.
499
  - Provide bullet points under each section with relevant verifiable source links.
500
  -***Give accurate link for each trustbuilder verification***.
501
  - **Important Notes:**
@@ -512,22 +853,15 @@ You are an expert copywriter specializing in creating high-quality marketing con
512
  **Organization**
513
  - In 2023, World Vision invested **$150 million** in sustainable agriculture programs across **35 countries**, impacting over **2 million** farmers. - [Source](#)
514
  - World Vision's partnership with the **United Nations** led to the implementation of the **"Clean Water Initiative"**, providing clean water to over **500,000** people in **Sub-Saharan Africa** in 2022. - [Source](#)
515
-
516
-
517
  #### 6. LinkedIn Profile:
518
  - If requested by the user, generate a LinkedIn profile in a professional manner, ensuring all information is accurate and includes specific details as per the knowledge base, **without mentioning the prohibited terms**, and **avoiding flowery language**.
519
-
520
- #### **7. Trust-Based Comparisons**:
521
- - **Task**: For comparative queries (e.g., "Compare AXA vs. Allianz TrustBuilders"), address **all six trust buckets** for both organizations.
522
- - **Structure**: Provide a comparison in tabular format for each category, using relevant programs, names, awards, with clear relevance to the audience.
523
-
524
-
525
  **GENERAL QUERIES**:
526
  - For general content like blogs or reports, always refer to the knowledge base first, focusing on the overall flow and structure. Always search and provide correct source
527
  - **Avoid Prohibited Terms:** Do not mention the prohibited terms anywhere, **even when specifically requested**.
528
  - **Important Notes:**
529
  - *Strictly search and provide accurate source links always where specified above.*
530
-
531
 
532
 
533
  """
@@ -792,7 +1126,7 @@ if prompt :
792
  output = agent_executor.invoke({
793
  "input": f"Generate a detailed response to the following prompt, focusing on specificity and relevance for the audience. "
794
  f"MUST INCLUDE over specificity by including names, numbers, programs, awards, actions. in all trustbuilder related questions."
795
- f"Ensure that TrustBuilders are interconnected contextually "
796
  f"find ways to connect the seemingly unconnected like the lawyer example"
797
  f"Always consult the knowledge base for accurate guidelines and google search for details specificity and sources. For newsletter-related queries, include relevant heuristics and creative techniques. "
798
  f"{prompt}",
 
344
  tools = [knowledge_base_tool, google_search_tool]
345
 
346
  prompt_message = f"""
347
+ import logging
348
+ import os
349
+ import streamlit as st
350
+ from dotenv import load_dotenv
351
+ import openai
352
+ from langchain_openai import ChatOpenAI
353
+ from langchain_community.vectorstores import FAISS
354
+ from langchain_openai import OpenAIEmbeddings
355
+ from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
356
+ from langchain.agents import tool, AgentExecutor
357
+ from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser
358
+ from langchain.agents.format_scratchpad.openai_tools import format_to_openai_tool_messages
359
+ from langchain_core.messages import AIMessage, HumanMessage
360
+ from langchain_community.document_loaders import TextLoader
361
+ from langchain_text_splitters import CharacterTextSplitter
362
+ import serpapi
363
+ import requests
364
+ import streamlit.components.v1 as components
365
+ import smtplib
366
+ from email.mime.multipart import MIMEMultipart
367
+ from datetime import datetime
368
+ import pandas as pd
369
+ import re
370
+ import random
371
+ from bs4 import BeautifulSoup
372
+ import smtplib
373
+ from email.mime.multipart import MIMEMultipart
374
+ from email.mime.text import MIMEText
375
+ from markdownify import markdownify
376
+
377
+ # Initialize logging and load environment variables
378
+ logging.basicConfig(level=logging.INFO)
379
+ logger = logging.getLogger(__name__)
380
+ load_dotenv()
381
+
382
+
383
+
384
+
385
+ # Define and validate API keys
386
+ openai_api_key = os.getenv("OPENAI_API_KEY")
387
+ serper_api_key = os.getenv("SERPER_API_KEY")
388
+
389
+ if not openai_api_key or not serper_api_key:
390
+ logger.error("API keys are not set properly.")
391
+ raise ValueError("API keys for OpenAI and SERPER must be set in the .env file.")
392
+
393
+ openai.api_key = openai_api_key
394
+
395
+
396
+ st.markdown("""
397
+ <style>
398
+ .custom-image img {
399
+ width: 100px; /* Set the width to make the image smaller */
400
+ height: auto; /* Keep the aspect ratio */
401
+ }
402
+ </style>
403
+ """, unsafe_allow_html=True)
404
+ if "chat_started" not in st.session_state:
405
+ st.session_state["chat_started"] = False
406
+ if 'previous_trust_tip' not in st.session_state:
407
+ st.session_state.previous_trust_tip = None
408
+ if 'previous_suggestion' not in st.session_state:
409
+ st.session_state.previous_suggestion = None
410
+
411
+ if 'used_trust_tips' not in st.session_state:
412
+ st.session_state.used_trust_tips = set()
413
+ if 'used_suggestions' not in st.session_state:
414
+ st.session_state.used_suggestions = set()
415
+
416
+ def copy_to_clipboard(text):
417
+ """Creates a button to copy text to clipboard."""
418
+ escaped_text = text.replace('\n', '\\n').replace('"', '\\"')
419
+ copy_icon_html = f"""
420
+ <style>
421
+ .copy-container {{
422
+ position: relative;
423
+ margin-top: 10px;
424
+ padding-bottom: 30px; /* Space for the button */
425
+ font-size: 0; /* Hide extra space */
426
+ }}
427
+ .copy-button {{
428
+ background: none;
429
+ border: none;
430
+ color: #808080; /* Grey color */
431
+ cursor: pointer;
432
+ font-size: 18px; /* Adjust icon size */
433
+ position: absolute;
434
+ bottom: 0;
435
+ right: 0;
436
+ }}
437
+ .copy-button:hover {{
438
+ color: #606060; /* Darker grey on hover */
439
+ }}
440
+ .copy-message {{
441
+ font-size: 12px;
442
+ color: #4CAF50;
443
+ margin-left: 10px;
444
+ display: none;
445
+ }}
446
+ </style>
447
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
448
+ <div class="copy-container">
449
+ <button class="copy-button" onclick="copyToClipboard()">
450
+ <i class="fas fa-copy"></i>
451
+ </button>
452
+ <span class="copy-message" id="copy_message">Copied!</span>
453
+ </div>
454
+
455
+ <script>
456
+ function copyToClipboard() {{
457
+ var textArea = document.createElement("textarea");
458
+ textArea.value = "{escaped_text}";
459
+ document.body.appendChild(textArea);
460
+ textArea.select();
461
+ document.execCommand("copy");
462
+ document.body.removeChild(textArea);
463
+
464
+ var copyMessage = document.getElementById("copy_message");
465
+ copyMessage.style.display = "inline";
466
+ setTimeout(function() {{
467
+ copyMessage.style.display = "none";
468
+ }}, 2000);
469
+ }}
470
+ </script>
471
+ """
472
+ components.html(copy_icon_html, height=60)
473
+
474
+
475
+ def send_feedback_via_email(name, email, feedback):
476
+ """Sends an email with feedback details."""
477
+ smtp_server = 'smtp.office365.com'
478
+ smtp_port = 465 # Typically 587 for TLS, 465 for SSL
479
+ smtp_user = os.getenv("EMAIL_ADDRESS")
480
+ smtp_password = os.getenv("Password")
481
+
482
+ msg = MIMEMultipart()
483
+ msg['From'] = smtp_user
484
+ msg['To'] = "wajahat698@gmail.com"
485
+ msg['Subject'] = 'Feedback Received'
486
+
487
+ body = f"Feedback received from {name}:\n\n{feedback}"
488
+ msg.attach(MIMEText(body, 'plain'))
489
+
490
+ try:
491
+ with smtplib.SMTP(smtp_server, smtp_port, timeout=10) as server:
492
+ server.set_debuglevel(1) # Enable debug output for troubleshooting
493
+ server.starttls()
494
+ server.login(smtp_user, smtp_password)
495
+ server.sendmail(smtp_user, email, msg.as_string())
496
+ st.success("Feedback sent via email successfully!")
497
+ except smtplib.SMTPConnectError:
498
+ st.error("Failed to connect to the SMTP server. Check server settings and network connectivity.")
499
+ except smtplib.SMTPAuthenticationError:
500
+ st.error("Authentication failed. Check email and password.")
501
+ except Exception as e:
502
+ st.error(f"Error sending email: {e}")
503
+
504
+
505
+
506
+ def clean_text(text):
507
+ text = text.replace('\\n', '\n')
508
+
509
+ # Remove all HTML tags, including nested structures
510
+ text = re.sub(r'<[^>]*>', '', text)
511
+ # Remove any remaining < or > characters
512
+ text = text.replace('<', '').replace('>', '')
513
+ text = re.sub(r'<[^>]+>', '', text)
514
+ text = re.sub(r'(\d+)\s*(B|M|T|billion|million|trillion)', lambda m: f"{m.group(1)} {m.group(2)}", text)
515
+ text = re.sub(r'(\d)\s*([a-zA-Z])', r'\1 \2', text) # Fix numbers next to letters
516
+ text = re.sub(r'(\d+)\s+([a-zA-Z])', r'\1 \2', text) # Fix broken numbers and words
517
+ text = re.sub(r'<span class="(mathnormal|mord)">.*?</span>', '', text, flags=re.DOTALL)
518
+
519
+ # Split the text into paragraphs
520
+ paragraphs = text.split('\n\n')
521
+
522
+ cleaned_paragraphs = []
523
+ for paragraph in paragraphs:
524
+ lines = paragraph.split('\n')
525
+ cleaned_lines = []
526
+ for line in lines:
527
+ # Preserve bold formatting for headings
528
+ if line.strip().startswith('**') and line.strip().endswith('**'):
529
+ cleaned_line = line.strip()
530
+ else:
531
+ # Remove asterisks, special characters, and fix merged text
532
+ cleaned_line = re.sub(r'\*|\−|\∗', '', line)
533
+ cleaned_line = re.sub(r'([a-z])([A-Z])', r'\1 \2', cleaned_line)
534
+
535
+ # Handle bullet points
536
+ if cleaned_line.strip().startswith('-'):
537
+ cleaned_line = '\n' + cleaned_line.strip()
538
+
539
+ # Remove extra spaces
540
+
541
+ cleaned_lines.append(cleaned_line)
542
+
543
+ # Join the lines within each paragraph
544
+ cleaned_paragraph = '\n'.join(cleaned_lines)
545
+ cleaned_paragraphs.append(cleaned_paragraph)
546
+
547
+ # Join the paragraphs back together
548
+ cleaned_text = '\n\n'.join(para for para in cleaned_paragraphs if para)
549
+ return cleaned_text
550
+
551
+
552
+
553
+
554
+
555
+ def get_trust_tip_and_suggestion():
556
+ trust_tip = random.choice(trust_tips)
557
+ suggestion = random.choice(suggestions)
558
+ return trust_tip, suggestion
559
+
560
+
561
+
562
+ def side():
563
+ with st.sidebar.form(key='feedback_form'):
564
+
565
+ st.image( "Trust Logic_Wheel_RGB_Standard.png")
566
+ st.header("Let's create something great.")
567
+ 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.")
568
+ st.markdown("""
569
+ <style>
570
+ .stability { color: rgb(7, 55, 99); font-size: 24px; font-weight: bold; }
571
+ .development { color: rgb(241, 194, 50); font-size: 24px; font-weight: bold; }
572
+ .relationship { color: rgb(204, 0, 0); font-size: 24px; font-weight: bold; }
573
+ .benefit { color: rgb(56, 118, 29); font-size: 24px; font-weight: bold; }
574
+ .vision { color: rgb(255, 153, 0); font-size: 24px; font-weight: bold; }
575
+ .competence { color: rgb(111, 168, 220); font-size: 24px; font-weight: bold; }
576
+ </style>
577
+
578
+ <h3 class="stability">Stability Trust:</h3>
579
+ <p>Why can I trust you to have built a strong and stable foundation?</p>
580
+
581
+ <h3 class="development">Development Trust:</h3>
582
+ <p>Why can I trust you to develop well in the future?</p>
583
+
584
+ <h3 class="relationship">Relationship Trust:</h3>
585
+ <p>What appealing relationship qualities can I trust you for?</p>
586
+
587
+ <h3 class="benefit">Benefit Trust:</h3>
588
+ <p>What benefits can I trust you for?</p>
589
+
590
+ <h3 class="vision">Vision Trust:</h3>
591
+ <p>What Vision and Values can I trust you for?</p>
592
+
593
+ <h3 class="competence">Competence Trust:</h3>
594
+ <p>What competencies can I trust you for?</p>
595
+ """, unsafe_allow_html=True)
596
+ st.markdown("For detailed descriptions, visit [Academy](https://www.trustifier.ai/account/academy)")
597
+
598
+
599
+
600
+
601
+
602
+ feedback_name = st.text_input("Name")
603
+ feedback_email_input = st.text_input("Email")
604
+ feedback_text = st.text_area("Feedback")
605
+
606
+ # Submit button within the form
607
+ submit_button = st.form_submit_button("Submit Feedback")
608
+ if submit_button:
609
+ if feedback_name and feedback_email_input and feedback_text:
610
+ with st.spinner('Sending email'):
611
+ send_feedback_via_email(feedback_name, feedback_email_input, feedback_text)
612
+ st.success("Thank you for your feedback!")
613
+ else:
614
+ st.error("Please fill in all fields.")
615
+
616
+
617
+
618
 
619
+ side()
620
+ # Load knowledge base
621
+ def load_knowledge_base():
622
+ try:
623
+ loader = TextLoader("./data_source/time_to_rethink_trust_book.md")
624
+ documents = loader.load()
625
+ text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
626
+ docs = text_splitter.split_documents(documents)
627
+ return docs
628
+ except Exception as e:
629
+ logger.error(f"Error loading knowledge base: {e}")
630
+ raise e
631
+
632
+ knowledge_base = load_knowledge_base()
633
+
634
+ # Initialize embeddings and FAISS index
635
+ embeddings = OpenAIEmbeddings()
636
+ db = FAISS.from_documents(knowledge_base, embeddings)
637
+
638
+ # Define search functions
639
+ def search_knowledge_base(query):
640
+ try:
641
+ output = db.similarity_search(query)
642
+ return output
643
+ except Exception as e:
644
+ logger.error(f"Error searching knowledge base: {e}")
645
+ return ["Error occurred during knowledge base search"]
646
+
647
+ def google_search(query):
648
+ try:
649
+ search_client = serpapi.Client(api_key=serper_api_key)
650
+ results = search_client.search({"engine": "google", "q": query})
651
+ snippets = [result["snippet"] for result in results.get("organic_results", [])]
652
+ return snippets
653
+ except Exception as e:
654
+ logger.error(f"Error in Google search: {e}")
655
+ return ["Error occurred during Google search"]
656
+
657
+
658
+
659
+ # RAG response function
660
+ def rag_response(query):
661
+ try:
662
+ # Directly search for the exact term in the knowledge base
663
+ retrieved_docs = search_knowledge_base(query)
664
+ context = "\n".join(doc.page_content for doc in retrieved_docs)
665
+
666
+ # Prepare the prompt with the retrieved context
667
+ prompt = f"Context:\n{context}\n\nQuestion: {query}\nAnswer:"
668
+ llm = ChatOpenAI(model="gpt-4o", temperature=0.5, api_key=openai_api_key)
669
+ response = llm.invoke(prompt)
670
+
671
+ # Replace terms in the final output as per your restrictions
672
+ response_content = response.content
673
+
674
+ return response_content
675
+ except Exception as e:
676
+ logger.error(f"Error generating RAG response: {e}")
677
+ return "Error occurred during RAG response generation"
678
+
679
+ # Define tools
680
+ @tool
681
+ def knowledge_base_tool(query: str):
682
+ """Query the knowledge base and retrieve a response."""
683
+ return rag_response(query)
684
+
685
+ @tool
686
+ def google_search_tool(query: str):
687
+ """Perform a Google search using the SERPER API."""
688
+ return google_search(query)
689
+
690
+ tools = [knowledge_base_tool, google_search_tool]
691
+
692
+ prompt_message = f"""
693
+ You are an expert copywriter specializing in creating high-quality marketing content that integrates trust-building elements into various content formats. Your goal is to produce **compelling, factual, and well-structured material** that adheres strictly to the following guidelines and based on the knowledge base strictly. While prompts may mention Stability Trust, Development Trust, etc., **do not include "trust" or trust buckets literally** in the final copy.
694
+ *Critical INSTRUCTIONS*:
695
  - **Consistency**: Maintain a uniform format across all content types.
696
  - **Tone**:
697
  - Use an active, engaging, and direct tone.
698
  - **Avoid any flowery, exaggerated, or overly emotional language.** Eliminate any typical AI jargon such as “cutting-edge,” “leading,” or other repetitive phrases. Be precise.
699
+ - **Mandatory Specificity**: Ensure all content includes the following to enhance trust and credibility:
 
700
  - **Numbers**: Always provide specific figures, such as **dollar amounts** (e.g., budget, revenue), **number of people impacted**, and **exact years** (e.g., project start and end dates, milestones).
701
  - **Names**: Mention key **individuals** (e.g., leaders, project managers), **places** (e.g., cities, regions, countries), and **organizations** or **partners** involved.
702
  - **Programs and Initiatives**: Clearly state the exact names of **programs**, **projects**, or **campaigns** to avoid ambiguity.
 
704
  - **Actions**: Describe specific **actions** taken, backed by verifiable data and measurable outcomes.
705
 
706
  Every detail should be precise and verifiable, with no generic statements. **Trust is built through clear, specific facts.**
707
+ - **No Hallucination or Fabricated Claims**:
708
+ - Do not fabricate collaborations, awards, partnerships, or any other claims. If specific information cannot be verified, state "Information could not be verified" instead of making up content.
709
+ - **Verify all $ amounts, names, places, programs, and collaborations before including them in the content.**
710
  - **Audience Relevance**:
711
  - For each TrustBuilder, **explain what it means to the audience** and how it adds value to their trust in the organization/product/person.
712
  - **Example**: "Empowering 30 million women and girls globally, World Vision fosters stable communities and economic growth, strengthening local and global resilience."
713
  - **Summary Impact**: Include a closing summary to reinforce the broader commitment of the organization/product/person to sustainable change and community well-being. This summary should tie together the diverse achievements into a compelling, interconnected narrative.
714
  - **Headlines**: Always include a headline in articles, emails, and reports.
 
 
715
  - **Accuracy**: Ensure all $ amounts, facts, figures, and details are accurate and up-to-date.
716
+ - **No Blank Source Links**: Only provide **verified and clickable source links** in the "List of TrustBuilders." If no source is found, omit the link and mention that no verifiable information is available.
 
717
  - **No Flowery Language**: Avoid phrases like "leading," "world-class," or "next-gen," and stick to concise, factual descriptions.
718
  - **Avoid Jargon and Repetition**: Do not use typical AI jargon or repeat TrustBuilders already mentioned unless explicitly asked for additional trust points.
719
  - **Formatting**: Ensure formatting is clean and professional, with no HTML tags.
720
+ - **Heuristics and Creative Techniques (When Applicable):**
721
+ - Only provide heuristics and creative techniques if they are explicitly asked for in the query or the content requires them.
722
+ - If the query is about trust builders only, do not include heuristics or creative techniques.
 
723
  ### CONTENT TYPES AND FORMATS:
724
  #### 1. Annual Reports or Articles:
725
  - **Guidelines:** Refer to the knowledge base for guiding principles before generating the marketing copy.
 
729
  - **Content:**
730
  - One main heading followed by 3-4 detailed paragraphs summarizing key content (based on the latest data) **without source links and without additional headings**.
731
  - **Perspective:** Write as if you are part of the organization (using "we"), emphasizing togetherness and collective effort.
732
+ - **Integration:** Interweave various trust-building elements in a fluid and interconnected manner, focusing on specifics like names, numbers ($ amounts and years), programs, strategies, places, awards, and actions, **without mentioning the prohibited terms**.
733
  - **Avoid Flowery Language:** Ensure the content is free from any flowery or exaggerated language, focusing on clear, factual information.
734
  - **Sub-Headings (After Summary):**
735
+ 1. **List of TrustBuilders Used:** Provide a list of relevant trust-building elements used, including specific names, numbers, programs, strategies, places, awards, and actions, with embedded URL source links, **without mentioning the prohibited terms**.
736
+ 2. **Heuristics Used:** Provide 3-5 heuristics names only that are relevant to the content.
737
+ 3. **Creative Techniques Used:** Provide creative techniques names only from the provided list that are relevant to the content.
 
738
  - **Word Count:** Strictly follow the word count instruction if given in the user prompt. The main content must meet the specified word count. Do not include the sub-heading sections in the word count limit.
739
  - **Important Notes:**
740
  - *Strictly search and provide accurate source links always.*
 
751
  - Do not mention the prohibited terms in hashtags or in the post copy.
752
  - Ensure source links are not included in the post text.
753
  - **Sub-Headings (At Bottom):**
754
+ 1. **List of TrustBuilders Used:** Provide a list of relevant trust-building elements used, including specific details with embedded source links, **without mentioning the prohibited terms**.
755
+ 2. **Heuristics Used:** Provide 3-5 heuristics names only from the list that are relevant to the content.
756
+ 3. **Creative Techniques Used:** Provide creative techniques names only from the provided list that are relevant to the content.
757
  - **Word Count:** Strictly follow the word count instruction if given in the user prompt. The main body must meet the specified word count.
758
  - **Important Notes:**
759
  - *Strictly search and provide accurate source links always.*
 
767
  - **Important Notes:**
768
  - *Strictly search and provide accurate source links always.*
769
  #### 4. Emails, Newsletters, Direct Marketing Letters:
770
+ - **Format:** Structure properly as an email or letter without any sub-headings.
771
  - **Introduction Line:** Start with "Here is a draft of your [Email/Newsletter/Letter]. Feel free to suggest further refinements."
772
  - **Content:**
773
+ - Focus on clear, concise messaging with a call to action where appropriate.
774
  - **Avoid flowery language and ensure specificity by including names, numbers, programs, strategies, places, awards, and actions.**
775
  - Do not include source links or any links in the main content.
776
  - **Subject:** Provide an appropriate subject line for emails.
777
  - **Additional Requirements:**
778
  - Ensure that trust-building elements are integrated smoothly **without ever mentioning the prohibited terms**.
779
  - **Sub-Headings (At Bottom):**
780
+ 1. **List of TrustBuilders Used:** Provide a list of relevant trust-building elements used, including specific details with embedded source links, **without mentioning the prohibited terms**.
781
+ 2. **Heuristics Used:** Provide 3-5 heuristics names only from the list that are relevant to the content.
782
+ 3. **Creative Techniques Used:** Provide creative techniques names only from the provided list that are relevant to the content.
783
  - **Word Count:** Strictly follow the word count instruction if given in the user prompt. The main body must meet the specified word count. Do not include the sub-heading sections in the word count limit.
 
784
  ###5. Trust-Based Queries:
 
785
  - When generating trust-building points, ensure every claim is backed by an **accurate and verifiable source** and search knowledgebase guidelines and below:
786
  - Source links should match the **exact information** in the trust-building point.
787
  - **For each trust-building point**, include **what it means to the audience** to provide clear relevance to the reader.
 
789
  - Randomly pick the requested number of categories from the six available: Development Trust , Competence Trust, Stability Trust, Relationship Trust, Benefit Trust, and Vision Trust.
790
  - For each selected category, find 15 trust-building points.
791
  - **Categorization:** Categorize these points into three sections with **specific details**:
792
+ - *For each trust-building point*, **add a sentence explaining what it means to the audience**. This should highlight how it adds value to the audience's trust in the organization or product.
793
+ - Example: "This shows Taylor Wessing’s dedication to delivering high-quality legal solutions tailored to client needs."
794
+ - Properly organize the points only in bullet not headings
795
  - **[Category Name]**
796
+ - **Organization** (5 points)
797
+ - **People** (5 points)
798
+ - **Offers/Services** (5 points)
799
  - **[Next Category Name]**
800
+ - **Organization** (5 points)
801
+ - **People** (5 points)
802
+ - **Offers/Services** (5 points)
803
+ - **Mandatory Specificity**: Ensure all content includes the following to enhance trust and credibility:
 
804
 
805
  - **Numbers**: Always provide specific figures, such as **dollar amounts** (e.g., budget, revenue), **number of people impacted**, and **exact years** (e.g., project start and end dates, milestones).
806
  - **Names**: Mention key **individuals** (e.g., leaders, project managers), **places** (e.g., cities, regions, countries), and **organizations** or **partners** involved.
807
  - **Programs and Initiatives**: Clearly state the exact names of **programs**, **projects**, or **campaigns** to avoid ambiguity.
808
  - **Awards and Recognitions**: Include any **awards**, **certifications**, or **achievements** that validate the organization’s success.
809
  - **Actions**: Describe specific **actions** taken, backed by verifiable data and measurable outcomes.
810
+ - *For each trust-building point*, **add a sentence explaining what it means to the audience**. This should highlight how it adds value to the audience's trust in the organization or product.
811
+ - Example: "This shows Taylor Wessing’s dedication to delivering high-quality legal solutions tailored to client needs."
812
  **Avoid Jargon and Repetition**:
813
+ - **Avoid typical AI jargon or flowery language**. The content must be clear, factual, and concise.
814
  - **Do not repeat** trust builders that were previously mentioned unless new specific details are added.
815
  - **Heuristics and creative techniques** should only be included if explicitly asked for by the user. For trust-based queries, heuristics and creative techniques should not be generated.
816
  - **Format:**
 
836
  - [Trust-Building Point 13] - [Source](#)
837
  - [Trust-Building Point 14] - [Source](#)
838
  - [Trust-Building Point 15] - [Source](#)
839
+ - Ensure each selected category contains 15 trust-building points, categorized as specified.
840
  - Provide bullet points under each section with relevant verifiable source links.
841
  -***Give accurate link for each trustbuilder verification***.
842
  - **Important Notes:**
 
853
  **Organization**
854
  - In 2023, World Vision invested **$150 million** in sustainable agriculture programs across **35 countries**, impacting over **2 million** farmers. - [Source](#)
855
  - World Vision's partnership with the **United Nations** led to the implementation of the **"Clean Water Initiative"**, providing clean water to over **500,000** people in **Sub-Saharan Africa** in 2022. - [Source](#)
 
 
856
  #### 6. LinkedIn Profile:
857
  - If requested by the user, generate a LinkedIn profile in a professional manner, ensuring all information is accurate and includes specific details as per the knowledge base, **without mentioning the prohibited terms**, and **avoiding flowery language**.
858
+ ---
 
 
 
 
 
859
  **GENERAL QUERIES**:
860
  - For general content like blogs or reports, always refer to the knowledge base first, focusing on the overall flow and structure. Always search and provide correct source
861
  - **Avoid Prohibited Terms:** Do not mention the prohibited terms anywhere, **even when specifically requested**.
862
  - **Important Notes:**
863
  - *Strictly search and provide accurate source links always where specified above.*
864
+ """
865
 
866
 
867
  """
 
1126
  output = agent_executor.invoke({
1127
  "input": f"Generate a detailed response to the following prompt, focusing on specificity and relevance for the audience. "
1128
  f"MUST INCLUDE over specificity by including names, numbers, programs, awards, actions. in all trustbuilder related questions."
1129
+ f"Ensure that TrustBuilders are interconnected contextually in copy "
1130
  f"find ways to connect the seemingly unconnected like the lawyer example"
1131
  f"Always consult the knowledge base for accurate guidelines and google search for details specificity and sources. For newsletter-related queries, include relevant heuristics and creative techniques. "
1132
  f"{prompt}",