MemGPT Web前端:React、Vue框架集成

【免费下载链接】MemGPT Teaching LLMs memory management for unbounded context 📚🦙 【免费下载链接】MemGPT 项目地址: https://gitcode.com/GitHub_Trending/me/MemGPT

概述

MemGPT(现更名为Letta)是一个开源的**状态化智能体(Stateful Agents)**框架,为LLM提供透明的长期记忆管理能力。本文将详细介绍如何在React和Vue前端项目中集成MemGPT,构建具备高级推理能力的AI应用。

核心概念

MemGPT架构概览

mermaid

关键组件

组件 描述 前端集成点
Agent(智能体) 具备记忆和推理能力的AI实体 创建、管理、交互
Memory Blocks(记忆块) 存储核心记忆数据 读写操作
Tools(工具) 扩展Agent能力的函数 自定义工具集成
Messages(消息) 用户与Agent的交互记录 消息发送和接收

环境准备

1. 启动MemGPT服务器

# 使用Docker启动服务器
docker run \
  -v ~/.letta/.persist/pgdata:/var/lib/postgresql/data \
  -p 8283:8283 \
  -e OPENAI_API_KEY="your_openai_api_key" \
  letta/letta:latest

2. 安装客户端SDK

React项目安装:

npm install @letta-ai/letta-client
# 或
yarn add @letta-ai/letta-client

Vue项目安装:

npm install @letta-ai/letta-client
# 或
yarn add @letta-ai/letta-client

React集成示例

基础组件结构

import React, { useState, useEffect } from 'react';
import { LettaClient } from '@letta-ai/letta-client';

const MemGPTChat = () => {
  const [client, setClient] = useState(null);
  const [agent, setAgent] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');

  useEffect(() => {
    // 初始化客户端
    const lettaClient = new LettaClient({
      baseUrl: 'http://localhost:8283',
    });
    setClient(lettaClient);
  }, []);

  const createAgent = async () => {
    try {
      const newAgent = await client.agents.create({
        memoryBlocks: [
          {
            value: 'name: User',
            label: 'human',
          },
          {
            value: 'I am a helpful AI assistant',
            label: 'persona',
          },
        ],
        model: 'openai/gpt-4o-mini',
        embedding: 'openai/text-embedding-3-small',
      });
      setAgent(newAgent);
    } catch (error) {
      console.error('创建Agent失败:', error);
    }
  };

  const sendMessage = async () => {
    if (!agent || !input.trim()) return;

    try {
      const response = await client.agents.messages.create(agent.id, {
        messages: [
          {
            role: 'user',
            content: input,
          },
        ],
      });

      // 处理响应消息
      const newMessages = response.messages.map(msg => ({
        role: msg.role,
        content: msg.content || msg.reasoning,
        type: msg.__typename,
      }));

      setMessages(prev => [...prev, ...newMessages]);
      setInput('');
    } catch (error) {
      console.error('发送消息失败:', error);
    }
  };

  return (
    <div className="memgpt-chat-container">
      <h2>MemGPT聊天界面</h2>
      
      {!agent ? (
        <button onClick={createAgent}>创建AI助手</button>
      ) : (
        <>
          <div className="chat-messages">
            {messages.map((msg, index) => (
              <div key={index} className={`message ${msg.role}`}>
                <strong>{msg.role}:</strong> {msg.content}
              </div>
            ))}
          </div>
          
          <div className="chat-input">
            <input
              type="text"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
              placeholder="输入消息..."
            />
            <button onClick={sendMessage}>发送</button>
          </div>
        </>
      )}
    </div>
  );
};

export default MemGPTChat;

高级功能集成

import { useMemoGPT } from '../hooks/useMemoGPT';

const AdvancedMemGPT = () => {
  const {
    agents,
    currentAgent,
    messages,
    isLoading,
    createAgent,
    sendMessage,
    switchAgent,
    deleteAgent
  } = useMemoGPT();

  return (
    <div className="advanced-memgpt">
      <div className="agent-sidebar">
        <h3>智能体管理</h3>
        <button onClick={() => createAgent('新助手')}>新建智能体</button>
        {agents.map(agent => (
          <div key={agent.id} className="agent-item">
            <span>{agent.name}</span>
            <button onClick={() => switchAgent(agent.id)}>切换</button>
            <button onClick={() => deleteAgent(agent.id)}>删除</button>
          </div>
        ))}
      </div>

      <div className="chat-main">
        {currentAgent && (
          <ChatInterface
            agent={currentAgent}
            messages={messages}
            onSendMessage={sendMessage}
            isLoading={isLoading}
          />
        )}
      </div>
    </div>
  );
};

Vue集成示例

Composition API实现

<template>
  <div class="memgpt-chat">
    <h2>MemGPT聊天应用</h2>
    
    <div v-if="!agent">
      <button @click="createAgent">创建AI助手</button>
    </div>
    
    <div v-else>
      <div class="messages">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message', message.role]"
        >
          <strong>{{ message.role }}:</strong> {{ message.content }}
        </div>
      </div>
      
      <div class="input-area">
        <input
          v-model="inputText"
          @keyup.enter="sendMessage"
          placeholder="输入消息..."
        />
        <button @click="sendMessage" :disabled="isLoading">
          {{ isLoading ? '发送中...' : '发送' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { LettaClient } from '@letta-ai/letta-client';

const client = ref(null);
const agent = ref(null);
const messages = ref([]);
const inputText = ref('');
const isLoading = ref(false);

onMounted(() => {
  client.value = new LettaClient({
    baseUrl: 'http://localhost:8283',
  });
});

const createAgent = async () => {
  try {
    agent.value = await client.value.agents.create({
      memoryBlocks: [
        {
          value: '用户偏好:喜欢技术讨论',
          label: 'human',
        },
        {
          value: '我是一个技术专家助手',
          label: 'persona',
        },
      ],
      model: 'openai/gpt-4o-mini',
      embedding: 'openai/text-embedding-3-small',
    });
  } catch (error) {
    console.error('创建Agent失败:', error);
  }
};

const sendMessage = async () => {
  if (!agent.value || !inputText.value.trim() || isLoading.value) return;

  isLoading.value = true;
  try {
    const response = await client.value.agents.messages.create(agent.value.id, {
      messages: [
        {
          role: 'user',
          content: inputText.value,
        },
      ],
    });

    response.messages.forEach(msg => {
      messages.value.push({
        role: msg.role,
        content: msg.content || msg.reasoning,
        type: msg.__typename,
      });
    });

    inputText.value = '';
  } catch (error) {
    console.error('发送消息失败:', error);
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
.memgpt-chat {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.messages {
  height: 400px;
  overflow-y: auto;
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 10px;
}

.message {
  margin-bottom: 10px;
  padding: 8px;
  border-radius: 8px;
}

.message.user {
  background-color: #e3f2fd;
  text-align: right;
}

.message.assistant {
  background-color: #f3e5f5;
}

.input-area {
  display: flex;
  gap: 10px;
}

input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>

Pinia状态管理

// stores/memgpt.js
import { defineStore } from 'pinia';
import { LettaClient } from '@letta-ai/letta-client';

export const useMemGPTStore = defineStore('memgpt', {
  state: () => ({
    client: null,
    agents: [],
    currentAgent: null,
    messages: [],
    isLoading: false,
  }),
  
  actions: {
    initializeClient(baseUrl = 'http://localhost:8283') {
      this.client = new LettaClient({ baseUrl });
    },
    
    async createAgent(config) {
      if (!this.client) throw new Error('客户端未初始化');
      
      const agent = await this.client.agents.create({
        memoryBlocks: config.memoryBlocks || [],
        model: config.model || 'openai/gpt-4o-mini',
        embedding: config.embedding || 'openai/text-embedding-3-small',
      });
      
      this.agents.push(agent);
      this.currentAgent = agent;
      return agent;
    },
    
    async sendMessage(content) {
      if (!this.currentAgent || !content.trim()) return;
      
      this.isLoading = true;
      try {
        const response = await this.client.agents.messages.create(
          this.currentAgent.id,
          {
            messages: [{ role: 'user', content }],
          }
        );
        
        response.messages.forEach(msg => {
          this.messages.push({
            role: msg.role,
            content: msg.content || msg.reasoning,
            timestamp: new Date(),
          });
        });
      } catch (error) {
        console.error('发送消息失败:', error);
        throw error;
      } finally {
        this.isLoading = false;
      }
    },
  },
});

高级功能实现

自定义工具集成

// tools/customTools.js
export const createCustomTool = async (client, agentId, toolCode) => {
  const tool = await client.tools.upsert({
    sourceCode: toolCode,
  });
  
  await client.agents.tools.attach(agentId, tool.id);
  return tool;
};

// 示例工具代码
export const WEATHER_TOOL_CODE = `
def get_weather(city: str):
    """获取指定城市的天气信息"""
    # 这里可以集成实际的天气API
    return f"{city}的天气是晴朗,25°C"
`.trim();

export const CALCULATOR_TOOL_CODE = `
def calculate(expression: str):
    """计算数学表达式"""
    try:
        result = eval(expression)
        return f"{expression} = {result}"
    except:
        return "计算错误,请检查表达式"
`.trim();

记忆管理

// utils/memoryManager.js
export class MemoryManager {
  constructor(client) {
    this.client = client;
  }
  
  async getAgentMemory(agentId) {
    const blocks = await this.client.agents.blocks.list(agentId);
    return blocks.reduce((acc, block) => {
      acc[block.label] = block.value;
      return acc;
    }, {});
  }
  
  async updateMemory(agentId, label, newValue) {
    const block = await this.client.agents.blocks.retrieve(agentId, label);
    if (block) {
      await this.client.agents.blocks.update(agentId, label, {
        value: newValue,
      });
    } else {
      await this.client.agents.blocks.create(agentId, {
        label,
        value: newValue,
      });
    }
  }
  
  async shareMemory(sourceAgentId, targetAgentId, blockLabel) {
    const block = await this.client.agents.blocks.retrieve(sourceAgentId, blockLabel);
    await this.client.agents.blocks.attach(targetAgentId, block.id);
  }
}

性能优化和最佳实践

1. 连接管理

// utils/connectionManager.js
export class ConnectionManager {
  constructor() {
    this.clients = new Map();
    this.reconnectAttempts = 3;
  }
  
  getClient(baseUrl) {
    if (!this.clients.has(baseUrl)) {
      this.clients.set(baseUrl, new LettaClient({ baseUrl }));
    }
    return this.clients.get(baseUrl);
  }
  
  async testConnection(baseUrl) {
    try {
      const client = this.getClient(baseUrl);
      await client.models.list_llms();
      return true;
    } catch (error) {
      console.error('连接测试失败:', error);
      return false;
    }
  }
}

2. 错误处理

// utils/errorHandler.js
export class MemGPTErrorHandler {
  static handleError(error) {
    if (error.response) {
      // API错误
      switch (error.response.status) {
        case 401:
          throw new Error('认证失败,请检查服务器配置');
        case 404:
          throw new Error('资源不存在');
        case 500:
          throw new Error('服务器内部错误');
        default:
          throw new Error(`API错误: ${error.response.status}`);
      }
    } else if (error.request) {
      // 网络错误
      throw new Error('网络连接失败,请检查服务器状态');
    } else {
      // 其他错误
      throw new Error(`操作失败: ${error.message}`);
    }
  }
  
  static withRetry(operation, maxRetries = 3) {
    return async (...args) => {
      let lastError;
      for (let i = 0; i < maxRetries; i++) {
        try {
          return await operation(...args);
        } catch (error) {
          lastError = error;
          if (i < maxRetries - 1) {
            await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
          }
        }
      }
      throw lastError;
    };
  }
}

3. 类型安全(TypeScript)

// types/memgpt.ts
export interface MemGPTAgent {
  id: string;
  name: string;
  model: string;
  embedding: string;
  createdAt: Date;
}

export interface MemGPTMessage {
  role: 'user' | 'assistant' | 'system';
  content: string;
  reasoning?: string;
  timestamp: Date;
}

export interface MemoryBlock {
  label: string;
  value: string;
  id?: string;
}

export type ToolCallStatus = 'success' | 'error' | 'pending';

export interface ToolCall {
  name: string;
  arguments: any;
  status: ToolCallStatus;
  result?: any;
}

实际应用场景

1. 客户支持聊天机器人

// 客户支持专用配置
export const CUSTOMER_SUPPORT_CONFIG = {
  memoryBlocks: [
    {
      label: 'persona',
      value: `我是一个专业的客户支持助手,擅长解决技术问题。
              我友好、耐心,并且能够理解客户的需求。
              我会逐步引导客户解决问题。`
    },
    {
      label: 'human',
      value: '客户可能需要帮助解决产品使用问题'
    }
  ],
  model: 'openai/gpt-4o-mini',
  embedding: 'openai/text-embedding-3-small'
};

2. 个性化学习助手

// 学习助手配置
export const LEARNING_ASSISTANT_CONFIG = {
  memoryBlocks: [
    {
      label: 'persona',
      value: `我是一个个性化学习助手,能够根据学生的学习进度和偏好调整教学方法。
              我鼓励学生,提供建设性反馈,并创造积极的学习环境。`
    }
  ]
};

// 学习进度跟踪
export class LearningProgressTracker {
  constructor(agentId, client) {
    this.agentId = agentId;
    this.client = client;
  }
  
  async updateLearningProgress(topic, masteryLevel) {
    const progressBlock = await this.client.agents.blocks.retrieve(
      this.agentId, 
      'learning_progress'
    );
    
    let progress = {};
    if (progressBlock) {
      progress = JSON.parse(progressBlock.value);
    }
    
    progress[topic] = {
      masteryLevel,
      lastUpdated: new Date().toISOString()
    };
    
    await this.client.agents.blocks.update(this.agentId, 'learning_progress', {
      value: JSON.stringify(progress)
    });
  }
}

部署和运维

Docker Compose配置

version: '3.8'
services:
  memgpt-server:
    image: letta/letta:latest
    ports:
      - "8283:8283"
    environment:
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - POSTGRES_USER=memgpt
      - POSTGRES_PASSWORD=memgpt
      - POSTGRES_DB=memgpt
    volumes:
      - memgpt_data:/var/lib/postgresql/data
    depends_on:
      - postgres

  postgres:
    image: postgres:13
    environment:
      - POSTGRES_USER=memgpt
      - POSTGRES_PASSWORD=memgpt
      - POSTGRES_DB=memgpt
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  memgpt_data:
  postgres_data:

环境变量配置

# .env.production
VITE_MEMGPT_BASE_URL=https://your-memgpt-server.com
VITE_OPENAI_API_KEY=your_openai_api_key
VITE_MAX_RETRY_ATTEMPTS=3
VITE_REQUEST_TIMEOUT=30000

总结

MemGPT为前端开发者提供了强大的AI智能体集成能力,通过React和Vue可以轻松构建具备长期记忆和高级推理功能的应用程序。关键优势包括:

  1. 状态持久化 - 智能体记忆跨会话保持
  2. 工具扩展 - 支持自定义功能扩展
  3. 易于集成 - 清晰的REST API和客户端SDK
  4. 开源生态 - 活跃的社区支持和持续发展

通过本文的示例和最佳实践,您可以快速在现有或新项目中集成MemGPT,为用户提供更智能、更个性化的AI体验。

【免费下载链接】MemGPT Teaching LLMs memory management for unbounded context 📚🦙 【免费下载链接】MemGPT 项目地址: https://gitcode.com/GitHub_Trending/me/MemGPT

更多推荐