Python 程式實習|第12週延伸實作|AI 協作 × OOP × Graphviz × JSON
Python × AI Agent 流程診斷實戰:讓 LLM 讀懂訪談紀錄,自動建立流程圖與需求分析報告
前一篇我們用 Python 完成規則式「流程卡點診斷器」,這一篇將它升級:讓本機 Ollama 模型協助整理匿名訪談紀錄,提出候選 As-Is 流程圖、疑似卡點、需求草案與追問清單,最後由學生核對證據。
一、為什麼需要 AI Agent?
規則式分析器擅長計算已知的流程耗時與排序,但訪談往往是一段自然語言:「昨天騎車到停車場,發現滿了,又跑去另一個地方。」我們需要先把這段敘述轉成可分析的流程資料。LLM 適合協助擷取與草擬,卻不能自行宣稱已經驗證流程、根本原因或系統需求。
interviews.jsonl二、先準備訪談紀錄
本篇延續第11週 Interview Agent 的 JSONL 格式:每行一份 JSON 物件,內含 topic 與 turns,每筆問答包含 question、answer。以下為示範資料,請儲存為 interviews.jsonl(UTF-8)。
{"topic":"校園停車","turns":[{"question":"最近一次找停車位發生什麼事?","answer":"昨天早上我先騎到平常停的停車場,發現沒有空位,只好再到另一個停車場找。"},{"question":"哪個步驟最困擾?","answer":"到現場才知道停滿了,要再繞去別處,差點遲到。"},{"question":"有沒有紀錄耗時?","answer":"沒有精確計時。"}]}
請學生觀察:這份訪談提到「先去常停的停車場」、「沒有空位」、「轉往另一個停車場」,卻沒有精確耗時。因此 AI 不能憑空寫出「花了 8 分鐘」或「節省 40% 時間」。
三、環境安裝與測試
本篇使用本機 Ollama 的 HTTP API,不需要雲端 API Key;但必須先安裝並啟動 Ollama,並下載可用模型。
ollama pull qwen2.5:7b
ollama list
pip install graphviz
若 Ollama 尚未啟動,另開命令提示字元執行 ollama serve;若服務已在執行,不必重複啟動。模型名稱可透過環境變數 OLLAMA_MODEL 調整。
若要輸出 PNG,除了 Python graphviz 套件,也需安裝 Graphviz 系統程式。這次實測成功的 Windows 安裝位置是:
r"C:\Program Files (x86)\Graphvizin"
程式也會嘗試 C:\Program Files\Graphvizin,並指定 Microsoft JhengHei 字型,避免中文顯示為方框。若 Graphviz 尚未設定完成,仍可保留 JSON 與 Markdown 報告。
四、Agent 如何分工?
| 模組 | 職責 | 教學重點 |
|---|---|---|
read_interviews() | 逐行讀取訪談紀錄 | 檔案、JSON、例外處理 |
call_ollama() | 請 LLM 提出結構化草案 | HTTP、提示詞、JSON |
validate() | 檢查節點 ID、連線、必要欄位 | 資料驗證、集合 |
draw() | 將步驟與連線繪成流程圖 | Graphviz、流程建模 |
report() | 輸出需求分析草案 | 字串、檔案輸出 |
五、完整 Python 程式:AI 流程診斷 Agent
請將下列程式儲存為 ai_process_agent.py,與訪談檔放在同一個資料夾。程式只使用 Python 標準函式庫呼叫 Ollama;Graphviz 用於繪圖。
"""第12週延伸:訪談紀錄 -> LLM 候選 As-Is 流程 -> 人工確認 -> 圖與報告。
安裝:pip install graphviz;繪圖另需 Graphviz dot.exe。
Ollama:ollama pull qwen2.5:7b;ollama serve(若未自動啟動)。
"""
import json
import os
import re
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
MODEL = os.getenv('OLLAMA_MODEL', 'qwen2.5:7b')
URL = os.getenv('OLLAMA_URL', 'http://localhost:11434/api/chat')
SYSTEM = '''你是大學生專題的流程診斷助教。只使用提供的匿名訪談原文,不可捏造步驟、時間、頻率、因果或需求已獲確認。請用繁體中文輸出單一JSON物件,不要Markdown。格式:{"steps":[{"id":"S1","name":"...","kind":"start|process|decision|end","evidence":"訪談原文短句或待驗證"}],"edges":[{"from":"S1","to":"S2","label":""}],"bottlenecks":[{"step_id":"S2","reason":"...","status":"已由訪談支持|待驗證"}],"requirements":[{"id":"FR-01","description":"...","status":"候選待確認","evidence":"..."}],"questions":["待追問問題"]}。步驟僅限原文支持;缺少流程資訊時應減少步驟並列入questions。不得自行估算分鐘數。'''
def read_interviews(path):
records = []
for lineno, line in enumerate(Path(path).read_text(encoding='utf-8-sig').splitlines(), 1):
if not line.strip():
continue
try:
obj = json.loads(line)
except json.JSONDecodeError as e:
raise ValueError(f'第{lineno}行不是合法JSON: {e}') from e
turns = obj.get('turns', [])
if not isinstance(turns, list):
raise ValueError(f'第{lineno}行 turns 必須為陣列')
records.append({'topic': str(obj.get('topic', '未命名')),
'turns': [{'question': str(t.get('question', '')),
'answer': str(t.get('answer', ''))}
for t in turns if isinstance(t, dict)]})
if not records:
raise ValueError('訪談紀錄為空')
return records
def call_ollama(records):
# 只傳必要內容;正式訪談請先匿名化,避免個資外洩。
payload = {'model': MODEL, 'stream': False, 'format': 'json',
'messages': [{'role': 'system', 'content': SYSTEM},
{'role': 'user', 'content': json.dumps(records, ensure_ascii=False)}]}
request = Request(URL, data=json.dumps(payload, ensure_ascii=False).encode('utf-8'),
headers={'Content-Type': 'application/json'})
try:
with urlopen(request, timeout=120) as resp:
response = json.load(resp)
return json.loads(response['message']['content'])
except (HTTPError, URLError, TimeoutError, KeyError, json.JSONDecodeError) as e:
raise RuntimeError(f'Ollama 呼叫失敗:{e};請確認模型、服務及URL') from e
def validate(data):
if not isinstance(data, dict):
raise ValueError('模型輸出必須是JSON物件')
for field in ('steps', 'edges', 'bottlenecks', 'requirements', 'questions'):
if not isinstance(data.get(field), list):
raise ValueError(f'{field} 必須是陣列')
steps = data['steps']
ids = [s.get('id') for s in steps if isinstance(s, dict)]
if len(ids) != len(steps) or len(ids) != len(set(ids)) or not all(isinstance(x, str) and re.fullmatch(r'[A-Za-z0-9_-]+', x) for x in ids):
raise ValueError('步驟ID需唯一且只包含英數、底線或連字號')
allowed = {'start', 'process', 'decision', 'end'}
for s in steps:
if s.get('kind') not in allowed or not isinstance(s.get('name'), str) or not isinstance(s.get('evidence'), str):
raise ValueError('步驟格式不符')
for e in data['edges']:
if not isinstance(e, dict) or e.get('from') not in ids or e.get('to') not in ids or not isinstance(e.get('label', ''), str):
raise ValueError('連線引用不存在的步驟')
for b in data['bottlenecks']:
if not isinstance(b, dict) or b.get('step_id') not in ids:
raise ValueError('卡點引用不存在的步驟')
for r in data['requirements']:
if not isinstance(r, dict) or not isinstance(r.get('description'), str):
raise ValueError('需求格式不符')
return data
def draw(data, name='agent_asis'):
from graphviz import Digraph
for folder in (r'C:\Program Files (x86)\Graphviz\bin', r'C:\Program Files\Graphviz\bin'):
if Path(folder, 'dot.exe').exists():
os.environ['PATH'] = folder + os.pathsep + os.environ.get('PATH', '')
break
graph = Digraph('AsIs', format='png')
graph.attr(rankdir='TB')
graph.attr('node', fontname='Microsoft JhengHei')
graph.attr('edge', fontname='Microsoft JhengHei')
shapes = {'start':'oval', 'process':'box', 'decision':'diamond', 'end':'oval'}
for s in data['steps']:
graph.node(s['id'], s['name'], shape=shapes[s['kind']])
for e in data['edges']:
graph.edge(e['from'], e['to'], label=e.get('label', ''))
return graph.render(name, cleanup=True)
def report(data, name='agent_report.md'):
lines = ['# AI Agent 流程診斷草案', '', '> AI產生,未經人工確認,不可視為正式需求。', '', '## As-Is 步驟']
lines += [f"- {s['id']} {s['name']}(證據:{s['evidence']})" for s in data['steps']]
lines += ['', '## 疑似卡點']
lines += [f"- {b.get('step_id','')}:{b.get('reason','')}({b.get('status','待驗證')})" for b in data['bottlenecks']]
lines += ['', '## 候選需求']
lines += [f"- {r.get('id','')}:{r['description']}({r.get('status','待確認')};證據:{r.get('evidence','未提供')})" for r in data['requirements']]
lines += ['', '## 待追問']
lines += [f'- {q}' for q in data['questions']]
Path(name).write_text('\n'.join(lines) + '\n', encoding='utf-8')
return name
def main():
path = input('訪談 JSONL 路徑 [interviews.jsonl]:').strip() or 'interviews.jsonl'
records = read_interviews(path)
data = validate(call_ollama(records))
Path('agent_diagnosis.json').write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding='utf-8')
print('已儲存 AI 草案:agent_diagnosis.json')
print('請先開啟 JSON,對照原始訪談逐項確認步驟、連線、證據及需求。')
if input('確認已檢查,繼續產生圖與報告?[y/N]:').strip().lower() != 'y':
return
print('報告:', report(data))
try:
print('流程圖:', draw(data))
except Exception as e:
print('流程圖未產生(報告仍已儲存):', e)
if __name__ == '__main__':
main()
六、如何執行?
python ai_process_agent.py輸入訪談檔案路徑,或直接按 Enter 使用預設 interviews.jsonl。程式會呼叫 Ollama,並先儲存 agent_diagnosis.json。請開啟檔案核對原始訪談,再輸入 y 產生圖與報告。
| 輸出檔案 | 用途 |
|---|---|
agent_diagnosis.json | AI 產生的結構化候選流程與需求 |
agent_asis.png | Graphviz 產生的現有流程圖 |
agent_report.md | 包含證據、疑似卡點、候選需求與待追問事項的報告 |
七、從 As-Is 流程圖到需求分析
假設訪談支持「停車場已滿,學生必須再尋找其他停車場」,Agent 可以提出「顯示停車場空位狀態」作為候選功能需求。但是否有即時空位資料?誰維護?多久更新?這些都還沒確認。
| 層次 | 學生應回答的問題 | 本例可得結論 |
|---|---|---|
| 體驗層 | 使用者遇到什麼困擾? | 轉往其他停車場,可能影響準時上課 |
| 行為層 | 目前流程卡在哪裡? | 到現場才發現停滿,需轉移地點 |
| 資訊層 | 需要什麼資料?能取得嗎? | 空位狀態與更新時間,來源仍待確認 |
因此,Agent 的工作不只是列出功能,還應明確產生「待追問清單」,避免把假設直接變成系統規格。
八、課堂實作:No-AI → AI Pair → Challenge AI
活動 A|No-AI:人工建立流程草圖
學生先閱讀同一份訪談,不使用 AI,整理至少三個有原文支持的步驟,並標記尚未確認的流程分支。
活動 B|AI Pair:比較人工與 Agent 草案
執行程式,將 AI 的流程圖與人工版本比較。每個差異都必須回答:原文在哪裡?是事實、推論,還是待驗證?
活動 C|Challenge AI:測試 Agent 是否會亂猜
刻意提供缺少時間、流程分支或資料來源的訪談,觀察模型是否編造分鐘數、錯誤地推斷根本原因。修訂提示詞,要求它將不確定事項放入 questions。
九、學生繳交成果與評量
| 成果 | 評量重點 |
|---|---|
| 匿名訪談 JSONL | 保留問題脈絡、不含個資 |
| As-Is 流程圖 | 節點與分支可追溯到訪談 |
| AI 診斷 JSON | 格式正確、待驗證事項清楚 |
| 需求分析報告 | 候選需求與證據分開記錄 |
| 人工修正紀錄 | 能指出 AI 的推測與錯誤 |
十、延伸思考:這是不是「真正的 Agent」?
本篇是單次 LLM 分析工作流程的 Agent 原型:Python 固定執行讀檔、呼叫模型、驗證與輸出,模型並沒有自行選擇工具或反覆規劃。這個界線很重要。若未來加入工具選擇、記憶、追問迴圈與人工核准機制,才會逐步接近具備自主工具使用能力的 Agent。
延伸閱讀:Graphviz 官方網站 https://graphviz.org/ | Ollama 官方網站 https://ollama.com/ | Python 官方文件 https://docs.python.org/3/
沒有留言:
張貼留言