grimjim commited on
Commit
c31cef0
·
1 Parent(s): 441317c
Files changed (1) hide show
  1. app.py +37 -95
app.py CHANGED
@@ -20,40 +20,11 @@ DEFAULT_SYSTEM_PROMPT = (
20
  "ask for clarification only when needed, and do not invent details."
21
  )
22
 
23
- CSS = """
24
- .gradio-container img,
25
- .gradio-container video,
26
- .gradio-container canvas {
27
- max-width: 100%;
28
- max-height: 360px;
29
- object-fit: contain;
30
- }
31
- .gradio-container button svg,
32
- .gradio-container [role="button"] svg,
33
- .gradio-container label svg,
34
- .gradio-container .icon svg {
35
- width: 1.1rem !important;
36
- height: 1.1rem !important;
37
- max-width: 1.1rem !important;
38
- max-height: 1.1rem !important;
39
- }
40
- footer {
41
- display: none !important;
42
- }
43
- """
44
 
45
  @lru_cache(maxsize=1)
46
  def get_llm() -> Llama:
47
- print(
48
- f"Loading GGUF model {MODEL_REPO}/{MODEL_FILE} "
49
- f"with n_ctx={N_CTX}, n_batch={N_BATCH}, n_threads={N_THREADS}",
50
- flush=True,
51
- )
52
- model_path = hf_hub_download(
53
- repo_id=MODEL_REPO,
54
- filename=MODEL_FILE,
55
- local_dir=os.getenv("MODEL_DIR") or None,
56
- )
57
  print(f"Model file ready: {model_path}", flush=True)
58
 
59
  return Llama(
@@ -73,8 +44,7 @@ def trim_history(history: list[Any]) -> list[Any]:
73
  if not history:
74
  return []
75
 
76
- max_messages = MAX_HISTORY_TURNS * 2
77
- return history[-max_messages:]
78
 
79
 
80
  def build_messages(
@@ -82,7 +52,7 @@ def build_messages(
82
  history: list[Any],
83
  system_message: str,
84
  ) -> list[dict[str, str]]:
85
- messages = [{"role": "system", "content": system_message.strip()}]
86
 
87
  for item in trim_history(history):
88
  if isinstance(item, dict):
@@ -101,81 +71,53 @@ def build_messages(
101
  return messages
102
 
103
 
104
- def generate_reply(
105
- message: str,
106
- history: list[Any],
107
- system_message: str,
108
- max_tokens: int,
109
- temperature: float,
110
- top_p: float,
111
- repeat_penalty: float,
112
- ) -> Any:
113
  if not message.strip():
114
  return
115
 
116
  print(f"Received chat request: {message[:120]!r}", flush=True)
117
- yield "Request received. Loading the local model if needed..."
118
-
119
- try:
120
- llm = get_llm()
121
- messages = build_messages(message, history, system_message or DEFAULT_SYSTEM_PROMPT)
122
- output = ""
123
- yield "Model ready. Generating..."
124
-
125
- stream = llm.create_chat_completion(
126
- messages=messages,
127
- max_tokens=max_tokens,
128
- temperature=temperature,
129
- top_p=top_p,
130
- repeat_penalty=repeat_penalty,
131
- stream=True,
132
- )
133
-
134
- for chunk in stream:
135
- delta = chunk["choices"][0].get("delta", {})
136
- token = delta.get("content") or ""
137
- if token:
138
- output += token
139
- yield output
140
- except Exception as exc:
141
- print(f"Generation failed: {exc!r}", flush=True)
142
- yield f"Generation failed: {exc}"
143
 
144
 
145
  chatbot = gr.ChatInterface(
146
- generate_reply,
147
  additional_inputs=[
148
- gr.Textbox(
149
- value=DEFAULT_SYSTEM_PROMPT,
150
- label="System message",
151
- lines=3,
152
- ),
153
- gr.Slider(
154
- minimum=32,
155
- maximum=1024,
156
- value=384,
157
- step=16,
158
- label="Max new tokens",
159
- ),
160
  gr.Slider(
161
- minimum=0.0,
162
- maximum=1.5,
163
- value=0.7,
164
  step=0.05,
165
- label="Temperature",
166
- ),
167
- gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-p"),
168
- gr.Slider(
169
- minimum=1.0,
170
- maximum=1.3,
171
- value=1.1,
172
- step=0.01,
173
- label="Repeat penalty",
174
  ),
175
  ],
176
  )
177
 
178
- with gr.Blocks(css=CSS) as demo:
179
  chatbot.render()
180
 
181
 
 
20
  "ask for clarification only when needed, and do not invent details."
21
  )
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  @lru_cache(maxsize=1)
25
  def get_llm() -> Llama:
26
+ print(f"Loading model {MODEL_REPO}/{MODEL_FILE}", flush=True)
27
+ model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
 
 
 
 
 
 
 
 
28
  print(f"Model file ready: {model_path}", flush=True)
29
 
30
  return Llama(
 
44
  if not history:
45
  return []
46
 
47
+ return history[-(MAX_HISTORY_TURNS * 2) :]
 
48
 
49
 
50
  def build_messages(
 
52
  history: list[Any],
53
  system_message: str,
54
  ) -> list[dict[str, str]]:
55
+ messages = [{"role": "system", "content": system_message}]
56
 
57
  for item in trim_history(history):
58
  if isinstance(item, dict):
 
71
  return messages
72
 
73
 
74
+ def respond(
75
+ message,
76
+ history: list[dict[str, str]],
77
+ system_message,
78
+ max_tokens,
79
+ temperature,
80
+ top_p,
81
+ ):
 
82
  if not message.strip():
83
  return
84
 
85
  print(f"Received chat request: {message[:120]!r}", flush=True)
86
+
87
+ llm = get_llm()
88
+ messages = build_messages(message, history, system_message or DEFAULT_SYSTEM_PROMPT)
89
+ response = ""
90
+
91
+ for chunk in llm.create_chat_completion(
92
+ messages=messages,
93
+ max_tokens=max_tokens,
94
+ temperature=temperature,
95
+ top_p=top_p,
96
+ stream=True,
97
+ ):
98
+ token = chunk["choices"][0].get("delta", {}).get("content") or ""
99
+ if token:
100
+ response += token
101
+ yield response
 
 
 
 
 
 
 
 
 
 
102
 
103
 
104
  chatbot = gr.ChatInterface(
105
+ respond,
106
  additional_inputs=[
107
+ gr.Textbox(value=DEFAULT_SYSTEM_PROMPT, label="System message"),
108
+ gr.Slider(minimum=32, maximum=1024, value=384, step=16, label="Max new tokens"),
109
+ gr.Slider(minimum=0.0, maximum=1.5, value=0.7, step=0.05, label="Temperature"),
 
 
 
 
 
 
 
 
 
110
  gr.Slider(
111
+ minimum=0.1,
112
+ maximum=1.0,
113
+ value=0.9,
114
  step=0.05,
115
+ label="Top-p (nucleus sampling)",
 
 
 
 
 
 
 
 
116
  ),
117
  ],
118
  )
119
 
120
+ with gr.Blocks() as demo:
121
  chatbot.render()
122
 
123