W4 · 知识点14:第一阶段项目实战与总结
学习目标:整合前13个知识点,完成设备维修养护系统的AI诊断模块原型。
一、项目一:《AI能力测评笔记》(设备维修版)
markdown
# 设备维修场景AI能力测评笔记
## 一、产品对比(故障诊断场景)
| 产品 | 故障诊断准确率 | 专业术语使用 | 安全规范意识 | 响应速度 |
|------|--------------|-------------|-------------|---------|
| ChatGPT | | | | |
| Claude | | | | |
| 通义千问 | | | | |
## 二、有效Prompt案例(10个)
### 案例1: 故障分类
- 类型: Zero-shot
- Prompt: "将以下故障分类为机械/电气/液压/气动:空压机运行时主轴振动异常..."
- 为什么有效: 任务明确,模型有足够训练数据
### 案例2: 维修工单结构化
- 类型: Few-shot
- Prompt: (包含2个实际工单示例的解析Prompt)
- 为什么有效: 示例来自真实系统,格式高度统一
... (补充到10个)
## 三、无效Prompt案例(10个)
### 案例1: 过于模糊的诊断请求
- Prompt: "这个设备坏了,帮我看看"
- 问题: 没有任何设备信息和故障描述
- 改进后: 加了角色设定 + 引导收集信息的框架
... (补充到10个)
## 四、关键发现
1. 设备故障诊断必须用CoT,直接给结论误判率高
2. JSON输出必须用response_format或Structured Outputs
3. Temperature对诊断一致性影响很大
二、项目二:《设备维修AI诊断助手》完整代码
python
"""
设备维修养护系统 - AI诊断模块 v1.0
功能:故障诊断、工单解析、维修报告生成
整合:API调用 + 流式输出 + JSON结构化 + 错误处理 + Token管理
"""
from openai import OpenAI, RateLimitError, APIConnectionError, InternalServerError
from pydantic import BaseModel, Field
from typing import Optional
import json
import time
import logging
from datetime import datetime
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("maintenance_ai")
client = OpenAI(timeout=30)
# ─── 数据模型 ───
class SparePart(BaseModel):
name: str = Field(description="备件名称")
spec: Optional[str] = Field(default=None, description="规格型号")
qty: int = Field(default=1, description="数量", ge=1)
class DiagnosisResult(BaseModel):
fault_type: str = Field(description="故障类型: mechanical|electrical|hydraulic|pneumatic|control|other")
root_cause: str = Field(description="根本原因分析")
confidence: str = Field(description="诊断置信度: high|medium|low")
diagnosis_steps: list[str] = Field(description="诊断推理步骤")
repair_steps: list[str] = Field(description="维修操作步骤")
spare_parts: list[SparePart] = Field(description="所需备件")
tools_needed: list[str] = Field(description="所需工具")
estimated_hours: float = Field(description="预估维修工时")
safety_warnings: list[str] = Field(description="安全警告")
follow_up: Optional[str] = Field(default=None, description="后续建议")
# ─── 核心诊断引擎 ───
class MaintenanceDiagnosisEngine:
"""设备维修AI诊断引擎"""
ROLES = {
"diagnose": "你是一位有15年经验的设备维修工程师,精通故障诊断和维修方案制定。",
"report": "你是一位技术文档专员,擅长撰写设备维修报告。",
"plan": "你是一位设备管理顾问,擅长制定预防性维护计划。",
}
def __init__(self, model="deepseek-chat"):
self.model = model
self.stats = {"calls": 0, "tokens": 0, "errors": 0, "cost": 0.0}
def diagnose_fault(self, fault_description, device_info=None):
"""
核心功能:设备故障智能诊断
返回结构化的诊断结果
"""
context = f"故障描述:{fault_description}"
if device_info:
context = f"设备信息:{device_info}\n{context}"
try:
response = client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": self.ROLES["diagnose"]},
{"role": "user", "content": f"""请对以下设备故障进行诊断分析:
{context}
请以JSON格式输出诊断结果,包含:
- fault_type: 故障类型(mechanical/electrical/hydraulic/pneumatic/control/other)
- root_cause: 根本原因
- confidence: 置信度(high/medium/low)
- diagnosis_steps: 诊断推理步骤
- repair_steps: 维修操作步骤
- spare_parts: 所需备件(name/spec/qty)
- tools_needed: 所需工具
- estimated_hours: 预估工时
- safety_warnings: 安全警告
- follow_up: 后续建议"""},
],
response_format={"type": "json_object"},
temperature=0.2,
)
self.stats["calls"] += 1
self.stats["tokens"] += response.usage.total_tokens
result = json.loads(response.choices[0].message.content)
return {"success": True, "data": result}
except (RateLimitError, APIConnectionError, InternalServerError) as e:
self.stats["errors"] += 1
logger.error(f"API错误: {e}")
return {"success": False, "error": str(e), "retryable": True}
except Exception as e:
self.stats["errors"] += 1
logger.error(f"未知错误: {e}")
return {"success": False, "error": str(e), "retryable": False}
def stream_diagnose(self, fault_description):
"""流式输出版本的诊断"""
stream = client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": self.ROLES["diagnose"]},
{"role": "user", "content": f"诊断故障:{fault_description}"},
],
stream=True,
stream_options={"include_usage": True},
temperature=0.2,
)
print("\n诊断分析: ", end="", flush=True)
full_reply = []
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
text = chunk.choices[0].delta.content
full_reply.append(text)
print(text, end="", flush=True)
if chunk.usage:
self.stats["tokens"] += chunk.usage.total_tokens
print()
self.stats["calls"] += 1
return "".join(full_reply)
def generate_report(self, repair_record):
"""生成维修报告"""
response = client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": self.ROLES["report"]},
{"role": "user", "content": f"根据以下维修记录生成规范的维修报告:\n{repair_record}"},
],
temperature=0.3,
)
self.stats["calls"] += 1
self.stats["tokens"] += response.usage.total_tokens
return response.choices[0].message.content
def print_stats(self):
s = self.stats
success_rate = (s["calls"] - s["errors"]) / max(s["calls"], 1)
print(f"\n{'='*50}")
print(f" 设备维修AI诊断引擎 - 运行统计")
print(f"{'='*50}")
print(f" 调用次数: {s['calls']}")
print(f" Token消耗: {s['tokens']}")
print(f" 错误次数: {s['errors']}")
print(f" 成功率: {success_rate:.1%}")
print(f"{'='*50}")
# ─── 命令行交互 ───
def main():
engine = MaintenanceDiagnosisEngine()
print("=" * 50)
print(" 设备维修养护系统 - AI诊断模块 v1.0")
print("=" * 50)
print("功能: /diagnose 故障诊断 | /report 生成报告 | /stream 流式诊断")
print("命令: /stats 查看统计 | /quit 退出")
print()
mode = "diagnose"
while True:
try:
user_input = input(f"[{mode}]> ").strip()
except (KeyboardInterrupt, EOFError):
break
if not user_input:
continue
if user_input in ('/quit', '/q'):
break
if user_input == '/stats':
engine.print_stats()
continue
if user_input.startswith('/diagnose'):
mode = "diagnose"
print("[已切换到:故障诊断模式]")
continue
if user_input.startswith('/report'):
mode = "report"
print("[已切换到:报告生成模式]")
continue
if user_input.startswith('/stream'):
mode = "stream"
print("[已切换到:流式诊断模式]")
continue
# 执行对应功能
if mode == "diagnose":
result = engine.diagnose_fault(user_input)
if result["success"]:
data = result["data"]
print(f"\n故障类型: {data.get('fault_type', 'N/A')}")
print(f"根本原因: {data.get('root_cause', 'N/A')}")
print(f"置信度: {data.get('confidence', 'N/A')}")
print(f"维修步骤: {data.get('repair_steps', [])}")
print(f"安全警告: {data.get('safety_warnings', [])}")
print(f"\n完整数据: {json.dumps(data, ensure_ascii=False, indent=2)}")
else:
print(f"\n诊断失败: {result['error']}")
if result.get("retryable"):
print("(此错误可重试,请稍后再试)")
elif mode == "stream":
engine.stream_diagnose(user_input)
elif mode == "report":
print("\n生成维修报告中...")
report = engine.generate_report(user_input)
print(f"\n{report}")
print()
engine.print_stats()
print("\n系统退出,注意安全操作!")
if __name__ == "__main__":
main()
三、第一阶段自检清单
理论知识:
- [ ] 能说出Token、Temperature、Top-P在设备维修系统中的配置策略
- [ ] 能区分Zero-shot、Few-shot、CoT在故障诊断场景的适用情况
- [ ] 理解Messages结构在多轮诊断对话中的作用
实践能力:
- [ ] 完成AI产品在设备维修场景下的对比测评
- [ ] 积累10+设备维修场景的有效Prompt
- [ ] 成功调用API完成故障诊断分析
- [ ] 实现JSON结构化的工单解析(成功率>95%)
- [ ] 完成命令行诊断助手(支持多轮对话+流式输出+错误处理)
产出物:
- [ ] 《设备维修场景AI能力测评笔记》
- [ ] 《设备维修AI诊断助手》可运行程序
- [ ] 《设备维修Prompt模板库》5个核心模板
- [ ] 诊断助手完整代码(本文中的项目代码)
进阶准备:
- [ ] 了解Embedding概念(为第二阶段RAG做准备------你的维修知识库需要它)
- [ ] 安装Python环境和openai库
- [ ] 准备好第二阶段目标:用RAG构建维修知识库问答
四、延伸阅读与第二阶段预习
- What Are Embeddings? --- 理解Embedding
- LangChain RAG教程 --- 第二阶段核心:用RAG构建维修知识库
- 思考:你的设备维修系统第二阶段要实现什么?
→ 上传设备手册 → AI自动检索 → 基于手册内容回答维修问题