Maxwell commited on
Commit
2d4df92
Β·
verified Β·
1 Parent(s): e921e0a

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +53 -23
app.py CHANGED
@@ -3,6 +3,8 @@ import json
3
  import time
4
  import uuid
5
  import asyncio
 
 
6
  import gradio as gr
7
  from fastapi import FastAPI, Request
8
  from fastapi.responses import StreamingResponse, JSONResponse
@@ -19,6 +21,8 @@ SYSTEM_PROMPT = (
19
  )
20
 
21
  llm = None # loaded in background on startup
 
 
22
 
23
  def _load_model():
24
  global llm
@@ -44,7 +48,7 @@ def _load_model():
44
  llm = Llama(
45
  model_path=BASE_PATH,
46
  lora_path=LORA_PATH,
47
- n_ctx=2048,
48
  n_threads=2,
49
  verbose=False,
50
  )
@@ -82,12 +86,34 @@ async def chat_completions(request: Request):
82
  async def event_stream():
83
  resp_id = "chatcmpl-" + uuid.uuid4().hex
84
  created = int(time.time())
85
- for chunk in llm.create_chat_completion(
86
- messages=messages,
87
- max_tokens=max_tokens,
88
- temperature=temperature,
89
- stream=True,
90
- ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  delta = chunk["choices"][0]["delta"]
92
  finish = chunk["choices"][0].get("finish_reason")
93
  data = {
@@ -98,16 +124,19 @@ async def chat_completions(request: Request):
98
  "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
99
  }
100
  yield f"data: {json.dumps(data)}\n\n"
101
- await asyncio.sleep(0)
102
  yield "data: [DONE]\n\n"
103
  return StreamingResponse(event_stream(), media_type="text/event-stream")
104
 
105
- result = llm.create_chat_completion(
106
- messages=messages,
107
- max_tokens=max_tokens,
108
- temperature=temperature,
109
- stream=False,
110
- )
 
 
 
 
111
  return JSONResponse(result)
112
 
113
  # ── Gradio UI ─────────────────────────────────────────────────────────────────
@@ -131,15 +160,16 @@ def respond(message, history, temperature, max_tokens):
131
  messages.append({"role": "user", "content": message})
132
 
133
  response = ""
134
- for chunk in llm.create_chat_completion(
135
- messages=messages,
136
- max_tokens=int(max_tokens),
137
- temperature=temperature,
138
- stream=True,
139
- ):
140
- delta = chunk["choices"][0]["delta"].get("content", "")
141
- response += delta
142
- yield response
 
143
 
144
  def model_status():
145
  if llm is not None:
 
3
  import time
4
  import uuid
5
  import asyncio
6
+ import threading
7
+ import queue as queue_mod
8
  import gradio as gr
9
  from fastapi import FastAPI, Request
10
  from fastapi.responses import StreamingResponse, JSONResponse
 
21
  )
22
 
23
  llm = None # loaded in background on startup
24
+ # llama.cpp contexts are not safe for concurrent generation β€” one request at a time
25
+ infer_lock = threading.Lock()
26
 
27
  def _load_model():
28
  global llm
 
48
  llm = Llama(
49
  model_path=BASE_PATH,
50
  lora_path=LORA_PATH,
51
+ n_ctx=8192,
52
  n_threads=2,
53
  verbose=False,
54
  )
 
86
  async def event_stream():
87
  resp_id = "chatcmpl-" + uuid.uuid4().hex
88
  created = int(time.time())
89
+ # Run generation in a worker thread; pass chunks back through a
90
+ # queue so the event loop (health checks, UI) never blocks.
91
+ q = queue_mod.Queue(maxsize=64)
92
+ DONE = object()
93
+
94
+ def produce():
95
+ try:
96
+ with infer_lock:
97
+ for chunk in llm.create_chat_completion(
98
+ messages=messages,
99
+ max_tokens=max_tokens,
100
+ temperature=temperature,
101
+ stream=True,
102
+ ):
103
+ q.put(chunk)
104
+ except Exception as e:
105
+ q.put(e)
106
+ finally:
107
+ q.put(DONE)
108
+
109
+ threading.Thread(target=produce, daemon=True).start()
110
+ while True:
111
+ chunk = await asyncio.to_thread(q.get)
112
+ if chunk is DONE:
113
+ break
114
+ if isinstance(chunk, Exception):
115
+ yield f"data: {json.dumps({'error': str(chunk)})}\n\n"
116
+ break
117
  delta = chunk["choices"][0]["delta"]
118
  finish = chunk["choices"][0].get("finish_reason")
119
  data = {
 
124
  "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
125
  }
126
  yield f"data: {json.dumps(data)}\n\n"
 
127
  yield "data: [DONE]\n\n"
128
  return StreamingResponse(event_stream(), media_type="text/event-stream")
129
 
130
+ def generate():
131
+ with infer_lock:
132
+ return llm.create_chat_completion(
133
+ messages=messages,
134
+ max_tokens=max_tokens,
135
+ temperature=temperature,
136
+ stream=False,
137
+ )
138
+
139
+ result = await asyncio.to_thread(generate)
140
  return JSONResponse(result)
141
 
142
  # ── Gradio UI ─────────────────────────────────────────────────────────────────
 
160
  messages.append({"role": "user", "content": message})
161
 
162
  response = ""
163
+ with infer_lock:
164
+ for chunk in llm.create_chat_completion(
165
+ messages=messages,
166
+ max_tokens=int(max_tokens),
167
+ temperature=temperature,
168
+ stream=True,
169
+ ):
170
+ delta = chunk["choices"][0]["delta"].get("content", "")
171
+ response += delta
172
+ yield response
173
 
174
  def model_status():
175
  if llm is not None: