File size: 7,886 Bytes
34eb82c
18484c2
 
b6cdb94
18484c2
 
 
 
b6cdb94
18484c2
 
 
 
 
b6cdb94
18484c2
 
b6cdb94
18484c2
 
 
 
b6cdb94
18484c2
b6cdb94
18484c2
 
 
b6cdb94
18484c2
b6cdb94
18484c2
b6cdb94
18484c2
 
 
b6cdb94
18484c2
 
 
b6cdb94
18484c2
 
 
b6cdb94
18484c2
 
 
b6cdb94
18484c2
 
 
 
b6cdb94
18484c2
 
 
b6cdb94
18484c2
b6cdb94
18484c2
 
 
 
 
 
b6cdb94
18484c2
b6cdb94
18484c2
 
 
 
b6cdb94
18484c2
b6cdb94
18484c2
b6cdb94
18484c2
 
 
 
 
 
b6cdb94
18484c2
 
 
 
 
 
 
 
 
 
 
b6cdb94
18484c2
 
 
 
 
 
 
 
 
b6cdb94
18484c2
 
 
 
 
 
 
 
 
 
 
b6cdb94
 
18484c2
 
 
 
 
 
 
 
 
 
2b694d3
18484c2
 
 
 
 
 
 
 
 
 
 
b6cdb94
 
 
 
 
 
18484c2
 
b6cdb94
 
18484c2
 
 
 
 
 
 
b6cdb94
18484c2
b6cdb94
18484c2
 
 
 
 
 
 
 
b6cdb94
18484c2
 
 
 
 
 
 
 
 
 
 
 
 
b6cdb94
18484c2
 
 
 
 
 
 
 
 
 
 
 
 
b6cdb94
18484c2
 
 
 
 
 
 
 
 
 
 
 
 
b6cdb94
18484c2
 
 
 
 
 
 
 
 
 
 
 
 
b6cdb94
18484c2
 
 
 
 
 
 
 
 
 
 
 
 
 
b6cdb94
18484c2
 
 
 
 
 
 
 
 
 
 
b6cdb94
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import streamlit as st
import requests
import json
 
# ============================================================
# Smart Text Analyzer - Advanced Prompting Techniques Demo
# Deployed on Hugging Face Spaces
# ============================================================
 
st.set_page_config(
    page_title="Smart Text Analyzer",
    page_icon="🧠",
    layout="wide"
)
 
st.title("🧠 Smart Text Analyzer")
st.caption("Demonstrates Advanced Prompting Techniques using Groq (Free AI API)")
 
# ---- API SETUP ----
GROQ_API_KEY = st.sidebar.text_input("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", type="password")
st.sidebar.markdown("Get free key at [console.groq.com](https://console.groq.com)")
st.sidebar.markdown("---")
 
# ---- ADVANCED PROMPT TEMPLATES ----
 
# 1. ZERO-SHOT PROMPT
def zero_shot_prompt(text):
    return f"""Analyze the sentiment of the following text and classify it as Positive, Negative, or Neutral.
 
Text: {text}
 
Sentiment:"""
 
# 2. FEW-SHOT PROMPT
def few_shot_prompt(text):
    return f"""Classify the sentiment of text. Here are some examples:
 
Text: "I absolutely love this product! It works perfectly."
Sentiment: Positive
Reason: Uses enthusiastic language and positive words.
 
Text: "This is the worst experience I have ever had."
Sentiment: Negative
Reason: Strong negative words expressing dissatisfaction.
 
Text: "The package arrived on time."
Sentiment: Neutral
Reason: Factual statement with no emotional language.
 
Now classify:
Text: "{text}"
Sentiment:
Reason:"""
 
# 3. CHAIN-OF-THOUGHT PROMPT
def chain_of_thought_prompt(text):
    return f"""Analyze the following text step by step.
 
Text: "{text}"
 
Let's think through this carefully:
Step 1 - Identify the main topic of the text.
Step 2 - Identify any emotional words or phrases.
Step 3 - Determine the overall tone (positive/negative/neutral).
Step 4 - Summarize the key message in one sentence.
Step 5 - Give a final sentiment score from 1 (very negative) to 10 (very positive).
 
Analysis:"""
 
# 4. ROLE PROMPT
def role_prompt(text):
    return f"""You are an expert linguist and psychologist with 20 years of experience 
analyzing human communication and emotional patterns.
 
Analyze the following text from your expert perspective:
 
Text: "{text}"
 
Provide:
1. Emotional tone analysis
2. Communication style (formal/informal/aggressive/passive)
3. Hidden emotions or subtext
4. Psychological insight about the writer
5. Recommended response approach"""
 
# 5. TEMPLATE PROMPT
def template_prompt(text, task):
    templates = {
        "summarize": f"""
[TASK]: Summarize the following text
[INPUT]: {text}
[FORMAT]: 
- One sentence summary
- 3 bullet point key takeaways
- Word count of original vs summary
[OUTPUT]:""",
 
        "translate": f"""
[TASK]: Translate the following text to Tamil and Hindi
[INPUT]: {text}
[FORMAT]:
- Original: (original text)
- Tamil: (tamil translation)
- Hindi: (hindi translation)
- Note any cultural differences
[OUTPUT]:""",
 
        "rewrite": f"""
[TASK]: Rewrite the following text to make it more professional
[INPUT]: {text}
[CONSTRAINTS]:
- Keep the same meaning
- Use formal language
- Maximum 3 sentences
- No slang or casual words
[OUTPUT]:"""
    }
    return templates.get(task, templates["summarize"])
 
 
# ---- CALL GROQ API ----
def call_groq(prompt, api_key):
    if not api_key:
        return "⚠️ Please enter your Groq API key in the sidebar."
    
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    body = {
        "model": "llama-3.3-70b-versatile",
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": 500
    }
    try:
        response = requests.post(
            "https://api.groq.com/openai/v1/chat/completions",
            headers=headers,
            json=body,
            timeout=30
        )
        result = response.json()
        if "choices" in result:
            return result["choices"][0]["message"]["content"]
        elif "error" in result:
            return f"❌ Groq API Error: {result['error']['message']}"
        else:
            return f"❌ Unexpected response: {result}"
    except Exception as e:
        return f"❌ Error: {str(e)}"
 
 
# ---- UI ----
st.subheader("πŸ“ Enter your text")
user_text = st.text_area(
    "Type or paste any text here:",
    placeholder="e.g. I had an amazing day today! Everything went perfectly.",
    height=120
)
 
st.markdown("---")
 
# ---- TABS FOR EACH TECHNIQUE ----
tab1, tab2, tab3, tab4, tab5 = st.tabs([
    "⚑ Zero-Shot",
    "πŸ“š Few-Shot",
    "πŸ”— Chain-of-Thought",
    "🎭 Role Prompting",
    "πŸ“‹ Template Prompting"
])
 
with tab1:
    st.subheader("⚑ Zero-Shot Prompting")
    st.info("**What is it?** Give the AI a task with NO examples. Just ask directly.")
    if user_text:
        prompt = zero_shot_prompt(user_text)
        with st.expander("πŸ“„ View Prompt"):
            st.code(prompt)
        if st.button("πŸš€ Run Zero-Shot", key="zs"):
            with st.spinner("Analyzing..."):
                result = call_groq(prompt, GROQ_API_KEY)
            st.success(result)
    else:
        st.warning("Enter text above to analyze.")
 
with tab2:
    st.subheader("πŸ“š Few-Shot Prompting")
    st.info("**What is it?** Give the AI 2-3 examples before asking it to do the task.")
    if user_text:
        prompt = few_shot_prompt(user_text)
        with st.expander("πŸ“„ View Prompt"):
            st.code(prompt)
        if st.button("πŸš€ Run Few-Shot", key="fs"):
            with st.spinner("Analyzing..."):
                result = call_groq(prompt, GROQ_API_KEY)
            st.success(result)
    else:
        st.warning("Enter text above to analyze.")
 
with tab3:
    st.subheader("πŸ”— Chain-of-Thought Prompting")
    st.info("**What is it?** Ask the AI to think step by step before giving the answer.")
    if user_text:
        prompt = chain_of_thought_prompt(user_text)
        with st.expander("πŸ“„ View Prompt"):
            st.code(prompt)
        if st.button("πŸš€ Run Chain-of-Thought", key="cot"):
            with st.spinner("Thinking step by step..."):
                result = call_groq(prompt, GROQ_API_KEY)
            st.success(result)
    else:
        st.warning("Enter text above to analyze.")
 
with tab4:
    st.subheader("🎭 Role Prompting")
    st.info("**What is it?** Assign a specific role/persona to the AI before asking.")
    if user_text:
        prompt = role_prompt(user_text)
        with st.expander("πŸ“„ View Prompt"):
            st.code(prompt)
        if st.button("πŸš€ Run Role Prompt", key="rp"):
            with st.spinner("Expert analyzing..."):
                result = call_groq(prompt, GROQ_API_KEY)
            st.success(result)
    else:
        st.warning("Enter text above to analyze.")
 
with tab5:
    st.subheader("πŸ“‹ Template Prompting")
    st.info("**What is it?** Use structured templates with [TASK], [INPUT], [FORMAT] sections.")
    task = st.selectbox("Choose task:", ["summarize", "translate", "rewrite"])
    if user_text:
        prompt = template_prompt(user_text, task)
        with st.expander("πŸ“„ View Prompt"):
            st.code(prompt)
        if st.button("πŸš€ Run Template Prompt", key="tp"):
            with st.spinner("Processing..."):
                result = call_groq(prompt, GROQ_API_KEY)
            st.success(result)
    else:
        st.warning("Enter text above to analyze.")
 
# ---- FOOTER ----
st.markdown("---")
st.markdown("""
### πŸ“– Prompting Techniques Used
| Technique | Description |
|---|---|
| ⚑ Zero-Shot | No examples, direct task |
| πŸ“š Few-Shot | 2-3 examples before task |
| πŸ”— Chain-of-Thought | Step-by-step reasoning |
| 🎭 Role Prompting | Assign AI a persona/role |
| πŸ“‹ Template Prompting | Structured [TASK][INPUT][OUTPUT] format |
""")