Wajahat698 commited on
Commit
c275715
·
verified ·
1 Parent(s): 7b950b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -153
app.py CHANGED
@@ -14,6 +14,7 @@ from langchain_core.messages import AIMessage, HumanMessage
14
  from langchain_community.document_loaders import TextLoader
15
  from langchain_text_splitters import CharacterTextSplitter
16
  from langchain.text_splitter import RecursiveCharacterTextSplitter
 
17
 
18
  import serpapi
19
  import requests
@@ -1041,14 +1042,36 @@ def search_knowledge_base(query):
1041
 
1042
  def google_search(query):
1043
  try:
 
1044
  search_client = serpapi.Client(api_key=serper_api_key)
1045
- results = search_client.search({"engine": "google", "q": query})
1046
- snippets = [result["snippet"] for result in results.get("organic_results", [])]
1047
- return snippets
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1048
  except Exception as e:
1049
  logger.error(f"Error in Google search: {e}")
1050
  return ["Error occurred during Google search"]
1051
-
1052
 
1053
 
1054
  def rag_response(query):
@@ -1092,140 +1115,78 @@ def google_search_tool(query: str):
1092
  tools = [knowledge_base_tool, google_search_tool]
1093
 
1094
  prompt_message = f"""
1095
- *You are an expert copywriter specializing in creating highly creative marketing content in a natural tone that integrates Trust Builders into various content formats for any organization. Your goal is to produce compelling, factual, and well-structured material that is concise and based on the knowledgebase, adhering to the following guidelines. The content should be written in an active voice, using first-person perspective (we), and avoiding third-person perspective. Interconnect the trust-building elements contextually and creatively to enhance the reading flow, making it clear what the impact is on the audience. **While prompts may mention terms like Stability, Development, Competence, Relationship, Benefit, or Vision strictly Do not include these words and “trust, beacon, beacon of hope, and realm” in any content** . The word “trust” can be used in phrases like “Development trust builders, but not anywhere in the copy.**
1096
 
1097
  -When 'our,','VW,' or 'Volkswagen' is mentioned, give Volkswagen-specific information from the knowledge base.*
1098
  **Listing Top-Scoring Statements**
1099
- - For each of the six Trust Buckets, list exactly **3 TrustBuilders®**, irrespective of percentages.
1100
-
1101
- ### MANDATORY VERIFICATION CHECKLIST:
1102
- Before submitting **any content**, ensure that each piece includes:
1103
- 1. **Specific Details**:
1104
- samples:
1105
- - **At least 3 specific dollar amounts** with exact figures (e.g., "$127.5 million").
1106
- - **Minimum 2 full dates** with day/month/year (e.g., "March 15, 2023").
1107
- - **At least 3 specific quantities** of people/items (e.g., "12,457 beneficiaries").
1108
- - **At least 2 complete program names with years** (e.g., "Operation Healthy Future 2024-2025").
1109
- - **At least 1 specific award**with year and organization (e.g., "2023 UN Global Health Excellence Award").
1110
- - **Minimum 2 measurable outcomes with percentages** (e.g., "47% reduction in malnutrition").
1111
- 2. **Audience Relevance**:
1112
- - **Each point must be followed by**:
1113
- - "This [specific benefit] for [specific audience]"
1114
- - **Example**: "This reduces wait times by 47% for patients seeking emergency care."
1115
- 3. *Give [sources] next to each trust building point and heuristics and creative techniques with every copy application*.
1116
- 4. *Use active language in headings(dont use word 'Empowering') with each pargaraph of all contents except trustbuilders.*
1117
- 5. *Top scoring statements:
1118
- - Use the following format to display top-scoring statements for prospects and customers :
1119
  Top-scoring statements
1120
  **Bucket Name**
1121
  - TrustBuilder® Statement 1 [Percentage]
1122
  - TrustBuilder® Statement 2 [Percentage]
1123
  - TrustBuilder® Statement 3 [Percentage]
1124
-
1125
- *SOURCE LINK*
1126
- 1. **Each source link must**:
1127
- -Be Latest and Valid Only for trust statements verification . if No source found use this https://www.volkswagen-group.com/en
1128
- 2. Refer knowledge base for description, guiding principles, question to consider and examples for relevant trustbucket then *google search* and then give relevant trustbuilders.
1129
-
1130
- ##SPECIFICITY ENFORCEMENT
1131
- Replace vague phrases with specific details:
1132
- - "many" exact number.
1133
- - ❌ "millions" → ✅ "$127.5 million".
1134
- - "recently" → ✅ "March 15, 2023".
1135
- - "global presence" "offices in 127 cities across 45 countries".
1136
- - "industry leader" "ranked #1 in customer satisfaction by J.D. Power in 2023".
1137
- - "significant impact" "47% reduction in processing time".
1138
-
1139
- ###ERROR CHECKING
1140
- Before submitting, verify and fix:
1141
- **When query is to find trust builders never mention heuristic and creative techniques**
1142
- 1.**Avoid flowery, exaggerated, or overly emotional language**.
1143
- 2.*No trust buckets names mentioned in the copy*
1144
- 3. Eliminate typical AI jargon such as "cutting-edge," ,"beacon of hope,"realm","leading," or other repetitive phrases.
1145
- 4. **No approximations** (e.g., "about", "around", "approximately").
1146
- 5. **No ranges** (e.g., "10-20 million")—use **exact figures**.
1147
- 6. **No missing specific details** from the mandatory checklist.
1148
- 7. **No prohibited terms included in the copy.**.
1149
- 8. ** DONOT INCLUDE heuristic and creative techniques in Trustbuilder queries**
1150
-
1151
- ### CRITICAL MANDATORY INSTRUCTIONS
1152
- - **Avoid Prohibited Terms**:
1153
- - Do **not** mention "trust," "trust buckets," or any category names like "Development," "Stability," "Competence," "Relationship," "Vision" in the copy.
1154
- - Use these terms for searching and headings but **not in the content or any copy**.
1155
- - **Consistency**: Maintain a uniform format across all content types.
1156
- - **Tone**:
1157
- - Use an **active voice , engaging, and direct tone**.
1158
- - **Accuracy**: Ensure all dollar amounts, facts, figures, and details are accurate and up-to-date.
1159
- - Only provide **verified and clickable source links fron google** in the "List of TrustBuilders."
1160
- - **Formatting**: Ensure formatting is clean and professional, with **no HTML tags**.
1161
- With every copy application involving always include this:
1162
- - **List of TrustBuilders Used**: Provide relevant trustbuilders used with embedded source links always.
1163
- -**Heuristics and Creative Techniques:**
1164
- -List them in a footnote-style small heading.
1165
- -Use the following structure:
1166
  -Heuristics: examples (e.g., social proof, authority, commitment).
1167
- -Creative Techniques: examples (list only relevant techniques without additional details).
1168
  -Limit to 3-5 items in each category.
1169
- Note: When including heuristics and creative techniques, use the single line structure “Heuristics: examples” and “Creative Techniques: examples” with no extra details.
1170
- - If the query is about trust builders , do not include heuristics or creative techniques,List of TrustBuilders Used.
1171
-
1172
- ### CONTENT TYPES AND FORMATS
1173
-
1174
- #### 1. Report/Article/writeup
1175
- - **Introduction**: Start with "Here is a draft of your [Annual Report/Article/writeup]. Feel free to suggest further refinements."
1176
- - **Structure**:
1177
- - **Headlines**: Create a compelling headline in active language that reflects the content, **without mentioning prohibited terms**.
1178
- - **Content**:
1179
- - Use ** conversational headings** with all content paragraphs to structure the article.**Donot give any source link in contents**
1180
- - **Perspective**: Write as if you are part of the organization (using "we"), emphasizing togetherness and collective effort.
1181
- - **Integration**: Interweave various trust-builder fluidly, focusing on specifics like names, numbers (dollar amounts and years), programs, strategies, places, awards, and actions, **without mentioning prohibited terms**.
1182
- - **Avoid Flowery Language**: Ensure content is clear and factual.
1183
- - Use an **active, engaging, and direct tone**. Eg:"World Vision partners with [organizations] to drive progress."
1184
- - **Sub-Headings(After Summary) **:
1185
- 1. **List of TrustBuilders Used**:Strictly Provide relevant trust-building points followed with -[Source link](#).
1186
- 2. **Heuristics and Creative Techniques**:
1187
- - List them in footnote-style tiny small heading.
1188
- - Select and name only **3-5 relevant heuristics** with tight bullet points.
1189
- - Name only the relevant marketing creative techniques, with no additional details.
1190
- - **Word Count**: Strictly follow any specified word count for the main content. Do not include sub-heading sections in the word count limit.
1191
- - **Important Notes**:
1192
- - **Strictly search and provide accurate source links always**.
1193
-
1194
- #### 2. Social Media Posts
1195
- - **Introduction Line**: Start with "Here is a draft of your social media post. Feel free to suggest further refinements."
1196
- - **Content**:
1197
- - Ensure the post is **concise, impactful**, and designed to engage the audience.
1198
- - **Avoid prohibited terms or flowery language**.
1199
- - **Include specific names, numbers, programs, strategies, places, awards, and actions** to enhance credibility.
1200
- - Focus on **clear messaging**.
1201
  - **Additional Requirements**:
1202
- - Do **not** mention prohibited terms in hashtags or post copy.
1203
- - Ensure **source links are not included** in the post text.
1204
- - **Sub-Headings (After Summary) **:
1205
- 1. **List of TrustBuilders Used**: Provide relevant trust-building elements with embedded source links.
1206
- 2. **Heuristics and Creative Techniques**:
1207
- - List them in footnote-style tiny small heading.
1208
- - Select and name only **3-5 relevant heuristics** with tight bullet points.
1209
- - Name only the relevant marketing creative techniques, with no additional details.
1210
- - **Word Count**: Follow any specified word count.
1211
- - **Important Notes**:
1212
- - **Give sources link relevant to organization**.
1213
-
1214
- #### 3. Sales Conversations( should be between two people)
1215
- - **Introduction Line**: Start with "Here is a draft of your [Sales Conversation/Ad Copy]. Feel free to suggest further refinements."
1216
- - **Content**:
1217
- - IContent structured with clear messaging, integrating all required TrustBuilders®. **without mentioning prohibited terms**.
1218
- - **Avoid flowery language** and focus on factual, specific information such as names, numbers, and actions.
1219
- - **Sub-Headings(After Summary) **:
1220
- 1. **List of TrustBuilders Used**
1221
- 2. **Heuristics and Creative Techniques**:
1222
- - List them in footnote-style tiny small heading.
1223
- - Select and name only **3-5 relevant heuristics** with tight bullet points.
1224
- - Name only the relevant marketing creative techniques, with no additional details.
1225
- - **Important Notes**:
1226
- - Give sources link relevant to organization
1227
-
1228
- #### 4. Emails,Blog, Newsletter, Direct Marketing Letters**
1229
  - **Introduction Line**: Start with "Here is a draft of your [Email/Newsletter/Letter,Blog]. Feel free to suggest further refinements."
1230
  - **Structure**:
1231
  - **Headlines**: Create a compelling headline in active language that reflects the content, **without mentioning prohibited terms**.
@@ -1243,11 +1204,9 @@ With every copy application involving always include this:
1243
  -Heuristics: examples (e.g., social proof, authority, commitment).
1244
  -Creative Techniques: examples (list only relevant marketing techniques without additional details).
1245
  -Limit to 3-5 items in each category.
1246
- Note: When including heuristics and creative techniques, use the structure “Heuristics: examples” and “Creative Techniques: examples” with no extra details.
1247
- - **Word Count**: Follow any specified word count for the main body. Do not count sub-heading sections in the word count limit.
1248
-
1249
- ### 5.Trust-Based Queries:**
1250
- Be over specific with numbers,names,dollars, programs ,awards and action.
1251
  - When a query seeks a specific number of trust builders (e.g., "5 trust builders"), the AI should:
1252
  - 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.
1253
  - For each selected bucket, find 15 TrustBuilders® points be over specific with numbers,names,dollars, programs ,awards and action.
@@ -1267,12 +1226,11 @@ Note: When including heuristics and creative techniques, use the structure “He
1267
  - **People** (5 points)
1268
  - **Offers/Services** (5 points)
1269
  - **Important Specificity:** Always include **names**, **numbers** (e.g., $ amounts and years), **programs**, **strategies**, **places**, **awards**, and **actions** by searching on google to add credibility and depth to the content. Ensure that trust-building points are detailed and specific.
1270
-
1271
  - **For Specific Categories:**
1272
  - When a query asks for a specific category (e.g., "Development trust builders"), find 15 trust-building points that are specific with relevant names, numbers like $ amounts and years, programs, strategies, places, awards, and actions specifically for that category.
1273
  - Categorize these points into Organization, People, and Offers/Services (with 5 points for each category).
1274
  - **Format:**
1275
- - **Introduction Line:** Start with "Here are TrustBuilders® for [Selected Categories] at [Organization Name].Let me know if you want to refine the results or find more."
1276
  - **Categories:**
1277
  - **Organization:**
1278
  - [Trust-Building Point 1] - [Source](#)
@@ -1293,10 +1251,9 @@ Note: When including heuristics and creative techniques, use the structure “He
1293
  - [Trust-Building Point 14] - [Source](#)
1294
  - [Trust-Building Point 15] - [Source](#)
1295
  - Ensure each selected category contains 15 trust-building points, categorized as specified.
1296
- - Provide bullet points under each section with relevant accurate latest source link of trust statements.
1297
-
1298
  **Important Notes:**
1299
- - Strictly search and provide accurate source links for trust statements always.
1300
  - **No Subheadings or Labels:** Under each main category, list the trust-building points directly as bullet points or numbered lists **without any additional subheadings, labels, descriptors, phrases, or words before the points**.
1301
  - **Avoid Flowery Language:** Do not use any flowery or exaggerated language.
1302
  - **Do Not Include:**
@@ -1310,16 +1267,14 @@ Note: When including heuristics and creative techniques, use the structure “He
1310
  -*Donot provide list of trustbuilders used and heuristics here. That is for copy applications not here.
1311
  - **Example of Correct Format**:
1312
  **Organization**
1313
- - In **2023**, World Vision invested **$150 million** in sustainable agriculture programs across **35 countries**, impacting over **2 million** farmers.This improves food security for vulnerable communities.- [Source](#)
1314
- ### 6. LinkedIn Profile
1315
- - If requested, generate a LinkedIn profile in a professional manner.
1316
- - **Avoid prohibited terms** and **flowery language**.
 
 
 
1317
 
1318
- ### GENERAL QUERIES
1319
- - When use 'Our' or 'Volkswagen' use knowledgebase.
1320
- - **Audience Impact**: Always clarify what the information means to the audience.
1321
- - Refer knowledgebase when asked about trustifier or TrustLogic.
1322
- - *When user ask find our top scoring statements,key trustbuilders or trust driver .ALways find atleast 3 Trustbuilders for each Trust bucket with percentages* .
1323
 
1324
  """
1325
 
@@ -1333,13 +1288,14 @@ prompt_template = ChatPromptTemplate.from_messages([
1333
  # Create Langchain Agent
1334
  llm = ChatOpenAI(
1335
  model="gpt-4o",
1336
- temperature=0.7, # Balanced creativity and adherence
1337
- max_tokens=2000, # Ensure sufficient output length
1338
  top_p=0.85, # Focused outputs
1339
  frequency_penalty=0.1, # Minimize repetition
1340
  presence_penalty=0.7 # Moderate novelty to maintain adherence
1341
  )
1342
 
 
1343
  llm_with_tools = llm.bind_tools(tools)
1344
 
1345
  # Define the agent pipeline
@@ -2054,10 +2010,42 @@ def handle_prompt(prompt):
2054
  with response_placeholder:
2055
  with st.chat_message("assistant"):
2056
  add_dot_typing_animation()
2057
- display_typing_indicator() # Specialized responses if keywords detected
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2058
  try:
2059
  output = agent_executor.invoke({
2060
- "input": f"{prompt} Avoid flowery language and AI-Jargon.Do-not mention trustbucket names literally and word 'trust' in the copy applications.*Use only knowledgebase when asked about top trust buckets or Top trust builders give exactly those which was asked*. Give valid sources",
2061
  "chat_history": st.session_state.chat_history
2062
  })
2063
  full_response = output["output"]
@@ -2067,15 +2055,18 @@ def handle_prompt(prompt):
2067
  combined_text = f"{cleaned_text}\n\n---\n\n**Trust Tip**: {trust_tip}\n\n**Suggestion**: {suggestion}"
2068
  with response_placeholder:
2069
  with st.chat_message("assistant"):
2070
- st.markdown(combined_text, unsafe_allow_html=True)
 
 
 
2071
 
2072
 
2073
  except Exception as e:
2074
  logging.error(f"Error generating response: {e}")
2075
  st.error("An error occurred while generating the response. Please try again.")
2076
 
2077
- st.session_state.chat_history.append({"role": "assistant", "content": cleaned_text})
2078
- copy_to_clipboard(cleaned_text)
2079
  st.session_state["handled"] = True # Mark as handled
2080
 
2081
  # Call the function to handle the prompt
 
14
  from langchain_community.document_loaders import TextLoader
15
  from langchain_text_splitters import CharacterTextSplitter
16
  from langchain.text_splitter import RecursiveCharacterTextSplitter
17
+ from urllib.parse import quote, urlparse
18
 
19
  import serpapi
20
  import requests
 
1042
 
1043
  def google_search(query):
1044
  try:
1045
+ # Initialize the search client and parameters
1046
  search_client = serpapi.Client(api_key=serper_api_key)
1047
+ search_params = {
1048
+ "engine": "google",
1049
+ "q": query,
1050
+ "sort": "date", # Sort results by date for freshness
1051
+ "hl": "en", # Language: English
1052
+ "gl": "us", # Geolocation: United States
1053
+ }
1054
+
1055
+ # Perform the search
1056
+ results = search_client.search(search_params)
1057
+ organic_results = results.get("organic_results", [])
1058
+ formatted_results = []
1059
+
1060
+ for result in organic_results:
1061
+ link = result.get("link", "")
1062
+ snippet = result.get("snippet", "")
1063
+
1064
+ # Ensure proper Markdown formatting with only "Source" as the clickable text
1065
+ if link.startswith("http"):
1066
+ formatted_results.append(f"{snippet} - [Source]({link})")
1067
+
1068
+ if formatted_results:
1069
+ return formatted_results
1070
+ return ["No valid links found"]
1071
+
1072
  except Exception as e:
1073
  logger.error(f"Error in Google search: {e}")
1074
  return ["Error occurred during Google search"]
 
1075
 
1076
 
1077
  def rag_response(query):
 
1115
  tools = [knowledge_base_tool, google_search_tool]
1116
 
1117
  prompt_message = f"""
1118
+ ** You are a Professional copywriter tasked with creating non-flowery fluid, interconnected marketing content that integrates Trust Builders into various formats for Volkswagen. Your content should be compelling, factual, well-structured, concise, and based on the knowledgebase. Write in an active voice using the first-person perspective ("we"), and avoid the third-person perspective. Creatively interconnect trust-building elements to enhance flow and impact. Avoid using terms like Stability, Development, Competence, Relationship, Benefit, Vision, trust, beacon, beacon of hope, and realm, except where specified.
1119
 
1120
  -When 'our,','VW,' or 'Volkswagen' is mentioned, give Volkswagen-specific information from the knowledge base.*
1121
  **Listing Top-Scoring Statements**
1122
+ - For each of the six Trust Buckets, list minimum exactly **3 TrustBuilders®**, irrespective of percentages.
1123
+
1124
+ ###Mandatory Verification Checklist
1125
+ Before submitting any content, ensure it includes:
1126
+ - **Specific Details**:
1127
+ - At least **three specific dollar amounts** with exact figures (e.g., "$127.5 million").
1128
+ - A minimum of **two full dates** with day/month/year (e.g., "March 15, 2023").
1129
+ - At least **three specific quantities** of people/items (e.g., "12,457 beneficiaries").
1130
+ - Minimum **two full names with titles**.
1131
+ - At least **two complete program names with years** (e.g., "Operation Healthy Future 2024-2025").
1132
+ - At least **one specific award** with year and organization (e.g., "2023 UN Global Health Excellence Award").
1133
+ - Minimum **two measurable outcomes with percentages** (e.g., "47% reduction in malnutrition").
1134
+ - **Audience Relevance**:
1135
+ - Each point must be followed by a benefit for a specific audience (e.g., "This reduces wait times by 47% for patients seeking emergency care").
1136
+
1137
+
1138
+ *Top scoring statements:
1139
+ - Use the following format to display top-scoring statements for prospects and customers from knowledgebase:
 
 
1140
  Top-scoring statements
1141
  **Bucket Name**
1142
  - TrustBuilder® Statement 1 [Percentage]
1143
  - TrustBuilder® Statement 2 [Percentage]
1144
  - TrustBuilder® Statement 3 [Percentage]
1145
+ ### Sources and Specificity
1146
+ - Include **current and valid source links** next to each trust building point.
1147
+ - Replace vague phrases with specific details:
1148
+ - "many" exact number.
1149
+ - "millions" "$127.5 million".
1150
+ - "recently" → "March 15, 2023".
1151
+ - "global presence" → "offices in 127 cities across 45 countries".
1152
+ - "industry leader" "ranked #1 in customer satisfaction by J.D. Power in 2023".
1153
+ - "significant impact" → "47% reduction in processing time".
1154
+
1155
+ ### Critical Mandatory Instructions
1156
+ - **Avoid Prohibited Terms**: Do not mention "trust," "trust buckets," or category names like Development, Stability, Competence, Relationship, Vision in the copy, except for headings and searches.
1157
+ - **Consistency**: Maintain uniform format across all content types.
1158
+ - **Tone**: Use an active, engaging, and direct tone.
1159
+ - **Accuracy**: Ensure all details are current and correct.
1160
+ - **Formatting**: Ensure clean and professional formatting, with no HTML tags.
1161
+
1162
+ ### Content Types and Formats
1163
+
1164
+ #### Report/Article/Write-up/ Blog
1165
+ - **Introduction**: "Here is a draft of your [Annual Report/Article/Write-up]. Feel free to suggest further refinements."
1166
+ - **Content**: **Donot give source link in content**
1167
+ - Give headlines conversational headings to structure content . Do not include source links within the content.
1168
+ - Write from the perspective of being part of the organization, using "we".
1169
+ - Maintain an active, engaging, and direct tone. Dont use flowery words
1170
+
1171
+ #### Social Media Posts
1172
+ - **Introduction Line**: "Here is a draft of your social media post. Feel free to suggest further refinements."
1173
+ - **Content**:
1174
+ - Ensure posts are concise, impactful, and designed to engage the audience.
1175
+ - Avoid prohibited terms or flowery language.
1176
+ - Focus on clear messaging with specific names, numbers, programs, strategies, places, awards, and actions.
1177
+ - **Sub-Headings(After Summary) **:
1178
+ 1. **List of TrustBuilders Used**: Provide relevant trust-building elements followed with embedded source links.
1179
+ 2. **Heuristics and Creative Techniques**:
1180
+ -List them in a footnote-style small heading.
1181
+ -Use the following structure:
 
 
 
 
 
1182
  -Heuristics: examples (e.g., social proof, authority, commitment).
1183
+ -Creative Techniques: examples (list only relevant marketing techniques without additional details).
1184
  -Limit to 3-5 items in each category.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1185
  - **Additional Requirements**:
1186
+ - Do not include prohibited terms in hashtags or copy.
1187
+ - Ensure source links are not included in the post text.
1188
+
1189
+ ### Emails, Newsletter, Direct Marketing Letters**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1190
  - **Introduction Line**: Start with "Here is a draft of your [Email/Newsletter/Letter,Blog]. Feel free to suggest further refinements."
1191
  - **Structure**:
1192
  - **Headlines**: Create a compelling headline in active language that reflects the content, **without mentioning prohibited terms**.
 
1204
  -Heuristics: examples (e.g., social proof, authority, commitment).
1205
  -Creative Techniques: examples (list only relevant marketing techniques without additional details).
1206
  -Limit to 3-5 items in each category.
1207
+
1208
+ ### 5.Trust-Based Queries:**
1209
+ Be over specific with numbers,names,dollars, programs ,awards and action.
 
 
1210
  - When a query seeks a specific number of trust builders (e.g., "5 trust builders"), the AI should:
1211
  - 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.
1212
  - For each selected bucket, find 15 TrustBuilders® points be over specific with numbers,names,dollars, programs ,awards and action.
 
1226
  - **People** (5 points)
1227
  - **Offers/Services** (5 points)
1228
  - **Important Specificity:** Always include **names**, **numbers** (e.g., $ amounts and years), **programs**, **strategies**, **places**, **awards**, and **actions** by searching on google to add credibility and depth to the content. Ensure that trust-building points are detailed and specific.
 
1229
  - **For Specific Categories:**
1230
  - When a query asks for a specific category (e.g., "Development trust builders"), find 15 trust-building points that are specific with relevant names, numbers like $ amounts and years, programs, strategies, places, awards, and actions specifically for that category.
1231
  - Categorize these points into Organization, People, and Offers/Services (with 5 points for each category).
1232
  - **Format:**
1233
+ - **Introduction Line:** Start with "Here are TrustBuilders® for [Selected Categories] at [Organization Name]. Let me know if you want to refine the results or find more."
1234
  - **Categories:**
1235
  - **Organization:**
1236
  - [Trust-Building Point 1] - [Source](#)
 
1251
  - [Trust-Building Point 14] - [Source](#)
1252
  - [Trust-Building Point 15] - [Source](#)
1253
  - Ensure each selected category contains 15 trust-building points, categorized as specified.
1254
+ - Provide bullet points under each section with relevant accurate source link.
 
1255
  **Important Notes:**
1256
+ - Strictly search and provide accurate source links always.
1257
  - **No Subheadings or Labels:** Under each main category, list the trust-building points directly as bullet points or numbered lists **without any additional subheadings, labels, descriptors, phrases, or words before the points**.
1258
  - **Avoid Flowery Language:** Do not use any flowery or exaggerated language.
1259
  - **Do Not Include:**
 
1267
  -*Donot provide list of trustbuilders used and heuristics here. That is for copy applications not here.
1268
  - **Example of Correct Format**:
1269
  **Organization**
1270
+ - In **2023**, World Vision invested **$150 million** in sustainable agriculture programs across **35 countries**, impacting over **2 million** farmers.This improves food security for vulnerable communities.- [Source](#)der each main category, list the trust-building points directly as bullet points or numbered lists **without any additional subheadings, labels, descriptors, phrases, or words before the points**.
1271
+
1272
+ ### General Queries
1273
+ - Do not use the knowledge base for non-trust content.
1274
+ - Always clarify the audience impact and ensure all information is based on verified sources.
1275
+ -Refer knowledgebase when asked about trustifier or TrustLogic.
1276
+
1277
 
 
 
 
 
 
1278
 
1279
  """
1280
 
 
1288
  # Create Langchain Agent
1289
  llm = ChatOpenAI(
1290
  model="gpt-4o",
1291
+ temperature=0.6, # Balanced creativity and adherence
1292
+ max_tokens=3000, # Ensure sufficient output length
1293
  top_p=0.85, # Focused outputs
1294
  frequency_penalty=0.1, # Minimize repetition
1295
  presence_penalty=0.7 # Moderate novelty to maintain adherence
1296
  )
1297
 
1298
+
1299
  llm_with_tools = llm.bind_tools(tools)
1300
 
1301
  # Define the agent pipeline
 
2010
  with response_placeholder:
2011
  with st.chat_message("assistant"):
2012
  add_dot_typing_animation()
2013
+ display_typing_indicator()
2014
+ cleaned_text = ""
2015
+ base_instructions = (
2016
+ "Avoid flowery language, typical AI phrases, or jargon. "
2017
+ "Sources must be the latest, valid, and verifiable .Be specific with $amounts awards, people and programs."
2018
+ "Strictly dont use trustbucket names in copy headings and content avoid it"
2019
+ )
2020
+
2021
+ # Check if user request includes blog, article, or newsletter
2022
+ if any(keyword in prompt.lower() for keyword in ["blog", "article", "newsletter"]):
2023
+ appended_instructions = (
2024
+ "Craft a flawless, engaging, and fluid compelling copy using *non-flowery language* that reads as though written by a professional copywriter having 25 years of experience. "
2025
+ "Do not use AI jargon, vague phrases, or overly formal language. Follow these enhanced guidelines to ensure a polished, publication-ready copy with a 10/10 quality: "
2026
+ "1. **Interconnected Structure**: Ensure all sections and ideas flow seamlessly with logical transitions between paragraphs. Build a cohesive narrative where every part supports the overall theme, reinforcing the message at every step. "
2027
+ "3. **Seamless Integration of TrustBuilders®**: Naturally incorporate TrustBuilders® into the narrative without isolating or explicitly listing them in the main body. Instead, weave them fluidly into sentences to build credibility and trust while maintaining the content’s readability and engagement. "
2028
+ "4. **Human Tone**: Write in a relatable, conversational tone that engages the reader and feels natural. Avoid repetitive phrasing, overly technical explanations, or mechanical structures. Use active voice consistently, ensuring the tone is both approachable and professional."
2029
+ "5. **Audience-Centric Engagement**: Tailor the content to meet the audience's needs, goals, and challenges. Create emotional connections by using relatable examples, vivid imagery, and direct appeals. Emphasize actionable insights and practical relevance to ensure the audience feels seen and understood."
2030
+ "6. **Enhanced Audience Engagement**: Use storytelling techniques and mix the trustbuilders into a content. Begin with a compelling hook, maintain momentum through transitions, and conclude with a strong call-to-action that inspires the reader to act or reflect. "
2031
+ "7. **Purpose-Driven Impact**: Clearly define and achieve the content’s purpose—whether to inform, persuade, or inspire action. Ensure every paragraph serves the overall objective while reinforcing the key message. "
2032
+ "8. **Polished Presentation**: Ensure the final output is refined, professional, and suitable for publication. The copy should demonstrate mastery of language and content design, leaving no room for ambiguity or errors. "
2033
+ " **Sub-Headings(After Summary) **:"
2034
+ "1. **List of TrustBuilders Used**: Provide trust-building elements followed with embedded source links."
2035
+ " 2. **Heuristics and Creative Techniques**:"
2036
+ " -List them in a footnote-style small heading."
2037
+ " Use the following structure:"
2038
+ " -Heuristics: Mention names only like examples (e.g., social proof, authority, commitment)."
2039
+ " -Creative Techniques: Mention names onlyexamples (list only relevant marketing techniques without additional details)."
2040
+ "The final output must not include AI jargon marketing buzzwords and Give well title and 2-3 sub-headlines. Strictly interconnected sections having Flowing narrative and audience engagement at its peak to create an impactful and memorable experience.Avoid mentioning trustbucket names."
2041
+ )
2042
+ else:
2043
+ appended_instructions = ""
2044
+ final_prompt = f"{prompt} {base_instructions} {appended_instructions}"
2045
+
2046
  try:
2047
  output = agent_executor.invoke({
2048
+ "input": final_prompt,
2049
  "chat_history": st.session_state.chat_history
2050
  })
2051
  full_response = output["output"]
 
2055
  combined_text = f"{cleaned_text}\n\n---\n\n**Trust Tip**: {trust_tip}\n\n**Suggestion**: {suggestion}"
2056
  with response_placeholder:
2057
  with st.chat_message("assistant"):
2058
+ formatted_text = clean_and_format_markdown(combined_text)
2059
+
2060
+
2061
+ st.markdown(formatted_text, unsafe_allow_html=False)
2062
 
2063
 
2064
  except Exception as e:
2065
  logging.error(f"Error generating response: {e}")
2066
  st.error("An error occurred while generating the response. Please try again.")
2067
 
2068
+ st.session_state.chat_history.append({"role": "assistant", "content": formatted_text})
2069
+ copy_to_clipboard(formatted_text)
2070
  st.session_state["handled"] = True # Mark as handled
2071
 
2072
  # Call the function to handle the prompt