Spaces:
Paused
Paused
Upload folder using huggingface_hub
Browse files- README.md +32 -7
- app.py +337 -0
- requirements.txt +3 -0
README.md
CHANGED
|
@@ -1,13 +1,38 @@
|
|
| 1 |
---
|
| 2 |
-
title: Graph
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.19.0
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
-
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Graph-PrefLexOR Scientific Reasoning
|
| 3 |
+
emoji: 🧠
|
| 4 |
+
colorFrom: gray
|
| 5 |
+
colorTo: blue
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.19.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
+
short_description: Graph-native LLM scientific reasoning with graph viz
|
| 10 |
+
python_version: "3.12"
|
| 11 |
+
startup_duration_timeout: 1h
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# Graph-PrefLexOR: Graph-Native Reinforcement Learning for Scientific Hypothesis Generation
|
| 15 |
+
|
| 16 |
+
This Space demonstrates **[lamm-mit/Graph-Preflexor-8b_12292025](https://huggingface.co/lamm-mit/Graph-Preflexor-8b_12292025)** — a Qwen3-8B model fine-tuned with graph-native reinforcement learning (ORPO + Graph-GRPO) to produce structured, traceable scientific reasoning.
|
| 17 |
+
|
| 18 |
+
## How it works
|
| 19 |
+
|
| 20 |
+
The model reasons through scientific questions using explicit structured blocks:
|
| 21 |
+
|
| 22 |
+
1. **`<brainstorm>`** — divergent exploration of hypotheses and mechanisms
|
| 23 |
+
2. **`<graph>`** — verbal sketch of the conceptual graph
|
| 24 |
+
3. **`<graph_json>`** — machine-readable knowledge graph (nodes + edges)
|
| 25 |
+
4. **`<patterns>`** — abstract motifs and design rules
|
| 26 |
+
5. **`<synthesis>`** — coherent narrative assembled from the graph
|
| 27 |
+
|
| 28 |
+
The Space parses the `<graph_json>` block and renders it as an interactive **Mermaid diagram** alongside the chat.
|
| 29 |
+
|
| 30 |
+
## Paper
|
| 31 |
+
|
| 32 |
+
[Graph-Native Reinforcement Learning Enables Traceable Scientific Hypothesis Generation through Conceptual Recombination](https://huggingface.co/papers/2607.00924) — [GitHub](https://github.com/lamm-mit/graph-preflexor-grpo)
|
| 33 |
+
|
| 34 |
+
## Tips
|
| 35 |
+
|
| 36 |
+
- Ask materials science, biology, or interdisciplinary scientific questions for best results.
|
| 37 |
+
- The graph panel updates after generation completes.
|
| 38 |
+
- Adjust temperature and max tokens in the Advanced settings.
|
app.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Graph-PrefLexOR: Graph-Native Reinforcement Learning for Scientific Hypothesis Generation.
|
| 2 |
+
|
| 3 |
+
A chat demo that loads the lamm-mit/Graph-Preflexor-8b_12292025 model, streams its
|
| 4 |
+
structured reasoning output, parses the <graph_json> block, and renders the relational
|
| 5 |
+
graph as an interactive Mermaid diagram alongside the conversation.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import re
|
| 10 |
+
import spaces # MUST come before torch / transformers
|
| 11 |
+
import torch
|
| 12 |
+
from threading import Thread
|
| 13 |
+
from transformers import (
|
| 14 |
+
AutoModelForCausalLM,
|
| 15 |
+
AutoTokenizer,
|
| 16 |
+
TextIteratorStreamer,
|
| 17 |
+
GenerationConfig,
|
| 18 |
+
)
|
| 19 |
+
import gradio as gr
|
| 20 |
+
|
| 21 |
+
MODEL_ID = "lamm-mit/Graph-Preflexor-8b_12292025"
|
| 22 |
+
THINK_END_TOKEN_ID = 151668 # </think> token for Qwen3
|
| 23 |
+
|
| 24 |
+
# ---------------------------------------------------------------------------
|
| 25 |
+
# Model loading (module scope, eager .to("cuda") per ZeroGPU rules)
|
| 26 |
+
# ---------------------------------------------------------------------------
|
| 27 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 28 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 29 |
+
MODEL_ID,
|
| 30 |
+
torch_dtype=torch.bfloat16,
|
| 31 |
+
attn_implementation="sdpa",
|
| 32 |
+
).to("cuda")
|
| 33 |
+
model.eval()
|
| 34 |
+
|
| 35 |
+
# ---------------------------------------------------------------------------
|
| 36 |
+
# Graph JSON → Mermaid conversion
|
| 37 |
+
# ---------------------------------------------------------------------------
|
| 38 |
+
GRAPH_JSON_RE = re.compile(
|
| 39 |
+
r"<graph_json>\s*(.*?)\s*</graph_json>", re.DOTALL
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def extract_graph_json(text: str):
|
| 44 |
+
"""Extract and parse the first <graph_json> block from model output."""
|
| 45 |
+
m = GRAPH_JSON_RE.search(text)
|
| 46 |
+
if not m:
|
| 47 |
+
return None
|
| 48 |
+
raw = m.group(1).strip()
|
| 49 |
+
# Try direct parse, then fallback to largest {...} region
|
| 50 |
+
try:
|
| 51 |
+
return json.loads(raw)
|
| 52 |
+
except Exception:
|
| 53 |
+
i1 = raw.find("{")
|
| 54 |
+
i2 = raw.rfind("}")
|
| 55 |
+
if i1 != -1 and i2 > i1:
|
| 56 |
+
try:
|
| 57 |
+
return json.loads(raw[i1 : i2 + 1])
|
| 58 |
+
except Exception:
|
| 59 |
+
return None
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def graph_to_mermaid(graph_obj: dict) -> str:
|
| 64 |
+
"""Convert a {nodes, edges} graph dict to a Mermaid flowchart definition."""
|
| 65 |
+
if not graph_obj:
|
| 66 |
+
return ""
|
| 67 |
+
nodes = graph_obj.get("nodes", []) or []
|
| 68 |
+
edges = graph_obj.get("edges", []) or []
|
| 69 |
+
|
| 70 |
+
lines = ["flowchart LR"]
|
| 71 |
+
seen = set()
|
| 72 |
+
|
| 73 |
+
# Emit nodes with optional type labels
|
| 74 |
+
for n in nodes:
|
| 75 |
+
if not isinstance(n, dict):
|
| 76 |
+
continue
|
| 77 |
+
nid = n.get("id")
|
| 78 |
+
if not nid:
|
| 79 |
+
continue
|
| 80 |
+
safe = _safe_id(nid)
|
| 81 |
+
if safe in seen:
|
| 82 |
+
continue
|
| 83 |
+
seen.add(safe)
|
| 84 |
+
ntype = n.get("type", "")
|
| 85 |
+
label = nid
|
| 86 |
+
if ntype:
|
| 87 |
+
label = f"{nid} ({ntype})"
|
| 88 |
+
lines.append(f' {safe}["{label}"]')
|
| 89 |
+
|
| 90 |
+
# Emit edges with relation labels
|
| 91 |
+
for e in edges:
|
| 92 |
+
if not isinstance(e, dict):
|
| 93 |
+
continue
|
| 94 |
+
src = e.get("source")
|
| 95 |
+
tgt = e.get("target")
|
| 96 |
+
if not src or not tgt:
|
| 97 |
+
continue
|
| 98 |
+
rel = e.get("relation", "")
|
| 99 |
+
s_safe = _safe_id(src)
|
| 100 |
+
t_safe = _safe_id(tgt)
|
| 101 |
+
if s_safe not in seen:
|
| 102 |
+
seen.add(s_safe)
|
| 103 |
+
lines.append(f' {s_safe}["{src}"]')
|
| 104 |
+
if t_safe not in seen:
|
| 105 |
+
seen.add(t_safe)
|
| 106 |
+
lines.append(f' {t_safe}["{tgt}"]')
|
| 107 |
+
if rel:
|
| 108 |
+
lines.append(f" {s_safe} -->|{rel}| {t_safe}")
|
| 109 |
+
else:
|
| 110 |
+
lines.append(f" {s_safe} --> {t_safe}")
|
| 111 |
+
|
| 112 |
+
return "\n".join(lines)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _safe_id(s: str) -> str:
|
| 116 |
+
"""Sanitize a node id for use as a Mermaid node identifier."""
|
| 117 |
+
out = re.sub(r"[^A-Za-z0-9_]", "_", str(s))
|
| 118 |
+
if out and out[0].isdigit():
|
| 119 |
+
out = "_" + out
|
| 120 |
+
return out or "_"
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def mermaid_html(mermaid_code: str) -> str:
|
| 124 |
+
"""Wrap Mermaid code in an HTML page that renders it via CDN Mermaid.js."""
|
| 125 |
+
if not mermaid_code:
|
| 126 |
+
return ""
|
| 127 |
+
escaped = mermaid_code.replace("\\", "\\\\").replace("`", "\\`")
|
| 128 |
+
return f"""
|
| 129 |
+
<div id="mermaid-container" style="display:flex;justify-content:center;padding:8px;overflow:auto;">
|
| 130 |
+
<pre class="mermaid" style="background:transparent;border:none;">{escaped}</pre>
|
| 131 |
+
</div>
|
| 132 |
+
<script type="module">
|
| 133 |
+
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
|
| 134 |
+
mermaid.initialize({{ startOnLoad: true, theme: 'default', securityLevel: 'loose' }});
|
| 135 |
+
mermaid.run({{ querySelector: '.mermaid' }});
|
| 136 |
+
</script>
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# ---------------------------------------------------------------------------
|
| 141 |
+
# Inference
|
| 142 |
+
# ---------------------------------------------------------------------------
|
| 143 |
+
def _estimate_duration(message, history, max_new_tokens):
|
| 144 |
+
"""Callable duration estimator: base + proportional to max_new_tokens."""
|
| 145 |
+
return min(300, 30 + int(max_new_tokens * 0.004))
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@spaces.GPU(duration=_estimate_duration)
|
| 149 |
+
def generate(
|
| 150 |
+
message: str,
|
| 151 |
+
history: list,
|
| 152 |
+
max_new_tokens: int,
|
| 153 |
+
temperature: float,
|
| 154 |
+
top_p: float,
|
| 155 |
+
):
|
| 156 |
+
"""Stream a graph-native reasoning response from the model.
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
message: The user's scientific question or prompt.
|
| 160 |
+
history: Chat history as a list of (user, assistant) tuples.
|
| 161 |
+
max_new_tokens: Maximum tokens to generate.
|
| 162 |
+
temperature: Sampling temperature.
|
| 163 |
+
top_p: Nucleus sampling threshold.
|
| 164 |
+
"""
|
| 165 |
+
# Build the prompt from history
|
| 166 |
+
messages = []
|
| 167 |
+
for user_msg, bot_msg in history:
|
| 168 |
+
if user_msg:
|
| 169 |
+
messages.append({"role": "user", "content": user_msg})
|
| 170 |
+
if bot_msg:
|
| 171 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
| 172 |
+
messages.append({"role": "user", "content": message})
|
| 173 |
+
|
| 174 |
+
# Apply chat template with thinking enabled
|
| 175 |
+
try:
|
| 176 |
+
prompt_text = tokenizer.apply_chat_template(
|
| 177 |
+
messages,
|
| 178 |
+
tokenize=False,
|
| 179 |
+
add_generation_prompt=True,
|
| 180 |
+
enable_thinking=True,
|
| 181 |
+
)
|
| 182 |
+
except TypeError:
|
| 183 |
+
prompt_text = tokenizer.apply_chat_template(
|
| 184 |
+
messages,
|
| 185 |
+
tokenize=False,
|
| 186 |
+
add_generation_prompt=True,
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
inputs = tokenizer(prompt_text, return_tensors="pt").to("cuda")
|
| 190 |
+
input_len = inputs["input_ids"].shape[1]
|
| 191 |
+
|
| 192 |
+
streamer = TextIteratorStreamer(
|
| 193 |
+
tokenizer,
|
| 194 |
+
skip_prompt=True,
|
| 195 |
+
skip_special_tokens=False,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
gen_config = GenerationConfig(
|
| 199 |
+
max_new_tokens=max_new_tokens,
|
| 200 |
+
do_sample=temperature > 0,
|
| 201 |
+
temperature=max(temperature, 0.01),
|
| 202 |
+
top_p=top_p,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
generation_kwargs = dict(
|
| 206 |
+
**inputs,
|
| 207 |
+
generation_config=gen_config,
|
| 208 |
+
streamer=streamer,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
| 212 |
+
thread.start()
|
| 213 |
+
|
| 214 |
+
# Stream text tokens as they arrive
|
| 215 |
+
full_text = ""
|
| 216 |
+
for chunk in streamer:
|
| 217 |
+
full_text += chunk
|
| 218 |
+
yield full_text, "" # streaming partial text, graph not ready yet
|
| 219 |
+
|
| 220 |
+
thread.join()
|
| 221 |
+
|
| 222 |
+
# After generation completes, extract and render graph
|
| 223 |
+
graph_obj = extract_graph_json(full_text)
|
| 224 |
+
mermaid_code = graph_to_mermaid(graph_obj) if graph_obj else ""
|
| 225 |
+
mermaid_render = mermaid_html(mermaid_code) if mermaid_code else ""
|
| 226 |
+
|
| 227 |
+
yield full_text, mermaid_render
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# ---------------------------------------------------------------------------
|
| 231 |
+
# UI
|
| 232 |
+
# ---------------------------------------------------------------------------
|
| 233 |
+
CSS = """
|
| 234 |
+
#col-container { max-width: 1200px; margin: 0 auto; }
|
| 235 |
+
.dark .gradio-container { color: var(--body-text-color); }
|
| 236 |
+
#graph-panel { min-height: 300px; }
|
| 237 |
+
"""
|
| 238 |
+
|
| 239 |
+
EXAMPLES = [
|
| 240 |
+
"What are the key mechanical properties of spider silk and how do they arise from its molecular structure?",
|
| 241 |
+
"Explain the relationship between hierarchical structures and material toughness in biological materials.",
|
| 242 |
+
"How do proteins fold and why is this important for their function?",
|
| 243 |
+
"Give me a short introduction to materiomics.",
|
| 244 |
+
"Propose a novel hypothesis for self-healing biopolymer composites.",
|
| 245 |
+
]
|
| 246 |
+
|
| 247 |
+
with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo:
|
| 248 |
+
gr.Markdown(
|
| 249 |
+
"""
|
| 250 |
+
# 🧠 Graph-PrefLexOR: Graph-Native Scientific Reasoning
|
| 251 |
+
Ask a scientific question and the model will reason through it using
|
| 252 |
+
structured graph-native thinking — brainstorming, building a knowledge
|
| 253 |
+
graph, extracting patterns, and synthesizing a final answer.
|
| 254 |
+
The extracted relational graph is visualized as an interactive Mermaid
|
| 255 |
+
diagram.
|
| 256 |
+
"""
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
with gr.Row():
|
| 260 |
+
with gr.Column(scale=3):
|
| 261 |
+
chatbot = gr.Chatbot(height=520, type="tuples")
|
| 262 |
+
with gr.Row():
|
| 263 |
+
msg_input = gr.Textbox(
|
| 264 |
+
show_label=False,
|
| 265 |
+
placeholder="Ask a scientific question…",
|
| 266 |
+
container=False,
|
| 267 |
+
scale=4,
|
| 268 |
+
)
|
| 269 |
+
send_btn = gr.Button("Send", variant="primary", scale=1)
|
| 270 |
+
with gr.Accordion("Advanced settings", open=False):
|
| 271 |
+
with gr.Row():
|
| 272 |
+
max_tokens = gr.Slider(
|
| 273 |
+
512, 16384, value=8192, step=512,
|
| 274 |
+
label="Max new tokens",
|
| 275 |
+
)
|
| 276 |
+
temperature = gr.Slider(
|
| 277 |
+
0.0, 1.5, value=0.2, step=0.05,
|
| 278 |
+
label="Temperature",
|
| 279 |
+
)
|
| 280 |
+
top_p = gr.Slider(
|
| 281 |
+
0.1, 1.0, value=0.95, step=0.05,
|
| 282 |
+
label="Top-p",
|
| 283 |
+
)
|
| 284 |
+
with gr.Row():
|
| 285 |
+
stop_btn = gr.Button("Stop", variant="stop")
|
| 286 |
+
clear_btn = gr.Button("Clear")
|
| 287 |
+
|
| 288 |
+
with gr.Column(scale=2):
|
| 289 |
+
gr.Markdown("### 📊 Relational Graph")
|
| 290 |
+
graph_output = gr.HTML(
|
| 291 |
+
value="<p style='color:#888;text-align:center;padding:40px;'>The extracted knowledge graph will appear here after generation.</p>",
|
| 292 |
+
elem_id="graph-panel",
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
gr.Examples(
|
| 296 |
+
examples=EXAMPLES,
|
| 297 |
+
inputs=msg_input,
|
| 298 |
+
outputs=[chatbot, graph_output],
|
| 299 |
+
fn=generate,
|
| 300 |
+
cache_examples=False,
|
| 301 |
+
run_on_click=True,
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
# Wire events
|
| 305 |
+
def user_submit(message, history):
|
| 306 |
+
"""Add user message to chat and clear input."""
|
| 307 |
+
if not message.strip():
|
| 308 |
+
return "", history + [(message, None)]
|
| 309 |
+
return "", history + [(message, None)]
|
| 310 |
+
|
| 311 |
+
def bot_respond(history, max_tok, temp, tp):
|
| 312 |
+
"""Run generation and stream the response."""
|
| 313 |
+
if not history or history[-1][1] is not None:
|
| 314 |
+
return history, ""
|
| 315 |
+
message = history[-1][0]
|
| 316 |
+
history_for_gen = history[:-1]
|
| 317 |
+
for text, graph_html in generate(message, history_for_gen, max_tok, temp, tp):
|
| 318 |
+
history[-1] = (message, text)
|
| 319 |
+
yield history, graph_html
|
| 320 |
+
|
| 321 |
+
send_events = [send_btn.click, msg_input.submit]
|
| 322 |
+
for evt in send_events:
|
| 323 |
+
evt(
|
| 324 |
+
user_submit,
|
| 325 |
+
[msg_input, chatbot],
|
| 326 |
+
[msg_input, chatbot],
|
| 327 |
+
).then(
|
| 328 |
+
bot_respond,
|
| 329 |
+
[chatbot, max_tokens, temperature, top_p],
|
| 330 |
+
[chatbot, graph_output],
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
clear_btn.click(lambda: ([], "<p style='color:#888;text-align:center;padding:40px;'>The extracted knowledge graph will appear here after generation.</p>"), None, [chatbot, graph_output])
|
| 334 |
+
stop_btn.click(None, None, None, cancels=[bot_respond])
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
demo.launch(mcp_server=True)
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers>=4.57
|
| 2 |
+
accelerate
|
| 3 |
+
sentencepiece
|