工程级参考答案(带完整注释):
// 生产级 Agent State Machine 实现
type AgentState = 'idle' | 'thinking' | 'awaiting_confirmation' | 'executing' | 'complete' | 'error';
interface AgentContext {
userInput: string;
action: string;
requiresConfirmation: boolean;
confirmationPrompt: string;
result?: any;
error?: Error;
}
class ProductionAgentSM {
private state: AgentState = 'idle';
private context: AgentContext;
private stateHandlers: Map Promise>;
constructor() {
this.context = {
userInput: '',
action: '',
requiresConfirmation: false,
confirmationPrompt: ''
};
this.stateHandlers = new Map([
['idle', this.onIdle.bind(this)],
['thinking', this.onThinking.bind(this)],
['awaiting_confirmation', this.onAwaitingConfirmation.bind(this)],
['executing', this.onExecuting.bind(this)],
['complete', this.onComplete.bind(this)],
['error', this.onError.bind(this)],
]);
}
async process(userInput: string): Promise {
this.context.userInput = userInput;
this.state = 'thinking';
try {
await this.stateHandlers.get(this.state)?.(this.context);
return this.getResponse();
} catch (err) {
this.state = 'error';
this.context.error = err as Error;
return `出错了:${this.context.error.message}`;
}
}
private async onIdle(ctx: AgentContext) { /* ... */ }
private async onThinking(ctx: AgentContext) {
// 分析用户输入,决定是否需要确认
if (this.requiresConfirmation(ctx.userInput)) {
ctx.requiresConfirmation = true;
this.state = 'awaiting_confirmation';
} else {
this.state = 'executing';
}
}
private async onAwaitingConfirmation(ctx: AgentContext) { /* ... */ }
private async onExecuting(ctx: AgentContext) {
ctx.result = await this.execute(ctx.action);
this.state = 'complete';
}
private async onComplete(ctx: AgentContext) { /* ... */ }
private async onError(ctx: AgentContext) { /* ... */ }
private requiresConfirmation(input: string): boolean {
return /删除|清空|重置|发送/.test(input);
}
private async execute(action: string): Promise {
// 实际执行逻辑
return { success: true };
}
private getResponse(): string {
// 根据当前状态返回用户友好的消息
return `[${this.state}] Agent 状态已更新`;
}
}