前言:在AI浪潮席卷各行各业的今天,你是否想过如何将GPT的强大能力集成到自己的C#应用中?传统的HTTP调用方式不仅繁琐,还难以实现复杂的业务逻辑。
今天,我将通过一个智能设备诊断系统的案例,手把手教你使用Microsoft Semantic Kernel框架,轻松构建一个具备专业诊断能力的AI助手。这不是简单的聊天机器人,而是能够调用业务数据、执行复杂分析的AI应用!算是抛转引玉。
在企业应用中集成AI功能时,开发者常常遇到:
通过Semantic Kernel + 函数调用,我们将实现:

Semantic Kernel是微软开源的AI编排框架,它的核心理念是让AI能够"调用函数"来完成复杂任务。
C#using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
namespace AppDeviceDiagnostics
{
public class AIDiagnosticService
{
private readonly Kernel _kernel;
private readonly DeviceService _deviceService;
public AIDiagnosticService(DeviceService deviceService)
{
_deviceService = deviceService;
_kernel = InitializeKernel();
RegisterDiagnosticPlugins();
}
private Kernel InitializeKernel()
{
var kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddOpenAIChatCompletion(
modelId: "deepseek-chat",
apiKey: Environment.GetEnvironmentVariable("DEEPSEEK_API_KEY") ?? "sk-xxxx",
endpoint: new Uri("https://api.deepseek.com/v1")
);
return kernelBuilder.Build();
}
private void RegisterDiagnosticPlugins()
{
// 1. 设备状态总览插件
var deviceOverviewFunction = _kernel.CreateFunctionFromMethod(
method: () =>
{
var report = _deviceService.GenerateAnalysisReport();
return JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true });
},
functionName: "GetDeviceOverview",
description: "获取所有设备的运行状态总览,包括正常、警告、故障和离线设备数量"
);
// 2. 故障设备查询插件
var errorDevicesFunction = _kernel.CreateFunctionFromMethod(
method: () =>
{
var errorDevices = _deviceService.GetDevicesByStatus(DeviceStatus.Error);
var offlineDevices = _deviceService.GetDevicesByStatus(DeviceStatus.Offline);
var criticalDevices = errorDevices.Concat(offlineDevices).ToList();
return JsonSerializer.Serialize(criticalDevices.Select(d => new
{
d.Id,
d.Name,
d.Type,
d.Status,
d.Location,
d.Temperature,
d.Pressure,
d.Vibration,
d.ErrorMessage,
d.RunningHours,
d.LastMaintenance
}), new JsonSerializerOptions { WriteIndented = true });
},
functionName: "GetCriticalDevices",
description: "获取所有故障和离线的关键设备信息"
);
// 3. 设备详情查询插件
var deviceDetailFunction = _kernel.CreateFunctionFromMethod(
method: ([Description("设备ID或设备名称")] string deviceIdentifier) =>
{
var devices = _deviceService.GetAllDevices();
Device device = devices.FirstOrDefault(d => d.Id == deviceIdentifier) ??
devices.FirstOrDefault(d => d.Name.Contains(deviceIdentifier, StringComparison.OrdinalIgnoreCase));
if (device == null)
{
return JsonSerializer.Serialize(new { success = false, message = $"未找到设备: {deviceIdentifier}" });
}
return JsonSerializer.Serialize(new
{
success = true,
device = new
{
device.Id,
device.Name,
device.Type,
device.Status,
device.Location,
device.Temperature,
device.Pressure,
device.Vibration,
device.RunningHours,
device.LastMaintenance,
device.ErrorMessage,
MaintenanceDaysAgo = (DateTime.Now - device.LastMaintenance).TotalDays,
HealthScore = CalculateHealthScore(device)
}
}, new JsonSerializerOptions { WriteIndented = true });
},
functionName: "GetDeviceDetail",
description: "获取指定设备的详细信息,包括健康度评分"
);
// 4. 预测性维护建议插件
var maintenanceAdviceFunction = _kernel.CreateFunctionFromMethod(
method: () =>
{
var devices = _deviceService.GetAllDevices();
var maintenanceAdvice = devices.Select(d => new
{
d.Id,
d.Name,
d.Location,
Priority = GetMaintenancePriority(d),
DaysToNextMaintenance = GetDaysToNextMaintenance(d),
Recommendations = GetMaintenanceRecommendations(d)
})
.OrderBy(x => x.Priority)
.ToList();
return JsonSerializer.Serialize(maintenanceAdvice, new JsonSerializerOptions { WriteIndented = true });
},
functionName: "GetMaintenanceAdvice",
description: "获取所有设备的预测性维护建议,按优先级排序"
);
// 5. 系统时间插件
var timeFunction = _kernel.CreateFunctionFromMethod(
method: () => DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
functionName: "GetCurrentTime",
description: "获取当前系统时间"
);
// 6. 设备性能分析插件
var performanceAnalysisFunction = _kernel.CreateFunctionFromMethod(
method: ([Description("设备类型,如Motor, Pump, Sensor, Controller")] string deviceType = "") =>
{
var devices = _deviceService.GetAllDevices();
if (!string.IsNullOrEmpty(deviceType) && Enum.TryParse<DeviceType>(deviceType, true, out var type))
{
devices = devices.Where(d => d.Type == type).ToList();
}
var analysis = devices.Select(d => new
{
d.Id,
d.Name,
d.Type,
d.Status,
HealthScore = CalculateHealthScore(d),
PerformanceMetrics = new
{
TemperatureStatus = GetTemperatureStatus(d),
VibrationStatus = GetVibrationStatus(d),
PressureStatus = GetPressureStatus(d),
UpTime = GetUptimePercentage(d)
},
Trend = GetPerformanceTrend(d)
}).ToList();
return JsonSerializer.Serialize(analysis, new JsonSerializerOptions { WriteIndented = true });
},
functionName: "AnalyzeDevicePerformance",
description: "分析设备性能指标,可按设备类型筛选"
);
// 注册插件
_kernel.ImportPluginFromFunctions("DeviceMonitoring", [deviceOverviewFunction, errorDevicesFunction]);
_kernel.ImportPluginFromFunctions("DeviceQuery", [deviceDetailFunction]);
_kernel.ImportPluginFromFunctions("MaintenanceAdvisor", [maintenanceAdviceFunction]);
_kernel.ImportPluginFromFunctions("PerformanceAnalyzer", [performanceAnalysisFunction]);
_kernel.ImportPluginFromFunctions("SystemInfo", [timeFunction]);
}
// 辅助方法
private int CalculateHealthScore(Device device)
{
int score = 100;
// 根据状态扣分
switch (device.Status)
{
case DeviceStatus.Error: score -= 50; break;
case DeviceStatus.Warning: score -= 20; break;
case DeviceStatus.Offline: score -= 80; break;
}
// 根据维护时间扣分
var daysSinceMaintenance = (DateTime.Now - device.LastMaintenance).TotalDays;
if (daysSinceMaintenance > 90) score -= 15;
else if (daysSinceMaintenance > 60) score -= 10;
// 根据运行参数扣分
if (device.Temperature > 90) score -= 15;
else if (device.Temperature > 80) score -= 5;
if (device.Vibration > 1.0) score -= 10;
else if (device.Vibration > 0.7) score -= 5;
return Math.Max(0, score);
}
private int GetMaintenancePriority(Device device)
{
if (device.Status == DeviceStatus.Error || device.Status == DeviceStatus.Offline) return 1;
if (device.Status == DeviceStatus.Warning) return 2;
if ((DateTime.Now - device.LastMaintenance).TotalDays > 90) return 2;
if ((DateTime.Now - device.LastMaintenance).TotalDays > 60) return 3;
return 4;
}
private int GetDaysToNextMaintenance(Device device)
{
var daysSinceLast = (DateTime.Now - device.LastMaintenance).TotalDays;
var standardInterval = 90; // 标准维护间隔90天
return Math.Max(0, standardInterval - (int)daysSinceLast);
}
private List<string> GetMaintenanceRecommendations(Device device)
{
var recommendations = new List<string>();
if (device.Status == DeviceStatus.Error)
recommendations.Add("立即停机检修");
if (device.Temperature > 85)
recommendations.Add("检查冷却系统");
if (device.Vibration > 0.8)
recommendations.Add("检查轴承和平衡");
if ((DateTime.Now - device.LastMaintenance).TotalDays > 90)
recommendations.Add("进行定期保养");
if (device.Type == DeviceType.Pump && device.Pressure < 2.0)
recommendations.Add("检查泵体密封");
if (recommendations.Count == 0)
recommendations.Add("继续监控");
return recommendations;
}
private string GetTemperatureStatus(Device device)
{
if (device.Temperature > 90) return "过热";
if (device.Temperature > 80) return "偏高";
if (device.Temperature < 20) return "过低";
return "正常";
}
private string GetVibrationStatus(Device device)
{
if (device.Vibration > 1.0) return "异常";
if (device.Vibration > 0.7) return "偏高";
return "正常";
}
private string GetPressureStatus(Device device)
{
if (device.Type != DeviceType.Pump) return "N/A";
if (device.Pressure < 1.5) return "不足";
if (device.Pressure > 5.0) return "过高";
return "正常";
}
private double GetUptimePercentage(Device device)
{
// 模拟正常运行时间百分比
return device.Status == DeviceStatus.Running ? 98.5 :
device.Status == DeviceStatus.Warning ? 95.0 :
device.Status == DeviceStatus.Error ? 60.0 : 0.0;
}
private string GetPerformanceTrend(Device device)
{
var healthScore = CalculateHealthScore(device);
if (healthScore > 90) return "稳定";
if (healthScore > 70) return "轻微下降";
if (healthScore > 50) return "明显下降";
return "急剧恶化";
}
public async Task<string> DiagnoseAsync(string userMessage, List<string> chatHistory = null)
{
var chatCompletionService = _kernel.GetRequiredService<IChatCompletionService>();
var systemMessage = @"你是一个专业的设备诊断AI专家。你可以:
1. 🔍 **实时监控**:提供设备运行状态总览和实时数据
2. ⚠️ **故障诊断**:分析设备故障原因并提供解决方案
3. 🔧 **预测性维护**:基于设备数据预测维护需求
4. 📊 **性能分析**:评估设备健康度和性能趋势
5. 💡 **专业建议**:提供运维优化建议
**专业知识领域**:
- 电机故障诊断(温度、振动、电流分析)
- 泵系统问题(压力、流量、密封检查)
- 传感器校准和维护
- 控制系统故障排除
**分析方法**:
- 实时数据趋势分析
- 多参数综合评估
- 历史数据对比
- 预测性算法应用
请根据用户询问,提供准确的技术分析和实用的解决方案。对于紧急故障,会优先给出安全建议。";
var history = new Microsoft.SemanticKernel.ChatCompletion.ChatHistory();
history.AddSystemMessage(systemMessage);
// 添加历史消息
if (chatHistory != null && chatHistory.Count > 0)
{
for (int i = 0; i < chatHistory.Count; i += 2)
{
if (i < chatHistory.Count)
history.AddUserMessage(chatHistory[i]);
if (i + 1 < chatHistory.Count)
history.AddAssistantMessage(chatHistory[i + 1]);
}
}
history.AddUserMessage(userMessage);
var executionSettings = new OpenAIPromptExecutionSettings
{
ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions,
MaxTokens = 2000,
Temperature = 0.3 // 降低温度以获得更准确的技术回答
};
var response = await chatCompletionService.GetChatMessageContentAsync(
history,
executionSettings,
_kernel
);
return response.Content;
}
}
}
🔥 核心优势:
C#private void RegisterDiagnosticPlugins()
{
// 设备状态总览插件
var deviceOverviewFunction = _kernel.CreateFunctionFromMethod(
method: () =>
{
var report = _deviceService.GenerateAnalysisReport();
return JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true });
},
functionName: "GetDeviceOverview",
description: "获取所有设备的运行状态总览,包括正常、警告、故障和离线设备数量"
);
// 注册到内核
_kernel.ImportPluginFromFunctions("DeviceMonitoring", [deviceOverviewFunction]);
}
C#// 故障设备查询插件
var errorDevicesFunction = _kernel.CreateFunctionFromMethod(
method: () =>
{
var errorDevices = _deviceService.GetDevicesByStatus(DeviceStatus.Error);
var offlineDevices = _deviceService.GetDevicesByStatus(DeviceStatus.Offline);
var criticalDevices = errorDevices.Concat(offlineDevices).ToList();
return JsonSerializer.Serialize(criticalDevices.Select(d => new
{
d.Id, d.Name, d.Type, d.Status, d.Location,
d.Temperature, d.Pressure, d.Vibration,
d.ErrorMessage, d.RunningHours, d.LastMaintenance
}), new JsonSerializerOptions { WriteIndented = true });
},
functionName: "GetCriticalDevices",
description: "获取所有故障和离线的关键设备信息"
);
C#// 设备详情查询插件(支持模糊搜索)
var deviceDetailFunction = _kernel.CreateFunctionFromMethod(
method: ([Description("设备ID或设备名称")] string deviceIdentifier) =>
{
var devices = _deviceService.GetAllDevices();
// 智能匹配:ID精确匹配 或 名称模糊匹配
Device device = devices.FirstOrDefault(d => d.Id == deviceIdentifier) ??
devices.FirstOrDefault(d => d.Name.Contains(deviceIdentifier, StringComparison.OrdinalIgnoreCase));
if (device == null)
{
return JsonSerializer.Serialize(new { success = false, message = $"未找到设备: {deviceIdentifier}" });
}
return JsonSerializer.Serialize(new
{
success = true,
device = new
{
device.Id, device.Name, device.Type, device.Status,
device.Location, device.Temperature, device.Pressure,
device.Vibration, device.RunningHours, device.LastMaintenance,
device.ErrorMessage,
MaintenanceDaysAgo = (DateTime.Now - device.LastMaintenance).TotalDays,
HealthScore = CalculateHealthScore(device) // 健康度评分
}
}, new JsonSerializerOptions { WriteIndented = true });
},
functionName: "GetDeviceDetail",
description: "获取指定设备的详细信息,包括健康度评分"
);
💡 设计亮点:
[Description]帮助AI理解参数用途C#private int CalculateHealthScore(Device device)
{
int score = 100;
// 根据设备状态扣分
switch (device.Status)
{
case DeviceStatus.Error: score -= 50; break;
case DeviceStatus.Warning: score -= 20; break;
case DeviceStatus.Offline: score -= 80; break;
}
// 根据维护周期扣分
var daysSinceMaintenance = (DateTime.Now - device.LastMaintenance).TotalDays;
if (daysSinceMaintenance > 90) score -= 15;
else if (daysSinceMaintenance > 60) score -= 10;
// 根据关键参数扣分
if (device.Temperature > 90) score -= 15;
else if (device.Temperature > 80) score -= 5;
if (device.Vibration > 1.0) score -= 10;
else if (device.Vibration > 0.7) score -= 5;
return Math.Max(0, score);
}
C#// 预测性维护建议插件
var maintenanceAdviceFunction = _kernel.CreateFunctionFromMethod(
method: () =>
{
var devices = _deviceService.GetAllDevices();
var maintenanceAdvice = devices.Select(d => new
{
d.Id, d.Name, d.Location,
Priority = GetMaintenancePriority(d),
DaysToNextMaintenance = GetDaysToNextMaintenance(d),
Recommendations = GetMaintenanceRecommendations(d)
})
.OrderBy(x => x.Priority) // 按优先级排序
.ToList();
return JsonSerializer.Serialize(maintenanceAdvice, new JsonSerializerOptions { WriteIndented = true });
},
functionName: "GetMaintenanceAdvice",
description: "获取所有设备的预测性维护建议,按优先级排序"
);
private List<string> GetMaintenanceRecommendations(Device device)
{
var recommendations = new List<string>();
if (device.Status == DeviceStatus.Error)
recommendations.Add("立即停机检修");
if (device.Temperature > 85)
recommendations.Add("检查冷却系统");
if (device.Vibration > 0.8)
recommendations.Add("检查轴承和平衡");
if ((DateTime.Now - device.LastMaintenance).TotalDays > 90)
recommendations.Add("进行定期保养");
if (device.Type == DeviceType.Pump && device.Pressure < 2.0)
recommendations.Add("检查泵体密封");
if (recommendations.Count == 0)
recommendations.Add("继续监控");
return recommendations;
}
🎯 专业特色:
C#public async Task<string> DiagnoseAsync(string userMessage, List<string> chatHistory = null)
{
var chatCompletionService = _kernel.GetRequiredService<IChatCompletionService>();
var systemMessage = @"你是一个专业的设备诊断AI专家。你可以:
1. 🔍 **实时监控**:提供设备运行状态总览和实时数据
2. ⚠️ **故障诊断**:分析设备故障原因并提供解决方案
3. 🔧 **预测性维护**:基于设备数据预测维护需求
4. 📊 **性能分析**:评估设备健康度和性能趋势
5. 💡 **专业建议**:提供运维优化建议
**专业知识领域**:
- 电机故障诊断(温度、振动、电流分析)
- 泵系统问题(压力、流量、密封检查)
- 传感器校准和维护
- 控制系统故障排除
**分析方法**:
- 实时数据趋势分析
- 多参数综合评估
- 历史数据对比
- 预测性算法应用
请根据用户询问,提供准确的技术分析和实用的解决方案。对于紧急故障,会优先给出安全建议。";
var history = new Microsoft.SemanticKernel.ChatCompletion.ChatHistory();
history.AddSystemMessage(systemMessage);
// 添加对话历史
if (chatHistory != null && chatHistory.Count > 0)
{
for (int i = 0; i < chatHistory.Count; i += 2)
{
if (i < chatHistory.Count)
history.AddUserMessage(chatHistory[i]);
if (i + 1 < chatHistory.Count)
history.AddAssistantMessage(chatHistory[i + 1]);
}
}
history.AddUserMessage(userMessage);
// 配置执行参数
var executionSettings = new OpenAIPromptExecutionSettings
{
ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions, // 自动调用函数
MaxTokens = 2000,
Temperature = 0.3 // 降低随机性,提高准确性
};
var response = await chatCompletionService.GetChatMessageContentAsync(
history,
executionSettings,
_kernel
);
return response.Content;
}
🔥 核心特性:
C#// 设备性能分析插件
var performanceAnalysisFunction = _kernel.CreateFunctionFromMethod(
method: ([Description("设备类型,如Motor, Pump, Sensor, Controller")] string deviceType = "") =>
{
var devices = _deviceService.GetAllDevices();
// 支持按类型筛选
if (!string.IsNullOrEmpty(deviceType) && Enum.TryParse<DeviceType>(deviceType, true, out var type))
{
devices = devices.Where(d => d.Type == type).ToList();
}
var analysis = devices.Select(d => new
{
d.Id, d.Name, d.Type, d.Status,
HealthScore = CalculateHealthScore(d),
PerformanceMetrics = new
{
TemperatureStatus = GetTemperatureStatus(d),
VibrationStatus = GetVibrationStatus(d),
PressureStatus = GetPressureStatus(d),
UpTime = GetUptimePercentage(d)
},
Trend = GetPerformanceTrend(d)
}).ToList();
return JsonSerializer.Serialize(analysis, new JsonSerializerOptions { WriteIndented = true });
},
functionName: "AnalyzeDevicePerformance",
description: "分析设备性能指标,可按设备类型筛选"
);
C#private string GetTemperatureStatus(Device device)
{
if (device.Temperature > 90) return "过热";
if (device.Temperature > 80) return "偏高";
if (device.Temperature < 20) return "过低";
return "正常";
}
private string GetPerformanceTrend(Device device)
{
var healthScore = CalculateHealthScore(device);
if (healthScore > 90) return "稳定";
if (healthScore > 70) return "轻微下降";
if (healthScore > 50) return "明显下降";
return "急剧恶化";
}
private double GetUptimePercentage(Device device)
{
// 基于状态计算运行时间百分比
return device.Status == DeviceStatus.Running ? 98.5 :
device.Status == DeviceStatus.Warning ? 95.0 :
device.Status == DeviceStatus.Error ? 60.0 : 0.0;
}


1. 函数描述不够清晰
C#❌ 错误写法:
description: "获取设备"
✅ 正确写法:
description: "获取所有故障和离线的关键设备信息"
2. JSON序列化问题
C#❌ 可能出现循环引用:
return JsonSerializer.Serialize(device);
✅ 使用匿名对象避免循环引用:
return JsonSerializer.Serialize(new { device.Id, device.Name, ... });
3. 异常处理缺失
C#✅ 完善的异常处理:
try
{
var response = await chatCompletionService.GetChatMessageContentAsync(...);
return response.Content;
}
catch (Exception ex)
{
return $"诊断服务暂时不可用:{ex.Message}";
}
1. 合理控制Token使用
C#var executionSettings = new OpenAIPromptExecutionSettings
{
MaxTokens = 2000, // 根据实际需要调整
Temperature = 0.3 // 技术场景降低随机性
};
2. 优化函数返回数据量
C#// 只返回必要的字段,避免传输冗余数据
return JsonSerializer.Serialize(devices.Select(d => new
{
d.Id, d.Name, d.Status, // 只选择必要字段
HealthScore = CalculateHealthScore(d)
}));
通过这个完整的AI诊断系统项目,我们掌握了Semantic Kernel的三大核心能力:
金句总结:
💬 互动时刻:
🔗 延伸学习:
🏷️ 标签:#C#开发 #SemanticKernel #AI应用 #企业开发 #智能诊断 #函数调用
相关信息
通过网盘分享的文件:AppAiDeviceDiagnostics.zip 链接: https://pan.baidu.com/s/1s3ixfqHSZAnBQcJ9Z5FzKg?pwd=mb3d 提取码: mb3d --来自百度网盘超级会员v9的分享
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!