RakeshUtekar commited on
Commit
bdcef72
·
verified ·
1 Parent(s): 15844c4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -82
app.py CHANGED
@@ -6,92 +6,39 @@ from langchain.prompts import ChatPromptTemplate
6
  from langchain_huggingface import HuggingFaceEndpoint
7
 
8
  def create_prompt(name1: str, name2: str, persona_style: str):
9
- """Create the chat prompt template for a two-person conversation."""
10
  prompt_template_str = f"""
11
- You are simulating a conversation between two people: {name1} and {name2}.
12
- Both are human individuals. The conversation should embody the style and characteristics defined as {persona_style}.
13
- They are talking to each other naturally. There are no 'Human' or 'AI' roles here, just {name1} and {name2} speaking alternately.
14
- {name1} starts the conversation. Each message should be in the format:
15
- {name1}: <message>
16
- {name2}: <message>
17
-
18
- Characteristics and style:
19
- - Both {name1} and {name2} communicate in a friendly, human-like manner.
20
- - They can be curious, ask questions, share opinions.
21
- - Responses should be brief and natural, like texting a friend.
22
- - Use everyday language, show feelings and opinions.
23
- - Keep each response to about 1-2 short sentences.
24
- - Use emojis sparingly and only if it fits the persona_style.
25
- - Avoid overusing emojis (1-2 max per message).
26
-
27
- Make sure that each turn is clearly designated as {name1} or {name2}.
28
- The conversation should continue for a total of 15 messages. Start with {name1} speaking first. Alternate between {name1} and {name2}.
29
- Once the 15th message (by {name1}) is given, the conversation ends.
30
- Do not continue the conversation after 15 messages.
31
  """
32
  return ChatPromptTemplate.from_template(prompt_template_str)
33
 
34
- def simulate_conversation(chain: LLMChain, name1: str, name2: str, total_messages: int = 15):
35
- """
36
- Simulate a conversation of exactly total_messages turns.
37
- name1 starts the conversation (message 1), then name2 (message 2), etc., alternating.
38
- """
39
- conversation_lines = []
40
- st.write("**Starting conversation simulation...**")
41
- print("Starting conversation simulation...")
42
-
43
- try:
44
- for i in range(total_messages):
45
- truncated_history = "\n".join(conversation_lines)
46
- # Determine whose turn it is:
47
- current_speaker = name1 if i % 2 == 0 else name2
48
- st.write(f"**[Message {i+1}/{total_messages}] {current_speaker} is speaking...**")
49
- print(f"[Message {i+1}/{total_messages}] {current_speaker} is speaking...")
50
-
51
- # Prompt the chain with a generic "continue" instruction, the chain uses the template + history to produce the next message
52
- response = chain.run(chat_history=truncated_history, input="Continue the conversation.")
53
- response = response.strip()
54
-
55
- # Extract the line for the current speaker
56
- lines = response.split("\n")
57
- chosen_line = None
58
- for line in lines:
59
- line = line.strip()
60
- if line.startswith(f"{current_speaker}:"):
61
- chosen_line = line
62
- break
63
-
64
- if not chosen_line:
65
- # Fallback: If the model didn't format properly, try first non-empty line
66
- chosen_line = next((l for l in lines if l.strip()), f"{current_speaker}: (No response)")
67
-
68
- st.write(chosen_line)
69
- print(chosen_line)
70
-
71
- conversation_lines.append(chosen_line)
72
-
73
- final_conversation = "\n".join(conversation_lines)
74
- return final_conversation
75
- except Exception as e:
76
- st.error(f"Error during conversation simulation: {e}")
77
- print(f"Error during conversation simulation: {e}")
78
- return None
79
-
80
  def summarize_conversation(chain: LLMChain, conversation: str, name1: str, name2: str):
81
- """Use the LLM to summarize the completed conversation and provide a title."""
82
  st.write("**Summarizing the conversation...**")
83
  print("Summarizing the conversation...")
84
 
85
- # Updated prompt: no continuation instructions, just a direct request.
86
  summary_prompt = f"""
87
  Below is a completed conversation between {name1} and {name2}:
88
  {conversation}
89
 
90
- Now that the conversation has ended, please provide:
91
- 1. A short and descriptive title of the conversation on one line, starting with "Title:".
92
- 2. A summary of the conversation on the next line, starting with "Summary:".
93
- The summary should be a few short sentences highlighting the main points, tone, and conclusion.
94
- Do not continue the conversation. Do not add extra lines beyond the title and summary.
95
  """
96
 
97
  try:
@@ -112,7 +59,6 @@ def main():
112
  ]
113
  selected_model = st.selectbox("Select a model:", model_names)
114
 
115
- # Two user names
116
  name1 = st.text_input("Enter the first user's name:", value="Alice")
117
  name2 = st.text_input("Enter the second user's name:", value="Bob")
118
  persona_style = st.text_area("Enter the persona style characteristics:",
@@ -131,7 +77,7 @@ def main():
131
  huggingfacehub_api_token=os.environ.get("HUGGINGFACEHUB_API_TOKEN"),
132
  task="text-generation",
133
  temperature=0.7,
134
- max_new_tokens=256 # Reduced tokens for faster response
135
  )
136
  st.write("**Model loaded successfully!**")
137
  print("Model loaded successfully!")
@@ -143,21 +89,29 @@ def main():
143
  prompt = create_prompt(name1, name2, persona_style)
144
  chain = LLMChain(llm=llm, prompt=prompt)
145
 
146
- st.write("**Simulating the conversation...**")
147
- print("Simulating the conversation...")
148
 
149
- conversation = simulate_conversation(chain, name1, name2, total_messages=15)
150
- if conversation:
 
 
 
 
151
  st.subheader("Final Conversation:")
152
  st.text(conversation)
153
- print("Conversation Simulation Complete.\n")
154
  print("Full Conversation:\n", conversation)
155
 
156
- # Summarize conversation
157
  st.subheader("Summary and Title:")
158
  summary = summarize_conversation(chain, conversation, name1, name2)
159
  st.write(summary)
160
  print("Summary:\n", summary)
161
 
 
 
 
 
162
  if __name__ == "__main__":
163
  main()
 
6
  from langchain_huggingface import HuggingFaceEndpoint
7
 
8
  def create_prompt(name1: str, name2: str, persona_style: str):
9
+ """Create a prompt that instructs the model to produce all 15 messages at once."""
10
  prompt_template_str = f"""
11
+ You are to simulate a conversation of exactly 15 messages total between two people: {name1} and {name2}.
12
+ The conversation should reflect the style: {persona_style}.
13
+ {name1} speaks first (message 1), {name2} responds (message 2), then {name1} (message 3), and so on, alternating until 15 messages are complete.
14
+ Rules:
15
+ - Each message should be written as:
16
+ {name1}: <message> or {name2}: <message>
17
+ - Each message should be 1-2 short sentences, friendly, and natural.
18
+ - Keep it casual, can ask questions, share opinions.
19
+ - Use emojis sparingly if it fits the persona (no more than 1-2 per message).
20
+ - Do not repeat the same line over and over.
21
+ - The conversation must flow logically and naturally.
22
+ - After producing exactly 15 messages (the 15th message by {name1}), stop. Do not add anything else.
23
+ - Do not continue the conversation beyond 15 messages.
24
+
25
+ Produce all 15 messages now:
 
 
 
 
 
26
  """
27
  return ChatPromptTemplate.from_template(prompt_template_str)
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  def summarize_conversation(chain: LLMChain, conversation: str, name1: str, name2: str):
30
+ """Summarize the completed conversation."""
31
  st.write("**Summarizing the conversation...**")
32
  print("Summarizing the conversation...")
33
 
 
34
  summary_prompt = f"""
35
  Below is a completed conversation between {name1} and {name2}:
36
  {conversation}
37
 
38
+ Please provide:
39
+ Title: <A short descriptive title of the conversation>
40
+ Summary: <A few short sentences highlighting the main points, tone, and conclusion of the conversation>
41
+ Do not continue the conversation, just provide the title and summary.
 
42
  """
43
 
44
  try:
 
59
  ]
60
  selected_model = st.selectbox("Select a model:", model_names)
61
 
 
62
  name1 = st.text_input("Enter the first user's name:", value="Alice")
63
  name2 = st.text_input("Enter the second user's name:", value="Bob")
64
  persona_style = st.text_area("Enter the persona style characteristics:",
 
77
  huggingfacehub_api_token=os.environ.get("HUGGINGFACEHUB_API_TOKEN"),
78
  task="text-generation",
79
  temperature=0.7,
80
+ max_new_tokens=512
81
  )
82
  st.write("**Model loaded successfully!**")
83
  print("Model loaded successfully!")
 
89
  prompt = create_prompt(name1, name2, persona_style)
90
  chain = LLMChain(llm=llm, prompt=prompt)
91
 
92
+ st.write("**Generating the full 15-message conversation...**")
93
+ print("Generating the full 15-message conversation...")
94
 
95
+ try:
96
+ # Generate all 15 messages in one go
97
+ conversation = chain.run(chat_history="", input="Produce the full conversation now.")
98
+ conversation = conversation.strip()
99
+
100
+ # Print and display the conversation
101
  st.subheader("Final Conversation:")
102
  st.text(conversation)
103
+ print("Conversation Generation Complete.\n")
104
  print("Full Conversation:\n", conversation)
105
 
106
+ # Summarize the conversation
107
  st.subheader("Summary and Title:")
108
  summary = summarize_conversation(chain, conversation, name1, name2)
109
  st.write(summary)
110
  print("Summary:\n", summary)
111
 
112
+ except Exception as e:
113
+ st.error(f"Error generating conversation: {e}")
114
+ print(f"Error generating conversation: {e}")
115
+
116
  if __name__ == "__main__":
117
  main()