63 lines
2.0 KiB
Markdown
63 lines
2.0 KiB
Markdown
|
|
# 在前端应用程序中处理记忆
|
|||
|
|
|
|||
|
|
构建使用 Mastra 记忆功能的前端应用程序时,重要的是在每次智能体调用中只发送最新的用户消息。Mastra 负责检索和注入必要的历史记录。自行发送完整历史记录会导致重复。
|
|||
|
|
|
|||
|
|
以下是如何在 React 应用程序中处理此问题的简化示例:
|
|||
|
|
|
|||
|
|
```tsx
|
|||
|
|
import { useState } from "react";
|
|||
|
|
import { memoryAgent } from "./agents";
|
|||
|
|
|
|||
|
|
function ChatApp() {
|
|||
|
|
const [messages, setMessages] = useState([]);
|
|||
|
|
const [input, setInput] = useState("");
|
|||
|
|
|
|||
|
|
const handleSendMessage = async () => {
|
|||
|
|
// 将用户消息添加到 UI
|
|||
|
|
setMessages([...messages, { role: "user", content: input }]);
|
|||
|
|
|
|||
|
|
// 只向智能体发送最新消息
|
|||
|
|
const response = await memoryAgent.stream(input, {
|
|||
|
|
resourceId: "user_123",
|
|||
|
|
threadId: "conversation_456",
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// 将智能体响应添加到 UI
|
|||
|
|
setMessages([...messages, { role: "assistant", content: response }]);
|
|||
|
|
setInput("");
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
return (
|
|||
|
|
<div>
|
|||
|
|
{/* 显示消息 */}
|
|||
|
|
<div>
|
|||
|
|
{messages.map((msg, index) => (
|
|||
|
|
<div key={index}>
|
|||
|
|
<strong>{msg.role}:</strong> {msg.content}
|
|||
|
|
</div>
|
|||
|
|
))}
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
{/* 新消息输入框 */}
|
|||
|
|
<input
|
|||
|
|
value={input}
|
|||
|
|
onChange={(e) => setInput(e.target.value)}
|
|||
|
|
onKeyPress={(e) => e.key === "Enter" && handleSendMessage()}
|
|||
|
|
/>
|
|||
|
|
<button onClick={handleSendMessage}>Send</button>
|
|||
|
|
</div>
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
此示例展示了在前端应用程序中处理记忆的常见模式:
|
|||
|
|
|
|||
|
|
1. 将对话消息存储在 UI 状态中以供显示
|
|||
|
|
2. 向智能体发送消息时,只发送最新消息
|
|||
|
|
3. 在每次智能体调用中包含 `resourceId` 和 `threadId`
|
|||
|
|
4. 让 Mastra 负责检索和注入对话历史记录
|
|||
|
|
|
|||
|
|
这种方法确保您的智能体能够访问对话历史记录,而不会在上下文窗口中重复消息。
|
|||
|
|
|
|||
|
|
下一步,我们将探索语义回忆,它允许您的智能体记住不再在最近历史记录中的较早对话的信息。
|