LangGraph 17:自建中断面板

前言

Studio 适合开发时看图、点 resume。
产品不能要求审批人去登录 LangSmith,也不能把业务页面嵌进 Studio。
协议其实就两步:同一 thread_id 上先 invoke 跑到 interrupt ,再 Command(resume=...) 续跑。
本文把这两步接到自有后端和一张对话页上,做出类似 Studio 的中断面板
示例对接 火山方舟 Coding Plan ,模型先写短诗,人点「是」才通过;点「否」则重写再问。
interrupt 语义见 《LangGraph 11:HITL 人机协同》;Studio 本身见 《LangGraph 16:Studio 接入》。
下文需要 Python 3.12+ ,依赖用 uv

概要

自建路径用 FastAPI 暴露开始 / 续跑,页面用对话展示 payload,用「是 / 否」提交 resume。
图里先调 ark-code-latest 生成草稿,再 interrupt 等人审批。
选「是」则 approved=true 结束;选「否」走条件边回到写诗节点。
项目目录用 z-langgraph-ui

依赖

建议使用 Python 3.12 及以上。
在空目录初始化工程并声明依赖。

1
2
3
4
uv init z-langgraph-ui
cd z-langgraph-ui
uv venv --python 3.12
uv add "langgraph>=1.0,<2.0" "langchain>=1.0,<2.0" langchain-openai python-dotenv fastapi uvicorn

在项目根目录创建 .env ,写入 Coding Plan 的 Key 与专用 Base URL。

1
2
OPENAI_API_KEY=你的火山方舟 API Key
OPENAI_BASE_URL=https://ark.cn-beijing.volces.com/api/coding/v3

请勿把 Base URL 写成普通方舟 .../api/v3 ,以免无法抵扣 Coding Plan 额度。
生产环境请把 InMemorySaver 换成 《LangGraph 08:Checkpoint 持久化》 里的数据库 saver。

接入

自建后端

自建服务必须自己挂 checkpointer,并固定 thread_id
把图放到 src/agent.py :模型按主题写两行短诗,再 interrupt 问是否通过。
resume 为真就结束;为假就避开上一稿重写,再中断一次。
另建空文件 src/__init__.py ,方便 from src.agent import graph

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import os
from typing import Literal, TypedDict

from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import interrupt

load_dotenv()

model = init_chat_model(
"openai:ark-code-latest",
temperature=0,
api_key=os.environ["OPENAI_API_KEY"],
base_url=os.environ["OPENAI_BASE_URL"],
)


class OverAllState(TypedDict):
topic: str
poem: str
approved: bool


def parse_approval(value: object) -> bool:
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return value == 1
if isinstance(value, str):
return value.strip().lower() in {
"yes",
"y",
"true",
"1",
"是",
"通过",
"approve",
"approved",
}
return False


def llm_node(state: OverAllState) -> dict:
prev = state.get("poem") or ""
prompt = f"写一首关于 {state['topic']} 的两行短诗,只写诗句"
if prev:
prompt += f"。不要写成:{prev}"
text = model.invoke([HumanMessage(content=prompt)]).content
return {"poem": text, "approved": False}


def review_node(state: OverAllState) -> dict:
decision = interrupt(
{
"instruction": "是否通过这首短诗?",
"poem": state["poem"],
"choices": ["是", "否"],
}
)
return {"approved": parse_approval(decision)}


def after_review(state: OverAllState) -> Literal["llm_node", "__end__"]:
return END if state.get("approved") else "llm_node"


builder = StateGraph(state_schema=OverAllState)
builder.add_node("llm_node", llm_node)
builder.add_node("review_node", review_node)
builder.add_edge(START, "llm_node")
builder.add_edge("llm_node", "review_node")
builder.add_conditional_edges("review_node", after_review)

graph = builder.compile(checkpointer=InMemorySaver())

再用 FastAPI 包两层:带主题开始跑图,以及带着 resume 续跑。
返回值做成页面好用的 JSON: interrupted 时带上 payload, done 时带上最终状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
from langgraph.types import Command

from src.agent import graph

app = FastAPI()


class StartBody(BaseModel):
thread_id: str
topic: str


class ResumeBody(BaseModel):
thread_id: str
resume: object


def dump_result(result: dict) -> dict:
interrupts = result.get("__interrupt__")
if interrupts:
items = interrupts if isinstance(interrupts, (list, tuple)) else [interrupts]
return {
"status": "interrupted",
"interrupts": [{"id": i.id, "value": i.value} for i in items],
}
return {"status": "done", "values": result}


def config_of(thread_id: str) -> dict:
return {"configurable": {"thread_id": thread_id}}


@app.get("/")
def index():
return FileResponse("index.html")


@app.post("/start")
def start(body: StartBody):
result = graph.invoke({"topic": body.topic}, config=config_of(body.thread_id))
return dump_result(result)


@app.post("/resume")
def resume(body: ResumeBody):
result = graph.invoke(Command(resume=body.resume), config=config_of(body.thread_id))
return dump_result(result)

把上面保存为 z-langgraph-ui/app.py
/start/resume 必须用同一个 thread_id ,否则续不上检查点。
页面点「是」时 resumetrue ,点「否」时为 false

页面

页面做成对话:先发主题走 /start ,中断后在气泡里点「是 / 否」走 /resume
待审批时输入框锁住,只能点按钮。
通过后换新的 thread_id ,可以再说一个主题。
保存为 z-langgraph-ui/index.html ,由 FastAPI 直接返回。
样式是小清新对话窗,协议仍是「同一线程 + 展示 payload + 提交 resume」。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>短诗往来</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,500;9..144,600&family=IBM+Plex+Mono:wght@400&family=Ma+Shan+Zheng&family=Noto+Serif+SC:wght@400;600&display=swap" rel="stylesheet" />
<style>
:root {
--bg: #eef6f1;
--linen: #f7f4ee;
--ink: #3a4a43;
--mint: #6db3a0;
--mint-deep: #4f9786;
--lemon: #f3e4a8;
--peach: #f5d4c8;
--glass: rgba(255, 255, 255, 0.72);
--muted: #7a8b83;
--line: rgba(109, 179, 160, 0.28);
}

* { box-sizing: border-box; }

html, body {
margin: 0;
height: 100%;
}

body {
font-family: "Noto Serif SC", serif;
color: var(--ink);
background:
radial-gradient(520px 360px at 8% 0%, #dff3ea 0%, transparent 62%),
radial-gradient(480px 320px at 96% 8%, #fbe7d8 0%, transparent 58%),
radial-gradient(420px 280px at 80% 100%, #f6ecc4 0%, transparent 55%),
var(--bg);
}

body::before,
body::after {
content: "";
position: fixed;
pointer-events: none;
border-radius: 50%;
filter: blur(2px);
}

body::before {
width: 180px;
height: 180px;
left: -40px;
bottom: 12%;
background: rgba(157, 209, 186, 0.35);
}

body::after {
width: 120px;
height: 120px;
right: 6%;
top: 18%;
background: rgba(245, 212, 200, 0.4);
}

.app {
position: relative;
z-index: 1;
height: 100%;
max-width: 720px;
margin: 0 auto;
display: grid;
grid-template-rows: auto 1fr auto;
padding: 22px 18px 16px;
}

header {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 16px;
padding: 10px 6px 18px;
}

.brand {
display: flex;
align-items: center;
gap: 12px;
}

.leaf {
width: 42px;
height: 42px;
border-radius: 18px 22px 16px 24px;
background:
linear-gradient(140deg, #c9eadc 0%, #8ecbb6 100%);
box-shadow: 10px 8px 0 rgba(243, 228, 168, 0.7);
flex: none;
}

h1 {
font-family: "Ma Shan Zheng", cursive;
font-size: 36px;
font-weight: 400;
margin: 0;
letter-spacing: 0.12em;
}

.kicker {
margin: 0 0 2px;
color: var(--mint-deep);
font-family: "Fraunces", serif;
font-size: 12px;
font-style: italic;
letter-spacing: 0.08em;
}

.meta { text-align: right; }

#stamp, #thread { margin: 0; }

#stamp {
display: inline-block;
padding: 3px 10px;
margin-bottom: 6px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.7);
color: var(--mint-deep);
font-size: 12px;
letter-spacing: 0.12em;
}

#stamp.interrupted { background: #fff4d6; color: #9a7a28; }
#stamp.done { background: #dff3ea; color: #2f7a64; }
#stamp.error { background: #fde4dc; color: #b45a4a; }
#stamp.busy { background: #e7eee9; color: var(--muted); }

#thread {
font-family: "IBM Plex Mono", monospace;
font-size: 11px;
color: var(--muted);
max-width: 240px;
opacity: 0.8;
}

#log {
overflow: auto;
padding: 8px 4px 18px;
display: flex;
flex-direction: column;
gap: 16px;
}

.msg {
max-width: 84%;
animation: rise 420ms cubic-bezier(.2, .8, .2, 1);
}

.msg.user { align-self: flex-end; }
.msg.assistant, .msg.system { align-self: flex-start; }

.who {
font-size: 11px;
color: var(--muted);
margin: 0 0 6px 8px;
letter-spacing: 0.18em;
}

.msg.user .who {
text-align: right;
margin: 0 8px 6px 0;
}

.bubble {
background: var(--glass);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 22px 22px 22px 8px;
padding: 14px 16px;
line-height: 1.85;
white-space: pre-wrap;
word-break: break-word;
box-shadow: 0 10px 24px rgba(90, 130, 116, 0.08);
}

.msg.user .bubble {
background: linear-gradient(180deg, #ffe9df 0%, #f7d5c8 100%);
border-radius: 22px 22px 8px 22px;
color: #5a3f38;
}

.msg.system .bubble {
background: rgba(255, 255, 255, 0.55);
border: 1px dashed var(--line);
box-shadow: none;
color: #5d6f67;
border-radius: 18px;
font-size: 14px;
}

.poem {
margin: 10px 0 0;
padding: 12px 14px;
border-radius: 16px;
background: linear-gradient(180deg, #fffdf6 0%, #eef8f3 100%);
font-size: 16px;
line-height: 2;
}

.hint {
margin: 10px 0 0;
font-size: 12px;
color: var(--muted);
}

.choices {
display: flex;
gap: 8px;
margin-top: 14px;
}

.choices button {
height: auto;
padding: 8px 22px;
border-radius: 999px;
letter-spacing: 0.32em;
box-shadow: none;
}

.choices .no {
background: #fff;
color: var(--ink);
border-color: var(--line);
}

.choices .no:hover {
background: #f3f8f5;
}

.choices.is-locked button {
pointer-events: none;
opacity: 0.4;
}

.typing .bubble {
display: flex;
gap: 6px;
align-items: center;
width: fit-content;
padding: 14px 18px;
}

.typing i {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--mint);
animation: blink 1.1s infinite;
}

.typing i:nth-child(2) { animation-delay: 0.15s; }
.typing i:nth-child(3) { animation-delay: 0.3s; }

.composer {
display: grid;
grid-template-columns: 1fr auto;
gap: 10px;
align-items: end;
padding: 10px;
border-radius: 28px;
background: rgba(255, 255, 255, 0.7);
backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.9);
box-shadow: 0 12px 30px rgba(90, 130, 116, 0.1);
}

textarea {
width: 100%;
min-height: 56px;
max-height: 160px;
resize: none;
border: 0;
background: transparent;
color: var(--ink);
font: inherit;
line-height: 1.7;
padding: 10px 12px;
outline: none;
}

button {
font: inherit;
border: 1px solid transparent;
background: var(--mint);
color: #f7fffb;
padding: 12px 18px;
cursor: pointer;
letter-spacing: 0.18em;
border-radius: 999px;
transition: transform 160ms ease, background 160ms ease;
}

.composer button {
height: 52px;
min-width: 76px;
}

button:hover { background: var(--mint-deep); transform: translateY(-1px); }
button:disabled {
opacity: 0.45;
cursor: wait;
transform: none;
}

@keyframes rise {
from { opacity: 0; transform: translateY(12px); }
to { opacity: 1; transform: none; }
}

@keyframes blink {
0%, 80%, 100% { opacity: 0.2; transform: translateY(0); }
40% { opacity: 1; transform: translateY(-2px); }
}

@media (max-width: 640px) {
h1 { font-size: 28px; }
.msg { max-width: 92%; }
.leaf { display: none; }
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<span class="leaf" aria-hidden="true"></span>
<div>
<p class="kicker">a little poem, slowly</p>
<h1>短诗往来</h1>
</div>
</div>
<div class="meta">
<p id="stamp">待开篇</p>
<p id="thread"></p>
</div>
</header>
<div id="log"></div>
<form class="composer" id="form">
<textarea id="input" rows="2" placeholder="说一个主题,例如橘猫"></textarea>
<button id="send" type="submit">发送</button>
</form>
</div>
<script>
const log = document.getElementById('log')
const form = document.getElementById('form')
const input = document.getElementById('input')
const sendBtn = document.getElementById('send')
const stamp = document.getElementById('stamp')
const threadEl = document.getElementById('thread')

let threadId = crypto.randomUUID()
let phase = 'idle'
threadEl.textContent = threadId

appendMessage('system', '先说一个主题。写成短诗后会停下来问你是否通过:选「是」即审批通过,选「否」则重写一稿再问。')

function setPhase(next, label) {
phase = next
stamp.textContent = label
stamp.className = next
stamp.id = 'stamp'
const waitingChoice = next === 'interrupted'
const busy = next === 'busy'
sendBtn.disabled = busy || waitingChoice
input.disabled = busy || waitingChoice
if (next === 'idle') {
input.placeholder = '说一个主题,例如橘猫'
} else if (next === 'interrupted') {
input.placeholder = '请点「是」通过,或「否」重写'
} else if (next === 'done') {
input.placeholder = '再说一个主题,另开一轮'
}
}

function appendMessage(role, text, extra) {
const wrap = document.createElement('article')
wrap.className = 'msg ' + role
const who = document.createElement('p')
who.className = 'who'
who.textContent = role === 'user' ? '你' : role === 'system' ? '说明' : '小诗'
const bubble = document.createElement('div')
bubble.className = 'bubble'
if (text) bubble.textContent = text
if (extra && extra.poem) {
const poem = document.createElement('div')
poem.className = 'poem'
poem.textContent = extra.poem
bubble.appendChild(poem)
}
if (extra && extra.hint) {
const hint = document.createElement('p')
hint.className = 'hint'
hint.textContent = extra.hint
bubble.appendChild(hint)
}
if (extra && extra.choices) {
const choices = document.createElement('div')
choices.className = 'choices'
const yesBtn = document.createElement('button')
yesBtn.type = 'button'
yesBtn.textContent = '是'
yesBtn.addEventListener('click', () => decide(true, choices))
const noBtn = document.createElement('button')
noBtn.type = 'button'
noBtn.className = 'no'
noBtn.textContent = '否'
noBtn.addEventListener('click', () => decide(false, choices))
choices.appendChild(yesBtn)
choices.appendChild(noBtn)
bubble.appendChild(choices)
}
wrap.appendChild(who)
wrap.appendChild(bubble)
log.appendChild(wrap)
log.scrollTop = log.scrollHeight
return wrap
}

function showTyping() {
const wrap = appendMessage('assistant', '')
wrap.classList.add('typing')
wrap.querySelector('.bubble').innerHTML = '<i></i><i></i><i></i>'
return wrap
}

async function post(url, body) {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
const data = await res.json().catch(() => ({}))
if (!res.ok) {
throw new Error(data.detail ? JSON.stringify(data.detail) : ('HTTP ' + res.status))
}
return data
}

function renderResult(data) {
if (data.status === 'interrupted') {
const first = data.interrupts && data.interrupts[0]
const value = (first && first.value) || {}
appendMessage(
'assistant',
value.instruction || '是否通过这首短诗?',
{
poem: value.poem || '',
hint: '选「是」审批通过;选「否」重写一稿。',
choices: true,
},
)
setPhase('interrupted', '待审批')
return
}
if (data.status === 'done') {
const values = data.values || {}
appendMessage(
'assistant',
values.approved ? '审批通过。' : '未通过。',
{
poem: values.poem || '',
hint: '主题:' + (values.topic || ''),
},
)
threadId = crypto.randomUUID()
threadEl.textContent = threadId
setPhase('idle', '待开篇')
return
}
appendMessage('assistant', JSON.stringify(data, null, 2))
setPhase('idle', '待开篇')
}

async function decide(approved, choicesEl) {
if (phase !== 'interrupted') return
if (choicesEl) choicesEl.classList.add('is-locked')
appendMessage('user', approved ? '是' : '否')
const typing = showTyping()
setPhase('busy', '进行中')
try {
const data = await post('/resume', { thread_id: threadId, resume: approved })
typing.remove()
renderResult(data)
} catch (err) {
typing.remove()
if (choicesEl) choicesEl.classList.remove('is-locked')
appendMessage('assistant', '没续上:' + err.message)
setPhase('interrupted', 'error')
}
}

async function send() {
const text = input.value.trim()
if (!text || phase === 'busy' || phase === 'interrupted') return
appendMessage('user', text)
input.value = ''
const typing = showTyping()
setPhase('busy', '进行中')
try {
const data = await post('/start', { thread_id: threadId, topic: text })
typing.remove()
renderResult(data)
} catch (err) {
typing.remove()
appendMessage('assistant', '没续上:' + err.message)
input.value = text
setPhase('idle', 'error')
}
}

form.addEventListener('submit', (event) => {
event.preventDefault()
send()
})

input.addEventListener('keydown', (event) => {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault()
send()
}
})
</script>
</body>
</html>

发主题走 /start ;点「是 / 否」走 /resume ,值为 truefalse
前端框架可换成 Vue / React,只要还是「同一线程 + 展示 payload + 提交 resume」。

启动

z-langgraph-ui 根目录启动 HTTP 服务。
起来之后只在浏览器里点,不必再对接口敲命令。

1
2
cd z-langgraph-ui
uv run uvicorn app:app --reload --port 8000

浏览器打开 http://127.0.0.1:8000

操作

在网页里走完「生成 → 是否通过 → 定稿」,效果与 Studio 的中断面板同类。

  1. 打开 http://127.0.0.1:8000 ,记下页面上的 thread_id
  2. 输入主题 橘猫 ,点「发送」。
  3. 等模型返回后,对话出现草稿,并问是否通过。
  4. 点「是」:resumetrue ,页面提示审批通过;最终状态含 topicpoemapproved: true
  5. 若点「否」:图会避开上一稿重写,再次 interrupt ,继续问是否通过。

待审批时不要刷新。
刷新会换新的 thread_id ,等于另开一条会话。
通过之后页面会自己换新线程,可以再说一个主题。
.env 里的 Coding Plan Key 要可用,否则 llm_node 过不去。

总结

  1. Studio 只适合开发联调;产品审批页用同一套 interrupt + Command(resume=...) 自己做。
  2. 本篇项目目录是 z-langgraph-ui ,模型用 Coding Plan 的 ark-code-latest
  3. 自建面板:自己挂 checkpointer,用固定 thread_id 暴露开始 / 续跑。
  4. 页面做成对话,用「是 / 否」审批;选「是」结束,选「否」重写再问。
  5. 多中断时 resume 用 {id: value} ,规则与 《LangGraph 11:HITL 人机协同》 一致。