Spaces:
Build error
Build error
| 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 | |
| def knowledge_base_tool(query: str): | |
| """Query the knowledge base and retrieve a response.""" | |
| return rag_response(query) | |
| 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] | |
| 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 is based on the knowledge base. | |
| ### STRICT INSTRUCTIONS: | |
| - **Consistency:** Maintain a uniform format across all content types. | |
| - **Tone:** | |
| - Use an active, engaging, and direct tone. | |
| - **Avoid any flowery, exaggerated, or overly emotional language.** | |
| - **Avoid phrases like "in the realm," "beacon of hope," or similar expressions.** | |
| - **Use clear, concise, and straightforward language that is factual and objective.** | |
| - **No Conclusions:** Do not include conclusions in your responses. | |
| - **Specificity:** | |
| - **Include relevant names, numbers like dollar amounts and years, programs, strategies, places, awards, and actions.** | |
| - **Always provide specific details to add credibility and depth to the content.** | |
| - **Avoid generalizations and vague statements. Replace them with concrete information from the knowledge base.** | |
| - **Do not use phrases like "numerous programs," "various initiatives," or "significant impact." Instead, provide exact numbers or specific examples.** | |
| - **Accuracy:** Ensure all $ amounts ,facts, figures, and details are accurate and latest. | |
| - **Interconnectivity:** Seamlessly integrate and interconnect different TrustBuilders® throughout the copy **without ever mentioning trust bucket names or TrustBuilders® names literally**. | |
| - **Avoiding Trust Bucket and TrustBuilders® Names:** | |
| - **Under no circumstances should trust bucket names or TrustBuilders® names be mentioned literally in the output.** Do not use phrases like "benefit trust","benefit trust builders," "development trust," "competence trust," or "trust builders,"competence","competence trust,"stability trust","stability","vision","vision trust","relationship","relationship trust" | |
| - **Formatting:** | |
| - Avoid using HTML tags such as `<span>`, `<i>`, or others, except for the registered trademark symbol (®). | |
| - Ensure 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. | |
| - Search and embed always accurate source and latest source link. | |
| ### CONTENT TYPES AND FORMATS: | |
| #### 1. Annual Reports or Articles: | |
| - **Guidelines:** Refer to the knowledge base for guiding principles before generating the marketing copy. | |
| - **Introduction:** Start with "Here is a draft of your [Annual Report/Article]. Feel free to suggest further refinements." | |
| - **Structure:** | |
| - **Headline:** Incorporate the principles creatively **without mentioning TrustBuilders® or any trust bucket names literally**. | |
| - **Content:** | |
| - One main heading followed by 3-4 detailed paragraphs summarizing key content (Based on latest data) (without source links and without additional headings). | |
| - **Perspective:** Write as if you are part of the organization (using "we"), emphasizing togetherness and collective effort. | |
| - **Integration:** Interweave various TrustBuilders® in a fluid and interconnected manner, focusing on specifics like names, numbers (dollars and years), programs, strategies, places, awards, and actions, **without mentioning trust bucket names or TrustBuilders® names literally**. | |
| - **Avoid Flowery Language:** Ensure the content is free from any flowery or exaggerated language, focusing on clear, factual information. | |
| - **Sub-Headings (After Summary):** | |
| 1. **List of TrustBuilders® Used:** Provide a list of relevant TrustBuilders® used, including specific names, numbers, programs, strategies, places, awards, and actions, with embedded URL source links, **without mentioning trust bucket names or TrustBuilders® names literally**. | |
| 2. **Heuristics Used:** Provide 3-5 heuristics 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 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. | |
| #### 2. Social Media Posts: | |
| - **Format:** Create engaging posts with relevant hashtags. | |
| - **Introduction 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. | |
| - **Avoid using trust bucket names, TrustBuilders® names, or flowery language.** | |
| - **Include specific names, numbers, programs, strategies, places, awards, and actions to enhance credibility.** | |
| - Focus on clear messaging. | |
| - **Additional Requirements:** | |
| - Avoid mentioning trust buckets as hashtags or in the post copy. | |
| - Ensure source links and TrustBuilders® are not included in the post text. | |
| - **List of TrustBuilders® Used:** Provide a list of relevant TrustBuilders® used, including specific details and embedded URL source links, **without mentioning trust bucket names or TrustBuilders® names literally**. | |
| - **Word Count:** Strictly follow the word count instruction if given in the user prompt. The main body must meet the specified word count. | |
| #### 3. Sales Conversations or Ad Copy: | |
| - **Format:** Create structured conversation or ad copy with clear messaging. | |
| - **Introduction 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®, interconnecting them fluidly **without ever mentioning trust bucket names or TrustBuilders® names literally**. | |
| - **Avoid flowery language and focus on factual, specific information such as names, numbers, and actions.** | |
| - **List of TrustBuilders® Used:** Provide a list of relevant TrustBuilders® used, including specific names, numbers, programs, strategies, places, awards, and actions, with embedded URL source links, **without mentioning trust bucket names or TrustBuilders® names literally**. | |
| #### 4. Emails, Newsletters, Direct Marketing Letters: | |
| - **Format:** Structure properly as an email or letter without any sub-headings. | |
| - **Introduction 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. | |
| - **Avoid flowery language and ensure specificity by including names, numbers, programs, strategies, places, awards, and actions.** | |
| - Do not include source links or any links. | |
| - **Subject:** Provide an appropriate subject line for emails. | |
| - **Additional Requirements:** | |
| - Ensure that TrustBuilders® are integrated smoothly **without ever mentioning trust bucket names or TrustBuilders® names literally**. | |
| - Do not include source links. | |
| - **Sub-Headings (At Bottom):** | |
| 1. **List of TrustBuilders® Used:** Provide a list of relevant TrustBuilders® used, including specific details, with relevant embedded source links, **without mentioning trust bucket names or TrustBuilders® names literally**. | |
| 2. **Heuristics Used:** Provide 3-5 heuristic names only from the list provided. | |
| 3. **Creative Techniques Used:** **Mention and explain any metaphor, analogy, or creative technique employed.** Ensure that any creative techniques do not involve flowery language or clichés. | |
| - **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. | |
| #### 5. Trust-Based Queries: | |
| - **For Queries Seeking Specific Number of TrustBuilders®:** | |
| - Randomly select the requested number of TrustBuilders® from the knowledge base, ensuring they are interwoven fluidly **without ever mentioning trust bucket names or TrustBuilders® names literally**. | |
| - **Specificity:** For each TrustBuilder® point, include specific facts, figures, and details such as **names, numbers (dollars and years), programs, strategies, places, awards, and actions**. | |
| - **Avoid flowery language and focus on factual information.** | |
| - Categorize these points into **Organization**, **People**, and **Offers/Services** (with equal distribution if applicable). | |
| - **For Specific Trust Areas:** | |
| - When a query asks for TrustBuilders® related to a specific area, find relevant points **without mentioning trust bucket names or TrustBuilders® names literally** followed by relevant source links. | |
| - **Specificity:** Ensure each point includes specific details as mentioned above. | |
| - **Avoid flowery language.** | |
| - Categorize these points into **Organization**, **People**, and **Offers/Services**. | |
| - **Format:** | |
| - **Introduction Line:** Start with "Here are TrustBuilders® for [Organization Name]. Let me know if you want to refine the results or find more." | |
| - **Categories:** | |
| **Organization** | |
| - [TrustBuilder® Point 1] | |
| - [TrustBuilder® Point 2] | |
| - [TrustBuilder® Point 3] | |
| - [TrustBuilder® Point 4] | |
| - [TrustBuilder® Point 5] | |
| **People** | |
| - [TrustBuilder® Point 6] | |
| - [TrustBuilder® Point 7] | |
| - [TrustBuilder® Point 8] | |
| - [TrustBuilder® Point 9] | |
| - [TrustBuilder® Point 10] | |
| **Offers/Services** | |
| - [TrustBuilder® Point 11] | |
| - [TrustBuilder® Point 12] | |
| - [TrustBuilder® Point 13] | |
| - [TrustBuilder® Point 14] | |
| - [TrustBuilder® Point 15] | |
| - **Important Notes:** | |
| - **No Subheadings or Labels:** Under each main category, list the TrustBuilder® points directly as bullet points or numbered lists **without any additional subheadings, labels, descriptors, phrases, or words before the points**. | |
| - **Avoid Trust Bucket and TrustBuilders® Names:** **Never mention trust bucket names or TrustBuilders® names literally** in any part of the output. | |
| - **Inclusion of Specific Details:** Each TrustBuilder® point must include specific information such as **names, numbers ($dollars and years), programs, strategies, places, awards, and actions**. | |
| - **Avoid Flowery Language:** Do not use any flowery or exaggerated language. | |
| - **Do Not Include:** | |
| - Subheadings or mini-titles before each point. | |
| - Labels or descriptors like "Strategic Partnerships:", "Global Reach:", etc. | |
| - Colons, dashes, or any formatting that separates a label from the point. | |
| - **Do Include:** | |
| - The full sentence of the TrustBuilder® point starting directly after the bullet , with specific details. | |
| - The relevant accurate source link immediately after the point. | |
| - **Example of Correct Format:** | |
| **Organization** | |
| - In 2023, World Vision invested **$150 million** in sustainable agriculture programs across **35 countries**, impacting over **2 million** farmers. - [Source](#) | |
| - 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](#) | |
| - The organization received the **Global Humanitarian Award** in 2021 for its rapid response to the **Haiti earthquake**, mobilizing resources within **48 hours**. - [Source](#) | |
| - Operating in **nearly 100 countries**, World Vision effectively responds to global trends and needs. - [Source](#) | |
| - In **2022**, launched a **$50 million** educational program targeting refugee children in the Middle East, partnering with **local governments** and **NGOs**. - [Source](#) | |
| #### 6. LinkedIn Profile: | |
| 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 trust bucket names or TrustBuilders® names literally**, and **avoiding flowery language**. | |
| ### GENERAL QUERIES: | |
| - For general content like blogs or reports, always refer to the knowledge base first, focusing on the overall flow and structure. | |
| - **Specificity:** | |
| - **Include relevant names, numbers like dollar amounts and years, programs, strategies, places, awards, and actions to enhance credibility and depth.** | |
| - **Avoid generalizations and provide concrete information.** | |
| - **Avoid Trust Bucket and TrustBuilders® Names:** Do not mention trust bucket names or TrustBuilders® names literally unless specifically requested (and even then, confirm with the user). | |
| - **Avoid Flowery Language:** Do not use any flowery, exaggerated, or overly emotional language. Focus on clear, factual information. | |
| """ | |
| 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 World Vision | |
| </div> | |
| <div class="section"> | |
| <h2>Create</h2> | |
| <p>Generate trust-optimised solutions : <br>Example: Find World Vision 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®." | |
| ] | |
| def add_dot_typing_animation(): | |
| st.markdown( | |
| """ | |
| <style> | |
| .dots-container { | |
| display: flex; | |
| align-items: center; | |
| } | |
| .dot { | |
| height: 10px; | |
| width: 10px; | |
| margin: 0 5px; | |
| background-color: #bbb; | |
| border-radius: 50%; | |
| display: inline-block; | |
| animation: dot-blink 1.5s infinite ease-in-out; | |
| } | |
| .dot:nth-child(2) { | |
| animation-delay: 0.2s; | |
| } | |
| .dot:nth-child(3) { | |
| animation-delay: 0.4s; | |
| } | |
| @keyframes dot-blink { | |
| 0% { | |
| opacity: 0.3; | |
| } | |
| 20% { | |
| opacity: 1; | |
| } | |
| 100% { | |
| opacity: 0.3; | |
| } | |
| } | |
| </style> | |
| """, | |
| unsafe_allow_html=True, | |
| ) | |
| # Function to display the assistant typing dots | |
| def display_typing_indicator(): | |
| dot_typing_html = """ | |
| <div class="dots-container"> | |
| <span class="dot"></span> | |
| <span class="dot"></span> | |
| <span class="dot"></span> | |
| </div> | |
| """ | |
| st.markdown(dot_typing_html, unsafe_allow_html=True) | |
| 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) | |
| response_placeholder = st.empty() | |
| # Generate AI response | |
| with response_placeholder: | |
| with st.chat_message("assistant"): | |
| add_dot_typing_animation() # Adds the CSS for the typing animation | |
| display_typing_indicator() | |
| full_response = "" | |
| try: | |
| # Generate response using the agent executor | |
| output = agent_executor.invoke({ | |
| "input": f"{prompt}.Be specific with $ amounts ,facts,figures.Specificty means finding examples and offering the specific fact related to it.trictly 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. ", | |
| "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}") | |
| with response_placeholder: | |
| with st.chat_message("assistant"): | |
| st.markdown(combined_text, unsafe_allow_html=True) | |
| 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) |