3.3 多轮对话实现

完整的多轮对话系统

核心代码

1
2
3
4
5
6
7
8
9
10
// agent.ts
export class Agent {
async process(userInput: string): Promise<string> {
this.conversation.addMessage('user', userInput);
const messages = this.conversation.getMessages();
const response = await this.llm.chat(messages);
this.conversation.addMessage('assistant', response);
return response;
}
}

多轮对话示例

1
2
3
4
5
6
7
8
你: TypeScript 是什么?
助手: TypeScript 是 JavaScript 的超集,添加了静态类型...

你: 它有什么优点?
助手: TypeScript 的优点包括:类型安全、更好的IDE支持...

你: 如何安装?
助手: 可以通过 npm 安装:npm install -g typescript

Step 1 完成总结

  • ✅ 对话历史存储
  • ✅ 上下文传递给 LLM
  • ✅ 多轮对话支持
  • ✅ 历史管理命令

下一章: 第四章:工具调用系统

导航

上一篇: 3.2 消息历史存储

下一篇: 4.1 Function Calling 原理