File size: 8,132 Bytes
a1361cf
 
5e6541a
5bd8413
5e6541a
a1361cf
 
 
5bd8413
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1361cf
 
 
 
 
 
 
 
 
4489ff3
 
 
 
 
 
 
 
a1361cf
4489ff3
 
 
 
 
 
 
 
a1361cf
4489ff3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1361cf
5e6541a
 
 
 
a1361cf
 
 
5bd8413
 
 
 
a1361cf
 
5e6541a
 
 
 
 
 
 
 
 
b6a8f39
 
5e6541a
 
 
 
 
 
 
 
a1361cf
 
5e6541a
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
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
@app.websocket("/chat/stream")
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)