Lancedb Memory

Polar Sponsor
爱发电 赞助
.NET 9.0

使用LanceDB,通过语义向量搜索、分类过滤和详细元数据存储来管理与检索长期记忆。

/usr/bin/env python3."".

功能概述

/usr/bin/env python3."".是一项面向实际任务的技能,主要用于LanceDB集成,用于长期内存管理. 提供矢量搜索和语义内存能力. . . 进口os.import json.import lancedb. 从日期导入日期开始.。它将相关步骤、工具调用和结果整理方式集中到统一流程中,帮助使用者更快完成目标并减少重复操作。

核心要点

  • 使用时应结合输入条件选择合适的执行方式,核对必要参数、依赖环境与输出内容,并按原始要求处理异常情况。
  • 从功能定位来看,该技能强调把分散的操作要求整理成清晰、可复用的处理流程,使用户能够围绕既定目标快速准备输入、选择执行方式并获得结构化结果。
  • 实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;

使用与执行

若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;

结果检查与注意事项

涉及批量任务时,还应保存进度,避免中断后重复操作。该技能适合用于一次性任务,也可以接入自动化工作流,与其他技能或上层代理配合完成更完整的业务链路;在组合使用时,应明确每一步的输入输出关系,并避免不同步骤之间出现参数冲突。

```python #!/usr/bin/env python3 """ LanceDB 集成,用于长期记忆管理。 提供向量搜索与语义记忆能力。 """ import os import json import lancedb from datetime import datetime from typing import List, Dict, Any, Optional from pathlib import Path class LanceMemoryDB: """LanceDB 封装器,用于长期记忆的存储与检索。""" def __init__(self, db_path: str = "/Users/prerak/clawd/memory/lancedb"): self.db_path = Path(db_path) self.db_path.mkdir(parents=True, exist_ok=True) self.db = lancedb.connect(self.db_path) # 确保 memory 表存在 if "memory" not in self.db.table_names(): self._create_memory_table() def _create_memory_table(self): """创建具备合适 schema 的 memory 表。""" schema = [ {"name": "id", "type": "int", "nullable": False}, {"name": "timestamp", "type": "timestamp", "nullable": False}, {"name": "content", "type": "str", "nullable": False}, {"name": "category", "type": "str", "nullable": True}, {"name": "tags", "type": "str[]", "nullable": True}, {"name": "importance", "type": "int", "nullable": True}, {"name": "metadata", "type": "json", "nullable": True}, ] self.db.create_table("memory", schema=schema) def add_memory(self, content: str, category: str = "general", tags: List[str] = None, importance: int = 5, metadata: Dict[str, Any] = None) -> int: """添加一条新的记忆记录。""" table = self.db.open_table("memory") # 获取下一个 ID max_id = table.to_pandas()["id"].max() if len(table) > 0 else 0 new_id = max_id + 1 # 插入新记忆 memory_data = { "id": new_id, "timestamp": datetime.now(), "content": content, "category": category, "tags": tags or [], "importance": importance, "metadata": metadata or {} } table.add([memory_data]) return new_id def search_memories(self, query: str, category: str = None, limit: int = 10) -> List[Dict]: """使用向量相似度搜索记忆。""" table = self.db.open_table("memory") # 构建过滤条件 where_clause = [] if category: where_clause.append(f"category = '{category}'") filter_expr = " AND ".join(where_clause) if where_clause else None # 向量搜索 results = table.vector_search(query).limit(limit).where(filter_expr).to_list() return results def get_memories_by_category(self, category: str, limit: int = 50) -> List[Dict]: """按类别获取记忆。""" table = self.db.open_table("memory") df = table.to_pandas() filtered = df[df["category"] == category].head(limit) return filtered.to_dict("records") def get_memory_by_id(self, memory_id: int) -> Optional[Dict]: """通过 ID 获取特定记忆。""" table = self.db.open_table("memory") df = table.to_pandas() result = df[df["id"] == memory_id] return result.to_dict("records")[0] if len(result) > 0 else None def update_memory(self, memory_id: int, **kwargs) -> bool: """更新一条记忆记录。""" table = self.db.open_table("memory") valid_fields = ["content", "category", "tags", "importance", "metadata"] updates = {k: v for k, v in kwargs.items() if k in valid_fields} if not updates: return False # 转换为 LanceDB 所需的正确类型 if "tags" in updates and isinstance(updates["tags"], list): updates["tags"] = str(updates["tags"]).replace("'", '"') table.update(updates, where=f"id = {memory_id}") return True def delete_memory(self, memory_id: int) -> bool: """删除一条记忆记录。""" table = self.db.open_table("memory") current_count = len(table) table.delete(f"id = {memory_id}") return len(table) < current_count def get_all_categories(self) -> List[str]: """获取所有唯一类别。""" table = self.db.open_table("memory") df = table.to_pandas() return df["category"].dropna().unique().tolist() def get_memory_stats(self) -> Dict[str, Any]: """获取记忆存储的统计信息。""" table = self.db.open_table("memory") df = table.to_pandas() return { "total_memories": len(df), "categories": len(self.get_all_categories()), "by_category": df["category"].value_counts().to_dict(), "date_range": { "earliest": df["timestamp"].min().isoformat() if len(df) > 0 else None, "latest": df["timestamp"].max().isoformat() if len(df) > 0 else None } }

全局实例

lancedb_memory = LanceMemoryDB()

def add_memory(content: str, category: str = "general", tags: List[str] = None, importance: int = 5, metadata: Dict[str, Any] = None) -> int: """向 LanceDB 存储中添加一条记忆。""" return lancedb_memory.add_memory(content, category, tags, importance, metadata) def search_memories(query: str, category: str = None, limit: int = 10) -> List[Dict]: """使用语义相似度搜索记忆。""" return lancedb_memory.search_memories(query, category, limit) def get_memories_by_category(category: str, limit: int = 50) -> List[Dict]: """按类别获取记忆。""" return lancedb_memory.get_memories_by_category(category, limit) def get_memory_stats() -> Dict[str, Any]: """获取记忆存储的统计信息。""" return lancedb_memory.get_memory_stats()

示例用法

if __name__ == "__main__": # 测试数据库 print("Testing LanceDB memory integration...")

```python # 添加一条测试记忆 test_id = add_memory( content="This is a test memory for LanceDB integration", category="test", tags=["lancedb", "integration", "test"], importance=8 ) print(f"Added memory with ID: {test_id}") # 搜索记忆 results = search_memories("test memory") print(f"Search results: {len(results)} memories found") # 获取统计信息 stats = get_memory_stats() print(f"Memory stats: {stats}") ```

相关专题

更多
LLVM自定义Pass怎么写
LLVM自定义Pass怎么写

本专题聚焦LLVM自定义Pass开发,整理Pass类结构、run()方法、PreservedAnalyses、CMake构建、插件注册、-load-pass-plugin加载和测试用例编写流程。

2026.09.30

0

10

LLVM RISC-V参数配置教程
LLVM RISC-V参数配置教程

本专题介绍LLVM对RISC-V基础ISA和扩展的支持方式,涵盖RV32、RV64、标准扩展、实验性扩展、厂商扩展、-menable-experimental-extensions和版本差异。

2026.09.30

0

14

LLVM IR中间表示入门指南
LLVM IR中间表示入门指南

本专题整理LLVM IR的核心概念,包括中间表示作用、模块结构、函数、基本块、SSA形式、类型系统和常见语法,帮助新手理解LLVM编译流程中的关键层。

2026.09.30

0

12

PDF转图片方法
PDF转图片方法

需要把 PDF 页面用于上传、预览、分享或图片归档时,PDF 转图片方法专题整理 JPG/PNG 格式选择、逐页导出、清晰度设置、批量下载和结果检查等流程,帮助用户稳定完成 PDF 图片化处理。

2026.09.30

0

26

PixTV AI视频生成与无限画布创作
PixTV AI视频生成与无限画布创作

PixTV专题整理AI视频与视觉内容创作相关功能使用教程,涵盖AI生图、视频生成、无限画布、多模型创作、素材管理、声音音乐及视频剪辑等功能,帮助用户快速掌握PixTV从创意到成片的完整制作方法。

2026.09.29

0

15

Buffalo框架数据库开发全教程
Buffalo框架数据库开发全教程

本专题围绕Buffalo框架数据库开发,讲解database.yml多环境配置、soda与fizz迁移生成回滚、模型结构体标签、增删改查与条件查询、一对多与多对多关联、数据校验、回调钩子、事务处理及原生SQL执行能力。

2026.09.23

0

15

Buffalo框架路由与请求处理实操指南
Buffalo框架路由与请求处理实操指南

本专题讲解Buffalo框架路由与请求处理机制,涵盖路由注册与分组、资源路由、Handler编写规范、Context上下文方法、参数绑定、中间件编写挂载、Session与Cookie读写、Flash消息及错误页面定制方法。

2026.09.23

0

15

Buffalo框架零基础入门教程
Buffalo框架零基础入门教程

本专题整理Buffalo框架入门内容,涵盖Go环境准备、buffalo CLI安装、新项目生成、目录结构说明、dev热加载启动、数据库连接配置与常见报错排查,帮助新手按约定优于配置的思路跑通第一个Buffalo框架应用。

2026.09.23

0

15

Conan创建软件包配方指南
Conan创建软件包配方指南

本专题介绍通过conanfile.py创建软件包的方法,讲解包名、版本、依赖和构建设置等基础信息,以及source、build、package、package_info等常用方法的作用及编写思路。

2026.09.22

0

12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
热门推荐
/
最新课程
phpStudy极速入门视频教程
phpStudy极速入门视频教程

共6课时 | 54.6万人学习

独孤九贱(4)_PHP视频教程
独孤九贱(4)_PHP视频教程

共89课时 | 133.4万人学习