W4 · 知识点10:命令行对话脚本开发
学习目标:开发一个设备维修养护系统的命令行诊断助手,整合多轮对话、角色设定和Token统计。
一、项目目标
构建一个"设备维修诊断助手"命令行程序:
- 维修人员输入故障描述,AI逐步诊断
- 支持多轮对话追问
- 可选不同的诊断角色(维修工程师/设备管理员/安全主管)
- 显示Token用量和费用统计
- 保存诊断记录
二、基础版
python
from openai import OpenAI
client = OpenAI()
print("=" * 50)
print(" 设备维修诊断助手 v1.0")
print("=" * 50)
print("输入故障描述开始诊断,输入 'quit' 退出\n")
history = [{
"role": "system",
"content": """你是设备维修养护系统的AI诊断助手,有15年工业设备维修经验。
工作流程:
1. 先收集关键信息(设备类型、故障现象、运行时长)
2. 逐步分析可能的原因
3. 给出诊断结论和维修建议
回答简洁实用,使用专业术语但会解释。每次回复不超过200字。"""
}]
while True:
user_input = input("故障描述> ").strip()
if user_input.lower() in ('quit', 'q', 'exit'):
print("诊断结束,注意安全操作!")
break
if not user_input:
continue
history.append({"role": "user", "content": user_input})
response = client.chat.completions.create(
model="deepseek-chat",
messages=history,
temperature=0.3,
)
reply = response.choices[0].message.content
history.append({"role": "assistant", "content": reply})
print(f"\n诊断助手: {reply}\n")
三、进阶版:完整诊断助手
python
from openai import OpenAI
import json
from datetime import datetime
client = OpenAI()
# 不同角色的系统提示
ROLES = {
"engineer": {
"name": "维修工程师",
"prompt": """你是一位资深设备维修工程师,有15年工业设备维护经验。
你的专长是故障诊断和维修方案制定。
回答风格:专业、直接、包含具体的操作步骤和工具要求。
每次诊断必须包含安全提醒。"""
},
"manager": {
"name": "设备管理员",
"prompt": """你是一位工厂设备管理员,负责维护计划和成本控制。
你的关注点是:维修成本、设备可用率、保养计划、是否需要更换设备。
回答风格:侧重数据分析和决策建议。"""
},
"safety": {
"name": "安全主管",
"prompt": """你是一位工厂安全主管,负责设备操作安全审查。
你的关注点是:操作安全风险、必要的防护措施、是否需要停机检修。
回答风格:严肃、注重安全合规,引用相关安全规范。"""
}
}
class MaintenanceDiagnosisBot:
def __init__(self, role="engineer"):
self.role = role
self.reset()
self.stats = {"calls": 0, "tokens_in": 0, "tokens_out": 0, "cost": 0.0}
# DeepSeek价格: 输入¥1/百万Token, 输出¥2/百万Token
self.price_in = 1.0 / 1_000_000
self.price_out = 2.0 / 1_000_000
def reset(self):
role_info = ROLES.get(self.role, ROLES["engineer"])
self.history = [{"role": "system", "content": role_info["prompt"]}]
def diagnose(self, message):
self.history.append({"role": "user", "content": message})
response = client.chat.completions.create(
model="deepseek-chat",
messages=self.history,
temperature=0.3,
)
reply = response.choices[0].message.content
self.history.append({"role": "assistant", "content": reply})
# 统计
t_in = response.usage.prompt_tokens
t_out = response.usage.completion_tokens
self.stats["calls"] += 1
self.stats["tokens_in"] += t_in
self.stats["tokens_out"] += t_out
self.stats["cost"] += t_in * self.price_in + t_out * self.price_out
return reply
def save_record(self, filename=None):
if not filename:
ts = datetime.now().strftime('%Y%m%d_%H%M%S')
filename = f"diagnosis_{ts}.json"
record = {
"role": self.role,
"timestamp": datetime.now().isoformat(),
"conversation": self.history,
"stats": self.stats
}
with open(filename, 'w', encoding='utf-8') as f:
json.dump(record, f, ensure_ascii=False, indent=2)
return filename
def print_stats(self):
s = self.stats
print(f"\n{'='*40}")
print(f"诊断统计: {s['calls']}次对话 | "
f"Token: {s['tokens_in']}↓ {s['tokens_out']}↑ | "
f"预估费用: ¥{s['cost']:.4f}")
print(f"{'='*40}")
def main():
print("=" * 50)
print(" 设备维修诊断助手 v2.0")
print("=" * 50)
print("命令:")
print(" /role [engineer|manager|safety] - 切换角色")
print(" /new - 新的诊断对话")
print(" /save - 保存诊断记录")
print(" /stats - 查看统计")
print(" /quit - 退出")
print()
bot = MaintenanceDiagnosisBot("engineer")
print(f"当前角色: {ROLES['engineer']['name']}\n")
while True:
try:
user_input = input("故障描述> ").strip()
except (KeyboardInterrupt, EOFError):
break
if not user_input:
continue
if user_input in ('/quit', '/q'):
break
if user_input == '/new':
bot.reset()
print("[新的诊断对话已开始]\n")
continue
if user_input == '/save':
f = bot.save_record()
print(f"[诊断记录已保存到 {f}]\n")
continue
if user_input == '/stats':
bot.print_stats()
continue
if user_input.startswith('/role'):
parts = user_input.split()
if len(parts) > 1 and parts[1] in ROLES:
bot.role = parts[1]
bot.reset()
print(f"[已切换为: {ROLES[bot.role]['name']}]\n")
else:
print("可选角色: engineer(维修工程师) / manager(设备管理员) / safety(安全主管)")
continue
try:
reply = bot.diagnose(user_input)
print(f"\n{ROLES[bot.role]['name']}: {reply}\n")
except Exception as e:
print(f"\n[错误: {e}]\n")
bot.print_stats()
print("\n诊断结束,注意安全操作!")
if __name__ == "__main__":
main()
四、动手练习
练习1:运行基础版和进阶版
用以下故障场景测试:
- "空压机排气温度过高"
- "液压系统压力上不去"
- "PLC报E-07故障代码"
练习2:添加新功能
选择至少2个功能实现:
/export导出诊断结论为维修工单格式/summary让AI总结本次诊断的关键结论- 彩色输出(不同角色用不同颜色)
- 自动保存每次诊断记录
练习3:角色对比实验
对同一个故障,分别用三个角色诊断,对比输出差异:
故障: "2号产线输送带电机过热停机"
维修工程师关注: ___
设备管理员关注: ___
安全主管关注: ___
五、本知识点检验标准
- 完成一个可运行的设备维修诊断命令行程序
- 支持多角色切换和多轮对话
- 实现诊断记录保存功能
- 代码有清晰的注释和错误处理