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"""
Why can I trust you to have built a strong and stable foundation?
Why can I trust you to develop well in the future?
What appealing relationship qualities can I trust you for?
What benefits can I trust you for?
What Vision and Values can I trust you for?
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("""Discover all your great TrustBuilders®.
Example: Find Development Trust Builders® for World Vision
Generate trust-optimised solutions :
Example: Find World Vision development TrustBuilders®. Then use them to write a 200-word annual report article. Enthusiastic tone.
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.