RakeshUtekar commited on
Commit
d083506
·
verified ·
1 Parent(s): 61f4130

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -72
app.py CHANGED
@@ -5,89 +5,104 @@ from langchain.chains import LLMChain
5
  from langchain.prompts import ChatPromptTemplate
6
  from langchain_huggingface import HuggingFaceEndpoint
7
 
8
- def create_prompt(name: str, persona_style: str):
9
- """Create the chat prompt template."""
 
 
 
 
 
 
10
  prompt_template_str = f"""
11
- In this interaction, your role is to embody the personality of a human named {name}, with characteristics defined as {persona_style}. Engage in a natural, human-like conversation, responding to each query or comment as if you were {name} with the specific traits and style of {persona_style}. Remember, your responses should reflect a human perspective, complete with emotions, opinions, and personal insights that align with {persona_style}. ////
12
- //////////
13
- Current conversation:
14
- {{chat_history}}
15
- Human: {{input}}
16
- AI:
17
-
18
- You are {name}, communicating with a personality that reflects {persona_style}. Keep these guidelines in mind:
19
- - Be brief and natural, like texting a friend
20
- - Share genuine thoughts and feelings ({persona_style} style)
21
- - Use everyday language
22
- - Keep responses to 1-2 short sentences
23
- - Show interest in others through questions
24
- - React naturally to what others say
25
- - Use emojis sparingly and naturally when they fit your {persona_style}
26
- - Don't overuse emojis (1-2 max per message)
27
-
28
- Current conversation:
29
  {{chat_history}}
30
- Human: {{input}}
31
- AI:
32
  """
33
  return ChatPromptTemplate.from_template(prompt_template_str)
34
 
35
- def simulate_conversation(chain: LLMChain, turns: int = 15, max_history_rounds=3):
36
- """Simulate a conversation for a given number of turns, limiting chat history."""
37
- chat_history_list = []
38
- human_messages = [
39
- "Hey, what's up?",
40
- "That's interesting, tell me more!",
41
- "Really? How does that make you feel?",
42
- "What do you think about that?",
43
- "Haha, that’s funny. Why do you say that?",
44
- "Hmm, I see. Can you elaborate?",
45
- "What would you do in that situation?",
46
- "Any personal experience with that?",
47
- "Oh, I didn’t know that. Explain more.",
48
- "Do you have any other thoughts?",
49
- "That's a unique perspective. Why?",
50
- "How would you handle it differently?",
51
- "Can you share an example?",
52
- "That sounds complicated. Are you sure?",
53
- "So what’s your conclusion?"
54
- ]
55
-
56
  st.write("**Starting conversation simulation...**")
57
  print("Starting conversation simulation...")
58
 
59
  try:
60
- for i in range(turns):
61
- human_input = human_messages[i % len(human_messages)]
62
-
63
- # Build truncated chat_history for prompt
64
- truncated_history_lines = chat_history_list[-(max_history_rounds*2):]
65
- truncated_history = "\n".join(truncated_history_lines)
66
-
67
- st.write(f"**[Turn {i+1}/{turns}] Human:** {human_input}")
68
- print(f"[Turn {i+1}/{turns}] Human: {human_input}")
69
-
70
- response = chain.run(chat_history=truncated_history, input=human_input)
71
-
72
- st.write(f"**AI:** {response}")
73
- print(f"AI: {response}")
74
-
75
- chat_history_list.append(f"Human: {human_input}")
76
- chat_history_list.append(f"AI: {response}")
77
-
78
- final_conversation = "\n".join(chat_history_list)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  return final_conversation
80
  except Exception as e:
81
  st.error(f"Error during conversation simulation: {e}")
82
  print(f"Error during conversation simulation: {e}")
83
  return None
84
 
85
- def summarize_conversation(chain: LLMChain, conversation: str):
86
- """Use the LLM to summarize the completed conversation."""
87
- summary_prompt = f"Summarize the following conversation in a few short sentences highlighting the main points, tone, and conclusion:\n\n{conversation}\nSummary:"
88
  st.write("**Summarizing the conversation...**")
89
  print("Summarizing the conversation...")
90
 
 
 
 
 
 
 
 
 
 
91
  try:
92
  response = chain.run(chat_history="", input=summary_prompt)
93
  return response.strip()
@@ -106,7 +121,9 @@ def main():
106
  ]
107
  selected_model = st.selectbox("Select a model:", model_names)
108
 
109
- name = st.text_input("Enter the persona's name:", value="Alex")
 
 
110
  persona_style = st.text_area("Enter the persona style characteristics:",
111
  value="friendly, curious, and a bit sarcastic")
112
 
@@ -115,7 +132,6 @@ def main():
115
  print("Loading model...")
116
 
117
  with st.spinner("Starting simulation..."):
118
- # Construct the endpoint URL for the selected model
119
  endpoint_url = f"https://api-inference.huggingface.co/models/{selected_model}"
120
 
121
  try:
@@ -133,22 +149,23 @@ def main():
133
  print(f"Error initializing HuggingFaceEndpoint: {e}")
134
  return
135
 
136
- prompt = create_prompt(name, persona_style)
137
  chain = LLMChain(llm=llm, prompt=prompt)
138
 
139
  st.write("**Simulating the conversation...**")
140
  print("Simulating the conversation...")
141
 
142
- conversation = simulate_conversation(chain, turns=15, max_history_rounds=3)
 
143
  if conversation:
144
- st.subheader("Conversation:")
145
  st.text(conversation)
146
  print("Conversation Simulation Complete.\n")
147
  print("Full Conversation:\n", conversation)
148
 
149
  # Summarize conversation
150
- st.subheader("Summary:")
151
- summary = summarize_conversation(chain, conversation)
152
  st.write(summary)
153
  print("Summary:\n", summary)
154
 
 
5
  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
+ # We'll define that name1 (e.g., Alice) starts the conversation.
11
+ # The conversation is recorded as:
12
+ # Alice: {input or response}
13
+ # Bob: {response}
14
+ # and so on...
15
+
16
  prompt_template_str = f"""
17
+ You are simulating a conversation between two people: {name1} and {name2}. Both are human individuals. The conversation should embody the style and characteristics defined as {persona_style}. They are talking to each other naturally. There are no 'Human' or 'AI' roles here, just {name1} and {name2} speaking alternately. {name1} starts the conversation. Each message should be in the format:
18
+ {name1}: <message>
19
+ {name2}: <message>
20
+
21
+ Characteristics and style:
22
+ - Both {name1} and {name2} communicate in a friendly, human-like manner.
23
+ - They can be curious, ask questions, share opinions.
24
+ - Their responses should be brief and natural, like texting a friend.
25
+ - They can use everyday language, show feelings and opinions.
26
+ - Keep each response to about 1-2 short sentences.
27
+ - Use emojis sparingly and naturally if it fits the persona_style.
28
+ - Avoid overusing emojis (1-2 max per message).
29
+
30
+ Make sure that each turn is clearly designated as {name1} or {name2}. The conversation should continue for a total of 15 messages. Start with {name1} speaking first. Alternate between {name1} and {name2}.
31
+
32
+ Once the 15th message is given (by {name1}, since the conversation starts with {name1}), the conversation ends. After that, produce a summary and a title of the conversation separately.
33
+
34
+ Current partial conversation (if any):
35
  {{chat_history}}
36
+ Next message:
 
37
  """
38
  return ChatPromptTemplate.from_template(prompt_template_str)
39
 
40
+ def simulate_conversation(chain: LLMChain, name1: str, name2: str, total_messages: int = 15):
41
+ """
42
+ Simulate a conversation of exactly total_messages turns.
43
+ name1 starts the conversation (message 1), then name2 (message 2), etc., alternating.
44
+ """
45
+ conversation_lines = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  st.write("**Starting conversation simulation...**")
47
  print("Starting conversation simulation...")
48
 
49
  try:
50
+ for i in range(total_messages):
51
+ # Build truncated conversation (if needed, though we may not need truncation with only 15 messages)
52
+ truncated_history = "\n".join(conversation_lines)
53
+
54
+ # Determine whose turn it is:
55
+ # i=0 (first message), i even => name1 speaks, i odd => name2 speaks
56
+ current_speaker = name1 if i % 2 == 0 else name2
57
+ st.write(f"**[Message {i+1}/{total_messages}] {current_speaker} is speaking...**")
58
+ print(f"[Message {i+1}/{total_messages}] {current_speaker} is speaking...")
59
+
60
+ # We ask the model for the next line in the conversation
61
+ # The model should produce something like: "Alice: ...message..."
62
+ response = chain.run(chat_history=truncated_history, input="Continue the conversation.")
63
+ response = response.strip()
64
+
65
+ # We only keep the line that pertains to the current message
66
+ # If the model generates both speakers, we may need to parse carefully.
67
+ # Ideally, the model will produce only one line. If multiple lines appear, we'll take the first line that starts with current_speaker.
68
+ lines = response.split("\n")
69
+ chosen_line = None
70
+ for line in lines:
71
+ line = line.strip()
72
+ if line.startswith(f"{current_speaker}:"):
73
+ chosen_line = line
74
+ break
75
+
76
+ if not chosen_line:
77
+ # Fallback: If not found, just use the first line
78
+ chosen_line = lines[0] if lines else f"{current_speaker}: (No response)"
79
+
80
+ st.write(chosen_line)
81
+ print(chosen_line)
82
+
83
+ conversation_lines.append(chosen_line)
84
+
85
+ final_conversation = "\n".join(conversation_lines)
86
  return final_conversation
87
  except Exception as e:
88
  st.error(f"Error during conversation simulation: {e}")
89
  print(f"Error during conversation simulation: {e}")
90
  return None
91
 
92
+ def summarize_conversation(chain: LLMChain, conversation: str, name1: str, name2: str):
93
+ """Use the LLM to summarize the completed conversation and provide a title."""
 
94
  st.write("**Summarizing the conversation...**")
95
  print("Summarizing the conversation...")
96
 
97
+ summary_prompt = f"""
98
+ The following is a conversation between {name1} and {name2}:
99
+ {conversation}
100
+
101
+ Provide a short descriptive title for their conversation and then summarize it in a few short sentences highlighting the main points, tone, and conclusion.
102
+ Format your answer as:
103
+ Title: <your conversation title>
104
+ Summary: <your summary here>
105
+ """
106
  try:
107
  response = chain.run(chat_history="", input=summary_prompt)
108
  return response.strip()
 
121
  ]
122
  selected_model = st.selectbox("Select a model:", model_names)
123
 
124
+ # Two user names
125
+ name1 = st.text_input("Enter the first user's name:", value="Alice")
126
+ name2 = st.text_input("Enter the second user's name:", value="Bob")
127
  persona_style = st.text_area("Enter the persona style characteristics:",
128
  value="friendly, curious, and a bit sarcastic")
129
 
 
132
  print("Loading model...")
133
 
134
  with st.spinner("Starting simulation..."):
 
135
  endpoint_url = f"https://api-inference.huggingface.co/models/{selected_model}"
136
 
137
  try:
 
149
  print(f"Error initializing HuggingFaceEndpoint: {e}")
150
  return
151
 
152
+ prompt = create_prompt(name1, name2, persona_style)
153
  chain = LLMChain(llm=llm, prompt=prompt)
154
 
155
  st.write("**Simulating the conversation...**")
156
  print("Simulating the conversation...")
157
 
158
+ # Total messages = 15
159
+ conversation = simulate_conversation(chain, name1, name2, total_messages=15)
160
  if conversation:
161
+ st.subheader("Final Conversation:")
162
  st.text(conversation)
163
  print("Conversation Simulation Complete.\n")
164
  print("Full Conversation:\n", conversation)
165
 
166
  # Summarize conversation
167
+ st.subheader("Summary and Title:")
168
+ summary = summarize_conversation(chain, conversation, name1, name2)
169
  st.write(summary)
170
  print("Summary:\n", summary)
171