imspsycho commited on
Commit
90b1f52
·
verified ·
1 Parent(s): db2f6a6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +288 -0
app.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request
2
+ from fastapi.responses import StreamingResponse, JSONResponse
3
+ import requests
4
+ import json
5
+ import uuid
6
+ import uvicorn
7
+ import random
8
+ import string
9
+ import time
10
+
11
+ app = FastAPI()
12
+
13
+ # =========================================================
14
+ # CONFIG
15
+ # =========================================================
16
+
17
+ HF_BASE = "https://akhaliq-kimi-k2-6.hf.space"
18
+
19
+ HEADERS = {
20
+ "accept": "*/*",
21
+ "content-type": "application/json",
22
+ "origin": HF_BASE,
23
+ "referer": f"{HF_BASE}/?__theme=system",
24
+ "user-agent": "Mozilla/5.0",
25
+ "x-gradio-user": "api"
26
+ }
27
+
28
+ # =========================================================
29
+ # HELPERS
30
+ # =========================================================
31
+
32
+ def random_session():
33
+
34
+ return ''.join(
35
+ random.choices(
36
+ string.ascii_lowercase + string.digits,
37
+ k=12
38
+ )
39
+ )
40
+
41
+ # =========================================================
42
+ # ROOT
43
+ # =========================================================
44
+
45
+ @app.get("/")
46
+ async def root():
47
+
48
+ return {
49
+ "status": "ok",
50
+ "provider": "Kimi K2",
51
+ "openai_compatible": True
52
+ }
53
+
54
+ # =========================================================
55
+ # MODELS
56
+ # =========================================================
57
+
58
+ @app.get("/v1/models")
59
+ async def models():
60
+
61
+ return {
62
+ "object": "list",
63
+ "data": [
64
+ {
65
+ "id": "kimi-k2",
66
+ "object": "model",
67
+ "owned_by": "custom"
68
+ }
69
+ ]
70
+ }
71
+
72
+ # =========================================================
73
+ # CHAT COMPLETIONS
74
+ # =========================================================
75
+
76
+ @app.post("/v1/chat/completions")
77
+ async def chat_completions(request: Request):
78
+
79
+ body = await request.json()
80
+
81
+ messages = body.get("messages", [])
82
+ stream = body.get("stream", False)
83
+
84
+ # =====================================================
85
+ # BUILD PROMPT
86
+ # =====================================================
87
+
88
+ prompt = ""
89
+
90
+ for msg in messages:
91
+
92
+ role = msg.get("role", "user")
93
+ content = msg.get("content", "")
94
+
95
+ prompt += f"{role.upper()}: {content}\n"
96
+
97
+ # =====================================================
98
+ # SESSION
99
+ # =====================================================
100
+
101
+ session_hash = random_session()
102
+
103
+ # =====================================================
104
+ # JOIN QUEUE
105
+ # =====================================================
106
+
107
+ payload = {
108
+ "data": [
109
+ prompt,
110
+ [],
111
+ None
112
+ ],
113
+ "event_data": None,
114
+ "fn_index": 0,
115
+ "trigger_id": None,
116
+ "session_hash": session_hash
117
+ }
118
+
119
+ join_response = requests.post(
120
+ f"{HF_BASE}/gradio_api/queue/join?__theme=system",
121
+ headers=HEADERS,
122
+ json=payload,
123
+ timeout=120
124
+ )
125
+
126
+ # =====================================================
127
+ # STREAM MODE
128
+ # =====================================================
129
+
130
+ if stream:
131
+
132
+ async def generate():
133
+
134
+ completion_id = f"chatcmpl-{uuid.uuid4().hex}"
135
+
136
+ with requests.get(
137
+ f"{HF_BASE}/gradio_api/queue/data?session_hash={session_hash}",
138
+ headers={
139
+ **HEADERS,
140
+ "accept": "text/event-stream"
141
+ },
142
+ stream=True,
143
+ timeout=600
144
+ ) as r:
145
+
146
+ for line in r.iter_lines():
147
+
148
+ if not line:
149
+ continue
150
+
151
+ try:
152
+
153
+ decoded = line.decode("utf-8")
154
+
155
+ if decoded.startswith("data:"):
156
+
157
+ data_str = decoded[5:].strip()
158
+
159
+ try:
160
+
161
+ parsed = json.loads(data_str)
162
+
163
+ msg = parsed.get("msg")
164
+
165
+ # =====================================
166
+ # PROCESSING COMPLETED
167
+ # =====================================
168
+
169
+ if msg == "process_completed":
170
+
171
+ output = parsed["output"]["data"][0]
172
+
173
+ chunk = {
174
+ "id": completion_id,
175
+ "object": "chat.completion.chunk",
176
+ "created": int(time.time()),
177
+ "model": "kimi-k2",
178
+ "choices": [
179
+ {
180
+ "index": 0,
181
+ "delta": {
182
+ "content": output
183
+ },
184
+ "finish_reason": "stop"
185
+ }
186
+ ]
187
+ }
188
+
189
+ yield f"data: {json.dumps(chunk)}\n\n"
190
+
191
+ yield "data: [DONE]\n\n"
192
+
193
+ break
194
+
195
+ except:
196
+ pass
197
+
198
+ except:
199
+ pass
200
+
201
+ return StreamingResponse(
202
+ generate(),
203
+ media_type="text/event-stream"
204
+ )
205
+
206
+ # =====================================================
207
+ # NON STREAM MODE
208
+ # =====================================================
209
+
210
+ full_output = ""
211
+
212
+ with requests.get(
213
+ f"{HF_BASE}/gradio_api/queue/data?session_hash={session_hash}",
214
+ headers={
215
+ **HEADERS,
216
+ "accept": "text/event-stream"
217
+ },
218
+ stream=True,
219
+ timeout=600
220
+ ) as r:
221
+
222
+ for line in r.iter_lines():
223
+
224
+ if not line:
225
+ continue
226
+
227
+ try:
228
+
229
+ decoded = line.decode("utf-8")
230
+
231
+ if decoded.startswith("data:"):
232
+
233
+ data_str = decoded[5:].strip()
234
+
235
+ try:
236
+
237
+ parsed = json.loads(data_str)
238
+
239
+ msg = parsed.get("msg")
240
+
241
+ if msg == "process_completed":
242
+
243
+ full_output = parsed["output"]["data"][0]
244
+
245
+ break
246
+
247
+ except:
248
+ pass
249
+
250
+ except:
251
+ pass
252
+
253
+ return JSONResponse({
254
+
255
+ "id": f"chatcmpl-{uuid.uuid4().hex}",
256
+ "object": "chat.completion",
257
+ "created": int(time.time()),
258
+ "model": "kimi-k2",
259
+
260
+ "choices": [
261
+ {
262
+ "index": 0,
263
+ "message": {
264
+ "role": "assistant",
265
+ "content": full_output
266
+ },
267
+ "finish_reason": "stop"
268
+ }
269
+ ],
270
+
271
+ "usage": {
272
+ "prompt_tokens": 0,
273
+ "completion_tokens": 0,
274
+ "total_tokens": 0
275
+ }
276
+ })
277
+
278
+ # =========================================================
279
+ # START
280
+ # =========================================================
281
+
282
+ if __name__ == "__main__":
283
+
284
+ uvicorn.run(
285
+ app,
286
+ host="0.0.0.0",
287
+ port=7860
288
+ )