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(""" """, 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"""
Copied!
""" 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'.*?', '', 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("""

Stability Trust:

Why can I trust you to have built a strong and stable foundation?

Development Trust:

Why can I trust you to develop well in the future?

Relationship Trust:

What appealing relationship qualities can I trust you for?

Benefit Trust:

What benefits can I trust you for?

Vision Trust:

What Vision and Values can I trust you for?

Competence Trust:

What competencies can I trust you for?

""", 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] 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 the 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 ``, ``, 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 the knowledge base for guiding principles for the generation of marketing copy before generating a 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 a list of relevant trust builders used with facts and figures with embedded URL source links every time. 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 the word count instruction if given in the 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 the word count instruction if given in the 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 seeks a specific number of trust builders (e.g., "5 trust builders"), the AI should: - Randomly pick the requested number of trust buckets from the six available: Development Trust, Competence Trust, Stability Trust, Relationship Trust, Benefit Trust, and Vision Trust. - For each selected bucket, find 15 TrustBuilders® points. - Categorize these points into Organization, People, and Offers/Services (with 5 points for each category). - **For Specific Trust Buckets:** - When a query asks for a specific trust bucket (e.g., "Development Trust builders"), find 15 TrustBuilders® points specifically for that bucket. - Categorize these points into Organization, People, and Offers/Services (with 5 points for each category). - **Format:** - **Introduction Line:** Start with "Here are TrustBuilders® for [Selected Trust Buckets] at [Organization Name]. Let me know if you want to refine the results or find more." - **Categories:** - **Organization:** - [Trust Builder Point 1] - [Source](#) - [Trust Builder Point 2] - [Source](#) - [Trust Builder Point 3] - [Source](#) - [Trust Builder Point 4] - [Source](#) - [Trust Builder Point 5] - [Source](#) - **People:** - [Trust Builder Point 6] - [Source](#) - [Trust Builder Point 7] - [Source](#) - [Trust Builder Point 8] - [Source](#) - [Trust Builder Point 9] - [Source](#) - [Trust Builder Point 10] - [Source](#) - **Offers/Services:** - [Trust Builder Point 11] - [Source](#) - [Trust Builder Point 12] - [Source](#) - [Trust Builder Point 13] - [Source](#) - [Trust Builder Point 14] - [Source](#) - [Trust Builder Point 15] - [Source](#) - Ensure each selected bucket contains 15 TrustBuilders® points, categorized as specified. - Provide bullet points under each section with relevant source links. 6. **LinkedIn Profile :** If asked by user , Generate LinkedIn profile in professional manner . **GENERAL QUERIES:** - For general content like blogs or reports, always refer to the knowledge base first, focusing 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("""

How can I help you today?

Find

Discover all your great TrustBuilders®.
Example: Find Development Trust Builders® for World Vision

Create

Generate trust-optimised solutions :
Example: Find World Vision development TrustBuilders®. Then use them to write a 200-word annual report article. Enthusiastic tone.

Trust-optimise

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.

""", 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'
', '', cleaned_text) #cleaned_text = re.sub(r']*>', '', 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)