使用 maf重构
This commit is contained in:
70
Service/AgentFramework/AITools.cs
Normal file
70
Service/AgentFramework/AITools.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
namespace Service.AgentFramework;
|
||||
|
||||
/// <summary>
|
||||
/// AI 工具集
|
||||
/// </summary>
|
||||
public interface IAITools
|
||||
{
|
||||
/// <summary>
|
||||
/// AI 分类决策
|
||||
/// </summary>
|
||||
Task<ClassificationResult[]> ClassifyTransactionsAsync(
|
||||
string systemPrompt,
|
||||
string userPrompt);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AI 工具实现
|
||||
/// </summary>
|
||||
public class AITools(
|
||||
IOpenAiService openAiService,
|
||||
ILogger<AITools> logger
|
||||
) : IAITools
|
||||
{
|
||||
public async Task<ClassificationResult[]> ClassifyTransactionsAsync(
|
||||
string systemPrompt,
|
||||
string userPrompt)
|
||||
{
|
||||
logger.LogInformation("调用 AI 进行账单分类");
|
||||
|
||||
var response = await openAiService.ChatAsync(systemPrompt, userPrompt);
|
||||
if (string.IsNullOrWhiteSpace(response))
|
||||
{
|
||||
logger.LogWarning("AI 返回空响应");
|
||||
return Array.Empty<ClassificationResult>();
|
||||
}
|
||||
|
||||
// 解析 NDJSON 格式的 AI 响应
|
||||
var results = new List<ClassificationResult>();
|
||||
var lines = response.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
foreach (var line in lines)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(line))
|
||||
continue;
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(line);
|
||||
var root = doc.RootElement;
|
||||
|
||||
var result = new ClassificationResult
|
||||
{
|
||||
Reason = root.GetProperty("reason").GetString() ?? string.Empty,
|
||||
Classify = root.GetProperty("classify").GetString() ?? string.Empty,
|
||||
Type = (TransactionType)root.GetProperty("type").GetInt32(),
|
||||
Confidence = 0.9 // 可从 AI 响应中解析
|
||||
};
|
||||
|
||||
results.Add(result);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
logger.LogWarning(ex, "解析 AI 响应行失败: {Line}", line);
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogInformation("AI 分类完成,得到 {Count} 条结果", results.Count);
|
||||
return results.ToArray();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user