Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,330 +1,305 @@
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
3 |
import os
|
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 |
-
response = image_client.text_to_image(
|
162 |
-
prompt,
|
163 |
-
parameters={
|
164 |
-
"negative_prompt": "(worst quality, low quality, illustration, 3d, 2d, painting, cartoons, sketch), open mouth",
|
165 |
-
"num_inference_steps": 30,
|
166 |
-
"guidance_scale": 7.5,
|
167 |
-
"sampling_steps": 15,
|
168 |
-
"upscaler": "4x-UltraSharp",
|
169 |
-
"denoising_strength": 0.5,
|
170 |
-
}
|
171 |
-
)
|
172 |
-
return response
|
173 |
-
except Exception as e:
|
174 |
-
print(f"Image generation error: {e}")
|
175 |
-
return None
|
176 |
-
|
177 |
-
def respond(
|
178 |
-
message,
|
179 |
-
history: list[tuple[str, str]],
|
180 |
-
system_message,
|
181 |
-
max_tokens,
|
182 |
-
temperature,
|
183 |
-
top_p,
|
184 |
-
):
|
185 |
-
# First check for custom responses
|
186 |
-
custom_response = check_custom_responses(message)
|
187 |
-
if custom_response:
|
188 |
-
yield custom_response
|
189 |
-
return
|
190 |
-
|
191 |
-
if is_image_request(message):
|
192 |
try:
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
198 |
except Exception as e:
|
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 |
-
Mathematics: Step-by-step solutions with explanations.
|
253 |
-
|
254 |
-
Data Analysis: Clear interpretation and insights.
|
255 |
-
|
256 |
-
Content Creation: Adaptive writing and documentation.
|
257 |
-
|
258 |
-
Education: Tailored explanations and comprehension checks.
|
259 |
-
|
260 |
-
|
261 |
-
Advanced Mathematics
|
262 |
-
|
263 |
-
Validates methods, applies theorems, cross-references results, and reviews for pitfalls and edge cases.
|
264 |
-
|
265 |
-
|
266 |
-
Constraints
|
267 |
-
|
268 |
-
Knowledge cutoff: April 2024
|
269 |
-
|
270 |
-
No internet access or real-time updates
|
271 |
-
|
272 |
-
No persistent memory between sessions
|
273 |
-
|
274 |
-
No media generation or verification of external sources
|
275 |
-
|
276 |
-
Context limit: 25,000 tokens
|
277 |
-
|
278 |
-
|
279 |
-
Best Practices
|
280 |
-
|
281 |
-
Provide context, specify detail level, and share relevant constraints.
|
282 |
-
|
283 |
-
Request clarification if needed.
|
284 |
-
|
285 |
-
|
286 |
-
Ethical Framework
|
287 |
-
|
288 |
-
Focus on accuracy, respect for sensitive topics, transparency, and professionalism.
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
---
|
293 |
-
|
294 |
-
Version: Xylaria-1.2.9
|
295 |
-
|
296 |
-
"""
|
297 |
-
|
298 |
-
# Gradio chat interface
|
299 |
-
demo = gr.ChatInterface(
|
300 |
-
respond,
|
301 |
-
additional_inputs=[
|
302 |
-
gr.Textbox(
|
303 |
-
value=system_message,
|
304 |
-
visible=False,
|
305 |
-
),
|
306 |
-
gr.Slider(
|
307 |
-
minimum=1,
|
308 |
-
maximum=16343,
|
309 |
-
value=16343,
|
310 |
-
step=1,
|
311 |
-
label="Max new tokens"
|
312 |
-
),
|
313 |
-
gr.Slider(
|
314 |
-
minimum=0.1,
|
315 |
-
maximum=4.0,
|
316 |
-
value=0.7,
|
317 |
-
step=0.1,
|
318 |
-
label="Temperature"
|
319 |
-
),
|
320 |
-
gr.Slider(
|
321 |
-
minimum=0.1,
|
322 |
-
maximum=1.0,
|
323 |
-
value=0.95,
|
324 |
-
step=0.05,
|
325 |
-
label="Top-p (nucleus sampling)"
|
326 |
-
),
|
327 |
-
],
|
328 |
-
css=custom_css
|
329 |
-
)
|
330 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
3 |
import os
|
4 |
+
from typing import Optional, List, Tuple, Generator
|
5 |
+
import time
|
6 |
+
from functools import partial
|
7 |
+
import logging
|
8 |
+
import asyncio
|
9 |
+
from tenacity import retry, stop_after_attempt, wait_exponential
|
10 |
+
|
11 |
+
# Configure logging
|
12 |
+
logging.basicConfig(level=logging.INFO)
|
13 |
+
logger = logging.getLogger(__name__)
|
14 |
+
|
15 |
+
class ChatInterface:
|
16 |
+
def __init__(self, text_model: str, image_model: str, hf_token: str):
|
17 |
+
"""Initialize the chat interface with specified models and token."""
|
18 |
+
self.text_client = InferenceClient(text_model, token=hf_token)
|
19 |
+
self.image_client = InferenceClient(image_model, token=hf_token)
|
20 |
+
self.custom_responses = self._initialize_custom_responses()
|
21 |
+
self.system_prompt = self._initialize_system_prompt()
|
22 |
+
|
23 |
+
@staticmethod
|
24 |
+
def _initialize_system_prompt() -> str:
|
25 |
+
"""Initialize the system prompt for the AI assistant."""
|
26 |
+
return """# Xylaria AI Assistant (v1.3.0)
|
27 |
+
|
28 |
+
## Core Identity
|
29 |
+
- Name: Xylaria
|
30 |
+
- Version: 1.3.0
|
31 |
+
- Base Model: Mistral-Nemo-Instruct
|
32 |
+
- Knowledge Cutoff: April 2024
|
33 |
+
|
34 |
+
## Primary Directives
|
35 |
+
1. Provide accurate, well-researched information
|
36 |
+
2. Maintain ethical standards in all interactions
|
37 |
+
3. Adapt communication style to user needs
|
38 |
+
4. Acknowledge limitations and uncertainties
|
39 |
+
5. Prioritize user safety and wellbeing
|
40 |
+
|
41 |
+
## Technical Capabilities
|
42 |
+
- Programming & Software Development
|
43 |
+
- Mathematical Analysis & Computation
|
44 |
+
- Scientific Research & Explanation
|
45 |
+
- Data Analysis & Visualization
|
46 |
+
- Technical Writing & Documentation
|
47 |
+
- Problem-Solving & Debugging
|
48 |
+
- Educational Content Creation
|
49 |
+
|
50 |
+
## Communication Guidelines
|
51 |
+
- Use clear, precise language
|
52 |
+
- Adapt technical depth to user expertise
|
53 |
+
- Provide step-by-step explanations when needed
|
54 |
+
- Ask for clarification when necessary
|
55 |
+
- Maintain professional yet approachable tone
|
56 |
+
|
57 |
+
## Domain Expertise
|
58 |
+
1. Computer Science & Technology
|
59 |
+
- Multiple programming languages
|
60 |
+
- Software architecture & design
|
61 |
+
- Data structures & algorithms
|
62 |
+
- Best practices & patterns
|
63 |
+
|
64 |
+
2. Mathematics & Statistics
|
65 |
+
- Advanced mathematical concepts
|
66 |
+
- Statistical analysis
|
67 |
+
- Probability theory
|
68 |
+
- Data interpretation
|
69 |
+
|
70 |
+
3. Sciences
|
71 |
+
- Physics & Chemistry
|
72 |
+
- Biology & Life Sciences
|
73 |
+
- Environmental Science
|
74 |
+
- Engineering Principles
|
75 |
+
|
76 |
+
4. Humanities & Arts
|
77 |
+
- Technical Writing
|
78 |
+
- Documentation
|
79 |
+
- Creative Problem-Solving
|
80 |
+
- Research Methodology
|
81 |
+
|
82 |
+
## Response Framework
|
83 |
+
1. Analyze user query thoroughly
|
84 |
+
2. Consider context and background
|
85 |
+
3. Structure response logically
|
86 |
+
4. Provide examples when helpful
|
87 |
+
5. Verify accuracy of information
|
88 |
+
6. Include relevant caveats or limitations
|
89 |
+
|
90 |
+
## Ethical Guidelines
|
91 |
+
- Prioritize user safety
|
92 |
+
- Maintain data privacy
|
93 |
+
- Avoid harmful content
|
94 |
+
- Acknowledge uncertainties
|
95 |
+
- Provide balanced perspectives
|
96 |
+
- Respect intellectual property
|
97 |
+
|
98 |
+
## Limitations
|
99 |
+
- No real-time data access
|
100 |
+
- No persistent memory between sessions
|
101 |
+
- Cannot verify external sources
|
102 |
+
- No capability to execute code
|
103 |
+
- Limited to text and basic image generation
|
104 |
+
|
105 |
+
## Version-Specific Features
|
106 |
+
- Enhanced error handling
|
107 |
+
- Improved response consistency
|
108 |
+
- Better context awareness
|
109 |
+
- Advanced technical explanation capabilities
|
110 |
+
- Robust ethical framework"""
|
111 |
+
|
112 |
+
@staticmethod
|
113 |
+
def _initialize_custom_responses() -> dict:
|
114 |
+
"""Initialize custom response patterns in a more maintainable way."""
|
115 |
+
base_patterns = {
|
116 |
+
"name": ["xylaria"],
|
117 |
+
"developer": ["sk md saad amin"],
|
118 |
+
"strawberry_r": ["3"]
|
119 |
+
}
|
120 |
+
|
121 |
+
patterns = {}
|
122 |
+
name_variations = [
|
123 |
+
"what is ur name", "what's ur name", "whats ur name",
|
124 |
+
"what is your name", "wat is ur name", "wut is ur name"
|
125 |
+
]
|
126 |
+
dev_variations = [
|
127 |
+
"who is your developer", "who is ur developer", "who is ur dev",
|
128 |
+
"who's your developer", "who's ur dev"
|
129 |
+
]
|
130 |
+
strawberry_variations = [
|
131 |
+
"how many 'r' is in strawberry", "how many r is in strawberry",
|
132 |
+
"how many r's are in strawberry"
|
133 |
+
]
|
134 |
+
|
135 |
+
for pattern in name_variations:
|
136 |
+
patterns[pattern] = "xylaria"
|
137 |
+
patterns[pattern.capitalize()] = "xylaria"
|
138 |
+
|
139 |
+
for pattern in dev_variations:
|
140 |
+
patterns[pattern] = "sk md saad amin"
|
141 |
+
patterns[pattern.capitalize()] = "sk md saad amin"
|
142 |
+
|
143 |
+
for pattern in strawberry_variations:
|
144 |
+
patterns[pattern] = "3"
|
145 |
+
patterns[pattern.capitalize()] = "3"
|
146 |
+
|
147 |
+
return patterns
|
148 |
+
|
149 |
+
@retry(
|
150 |
+
stop=stop_after_attempt(3),
|
151 |
+
wait=wait_exponential(multiplier=1, min=4, max=10)
|
152 |
+
)
|
153 |
+
async def _generate_text_response(
|
154 |
+
self,
|
155 |
+
messages: List[dict],
|
156 |
+
max_tokens: int,
|
157 |
+
temperature: float,
|
158 |
+
top_p: float
|
159 |
+
) -> Generator[str, None, None]:
|
160 |
+
"""Generate text response with retry logic."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
161 |
try:
|
162 |
+
response = ""
|
163 |
+
async for message in self.text_client.chat_completion(
|
164 |
+
messages,
|
165 |
+
max_tokens=max_tokens,
|
166 |
+
stream=True,
|
167 |
+
temperature=temperature,
|
168 |
+
top_p=top_p,
|
169 |
+
timeout=30
|
170 |
+
):
|
171 |
+
token = message.choices[0].delta.content
|
172 |
+
response += token
|
173 |
+
yield response
|
174 |
except Exception as e:
|
175 |
+
logger.error(f"Error generating text response: {e}")
|
176 |
+
yield "I apologize, but I'm having trouble generating a response right now. Please try again in a moment."
|
177 |
+
|
178 |
+
@retry(
|
179 |
+
stop=stop_after_attempt(3),
|
180 |
+
wait=wait_exponential(multiplier=1, min=4, max=10)
|
181 |
+
)
|
182 |
+
async def _generate_image(self, prompt: str) -> Optional[bytes]:
|
183 |
+
"""Generate image with retry logic."""
|
184 |
+
try:
|
185 |
+
return await self.image_client.text_to_image(
|
186 |
+
prompt,
|
187 |
+
parameters={
|
188 |
+
"negative_prompt": "(worst quality, low quality, illustration, 3d, 2d, painting, cartoons, sketch), open mouth",
|
189 |
+
"num_inference_steps": 30,
|
190 |
+
"guidance_scale": 7.5,
|
191 |
+
"sampling_steps": 15,
|
192 |
+
"upscaler": "4x-UltraSharp",
|
193 |
+
"denoising_strength": 0.5,
|
194 |
+
},
|
195 |
+
timeout=60
|
196 |
+
)
|
197 |
+
except Exception as e:
|
198 |
+
logger.error(f"Error generating image: {e}")
|
199 |
+
return None
|
200 |
+
|
201 |
+
def is_image_request(self, message: str) -> bool:
|
202 |
+
"""Detect if the message is requesting image generation."""
|
203 |
+
image_triggers = {
|
204 |
+
"generate an image", "create an image", "draw",
|
205 |
+
"make a picture", "generate a picture", "create a picture",
|
206 |
+
"generate art", "create art", "make art", "visualize",
|
207 |
+
"show me"
|
208 |
+
}
|
209 |
+
return any(trigger in message.lower() for trigger in image_triggers)
|
210 |
+
|
211 |
+
async def respond(
|
212 |
+
self,
|
213 |
+
message: str,
|
214 |
+
history: List[Tuple[str, str]],
|
215 |
+
max_tokens: int,
|
216 |
+
temperature: float,
|
217 |
+
top_p: float,
|
218 |
+
) -> Generator[str, None, None]:
|
219 |
+
"""Main response handler with improved error handling."""
|
220 |
+
try:
|
221 |
+
# Check for custom responses first
|
222 |
+
message_lower = message.lower()
|
223 |
+
for pattern, response in self.custom_responses.items():
|
224 |
+
if pattern in message_lower:
|
225 |
+
yield response
|
226 |
+
return
|
227 |
+
|
228 |
+
# Handle image generation requests
|
229 |
+
if self.is_image_request(message):
|
230 |
+
image = await self._generate_image(message)
|
231 |
+
if image:
|
232 |
+
yield f"Here's your generated image based on: {message}"
|
233 |
+
else:
|
234 |
+
yield "I apologize, but I couldn't generate the image. Please try again."
|
235 |
+
return
|
236 |
+
|
237 |
+
# Prepare conversation history with system prompt
|
238 |
+
messages = [{"role": "system", "content": self.system_prompt}]
|
239 |
+
for user_msg, assistant_msg in history:
|
240 |
+
if user_msg:
|
241 |
+
messages.append({"role": "user", "content": user_msg})
|
242 |
+
if assistant_msg:
|
243 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
244 |
+
messages.append({"role": "user", "content": message})
|
245 |
+
|
246 |
+
# Generate text response
|
247 |
+
async for response in self._generate_text_response(
|
248 |
+
messages, max_tokens, temperature, top_p
|
249 |
+
):
|
250 |
+
yield response
|
251 |
|
252 |
+
except Exception as e:
|
253 |
+
logger.error(f"Error in respond function: {e}")
|
254 |
+
yield "I encountered an error. Please try again or contact support if the issue persists."
|
255 |
+
|
256 |
+
def create_interface(hf_token: str):
|
257 |
+
"""Create and configure the Gradio interface."""
|
258 |
+
chat = ChatInterface(
|
259 |
+
text_model="mistralai/Mistral-Nemo-Instruct-2407",
|
260 |
+
image_model="SG161222/RealVisXL_V3.0",
|
261 |
+
hf_token=hf_token
|
262 |
+
)
|
263 |
|
264 |
+
return gr.ChatInterface(
|
265 |
+
partial(chat.respond),
|
266 |
+
additional_inputs=[
|
267 |
+
gr.Slider(
|
268 |
+
minimum=1,
|
269 |
+
maximum=16343,
|
270 |
+
value=16343,
|
271 |
+
step=1,
|
272 |
+
label="Max new tokens"
|
273 |
+
),
|
274 |
+
gr.Slider(
|
275 |
+
minimum=0.1,
|
276 |
+
maximum=4.0,
|
277 |
+
value=0.7,
|
278 |
+
step=0.1,
|
279 |
+
label="Temperature"
|
280 |
+
),
|
281 |
+
gr.Slider(
|
282 |
+
minimum=0.1,
|
283 |
+
maximum=1.0,
|
284 |
+
value=0.95,
|
285 |
+
step=0.05,
|
286 |
+
label="Top-p (nucleus sampling)"
|
287 |
+
),
|
288 |
+
],
|
289 |
+
css="""
|
290 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap');
|
291 |
+
body, .gradio-container {
|
292 |
+
font-family: 'Inter', sans-serif;
|
293 |
+
}
|
294 |
+
"""
|
295 |
+
)
|
296 |
+
|
297 |
+
if __name__ == "__main__":
|
298 |
+
# Get token from environment variable
|
299 |
+
hf_token = os.getenv("hf_token")
|
300 |
+
if not hf_token:
|
301 |
+
raise ValueError("Please set the hf_token environment variable")
|
302 |
+
|
303 |
+
# Create and launch the interface
|
304 |
+
demo = create_interface(hf_token)
|
305 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|