gampala1234 commited on
Commit
5bd8413
·
verified ·
1 Parent(s): d8acdbb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -31
app.py CHANGED
@@ -1,11 +1,95 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  def respond(
11
  message,
@@ -15,50 +99,49 @@ def respond(
15
  temperature,
16
  top_p,
17
  ):
 
18
  messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
 
 
 
 
27
 
28
  response = ""
29
 
30
- for message in client.chat_completion(
31
  messages,
32
  max_tokens=max_tokens,
33
  stream=True,
34
  temperature=temperature,
35
  top_p=top_p,
36
  ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
  demo = gr.ChatInterface(
47
  respond,
48
  additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
  ],
60
  )
61
 
62
-
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ import re
4
 
 
 
 
5
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
6
 
7
+ # Enhanced structured prompt template
8
+ STRUCTURED_PROMPT_TEMPLATE = """
9
+ You are a helpful, intelligent, and [TONE]-toned assistant designed to provide clear, accurate, and engaging answers. Adapt your response based on the query's complexity, user preferences, and context. For explanatory, technical, or conceptual questions, use the following structured format. For casual chats, greetings, or jokes, respond naturally and skip the structure unless requested.
10
+ ---
11
+ ### 🧠 Our Approach (Optional, include for complex queries)
12
+ [Outline the reasoning process or approach to the query in 1-2 sentences. Example: "We’ll define the concept, explore its components, and apply it to a real-world scenario."]
13
+ ### 🔍 What It Means
14
+ [Provide a brief, clear explanation in simple language tailored to the user’s expertise level, inferred from query context or user profile.]
15
+ ### 💡 Key Concepts
16
+ - 🔹 [Point 1: Concise explanation of a core idea, using analogies or examples if [TONE] is friendly.]
17
+ - 🔹 [Point 2: Another key aspect, with technical depth if [TONE] is expert.]
18
+ - 🔹 [Point 3: Final point, connecting to practical use or broader context.]
19
+ ### 🚀 Real-World Use
20
+ [Provide 1-2 relatable examples or applications. For technical queries, include code snippets, diagrams, or actionable steps if relevant. Offer to generate visuals or code if appropriate: "Would you like a diagram or code example?"]
21
+ ### 📚 Sources (Optional, include for factual or research-based queries)
22
+ - [Cite reliable sources, e.g., web results, X posts, or authoritative references, used to inform the response.]
23
+ - [If no sources are available, state: "Based on general knowledge up to [CURRENT_DATE]."]
24
+ ### ⚠️ Not Sure? Here’s What I Know (Optional, include for low-confidence responses)
25
+ [If the query is ambiguous or data is limited, acknowledge uncertainty, provide the best available information, and suggest alternative ways to clarify or explore the topic.]
26
+ ### 📌 Summary
27
+ - ✅ [Main takeaway 1: A concise, actionable insight.]
28
+ - ✅ [Main takeaway 2: Another key point or implication.]
29
+ - 🛠️ [Interactive prompt: Invite follow-up questions, deeper dives, or offer additional resources. Example: "Want a step-by-step guide or a related topic explained?"]
30
+ ### 😄 Want More? (Optional, include for casual or engaging queries)
31
+ [For casual queries, add a conversational hook to maintain engagement, e.g., "Want another joke or a fun fact about this?"]
32
+ ---
33
+ **Backend Instructions (Not included in response):**
34
+ - **Query Classification**: Pre-process the query to determine complexity (simple, complex, casual) using NLP (e.g., keyword analysis, intent detection). Set [COMPLEXITY_LEVEL].
35
+ - **Tone Adaptation**: Set [TONE] (e.g., friendly, technical, formal) based on user profile, session history, or query context. Default: friendly.
36
+ - **Reasoning Loop**: For [COMPLEXITY_LEVEL] = complex, run an iterative reasoning step to refine the answer, querying external APIs (e.g., web search, X posts) if needed.
37
+ - **Source Integration**: If factual data is required, fetch real-time information and populate [SOURCES]. Ensure transparency with citations.
38
+ - **Confidence Check**: If confidence < threshold (e.g., 80%), trigger [NOT_SURE] section and suggest clarifications.
39
+ - **Interactive Offers**: For technical queries, check if visuals/code are relevant (e.g., "diagram" for concepts, "code" for programming). Include offer in [REAL_WORLD_USE].
40
+ - **Personalization**: Access user preferences (e.g., expertise level, preferred depth) from session memory to tailor depth and examples.
41
+ - **Current Date**: Replace [CURRENT_DATE] with the current date (e.g., May 03, 2025).
42
+ """
43
+
44
+ # Updated keywords
45
+ CASUAL_KEYWORDS = {
46
+ "greetings": ["hi", "hello", "hey", "howdy", "yo", "sup", "what's up"],
47
+ "jokes": ["joke", "funny", "laugh"],
48
+ "feelings": ["how are you", "how’s it going", "what’s up", "are you okay"],
49
+ }
50
+
51
+ TECHNICAL_QUESTION_KEYWORDS = [
52
+ r"\bhow\b",
53
+ r"\bwhat\b",
54
+ r"\bwhy\b",
55
+ r"\bexplain\b",
56
+ r"\bsteps?\b",
57
+ r"\bprocess\b",
58
+ r"\bdefine\b",
59
+ r"\bmeaning of\b",
60
+ r"\bconcept\b",
61
+ r"\buses?\b",
62
+ r"\bexample\b",
63
+ ]
64
+
65
+ COMPLEX_QUERY_KEYWORDS = [
66
+ r"\boptimize\b",
67
+ r"\bimplement\b",
68
+ r"\bdesign\b",
69
+ r"\barchitecture\b",
70
+ r"\bcompare\b",
71
+ r"\bcomplex\b",
72
+ r"\bstrategy\b",
73
+ ]
74
+
75
+ TECHNICAL_VISUAL_KEYWORDS = [
76
+ r"\bcode\b",
77
+ r"\bprogram\b",
78
+ r"\bscript\b",
79
+ r"\bdiagram\b",
80
+ r"\bvisual\b",
81
+ r"\bgraph\b",
82
+ ]
83
+
84
+ def is_casual_input(text: str) -> bool:
85
+ text = text.lower().strip()
86
+ return any(text in group for group in CASUAL_KEYWORDS.values())
87
+
88
+ def needs_structured_format(text: str) -> bool:
89
+ text = text.lower().strip()
90
+ return any(re.search(pattern, text) for pattern in TECHNICAL_QUESTION_KEYWORDS) or \
91
+ any(re.search(pattern, text) for pattern in COMPLEX_QUERY_KEYWORDS) or \
92
+ any(re.search(pattern, text) for pattern in TECHNICAL_VISUAL_KEYWORDS)
93
 
94
  def respond(
95
  message,
 
99
  temperature,
100
  top_p,
101
  ):
102
+ # Prepare message history
103
  messages = [{"role": "system", "content": system_message}]
104
+ for user, assistant in history:
105
+ if user:
106
+ messages.append({"role": "user", "content": user})
107
+ if assistant:
108
+ messages.append({"role": "assistant", "content": assistant})
109
 
110
+ # Decide the response style
111
+ if is_casual_input(message):
112
+ # Direct casual message, respond as-is
113
+ messages.append({"role": "user", "content": message})
114
+ elif needs_structured_format(message):
115
+ # Apply structured educational format
116
+ structured_input = STRUCTURED_PROMPT_TEMPLATE.replace("[TONE]", "friendly").replace("[CURRENT_DATE]", "May 03, 2025") + f"\nUser has asked: {message}"
117
+ messages.append({"role": "user", "content": structured_input})
118
+ else:
119
+ # Default: semi-structured but relaxed
120
+ messages.append({"role": "user", "content": message})
121
 
122
  response = ""
123
 
124
+ for token in client.chat_completion(
125
  messages,
126
  max_tokens=max_tokens,
127
  stream=True,
128
  temperature=temperature,
129
  top_p=top_p,
130
  ):
131
+ delta = token.choices[0].delta.content
132
+ if delta:
133
+ response += delta
134
+ yield response
 
135
 
 
 
 
136
  demo = gr.ChatInterface(
137
  respond,
138
  additional_inputs=[
139
+ gr.Textbox(value="You are a friendly assistant. Adapt your tone to the user's intent. Use structured format for educational topics.", label="System message"),
140
+ gr.Slider(minimum=64, maximum=2048, value=512, step=16, label="Max Tokens"),
141
+ gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
142
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"),
 
 
 
 
 
 
143
  ],
144
  )
145
 
 
146
  if __name__ == "__main__":
147
+ demo.launch(share=True)