Spaces:
Sleeping
Sleeping
Download app.py from gampala1234/study: direct link, hf CLI and curl.
- Browser
- Download file 8.13 kB
-
https://huggingface.co/spaces/gampala1234/study/resolve/main/app.py
- Command line
-
hf download hf://spaces/gampala1234/study/app.py
-
curl -L -o app.py https://huggingface.co/spaces/gampala1234/study/resolve/main/app.py
8.13 kB
| import gradio as gr | |
| from huggingface_hub import InferenceClient | |
| from fastapi import FastAPI, WebSocket | |
| import re | |
| import uvicorn | |
| client = InferenceClient("HuggingFaceH4/zephyr-7b-beta") | |
| # Enhanced structured prompt template | |
| STRUCTURED_PROMPT_TEMPLATE = """ | |
| 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. | |
| --- | |
| ### 🧠 Our Approach (Optional, include for complex queries) | |
| [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."] | |
| ### 🔍 What It Means | |
| [Provide a brief, clear explanation in simple language tailored to the user’s expertise level, inferred from query context or user profile.] | |
| ### 💡 Key Concepts | |
| - 🔹 [Point 1: Concise explanation of a core idea, using analogies or examples if [TONE] is friendly.] | |
| - 🔹 [Point 2: Another key aspect, with technical depth if [TONE] is expert.] | |
| - 🔹 [Point 3: Final point, connecting to practical use or broader context.] | |
| ### 🚀 Real-World Use | |
| [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?"] | |
| ### 📚 Sources (Optional, include for factual or research-based queries) | |
| - [Cite reliable sources, e.g., web results, X posts, or authoritative references, used to inform the response.] | |
| - [If no sources are available, state: "Based on general knowledge up to [CURRENT_DATE]."] | |
| ### ⚠️ Not Sure? Here’s What I Know (Optional, include for low-confidence responses) | |
| [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.] | |
| ### 📌 Summary | |
| - ✅ [Main takeaway 1: A concise, actionable insight.] | |
| - ✅ [Main takeaway 2: Another key point or implication.] | |
| - 🛠️ [Interactive prompt: Invite follow-up questions, deeper dives, or offer additional resources. Example: "Want a step-by-step guide or a related topic explained?"] | |
| ### 😄 Want More? (Optional, include for casual or engaging queries) | |
| [For casual queries, add a conversational hook to maintain engagement, e.g., "Want another joke or a fun fact about this?"] | |
| --- | |
| **Backend Instructions (Not included in response):** | |
| - **Query Classification**: Pre-process the query to determine complexity (simple, complex, casual) using NLP (e.g., keyword analysis, intent detection). Set [COMPLEXITY_LEVEL]. | |
| - **Tone Adaptation**: Set [TONE] (e.g., friendly, technical, formal) based on user profile, session history, or query context. Default: friendly. | |
| - **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. | |
| - **Source Integration**: If factual data is required, fetch real-time information and populate [SOURCES]. Ensure transparency with citations. | |
| - **Confidence Check**: If confidence < threshold (e.g., 80%), trigger [NOT_SURE] section and suggest clarifications. | |
| - **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]. | |
| - **Personalization**: Access user preferences (e.g., expertise level, preferred depth) from session memory to tailor depth and examples. | |
| - **Current Date**: Replace [CURRENT_DATE] with the current date (e.g., May 03, 2025). | |
| """ | |
| # Updated keywords | |
| CASUAL_KEYWORDS = { | |
| "greetings": ["hi", "hello", "hey", "howdy", "yo", "sup", "what's up"], | |
| "jokes": ["joke", "funny", "laugh"], | |
| "feelings": ["how are you", "how’s it going", "what’s up", "are you okay"], | |
| } | |
| TECHNICAL_QUESTION_KEYWORDS = [ | |
| r"\bhow\b", | |
| r"\bwhat\b", | |
| r"\bwhy\b", | |
| r"\bexplain\b", | |
| r"\bsteps?\b", | |
| r"\bprocess\b", | |
| r"\bdefine\b", | |
| r"\bmeaning of\b", | |
| r"\bconcept\b", | |
| r"\buses?\b", | |
| r"\bexample\b", | |
| ] | |
| COMPLEX_QUERY_KEYWORDS = [ | |
| r"\boptimize\b", | |
| r"\bimplement\b", | |
| r"\bdesign\b", | |
| r"\barchitecture\b", | |
| r"\bcompare\b", | |
| r"\bcomplex\b", | |
| r"\bstrategy\b", | |
| ] | |
| TECHNICAL_VISUAL_KEYWORDS = [ | |
| r"\bcode\b", | |
| r"\bprogram\b", | |
| r"\bscript\b", | |
| r"\bdiagram\b", | |
| r"\bvisual\b", | |
| r"\bgraph\b", | |
| ] | |
| def is_casual_input(text: str) -> bool: | |
| text = text.lower().strip() | |
| return any(text in group for group in CASUAL_KEYWORDS.values()) | |
| def needs_structured_format(text: str) -> bool: | |
| text = text.lower().strip() | |
| return any(re.search(pattern, text) for pattern in TECHNICAL_QUESTION_KEYWORDS) or \ | |
| any(re.search(pattern, text) for pattern in COMPLEX_QUERY_KEYWORDS) or \ | |
| any(re.search(pattern, text) for pattern in TECHNICAL_VISUAL_KEYWORDS) | |
| def respond( | |
| message, | |
| history: list[tuple[str, str]], | |
| system_message, | |
| max_tokens, | |
| temperature, | |
| top_p, | |
| ): | |
| try: | |
| # Prepare message history | |
| messages = [{"role": "system", "content": system_message}] | |
| for user, assistant in history: | |
| if user: | |
| messages.append({"role": "user", "content": user}) | |
| if assistant: | |
| messages.append({"role": "assistant", "content": assistant}) | |
| # Decide the response style | |
| if is_casual_input(message): | |
| messages.append({"role": "user", "content": message}) | |
| elif needs_structured_format(message): | |
| structured_input = STRUCTURED_PROMPT_TEMPLATE.replace("[TONE]", "friendly").replace("[CURRENT_DATE]", "May 03, 2025") + f"\nUser has asked: {message}" | |
| messages.append({"role": "user", "content": structured_input}) | |
| else: | |
| messages.append({"role": "user", "content": message}) | |
| # Stream response | |
| response = "" | |
| for token in client.chat_completion( | |
| messages, | |
| max_tokens=max_tokens, | |
| stream=True, | |
| temperature=temperature, | |
| top_p=top_p, | |
| ): | |
| delta = token.choices[0].delta.content | |
| if delta: | |
| response += delta | |
| yield response | |
| except Exception as e: | |
| yield f"Error during streaming: {str(e)}" | |
| # FastAPI app | |
| app = FastAPI() | |
| # Mount Gradio app for debugging (optional) | |
| demo = gr.ChatInterface( | |
| respond, | |
| additional_inputs=[ | |
| 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"), | |
| gr.Slider(minimum=64, maximum=2048, value=512, step=16, label="Max Tokens"), | |
| gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature"), | |
| gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"), | |
| ], | |
| ) | |
| app = gr.mount_gradio_app(app, demo, path="/gradio") | |
| # Custom WebSocket endpoint for streaming | |
| async def stream_chat(websocket: WebSocket): | |
| await websocket.accept() | |
| try: | |
| data = await websocket.receive_json() | |
| message = data.get("message", "") | |
| system_message = data.get("system_message", "You are a friendly assistant. Adapt your tone to the user's intent. Use structured format for answering advanced and important topics.") | |
| max_tokens = data.get("max_tokens", 1200) | |
| temperature = data.get("temperature", 0.7) | |
| top_p = data.get("top_p", 0.95) | |
| for response in respond(message, [], system_message, max_tokens, temperature, top_p): | |
| await websocket.send_text(response) | |
| except Exception as e: | |
| await websocket.send_text(f"Error: {str(e)}") | |
| finally: | |
| await websocket.close() | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) |