UNPKG

flux-agent

Version:

FluxAgent - 一个可灵活插拔的AI Agent系统框架,基于TypeScript开发,支持流式执行、事件系统、插件系统、知识库管理等功能 (Protected Release) (Protected Release) (Protected Release) (Protected Release) (Protected Release) (Protected Release) (Protected Release) (Protected Release) (Protected Release) (

218 lines (217 loc) 9.09 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AgentStreamExecutionEngine = void 0; const ExecutionSession_1 = require("./ExecutionSession"); const PhaseManager_1 = require("./PhaseManager"); const LLMOrchestrator_1 = require("./LLMOrchestrator"); const ToolOrchestrator_1 = require("./ToolOrchestrator"); const types_1 = require("./types"); const Agent_1 = require("../Agent"); const EventHub_1 = require("../EventHub"); const State_1 = require("../State"); /** * Agent 流式执行引擎 * 基于原有AgentExecutionEngine,但支持流式输出 */ class AgentStreamExecutionEngine { constructor(agent) { this.agent = agent; this.stopped = true; this.phaseManager = new PhaseManager_1.PhaseManager(agent); this.llmOrchestrator = new LLMOrchestrator_1.LLMOrchestrator(agent); this.toolOrchestrator = new ToolOrchestrator_1.ToolOrchestrator(agent); this.agent.eventHub.registerType('StopEvent', () => { this.stopped = true; }); } /** * 流式运行方法 */ async runStream(callbacks) { this.stopped = false; this.streamCallbacks = callbacks; const currentPhase = this.agent.phases.getCurrentPhase(); const session = new ExecutionSession_1.ExecutionSession(this.agent, currentPhase); this.agent.changeAgentState(State_1.AgentState.RUNNING); Agent_1.AgentLogger.log(`流式执行引擎启动,当前阶段: ${currentPhase}`); try { while (session.shouldContinue()) { // 检查循环限制 const loopLimitResult = session.checkLoopLimits(); if (loopLimitResult) { await session.handlePhaseResult(loopLimitResult); break; } // 执行当前阶段 const phaseResult = await this.executePhaseStream(session); // 处理阶段结果 const oldPhase = session.getCurrentPhase(); await session.handlePhaseResult(phaseResult); const newPhase = session.getCurrentPhase(); // 发出阶段变更事件(如果阶段确实发生了变化) if (oldPhase !== newPhase) { this.agent.context.cleanUnrelatedMessages(); this.emitPhaseChange(oldPhase, newPhase); } // 如果需要暂停或出错,退出循环 if (phaseResult.type === 'stop' || phaseResult.type === 'pause' || phaseResult.type === 'error') { break; } } const finalResponse = session.getResponse(); this.agent.changeAgentState(State_1.AgentState.IDLE); Agent_1.AgentLogger.log('流式执行引擎结束', session.getExecutionStats()); return finalResponse; } catch (error) { Agent_1.AgentLogger.log('流式执行引擎错误', { error: error.message }); if (this.streamCallbacks?.onError) { this.streamCallbacks.onError(error, session.getCurrentPhase()); } this.agent.changeAgentState(State_1.AgentState.STOP); throw error; } } createStopEventPromise(phase) { return new Promise((resolve, reject) => { try { this.agent.eventHub.registerType('StopEvent', () => { const result = { content: '', toolCalls: [], }; resolve(new types_1.LLMResultImpl(result, result, phase, true)); }); } catch (error) { reject(error); } }); } /** * 执行单个阶段 - 流式版本 */ async executePhaseStream(session) { const currentPhase = session.getCurrentPhase(); try { // 1. 生成提示词 const tagedPrompt = await this.phaseManager.generatePrompt(currentPhase); // 2. 流式LLM交互 const llmResult = await Promise.race([this.llmOrchestrator.interactStream(currentPhase, session, tagedPrompt, this.createLLMStreamCallbacks(currentPhase)), this.createStopEventPromise(currentPhase)]); if (llmResult.isStop) { return types_1.PhaseResultBuilder.stop(); } // 3. 验证LLM响应 if (!this.llmOrchestrator.validateResponse(llmResult)) { return types_1.PhaseResultBuilder.error(new Error('LLM响应无效')); } // 4. 记录LLM响应 this.llmOrchestrator.recordResponse(llmResult); if (llmResult.enhancedResponse.content) { this.agent.eventHub.emit({ type: 'LLMResponseEvent', name: EventHub_1.AgentEventName.LLMResponseEvent, payload: { ...llmResult.enhancedResponse, phase: currentPhase } }); } // 5. 流式处理工具调用 const toolResult = await this.handleToolsStream(llmResult, session); // 6. 处理特殊阶段逻辑 const specialPhaseResult = await this.toolOrchestrator.handleSpecialPhaseLogic(llmResult); if (specialPhaseResult) { return specialPhaseResult; } // 7. 触发阶段后事件 this.phaseManager.triggerAfterPhaseEvent(currentPhase, tagedPrompt.prompt, llmResult.enhancedResponse); // 8. 返回结果 return this.convertToolResultToPhaseResult(toolResult); } catch (error) { Agent_1.AgentLogger.log(`阶段执行失败: ${currentPhase}`, { error: error.message }); if (this.streamCallbacks?.onError) { this.streamCallbacks.onError(error, currentPhase); } return types_1.PhaseResultBuilder.error(error); } } /** * 创建LLM流式回调 */ createLLMStreamCallbacks(phase) { return { onToken: (token, id) => { if (this.streamCallbacks?.onLLMToken && !this.stopped) { this.streamCallbacks.onLLMToken(token, phase, id); } }, onPartialResponse: (partial, id) => { if (this.streamCallbacks?.onLLMPartialResponse && !this.stopped) { this.streamCallbacks.onLLMPartialResponse(partial, phase, id); } }, onComplete: (llmResult, streamId) => { // LLM完成回调,暂时不需要特殊处理 if (this.streamCallbacks?.onComplete && !this.stopped) { this.streamCallbacks.onComplete(llmResult, streamId, phase); } }, onError: (error) => { if (this.streamCallbacks?.onError && !this.stopped) { this.streamCallbacks.onError(error, phase); } } }; } /** * 流式处理工具调用 */ async handleToolsStream(llmResult, session) { // 使用原有的工具处理逻辑 const tools = this.agent.toolManager.getToolsForPhase(session.getCurrentPhase()); // 强行限定调用的工具集,防止工具调用超出工具集范围 llmResult.enhancedResponse.toolCalls = llmResult.enhancedResponse.toolCalls?.filter(tool => tools.some((t) => t.getName() === tool.name)) || []; const toolResult = await this.toolOrchestrator.handleTools(llmResult, session); return toolResult; } /** * 发出阶段变更事件 */ emitPhaseChange(fromPhase, toPhase) { if (this.streamCallbacks?.onPhaseChange) { this.streamCallbacks.onPhaseChange(fromPhase, toPhase); } } /** * 将工具结果转换为阶段结果 */ convertToolResultToPhaseResult(toolResult) { switch (toolResult.type) { case 'pause': return types_1.PhaseResultBuilder.pause(toolResult.response || ''); case 'phase_end': // 阶段结束或终止,继续正常流程处理 return types_1.PhaseResultBuilder.complete(toolResult.response); // 工具执行错误,但是可以继续运行 case 'error': return types_1.PhaseResultBuilder.empty(); case 'success': default: return types_1.PhaseResultBuilder.empty(); } } /** * 获取执行引擎状态 */ getEngineStatus() { return { phaseManager: !!this.phaseManager, llmOrchestrator: !!this.llmOrchestrator, toolOrchestrator: !!this.toolOrchestrator, streamCallbacks: !!this.streamCallbacks }; } getStopped() { return this.stopped; } } exports.AgentStreamExecutionEngine = AgentStreamExecutionEngine;