asv7j commited on
Commit
fc95e33
1 Parent(s): 8bf909c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +216 -0
app.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.responses import HTMLResponse
3
+ from transformers import AutoTokenizer
4
+ from pydantic import BaseModel
5
+
6
+ class Message(BaseModel):
7
+ content: str
8
+ token: int
9
+
10
+ class System(BaseModel):
11
+ sys_prompt: str
12
+
13
+
14
+ app = FastAPI()
15
+
16
+ @app.get("/, response_class=HTMLResponse")
17
+ def greet_json():
18
+ return '''<!DOCTYPE html>
19
+ <html lang="en">
20
+ <head>
21
+ <meta charset="UTF-8">
22
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
23
+ <title>FastAPI Chatbot</title>
24
+ <style>
25
+ body {
26
+ font-family: Arial, sans-serif;
27
+ margin: 0;
28
+ padding: 0;
29
+ background-color: #f4f4f9;
30
+ display: flex;
31
+ flex-direction: column;
32
+ align-items: center;
33
+ }
34
+ .container {
35
+ margin-top: 60px;
36
+ width: 90%;
37
+ margin-bottom: 20px;
38
+ }
39
+ .system-prompt {
40
+ display: flex;
41
+ justify-content: space-between;
42
+ margin-bottom: 20px;
43
+ }
44
+ .system-prompt input {
45
+ width: 70%;
46
+ padding: 10px;
47
+ border: 1px solid #ccc;
48
+ border-radius: 4px;
49
+ }
50
+ .system-prompt button {
51
+ padding: 10px 20px;
52
+ border: none;
53
+ background-color: #007bff;
54
+ color: white;
55
+ border-radius: 4px;
56
+ cursor: pointer;
57
+ }
58
+ .system-prompt button:hover {
59
+ background-color: #0056b3;
60
+ }
61
+ .chatbox {
62
+ background-color: #fff;
63
+ border-radius: 8px;
64
+ box-shadow: 0 2px 5px rgba(0,0,0,0.1);
65
+ padding: 20px;
66
+ height: 400px;
67
+ overflow-y: auto;
68
+ }
69
+ .message {
70
+ margin-bottom: 10px;
71
+ }
72
+ .user {
73
+ text-align: right;
74
+ color: #007bff;
75
+ }
76
+ .assistant {
77
+ text-align: left;
78
+ color: #333;
79
+ }
80
+ .input-section {
81
+ display: flex;
82
+ width: 100%;
83
+ margin-top: 20px;
84
+ }
85
+ .input-section input {
86
+ flex: 1;
87
+ padding: 10px;
88
+ border: 1px solid #ccc;
89
+ border-radius: 4px;
90
+ margin-right: 10px;
91
+ }
92
+ .input-section input:focus {
93
+ outline: none;
94
+ border-color: #007bff;
95
+ }
96
+ .input-section button {
97
+ padding: 10px 20px;
98
+ border: none;
99
+ background-color: #28a745;
100
+ color: white;
101
+ border-radius: 4px;
102
+ cursor: pointer;
103
+ }
104
+ .input-section button:hover {
105
+ background-color: #218838;
106
+ }
107
+ .token-input {
108
+ width: 100px;
109
+ margin-left: 10px;
110
+ }
111
+ </style>
112
+ </head>
113
+ <body>
114
+ <div class="container">
115
+ <div class="system-prompt">
116
+ <input type="text" id="systemPrompt" placeholder="Enter System Prompt">
117
+ <button onclick="setSystemPromptAndClearHistory()">Set prompt and clear history</button>
118
+ </div>
119
+ <div class="chatbox" id="chatbox"></div>
120
+ <div class="input-section">
121
+ <input type="text" id="userInput" placeholder="Type your message here...">
122
+ <input type="number" id="tokenLength" class="token-input" value="50" placeholder="Tokens">
123
+ <button onclick="sendMessage()">Send</button>
124
+ </div>
125
+ </div>
126
+
127
+ <script>
128
+ async function setSystemPromptAndClearHistory() {
129
+ const systemPrompt = document.getElementById('systemPrompt').value;
130
+ const response = await fetch('/setSystemPrompt', {
131
+ method: 'POST',
132
+ headers: {
133
+ 'Content-Type': 'application/json'
134
+ },
135
+ body: JSON.stringify({ sys_prompt: systemPrompt })
136
+ });
137
+ if (response.ok) {
138
+ document.getElementById('chatbox').innerHTML = '';
139
+ alert('System prompt set and history cleared.');
140
+ } else {
141
+ alert('Failed to set system prompt.');
142
+ }
143
+ }
144
+
145
+ async function sendMessage() {
146
+ const userInput = document.getElementById('userInput').value;
147
+ const tokenLength = parseInt(document.getElementById('tokenLength').value);
148
+ if (!userInput || isNaN(tokenLength)) {
149
+ alert('Please enter a valid message and token length.');
150
+ return;
151
+ }
152
+
153
+ const chatbox = document.getElementById('chatbox');
154
+ const userMessage = document.createElement('div');
155
+ userMessage.className = 'message user';
156
+ userMessage.textContent = userInput;
157
+ chatbox.appendChild(userMessage);
158
+
159
+ const response = await fetch('/chat', {
160
+ method: 'POST',
161
+ headers: {
162
+ 'Content-Type': 'application/json'
163
+ },
164
+ body: JSON.stringify({ content: userInput, token: tokenLength })
165
+ });
166
+
167
+ if (response.ok) {
168
+ const data = await response.json();
169
+ const assistantMessage = document.createElement('div');
170
+ assistantMessage.className = 'message assistant';
171
+ assistantMessage.textContent = data.response;
172
+ chatbox.appendChild(assistantMessage);
173
+ document.getElementById('userInput').value = '';
174
+ } else {
175
+ alert('Failed to get response from server.');
176
+ }
177
+
178
+ chatbox.scrollTop = chatbox.scrollHeight;
179
+ }
180
+ </script>
181
+ </body>
182
+ </html>'''
183
+
184
+ llm = Llama.from_pretrained(
185
+ repo_id="Qwen/Qwen2.5-1.5B-Instruct-GGUF",
186
+ filename="qwen2.5-1.5b-instruct-q8_0.gguf",
187
+ verbose=False
188
+ )
189
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-1.5B-Instruct")
190
+
191
+ messages = []
192
+
193
+ @app.post("/chat")
194
+ def chat(req: Message):
195
+ messages.append({"role": "user", "content": req.content})
196
+ text = tokenizer.apply_chat_template(
197
+ messages, tokenize=False, add_generation_prompt=True
198
+ )
199
+ output = llm(text,max_tokens=req.token,echo=False)
200
+ response = output['choices'][0]['text']
201
+ messages.append({"role": "assistant", "content": response})
202
+
203
+ return {"response": response_text}
204
+
205
+
206
+ @app.post("/setSystemPrompt")
207
+ def chat(req: System):
208
+ messages.append({"role": "user", "content": req.sys_prompt})
209
+ return {"response": "System has been set"}
210
+
211
+ @app.post("/clear_chat")
212
+ def clear_chat():
213
+ global conversation_history
214
+ conversation_history = []
215
+ return {"message": "Chat history cleared"}
216
+