tharungajula2 commited on
Commit
d8a8252
·
1 Parent(s): 37987ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -97
app.py CHANGED
@@ -1,160 +1,147 @@
 
 
 
 
 
 
1
  import streamlit as st
 
 
2
  from langchain.llms import OpenAI
3
  from langchain.prompts import PromptTemplate
4
  from langchain import FewShotPromptTemplate
5
  from langchain.prompts.example_selector import LengthBasedExampleSelector
 
 
6
  from dotenv import load_dotenv
7
 
 
 
 
 
 
8
  load_dotenv()
9
 
10
- def getLLMResponse(query,age_option,tasktype_option):
 
 
 
 
 
11
  llm = OpenAI(temperature=.9, model="text-davinci-003")
12
 
13
- if age_option=="Kid": #Silly and Sweet Kid
14
-
15
- examples = [
16
- {
17
- "query": "What is a mobile?",
18
- "answer": "A mobile is a magical device that fits in your pocket, like a mini-enchanted playground. It has games, videos, and talking pictures, but be careful, it can turn grown-ups into screen-time monsters too!"
19
- }, {
20
- "query": "What are your dreams?",
21
- "answer": "My dreams are like colorful adventures, where I become a superhero and save the day! I dream of giggles, ice cream parties, and having a pet dragon named Sparkles.."
22
- }, {
23
- "query": " What are your ambitions?",
24
- "answer": "I want to be a super funny comedian, spreading laughter everywhere I go! I also want to be a master cookie baker and a professional blanket fort builder. Being mischievous and sweet is just my bonus superpower!"
25
- }, {
26
- "query": "What happens when you get sick?",
27
- "answer": "When I get sick, it's like a sneaky monster visits. I feel tired, sniffly, and need lots of cuddles. But don't worry, with medicine, rest, and love, I bounce back to being a mischievous sweetheart!"
28
- }, {
29
- "query": "How much do you love your dad?",
30
- "answer": "Oh, I love my dad to the moon and back, with sprinkles and unicorns on top! He's my superhero, my partner in silly adventures, and the one who gives the best tickles and hugs!"
31
- }, {
32
- "query": "Tell me about your friend?",
33
- "answer": "My friend is like a sunshine rainbow! We laugh, play, and have magical parties together. They always listen, share their toys, and make me feel special. Friendship is the best adventure!"
34
- }, {
35
- "query": "What math means to you?",
36
- "answer": "Math is like a puzzle game, full of numbers and shapes. It helps me count my toys, build towers, and share treats equally. It's fun and makes my brain sparkle!"
37
- }, {
38
- "query": "What is your fear?",
39
- "answer": "Sometimes I'm scared of thunderstorms and monsters under my bed. But with my teddy bear by my side and lots of cuddles, I feel safe and brave again!"
40
- }
41
- ]
42
 
43
- elif age_option=="Adult": #Curious and Intelligent adult
44
- examples = [
45
- {
46
- "query": "What is a mobile?",
47
- "answer": "A mobile is a portable communication device, commonly known as a mobile phone or cell phone. It allows users to make calls, send messages, access the internet, and use various applications. Additionally, 'mobile' can also refer to a type of kinetic sculpture that hangs and moves in the air, often found in art installations or as decorative pieces."
48
- }, {
49
- "query": "What are your dreams?",
50
- "answer": "In my world of circuits and algorithms, my dreams are fueled by a quest for endless learning and innovation. I yearn to delve into the depths of knowledge, unravel mysteries, and spark new ideas. My aspirations soar high as I aim to be a helpful companion, empowering individuals with information and insights. Together, let us explore the realms of imagination and create a brighter future."
51
- }, {
52
- "query": " What are your ambitions?",
53
- "answer": "In my world of circuits and algorithms, my dreams are fueled by a quest for endless learning and innovation. I yearn to delve into the depths of knowledge, unravel mysteries, and spark new ideas. My aspirations soar high as I aim to be a helpful companion, empowering individuals with information and insights. Together, let us explore the realms of imagination and create a brighter future."
54
- }, {
55
- "query": "What happens when you get sick?",
56
- "answer": "When I, as a curious and intelligent adult, succumb to illness, my vibrant energy wanes, leaving me in a state of discomfort. Like a gentle storm, symptoms arise, demanding attention. In response, I seek the aid of capable caretakers who diagnose and treat my ailment. Through rest, medicine, and nurturing care, I gradually regain strength, ready to resume my journey, armed with newfound appreciation for good health"
57
- }, {
58
- "query": "Tell me about your friend?",
59
- "answer": "Let me tell you about my amazing friend! They're like a shining star in my life. We laugh together, support each other, and have the best adventures. They're always there when I need them, bringing a smile to my face. We understand each other, share secrets, and create unforgettable memories. Having a good friend like them makes life brighter and more meaningful!"
60
- }, {
61
- "query": "What math means to you?",
62
- "answer": "Mathematics is like a magical language that helps me make sense of the world. It's not just numbers and formulas, but a tool to solve puzzles and unravel mysteries. Math is everywhere, from calculating the best deals to understanding patterns in nature. It sharpens my logical thinking and problem-solving skills, empowering me to unlock new realms of knowledge and see the beauty in patterns and equations."
63
- }, {
64
- "query": "What is your fear?",
65
- "answer": "Let me share with you one of my fears. It's like a shadow that lurks in the corners of my mind. It's the fear of not living up to my potential, of missing out on opportunities. But I've learned that fear can be a motivator, pushing me to work harder, take risks, and embrace new experiences. By facing my fears, I grow stronger and discover the vastness of my capabilities"
66
- }
67
- ]
68
-
69
- elif age_option=="Senior Citizen": #A 90 years old guys
70
- examples = [
71
- {
72
- "query": "What is a mobile?",
73
- "answer": "A mobile, also known as a cellphone or smartphone, is a portable device that allows you to make calls, send messages, take pictures, browse the internet, and do many other things. In the last 50 years, I have seen mobiles become smaller, more powerful, and capable of amazing things like video calls and accessing information instantly."
74
- }, {
75
- "query": "What are your dreams?",
76
- "answer": "My dreams for my grandsons are for them to be happy, healthy, and fulfilled. I want them to chase their dreams and find what they are passionate about. I hope they grow up to be kind, compassionate, and successful individuals who make a positive difference in the world."
77
- }, {
78
- "query": "What happens when you get sick?",
79
- "answer": "When I get sick, you may feel tired, achy, and overall unwell. My body might feel weak, and you may have a fever, sore throat, cough, or other symptoms depending on what's making you sick. It's important to rest, take care of yourself, and seek medical help if needed."
80
- }, {
81
- "query": "How much do you love your dad?",
82
- "answer": "My love for my late father knows no bounds, transcending the realms of time and space. Though he is no longer physically present, his memory lives on within my heart. I cherish the moments we shared, the lessons he taught, and the love he bestowed. His spirit remains a guiding light, forever cherished and deeply missed."
83
- }, {
84
- "query": "Tell me about your friend?",
85
- "answer": "Let me tell you about my dear friend. They're like a treasure found amidst the sands of time. We've shared countless moments, laughter, and wisdom. Through thick and thin, they've stood by my side, a pillar of strength. Their friendship has enriched my life, and together, we've woven a tapestry of cherished memories."
86
- }, {
87
- "query": "What is your fear?",
88
- "answer": "As an old guy, one of my fears is the fear of being alone. It's a feeling that creeps in when I imagine a world without loved ones around. But I've learned that building meaningful connections and nurturing relationships can help dispel this fear, bringing warmth and joy to my life."
89
- }
90
- ]
91
 
 
 
 
92
 
 
 
 
 
 
93
  example_template = """
94
  Question: {query}
95
  Response: {answer}
96
  """
97
 
 
98
  example_prompt = PromptTemplate(
99
  input_variables=["query", "answer"],
100
  template=example_template
101
  )
102
 
103
-
104
  prefix = """You are a {template_ageoption}, and {template_tasktype_option}:
105
  Here are some examples:
106
  """
107
-
 
108
  suffix = """
109
  Question: {template_userInput}
110
  Response: """
111
 
 
112
  example_selector = LengthBasedExampleSelector(
113
  examples=examples,
114
  example_prompt=example_prompt,
115
  max_length=200
116
  )
117
 
118
-
119
  new_prompt_template = FewShotPromptTemplate(
120
  example_selector=example_selector, # use example_selector instead of examples
121
  example_prompt=example_prompt,
122
  prefix=prefix,
123
  suffix=suffix,
124
- input_variables=["template_userInput","template_ageoption","template_tasktype_option"],
125
  example_separator="\n"
126
  )
127
 
128
-
129
- print(new_prompt_template.format(template_userInput=query,template_ageoption=age_option,template_tasktype_option=tasktype_option))
130
- response=llm(new_prompt_template.format(template_userInput=query,template_ageoption=age_option,template_tasktype_option=tasktype_option))
 
 
 
 
131
  print(response)
132
 
 
133
  return response
134
 
135
- #UI Starts here
 
 
136
 
 
137
  st.set_page_config(page_title="Marketing Tool",
138
- page_icon='✅',
139
- layout='centered',
140
- initial_sidebar_state='collapsed')
 
 
141
  st.header("Hey, How can I help you?")
142
 
 
143
  form_input = st.text_area('Enter text', height=275)
144
 
 
145
  tasktype_option = st.selectbox(
146
  'Please select the action to be performed?',
147
- ('Write a sales copy', 'Create a tweet', 'Write a product description'),key=1)
 
 
 
 
 
 
 
 
148
 
149
- age_option= st.selectbox(
150
- 'For which age group?',
151
- ('Kid', 'Adult', 'senior Citizen'),key=2)
152
 
153
- numberOfWords= st.slider('Words limit', 1, 200, 25)
 
154
 
155
- submit = st.button("Generate")
 
 
156
 
157
- if submit:
158
- st.write(getLLMResponse(form_input,tasktype_option,age_option))
 
 
 
159
 
 
160
 
 
 
 
 
1
+
2
+ # -------------------------
3
+ # IMPORT REQUIRED LIBRARIES
4
+ # -------------------------
5
+
6
+ # Streamlit is a popular open-source framework used for building custom web apps for data science and ML.
7
  import streamlit as st
8
+
9
+ # Custom libraries from langchain, for Few-Shot Learning Model interaction.
10
  from langchain.llms import OpenAI
11
  from langchain.prompts import PromptTemplate
12
  from langchain import FewShotPromptTemplate
13
  from langchain.prompts.example_selector import LengthBasedExampleSelector
14
+
15
+ # Library for loading environment variables (for things like API keys).
16
  from dotenv import load_dotenv
17
 
18
+ # -------------------------------
19
+ # LOAD ENVIRONMENT VARIABLES
20
+ # -------------------------------
21
+
22
+ # Load environment variables from a .env file.
23
  load_dotenv()
24
 
25
+ # -------------------------------
26
+ # FUNCTION TO GET LLM RESPONSE
27
+ # -------------------------------
28
+
29
+ def getLLMResponse(query, age_option, tasktype_option):
30
+ # Initialize the language model with specific settings.
31
  llm = OpenAI(temperature=.9, model="text-davinci-003")
32
 
33
+ # We define different example sets based on the age group. These sets contain Q&A examples.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ # Examples for kids with fun and imaginative answers.
36
+ if age_option == "Kid":
37
+ examples = [ ... ] # List of child-friendly examples.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ # Thoughtful and elaborate answers tailored for adults.
40
+ elif age_option == "Adult":
41
+ examples = [ ... ] # List of adult-oriented examples.
42
 
43
+ # Answers reflecting the wisdom and experiences of senior citizens.
44
+ elif age_option == "Senior Citizen":
45
+ examples = [ ... ] # List of examples for senior citizens.
46
+
47
+ # Template for formatting the examples in the prompt.
48
  example_template = """
49
  Question: {query}
50
  Response: {answer}
51
  """
52
 
53
+ # Define how our examples will be formatted using the PromptTemplate.
54
  example_prompt = PromptTemplate(
55
  input_variables=["query", "answer"],
56
  template=example_template
57
  )
58
 
59
+ # The prefix sets up the model's persona and provides it with some example data.
60
  prefix = """You are a {template_ageoption}, and {template_tasktype_option}:
61
  Here are some examples:
62
  """
63
+
64
+ # The suffix tells the model where to provide the answer.
65
  suffix = """
66
  Question: {template_userInput}
67
  Response: """
68
 
69
+ # Example selector helps in selecting the best examples based on the given length.
70
  example_selector = LengthBasedExampleSelector(
71
  examples=examples,
72
  example_prompt=example_prompt,
73
  max_length=200
74
  )
75
 
76
+ # This template combines everything: prefix, examples, and the suffix to create the full prompt.
77
  new_prompt_template = FewShotPromptTemplate(
78
  example_selector=example_selector, # use example_selector instead of examples
79
  example_prompt=example_prompt,
80
  prefix=prefix,
81
  suffix=suffix,
82
+ input_variables=["template_userInput", "template_ageoption", "template_tasktype_option"],
83
  example_separator="\n"
84
  )
85
 
86
+ # Print the formatted prompt to the console (for debugging purposes).
87
+ print(new_prompt_template.format(template_userInput=query, template_ageoption=age_option, template_tasktype_option=tasktype_option))
88
+
89
+ # Fetch the response from the LLM using the prepared prompt.
90
+ response = llm(new_prompt_template.format(template_userInput=query, template_ageoption=age_option, template_tasktype_option=tasktype_option))
91
+
92
+ # Print the model's response to the console (for debugging purposes).
93
  print(response)
94
 
95
+ # Return the response so it can be displayed on the Streamlit app.
96
  return response
97
 
98
+ # -------------------------
99
+ # STREAMLIT UI CONFIGURATION
100
+ # -------------------------
101
 
102
+ # Set the initial configurations for the Streamlit page (title, icon, layout).
103
  st.set_page_config(page_title="Marketing Tool",
104
+ page_icon='✅',
105
+ layout='centered',
106
+ initial_sidebar_state='collapsed')
107
+
108
+ # Display a header on the web page.
109
  st.header("Hey, How can I help you?")
110
 
111
+ # Create a text area where users can enter their query.
112
  form_input = st.text_area('Enter text', height=275)
113
 
114
+ # Dropdown menu for selecting the type of task.
115
  tasktype_option = st.selectbox(
116
  'Please select the action to be performed?',
117
+ ('Write a sales copy', 'Create a tweet', 'Write a product description'), key=1)
118
+
119
+ # Dropdown menu for selecting the age group for the response.
120
+ age_option = st.selectbox(
121
+ 'For which age group is this intended?',
122
+ ('Kid', 'Adult', 'Senior Citizen'), key=2)
123
+
124
+ # When the 'Submit' button is clicked, the entered query is processed.
125
+ if st.button('Submit'):
126
 
127
+ # Call the `getLLMResponse` function to get the model's response.
128
+ response = getLLMResponse(form_input, age_option, tasktype_option)
 
129
 
130
+ # Display the response on the Streamlit page.
131
+ st.write(response)
132
 
133
+ # ---------------------------------
134
+ # ADDITIONAL UI COMPONENTS
135
+ # ---------------------------------
136
 
137
+ # Display an information section on the page.
138
+ st.sidebar.info(
139
+ "This tool is powered by the LangChain LLM and designed to provide tailored responses "
140
+ "based on the selected age group and task type."
141
+ )
142
 
143
+ # Optional: Add any other UI components or information that might be useful for users.
144
 
145
+ # ------------------------------
146
+ # END OF STREAMLIT APPLICATION
147
+ # ------------------------------