当前AIKernel.ts中的processMessage(非流式)和processMessageStream(流式)有大量重复代码:
- 意图识别逻辑重复
- 工具调用处理逻辑重复
- JSON工具调用转换逻辑重复
- 第二次LLM调用逻辑重复
这导致了维护困难和bug同步问题(如本次JSON工具调用bug)。
class AIKernel {
/**
* 核心处理流水线:统一流式和非流式的共同逻辑
* 返回标准化的处理结果,由调用方决定如何输出
*/
private async executeProcessingPipeline(
input: string,
sessionId: string,
context?: any
): Promise<{
intent: IntentClassificationResult;
promptResult: any;
processedResponse: any;
toolResults?: any[];
finalResponse: any;
}> {
// 1. 意图识别
const intent = await this.classifyIntent(input, sessionId);
// 2. 构建提示
const promptResult = await this.buildPrompt(input, intent, sessionId, context);
// 3. 第一次LLM调用
const llmResponse = await this.callLLM(promptResult);
// 4. JSON工具调用转换
const processedResponse = await this.tryConvertJsonToolCall(llmResponse, sessionId, intent);
// 5. 工具执行(如果需要)
let toolResults: any[] | undefined;
let finalResponse = processedResponse;
if (processedResponse.toolCalls?.length > 0) {
toolResults = await this.toolExecutionManager.executeToolCalls(processedResponse.toolCalls);
// 构建带工具结果的消息
const messagesWithToolResults = this.buildMessagesWithToolResults(
promptResult.messages,
processedResponse,
toolResults
);
// 第二次LLM调用
finalResponse = await this.callLLM({
...promptResult,
messages: messagesWithToolResults,
tools: []
});
}
return { intent, promptResult, processedResponse, toolResults, finalResponse };
}
// 简化后的非流式处理
async processMessage(input: string, sessionId: string = 'default', context?: any): Promise<AIResponse> {
if (!this.isInitialized) await this.initialize();
try {
const { intent, toolResults, finalResponse, processedResponse } =
await this.executeProcessingPipeline(input, sessionId, context);
// 收集工具执行记录
const toolExecutions = this.collectToolExecutions(processedResponse.toolCalls, toolResults);
// 格式化响应
return this.formatResponse(finalResponse, sessionId, intent, toolExecutions);
} catch (error) {
// 错误处理...
}
}
// 简化后的流式处理
async processMessageStream(
sessionId: string,
message: string,
callback: StreamCallback,
context?: any
): Promise<void> {
if (!this.isInitialized) await this.initialize();
try {
this.stats.totalMessages++;
const { intent, processedResponse, toolResults, finalResponse } =
await this.executeProcessingPipeline(message, sessionId, context);
// 根据是否有工具调用选择输出策略
if (processedResponse.toolCalls?.length > 0) {
await this.handleStreamWithTools(callback, processedResponse, toolResults, finalResponse);
} else {
await this.handleStreamWithoutTools(callback, finalResponse);
}
} catch (error) {
// 错误处理...
}
}
}如果不想大幅修改现有结构,可以提取一些辅助方法:
class AIKernel {
// 提取消息构建逻辑
private buildMessagesWithToolResults(
baseMessages: any[],
processedResponse: any,
toolResults: any[]
): any[] {
return [
...baseMessages,
{
role: 'assistant' as const,
content: processedResponse.content || '',
tool_calls: processedResponse.toolCalls,
timestamp: new Date()
},
...toolResults.map((result, index) => {
const toolCall = processedResponse.toolCalls?.[index];
return {
role: 'tool' as const,
tool_call_id: toolCall?.id || `tool_${index}_${Date.now()}`,
content: typeof result.content === 'string' ? result.content : JSON.stringify(result.content),
name: result.name || toolCall?.function?.name,
timestamp: new Date()
};
})
];
}
// 提取工具执行记录收集逻辑
private collectToolExecutions(toolCalls: any[], toolResults?: any[]): any[] {
if (!toolResults || !toolCalls) return [];
return toolResults.map((result, index) => {
const toolCall = toolCalls[index];
return {
toolCallId: toolCall?.id || `tool_${index}_${Date.now()}`,
toolName: result.name || toolCall?.function?.name,
result: result,
timestamp: new Date()
};
});
}
// 提取标准工具处理流程
private async executeToolsIfNeeded(
processedResponse: any,
promptResult: any
): Promise<{ toolResults?: any[], finalResponse: any }> {
if (!processedResponse.toolCalls?.length) {
return { finalResponse: processedResponse };
}
// 执行工具
const toolResults = await this.toolExecutionManager.executeToolCalls(processedResponse.toolCalls);
// 构建消息
const messagesWithToolResults = this.buildMessagesWithToolResults(
promptResult.messages,
processedResponse,
toolResults
);
// 第二次LLM调用
const finalResponse = await this.callLLM({
...promptResult,
messages: messagesWithToolResults,
tools: []
});
return { toolResults, finalResponse };
}
}- 代码重用率:核心逻辑从重复 → 共享
- 维护成本:bug修复只需改一处
- 一致性保证:流式和非流式行为完全一致
- 扩展性:新增处理模式只需修改输出策略
- 风险最小:保持现有结构不变
- 渐进改善:逐步减少重复代码
- 向后兼容:现有接口完全不变
- 选择方案1:如果可以接受较大的结构调整
- 选择方案2:如果希望最小化风险和改动
无论选择哪种方案,都建议:
- 先添加完整的单元测试
- 保留原有实现作为备选
- 分阶段实施和验证
- 密切监控性能指标
describe('AIKernel重构验证', () => {
test('流式和非流式处理结果应该一致', async () => {
const input = "请读取main.ink文件";
const sessionId = "test-session";
// 非流式结果
const syncResult = await aiKernel.processMessage(input, sessionId);
// 流式结果(收集所有输出)
let streamResult = '';
await aiKernel.processMessageStream(sessionId, input, ({ content }) => {
streamResult += content;
});
// 验证核心内容一致
expect(syncResult.content).toBe(streamResult);
});
test('JSON工具调用在两种模式下都应该正常工作', async () => {
// 模拟返回JSON格式的LLM响应
const mockLLMResponse = {
content: '{"name": "read_file", "arguments": {"path": "main.ink"}}'
};
// 验证转换和执行逻辑一致
// ...
});
});这个最小化重构方案可以显著减少代码重复,提高可维护性,同时将风险控制在最低水平。