mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge 491d11519e into 15b3f0a8f5
This commit is contained in:
commit
3954cbc782
29 changed files with 73559 additions and 1 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -183,4 +183,5 @@ uploadfile
|
||||||
!main/manager-mobile/**/env/
|
!main/manager-mobile/**/env/
|
||||||
!main/manager-mobile/**/.env*
|
!main/manager-mobile/**/.env*
|
||||||
!main/manager-mobile/**/*.json
|
!main/manager-mobile/**/*.json
|
||||||
!main/xiaozhi-server/**/*.json
|
!main/xiaozhi-server/**/*.json# Claude Code local state
|
||||||
|
.claude/
|
||||||
|
|
|
||||||
221
.specify/memory/constitution.md
Normal file
221
.specify/memory/constitution.md
Normal file
|
|
@ -0,0 +1,221 @@
|
||||||
|
<!--
|
||||||
|
Sync Impact Report:
|
||||||
|
- Version: 1.0.1 (Amendment: execution constraints + governance neutralization + deployment flexibility)
|
||||||
|
- Modified principles: N/A (kept 7 principles, clarified enforcement)
|
||||||
|
- Added sections:
|
||||||
|
- 执行型硬约束(阶段门禁 / anti-gravity 执行规范 / MemoryBackend 接入边界)
|
||||||
|
- Modified sections:
|
||||||
|
- 架构约束:由“微服务架构要求”调整为“部署形态与服务边界要求(模块化优先)”
|
||||||
|
- 治理规范:宪章修订流程治理主体改为“核心维护团队/项目维护者”
|
||||||
|
- Removed sections: N/A
|
||||||
|
- Templates requiring updates:
|
||||||
|
✅ plan-template.md(需加入 Phase 门禁检查点)
|
||||||
|
✅ spec-template.md(需加入 MemoryBackend 边界与可擦除要求)
|
||||||
|
✅ tasks-template.md(需加入 1 task=1 PR、验收/测试/回滚字段)
|
||||||
|
- Follow-up TODOs:
|
||||||
|
- 将“Phase 0 可运行”验收写入首批 tasks(smoke test/启动文档/健康检查)
|
||||||
|
-->
|
||||||
|
|
||||||
|
# 小智ESP32服务器 项目宪章
|
||||||
|
|
||||||
|
## 核心原则
|
||||||
|
|
||||||
|
### I. 模块化与可扩展性
|
||||||
|
|
||||||
|
系统必须采用模块化架构,支持灵活的组件替换和功能扩展:
|
||||||
|
- 每个功能模块(ASR、LLM、VLLM、TTS、Intent、Memory等)必须通过统一接口实现
|
||||||
|
- 新增AI服务提供商或功能模块不得破坏现有系统架构
|
||||||
|
- 必须支持通过配置文件切换不同服务商,无需修改核心代码
|
||||||
|
- 插件系统必须支持热加载和动态扩展
|
||||||
|
|
||||||
|
**原理**:本项目服务于多样化的硬件设备和使用场景,模块化设计确保用户可以根据成本、性能和场景需求自由组合最优方案。
|
||||||
|
|
||||||
|
### II. 协议标准化
|
||||||
|
|
||||||
|
系统必须严格遵循统一的通信协议和接口规范:
|
||||||
|
- MQTT+UDP网关、WebSocket、HTTP服务必须遵循“小智通信协议”(见项目文档/协议规范)
|
||||||
|
- MCP(Model Context Protocol)集成必须符合标准MCP协议规范
|
||||||
|
- 客户端与服务端的数据交互必须使用标准化的JSON格式
|
||||||
|
- 所有API接口变更必须向后兼容或提供明确的版本管理和迁移路径
|
||||||
|
|
||||||
|
**原理**:标准化协议确保多设备兼容性,降低集成成本,支撑开源生态的健康发展。
|
||||||
|
|
||||||
|
### III. 性能优化优先(NON-NEGOTIABLE)
|
||||||
|
|
||||||
|
系统必须持续优化响应速度和资源利用效率:
|
||||||
|
- 必须提供流式处理支持(流式ASR、流式TTS、流式LLM)以最小化首字延迟
|
||||||
|
- 必须实现并行处理机制(如声纹识别与ASR并行)
|
||||||
|
- 每次功能更新必须通过性能测试工具验证,不得引入明显性能退化
|
||||||
|
- 必须为低配置环境(2核2G)和高性能环境提供差异化配置方案
|
||||||
|
|
||||||
|
**原理**:作为实时语音交互系统,响应速度直接影响用户体验。性能优化是非妥协的核心竞争力。
|
||||||
|
|
||||||
|
### IV. 成本可控与开源友好
|
||||||
|
|
||||||
|
系统必须平衡功能丰富性与使用成本:
|
||||||
|
- 必须提供“入门全免费”配置方案,确保个人用户零成本使用
|
||||||
|
- 新增功能不得强制依赖付费服务,应优先集成开源或免费方案
|
||||||
|
- 必须明确标注每个服务提供商的收费模式和推荐使用场景
|
||||||
|
- 文档必须包含各组件的性能对比和成本分析
|
||||||
|
|
||||||
|
**原理**:降低使用门槛,扩大开源社区参与度,确保项目的可持续发展。
|
||||||
|
|
||||||
|
### V. 安全与隐私保护
|
||||||
|
|
||||||
|
系统必须保障用户数据安全和隐私:
|
||||||
|
- 不得托管用户的第三方API密钥或敏感信息,仅提供配置引导
|
||||||
|
- 声纹识别数据必须本地存储,不得上传至云端
|
||||||
|
- 必须支持SSL/TLS加密连接(WebSocket WSS、HTTPS)
|
||||||
|
- 生产环境部署必须通过安全检查,文档需明确警告潜在风险
|
||||||
|
|
||||||
|
**原理**:作为智能硬件后端服务,处理语音、图像等敏感数据,安全性是用户信任的基础。
|
||||||
|
|
||||||
|
### VI. 测试驱动开发
|
||||||
|
|
||||||
|
新功能开发必须遵循测试优先原则:
|
||||||
|
- 核心模块变更必须包含单元测试和集成测试
|
||||||
|
- 性能优化必须通过`performance_tester.py`验证
|
||||||
|
- 音频处理功能必须通过`test_page.html`工具验证
|
||||||
|
- 破坏性更改必须提供测试覆盖率报告(或可替代的质量门禁说明)
|
||||||
|
|
||||||
|
**原理**:确保代码质量和系统稳定性,降低多组件集成带来的回归风险。
|
||||||
|
|
||||||
|
### VII. 多语言与国际化支持
|
||||||
|
|
||||||
|
系统必须支持多语言和多地区使用:
|
||||||
|
- 管理后台必须支持中文简体、中文繁体、英文切换
|
||||||
|
- ASR和TTS组件必须支持多语言识别和合成
|
||||||
|
- 文档必须提供中英文版本(包括README、部署文档、API文档)
|
||||||
|
- 错误提示和日志信息需考虑国际化需求
|
||||||
|
|
||||||
|
**原理**:面向全球开源社区,多语言支持扩大用户基础和贡献者范围。
|
||||||
|
|
||||||
|
## 架构约束
|
||||||
|
|
||||||
|
### 部署形态与服务边界要求(模块化优先)
|
||||||
|
|
||||||
|
本项目以“模块化优先、部署形态可变”为原则:支持单体与多服务两种形态,是否采用微服务由 plan 阶段依据规模与需求决定。
|
||||||
|
|
||||||
|
- **Phase 0 优先单体可运行**:默认以“单服务进程/单容器”方式跑通核心链路(设备接入、对话编排、最小可用能力),避免过早引入复杂编排。
|
||||||
|
- **可演进为多服务**:当存在明确动机(性能隔离、可靠性、团队协作、独立扩缩容、成本核算)时,可拆分为多个服务(如 Gateway / AI Worker / Memory Worker / 管理后台等)。
|
||||||
|
- **模块间必须通过标准接口解耦**:服务内模块(ASR/LLM/TTS/Intent/Memory 等)必须以统一接口接入;服务间通信必须通过标准协议(MQTT、WebSocket、HTTP REST API 或等价标准)。
|
||||||
|
- **禁止紧耦合依赖**:不得跨服务直接调用内部实现细节;跨服务必须有明确的 API/Schema/版本管理策略。
|
||||||
|
- **拆分必须可回退**:任何从单体到多服务的拆分必须提供回滚路径,确保可快速退回到稳定形态。
|
||||||
|
|
||||||
|
### 部署灵活性
|
||||||
|
|
||||||
|
- 必须同时支持Docker容器化部署和本地源码部署
|
||||||
|
- 配置管理必须支持环境变量和配置文件两种方式
|
||||||
|
- 必须提供一键部署脚本和详细的手动部署文档
|
||||||
|
- OTA升级功能必须支持远程设备固件更新
|
||||||
|
|
||||||
|
### 数据存储策略
|
||||||
|
|
||||||
|
- 轻量级部署使用配置文件(YAML/JSON)存储用户数据(或等价轻量持久化方案)
|
||||||
|
- 完整部署使用数据库存储用户、设备、日志等持久化数据(数据库选型由 plan 阶段决定,需给出理由与迁移策略)
|
||||||
|
- 缓存数据使用Redis(可选)
|
||||||
|
- 声纹数据必须本地文件系统存储
|
||||||
|
|
||||||
|
## 开发流程
|
||||||
|
|
||||||
|
### 代码贡献规范
|
||||||
|
|
||||||
|
- 所有代码贡献必须通过Pull Request提交
|
||||||
|
- PR描述必须包含:功能说明、测试结果、性能影响评估
|
||||||
|
- 必须遵循项目现有代码风格(Python PEP8、Java Google Style、Vue Standard)
|
||||||
|
- 新增第三方依赖必须在文档中说明其必要性和开源协议
|
||||||
|
|
||||||
|
### 文档要求
|
||||||
|
|
||||||
|
- 新增功能必须更新相应文档(README、FAQ、部署文档)
|
||||||
|
- API变更必须更新接口文档
|
||||||
|
- 配置项变更必须同步更新配置文件示例和说明
|
||||||
|
- 重大架构变更必须提供架构图和设计文档
|
||||||
|
|
||||||
|
### 版本发布流程
|
||||||
|
|
||||||
|
- 版本号遵循语义化版本规范(MAJOR.MINOR.PATCH)
|
||||||
|
- 每个版本必须包含更新日志(CHANGELOG)
|
||||||
|
- 稳定版本必须通过完整测试套件验证
|
||||||
|
- 必须提供Docker镜像和源码包两种发布形式
|
||||||
|
|
||||||
|
## 治理规范
|
||||||
|
|
||||||
|
本宪章是项目的最高指导原则,所有代码提交、功能设计、架构决策必须符合本宪章要求。
|
||||||
|
|
||||||
|
### 宪章修订流程
|
||||||
|
|
||||||
|
- 宪章修订必须通过项目核心维护团队审批(以 GitHub 仓库的 Maintainers/Owners 权限组为准)。
|
||||||
|
- 修订提案必须在GitHub Issues中公开讨论至少7天(紧急安全修订除外)。
|
||||||
|
- 重大修订(影响核心原则或核心架构约束)需要在GitHub Discussions征求社区意见,并在合并前给出决策记录(Decision Log)。
|
||||||
|
- 修订通过后必须更新版本号并同步相关模板文件。
|
||||||
|
|
||||||
|
### 合规性审查
|
||||||
|
|
||||||
|
- 所有Pull Request必须经过至少一名核心维护者的代码审查
|
||||||
|
- 违反宪章原则的提交必须提供充分的技术正当性说明
|
||||||
|
- 引入复杂性(如新增服务依赖、架构模式变更)必须在PR中明确说明必要性
|
||||||
|
- 性能退化超过10%的变更必须提供优化方案或回退机制
|
||||||
|
|
||||||
|
### 争议解决
|
||||||
|
|
||||||
|
- 技术争议优先通过GitHub Discussions公开讨论
|
||||||
|
- 核心维护团队拥有最终决策权
|
||||||
|
- 重大决策(如放弃某项核心功能、变更技术栈)必须在社区中征集反馈
|
||||||
|
|
||||||
|
### 开发指导文件
|
||||||
|
|
||||||
|
项目使用以下文件进行运行时开发指导:
|
||||||
|
- `.specify/memory/constitution.md`(本文件):项目治理和原则
|
||||||
|
- `docs/contributor_open_letter.md`:致开发者的公开信
|
||||||
|
- `docs/FAQ.md`:常见问题和最佳实践
|
||||||
|
- `README.md`:项目概览和快速开始
|
||||||
|
|
||||||
|
## 执行型硬约束(用于驱动 anti-gravity 自动交付)
|
||||||
|
|
||||||
|
### A. 阶段门禁(严格顺序,禁止跳关)
|
||||||
|
|
||||||
|
- **Phase 0:基础可运行(必须先完成)**
|
||||||
|
- 本地可启动,至少一个入口(HTTP/WS/MQTT 任一)可连通
|
||||||
|
- 提供最小 smoke test 命令(可复制执行)
|
||||||
|
- 满足以上门禁后,才允许进入 Phase 1
|
||||||
|
|
||||||
|
- **Phase 1:接口隔离 + O-Mem 接入**
|
||||||
|
- 引入 `MemoryBackend` 抽象;O-Mem 只能作为一个实现(如 `OmemBackend`)
|
||||||
|
- 记忆写入默认异步;检索输出必须受 token/条数/耗时上限约束
|
||||||
|
|
||||||
|
- **Phase 2:AWS 可部署(先能部署,再谈性能)**
|
||||||
|
- 必须 IaC(Terraform/CDK 二选一),具备 dev/staging 环境
|
||||||
|
- 日志/指标可观测,具备回滚策略
|
||||||
|
|
||||||
|
- **Phase 3:并发与性能(≥50 设备)**
|
||||||
|
- 提供可复现的 ≥50 设备并发模拟/压测脚本(k6 或 Python)
|
||||||
|
- 验收包含:连接稳定性、错误率、P95、队列积压(如有)
|
||||||
|
|
||||||
|
### B. anti-gravity 执行规范(强制)
|
||||||
|
|
||||||
|
- 任务来源:`.specify/` 生成 tasks 或由其导入的 GitHub Issues
|
||||||
|
- 只有带 `ag:ready` 标签的 Issue 允许执行
|
||||||
|
- **1 Task = 1 PR**,PR 必须包含:
|
||||||
|
- Closes #Issue
|
||||||
|
- How to test(精确命令)
|
||||||
|
- Acceptance criteria checklist
|
||||||
|
- 风险评估与回滚方案
|
||||||
|
- CI 必须全绿才允许合并;行为变化必须有测试覆盖
|
||||||
|
|
||||||
|
### C. 记忆系统接入边界(强制)
|
||||||
|
|
||||||
|
必须存在统一接口(名称可变但职责不变):
|
||||||
|
- `retrieve_context(user_id, device_id, query, token_budget)`
|
||||||
|
- `ingest_turn(user_id, device_id, messages, meta)`
|
||||||
|
- `end_session(user_id, device_id, session_meta)`
|
||||||
|
- `forget_user(user_id, scope)`
|
||||||
|
|
||||||
|
约束:
|
||||||
|
- 网关层不得直接写长期记忆;写入默认走队列/worker 异步
|
||||||
|
- 检索返回必须受 token_budget 约束,禁止无限拼接 prompt
|
||||||
|
|
||||||
|
## 参考链接(如需)
|
||||||
|
```text
|
||||||
|
小智通信协议(Feishu):
|
||||||
|
https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh
|
||||||
166
.specify/scripts/bash/check-prerequisites.sh
Executable file
166
.specify/scripts/bash/check-prerequisites.sh
Executable file
|
|
@ -0,0 +1,166 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
# Consolidated prerequisite checking script
|
||||||
|
#
|
||||||
|
# This script provides unified prerequisite checking for Spec-Driven Development workflow.
|
||||||
|
# It replaces the functionality previously spread across multiple scripts.
|
||||||
|
#
|
||||||
|
# Usage: ./check-prerequisites.sh [OPTIONS]
|
||||||
|
#
|
||||||
|
# OPTIONS:
|
||||||
|
# --json Output in JSON format
|
||||||
|
# --require-tasks Require tasks.md to exist (for implementation phase)
|
||||||
|
# --include-tasks Include tasks.md in AVAILABLE_DOCS list
|
||||||
|
# --paths-only Only output path variables (no validation)
|
||||||
|
# --help, -h Show help message
|
||||||
|
#
|
||||||
|
# OUTPUTS:
|
||||||
|
# JSON mode: {"FEATURE_DIR":"...", "AVAILABLE_DOCS":["..."]}
|
||||||
|
# Text mode: FEATURE_DIR:... \n AVAILABLE_DOCS: \n ✓/✗ file.md
|
||||||
|
# Paths only: REPO_ROOT: ... \n BRANCH: ... \n FEATURE_DIR: ... etc.
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Parse command line arguments
|
||||||
|
JSON_MODE=false
|
||||||
|
REQUIRE_TASKS=false
|
||||||
|
INCLUDE_TASKS=false
|
||||||
|
PATHS_ONLY=false
|
||||||
|
|
||||||
|
for arg in "$@"; do
|
||||||
|
case "$arg" in
|
||||||
|
--json)
|
||||||
|
JSON_MODE=true
|
||||||
|
;;
|
||||||
|
--require-tasks)
|
||||||
|
REQUIRE_TASKS=true
|
||||||
|
;;
|
||||||
|
--include-tasks)
|
||||||
|
INCLUDE_TASKS=true
|
||||||
|
;;
|
||||||
|
--paths-only)
|
||||||
|
PATHS_ONLY=true
|
||||||
|
;;
|
||||||
|
--help|-h)
|
||||||
|
cat << 'EOF'
|
||||||
|
Usage: check-prerequisites.sh [OPTIONS]
|
||||||
|
|
||||||
|
Consolidated prerequisite checking for Spec-Driven Development workflow.
|
||||||
|
|
||||||
|
OPTIONS:
|
||||||
|
--json Output in JSON format
|
||||||
|
--require-tasks Require tasks.md to exist (for implementation phase)
|
||||||
|
--include-tasks Include tasks.md in AVAILABLE_DOCS list
|
||||||
|
--paths-only Only output path variables (no prerequisite validation)
|
||||||
|
--help, -h Show this help message
|
||||||
|
|
||||||
|
EXAMPLES:
|
||||||
|
# Check task prerequisites (plan.md required)
|
||||||
|
./check-prerequisites.sh --json
|
||||||
|
|
||||||
|
# Check implementation prerequisites (plan.md + tasks.md required)
|
||||||
|
./check-prerequisites.sh --json --require-tasks --include-tasks
|
||||||
|
|
||||||
|
# Get feature paths only (no validation)
|
||||||
|
./check-prerequisites.sh --paths-only
|
||||||
|
|
||||||
|
EOF
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "ERROR: Unknown option '$arg'. Use --help for usage information." >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# Source common functions
|
||||||
|
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
source "$SCRIPT_DIR/common.sh"
|
||||||
|
|
||||||
|
# Get feature paths and validate branch
|
||||||
|
eval $(get_feature_paths)
|
||||||
|
check_feature_branch "$CURRENT_BRANCH" "$HAS_GIT" || exit 1
|
||||||
|
|
||||||
|
# If paths-only mode, output paths and exit (support JSON + paths-only combined)
|
||||||
|
if $PATHS_ONLY; then
|
||||||
|
if $JSON_MODE; then
|
||||||
|
# Minimal JSON paths payload (no validation performed)
|
||||||
|
printf '{"REPO_ROOT":"%s","BRANCH":"%s","FEATURE_DIR":"%s","FEATURE_SPEC":"%s","IMPL_PLAN":"%s","TASKS":"%s"}\n' \
|
||||||
|
"$REPO_ROOT" "$CURRENT_BRANCH" "$FEATURE_DIR" "$FEATURE_SPEC" "$IMPL_PLAN" "$TASKS"
|
||||||
|
else
|
||||||
|
echo "REPO_ROOT: $REPO_ROOT"
|
||||||
|
echo "BRANCH: $CURRENT_BRANCH"
|
||||||
|
echo "FEATURE_DIR: $FEATURE_DIR"
|
||||||
|
echo "FEATURE_SPEC: $FEATURE_SPEC"
|
||||||
|
echo "IMPL_PLAN: $IMPL_PLAN"
|
||||||
|
echo "TASKS: $TASKS"
|
||||||
|
fi
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Validate required directories and files
|
||||||
|
if [[ ! -d "$FEATURE_DIR" ]]; then
|
||||||
|
echo "ERROR: Feature directory not found: $FEATURE_DIR" >&2
|
||||||
|
echo "Run /speckit.specify first to create the feature structure." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ! -f "$IMPL_PLAN" ]]; then
|
||||||
|
echo "ERROR: plan.md not found in $FEATURE_DIR" >&2
|
||||||
|
echo "Run /speckit.plan first to create the implementation plan." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Check for tasks.md if required
|
||||||
|
if $REQUIRE_TASKS && [[ ! -f "$TASKS" ]]; then
|
||||||
|
echo "ERROR: tasks.md not found in $FEATURE_DIR" >&2
|
||||||
|
echo "Run /speckit.tasks first to create the task list." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Build list of available documents
|
||||||
|
docs=()
|
||||||
|
|
||||||
|
# Always check these optional docs
|
||||||
|
[[ -f "$RESEARCH" ]] && docs+=("research.md")
|
||||||
|
[[ -f "$DATA_MODEL" ]] && docs+=("data-model.md")
|
||||||
|
|
||||||
|
# Check contracts directory (only if it exists and has files)
|
||||||
|
if [[ -d "$CONTRACTS_DIR" ]] && [[ -n "$(ls -A "$CONTRACTS_DIR" 2>/dev/null)" ]]; then
|
||||||
|
docs+=("contracts/")
|
||||||
|
fi
|
||||||
|
|
||||||
|
[[ -f "$QUICKSTART" ]] && docs+=("quickstart.md")
|
||||||
|
|
||||||
|
# Include tasks.md if requested and it exists
|
||||||
|
if $INCLUDE_TASKS && [[ -f "$TASKS" ]]; then
|
||||||
|
docs+=("tasks.md")
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Output results
|
||||||
|
if $JSON_MODE; then
|
||||||
|
# Build JSON array of documents
|
||||||
|
if [[ ${#docs[@]} -eq 0 ]]; then
|
||||||
|
json_docs="[]"
|
||||||
|
else
|
||||||
|
json_docs=$(printf '"%s",' "${docs[@]}")
|
||||||
|
json_docs="[${json_docs%,}]"
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '{"FEATURE_DIR":"%s","AVAILABLE_DOCS":%s}\n' "$FEATURE_DIR" "$json_docs"
|
||||||
|
else
|
||||||
|
# Text output
|
||||||
|
echo "FEATURE_DIR:$FEATURE_DIR"
|
||||||
|
echo "AVAILABLE_DOCS:"
|
||||||
|
|
||||||
|
# Show status of each potential document
|
||||||
|
check_file "$RESEARCH" "research.md"
|
||||||
|
check_file "$DATA_MODEL" "data-model.md"
|
||||||
|
check_dir "$CONTRACTS_DIR" "contracts/"
|
||||||
|
check_file "$QUICKSTART" "quickstart.md"
|
||||||
|
|
||||||
|
if $INCLUDE_TASKS; then
|
||||||
|
check_file "$TASKS" "tasks.md"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
156
.specify/scripts/bash/common.sh
Executable file
156
.specify/scripts/bash/common.sh
Executable file
|
|
@ -0,0 +1,156 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Common functions and variables for all scripts
|
||||||
|
|
||||||
|
# Get repository root, with fallback for non-git repositories
|
||||||
|
get_repo_root() {
|
||||||
|
if git rev-parse --show-toplevel >/dev/null 2>&1; then
|
||||||
|
git rev-parse --show-toplevel
|
||||||
|
else
|
||||||
|
# Fall back to script location for non-git repos
|
||||||
|
local script_dir="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
(cd "$script_dir/../../.." && pwd)
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Get current branch, with fallback for non-git repositories
|
||||||
|
get_current_branch() {
|
||||||
|
# First check if SPECIFY_FEATURE environment variable is set
|
||||||
|
if [[ -n "${SPECIFY_FEATURE:-}" ]]; then
|
||||||
|
echo "$SPECIFY_FEATURE"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Then check git if available
|
||||||
|
if git rev-parse --abbrev-ref HEAD >/dev/null 2>&1; then
|
||||||
|
git rev-parse --abbrev-ref HEAD
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
# For non-git repos, try to find the latest feature directory
|
||||||
|
local repo_root=$(get_repo_root)
|
||||||
|
local specs_dir="$repo_root/specs"
|
||||||
|
|
||||||
|
if [[ -d "$specs_dir" ]]; then
|
||||||
|
local latest_feature=""
|
||||||
|
local highest=0
|
||||||
|
|
||||||
|
for dir in "$specs_dir"/*; do
|
||||||
|
if [[ -d "$dir" ]]; then
|
||||||
|
local dirname=$(basename "$dir")
|
||||||
|
if [[ "$dirname" =~ ^([0-9]{3})- ]]; then
|
||||||
|
local number=${BASH_REMATCH[1]}
|
||||||
|
number=$((10#$number))
|
||||||
|
if [[ "$number" -gt "$highest" ]]; then
|
||||||
|
highest=$number
|
||||||
|
latest_feature=$dirname
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ -n "$latest_feature" ]]; then
|
||||||
|
echo "$latest_feature"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "main" # Final fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check if we have git available
|
||||||
|
has_git() {
|
||||||
|
git rev-parse --show-toplevel >/dev/null 2>&1
|
||||||
|
}
|
||||||
|
|
||||||
|
check_feature_branch() {
|
||||||
|
local branch="$1"
|
||||||
|
local has_git_repo="$2"
|
||||||
|
|
||||||
|
# For non-git repos, we can't enforce branch naming but still provide output
|
||||||
|
if [[ "$has_git_repo" != "true" ]]; then
|
||||||
|
echo "[specify] Warning: Git repository not detected; skipped branch validation" >&2
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ! "$branch" =~ ^[0-9]{3}- ]]; then
|
||||||
|
echo "ERROR: Not on a feature branch. Current branch: $branch" >&2
|
||||||
|
echo "Feature branches should be named like: 001-feature-name" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
get_feature_dir() { echo "$1/specs/$2"; }
|
||||||
|
|
||||||
|
# Find feature directory by numeric prefix instead of exact branch match
|
||||||
|
# This allows multiple branches to work on the same spec (e.g., 004-fix-bug, 004-add-feature)
|
||||||
|
find_feature_dir_by_prefix() {
|
||||||
|
local repo_root="$1"
|
||||||
|
local branch_name="$2"
|
||||||
|
local specs_dir="$repo_root/specs"
|
||||||
|
|
||||||
|
# Extract numeric prefix from branch (e.g., "004" from "004-whatever")
|
||||||
|
if [[ ! "$branch_name" =~ ^([0-9]{3})- ]]; then
|
||||||
|
# If branch doesn't have numeric prefix, fall back to exact match
|
||||||
|
echo "$specs_dir/$branch_name"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
local prefix="${BASH_REMATCH[1]}"
|
||||||
|
|
||||||
|
# Search for directories in specs/ that start with this prefix
|
||||||
|
local matches=()
|
||||||
|
if [[ -d "$specs_dir" ]]; then
|
||||||
|
for dir in "$specs_dir"/"$prefix"-*; do
|
||||||
|
if [[ -d "$dir" ]]; then
|
||||||
|
matches+=("$(basename "$dir")")
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Handle results
|
||||||
|
if [[ ${#matches[@]} -eq 0 ]]; then
|
||||||
|
# No match found - return the branch name path (will fail later with clear error)
|
||||||
|
echo "$specs_dir/$branch_name"
|
||||||
|
elif [[ ${#matches[@]} -eq 1 ]]; then
|
||||||
|
# Exactly one match - perfect!
|
||||||
|
echo "$specs_dir/${matches[0]}"
|
||||||
|
else
|
||||||
|
# Multiple matches - this shouldn't happen with proper naming convention
|
||||||
|
echo "ERROR: Multiple spec directories found with prefix '$prefix': ${matches[*]}" >&2
|
||||||
|
echo "Please ensure only one spec directory exists per numeric prefix." >&2
|
||||||
|
echo "$specs_dir/$branch_name" # Return something to avoid breaking the script
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
get_feature_paths() {
|
||||||
|
local repo_root=$(get_repo_root)
|
||||||
|
local current_branch=$(get_current_branch)
|
||||||
|
local has_git_repo="false"
|
||||||
|
|
||||||
|
if has_git; then
|
||||||
|
has_git_repo="true"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use prefix-based lookup to support multiple branches per spec
|
||||||
|
local feature_dir=$(find_feature_dir_by_prefix "$repo_root" "$current_branch")
|
||||||
|
|
||||||
|
cat <<EOF
|
||||||
|
REPO_ROOT='$repo_root'
|
||||||
|
CURRENT_BRANCH='$current_branch'
|
||||||
|
HAS_GIT='$has_git_repo'
|
||||||
|
FEATURE_DIR='$feature_dir'
|
||||||
|
FEATURE_SPEC='$feature_dir/spec.md'
|
||||||
|
IMPL_PLAN='$feature_dir/plan.md'
|
||||||
|
TASKS='$feature_dir/tasks.md'
|
||||||
|
RESEARCH='$feature_dir/research.md'
|
||||||
|
DATA_MODEL='$feature_dir/data-model.md'
|
||||||
|
QUICKSTART='$feature_dir/quickstart.md'
|
||||||
|
CONTRACTS_DIR='$feature_dir/contracts'
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
check_file() { [[ -f "$1" ]] && echo " ✓ $2" || echo " ✗ $2"; }
|
||||||
|
check_dir() { [[ -d "$1" && -n $(ls -A "$1" 2>/dev/null) ]] && echo " ✓ $2" || echo " ✗ $2"; }
|
||||||
|
|
||||||
297
.specify/scripts/bash/create-new-feature.sh
Executable file
297
.specify/scripts/bash/create-new-feature.sh
Executable file
|
|
@ -0,0 +1,297 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
JSON_MODE=false
|
||||||
|
SHORT_NAME=""
|
||||||
|
BRANCH_NUMBER=""
|
||||||
|
ARGS=()
|
||||||
|
i=1
|
||||||
|
while [ $i -le $# ]; do
|
||||||
|
arg="${!i}"
|
||||||
|
case "$arg" in
|
||||||
|
--json)
|
||||||
|
JSON_MODE=true
|
||||||
|
;;
|
||||||
|
--short-name)
|
||||||
|
if [ $((i + 1)) -gt $# ]; then
|
||||||
|
echo 'Error: --short-name requires a value' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
i=$((i + 1))
|
||||||
|
next_arg="${!i}"
|
||||||
|
# Check if the next argument is another option (starts with --)
|
||||||
|
if [[ "$next_arg" == --* ]]; then
|
||||||
|
echo 'Error: --short-name requires a value' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
SHORT_NAME="$next_arg"
|
||||||
|
;;
|
||||||
|
--number)
|
||||||
|
if [ $((i + 1)) -gt $# ]; then
|
||||||
|
echo 'Error: --number requires a value' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
i=$((i + 1))
|
||||||
|
next_arg="${!i}"
|
||||||
|
if [[ "$next_arg" == --* ]]; then
|
||||||
|
echo 'Error: --number requires a value' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
BRANCH_NUMBER="$next_arg"
|
||||||
|
;;
|
||||||
|
--help|-h)
|
||||||
|
echo "Usage: $0 [--json] [--short-name <name>] [--number N] <feature_description>"
|
||||||
|
echo ""
|
||||||
|
echo "Options:"
|
||||||
|
echo " --json Output in JSON format"
|
||||||
|
echo " --short-name <name> Provide a custom short name (2-4 words) for the branch"
|
||||||
|
echo " --number N Specify branch number manually (overrides auto-detection)"
|
||||||
|
echo " --help, -h Show this help message"
|
||||||
|
echo ""
|
||||||
|
echo "Examples:"
|
||||||
|
echo " $0 'Add user authentication system' --short-name 'user-auth'"
|
||||||
|
echo " $0 'Implement OAuth2 integration for API' --number 5"
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
ARGS+=("$arg")
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
i=$((i + 1))
|
||||||
|
done
|
||||||
|
|
||||||
|
FEATURE_DESCRIPTION="${ARGS[*]}"
|
||||||
|
if [ -z "$FEATURE_DESCRIPTION" ]; then
|
||||||
|
echo "Usage: $0 [--json] [--short-name <name>] [--number N] <feature_description>" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Function to find the repository root by searching for existing project markers
|
||||||
|
find_repo_root() {
|
||||||
|
local dir="$1"
|
||||||
|
while [ "$dir" != "/" ]; do
|
||||||
|
if [ -d "$dir/.git" ] || [ -d "$dir/.specify" ]; then
|
||||||
|
echo "$dir"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
dir="$(dirname "$dir")"
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Function to get highest number from specs directory
|
||||||
|
get_highest_from_specs() {
|
||||||
|
local specs_dir="$1"
|
||||||
|
local highest=0
|
||||||
|
|
||||||
|
if [ -d "$specs_dir" ]; then
|
||||||
|
for dir in "$specs_dir"/*; do
|
||||||
|
[ -d "$dir" ] || continue
|
||||||
|
dirname=$(basename "$dir")
|
||||||
|
number=$(echo "$dirname" | grep -o '^[0-9]\+' || echo "0")
|
||||||
|
number=$((10#$number))
|
||||||
|
if [ "$number" -gt "$highest" ]; then
|
||||||
|
highest=$number
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "$highest"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Function to get highest number from git branches
|
||||||
|
get_highest_from_branches() {
|
||||||
|
local highest=0
|
||||||
|
|
||||||
|
# Get all branches (local and remote)
|
||||||
|
branches=$(git branch -a 2>/dev/null || echo "")
|
||||||
|
|
||||||
|
if [ -n "$branches" ]; then
|
||||||
|
while IFS= read -r branch; do
|
||||||
|
# Clean branch name: remove leading markers and remote prefixes
|
||||||
|
clean_branch=$(echo "$branch" | sed 's/^[* ]*//; s|^remotes/[^/]*/||')
|
||||||
|
|
||||||
|
# Extract feature number if branch matches pattern ###-*
|
||||||
|
if echo "$clean_branch" | grep -q '^[0-9]\{3\}-'; then
|
||||||
|
number=$(echo "$clean_branch" | grep -o '^[0-9]\{3\}' || echo "0")
|
||||||
|
number=$((10#$number))
|
||||||
|
if [ "$number" -gt "$highest" ]; then
|
||||||
|
highest=$number
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done <<< "$branches"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "$highest"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Function to check existing branches (local and remote) and return next available number
|
||||||
|
check_existing_branches() {
|
||||||
|
local specs_dir="$1"
|
||||||
|
|
||||||
|
# Fetch all remotes to get latest branch info (suppress errors if no remotes)
|
||||||
|
git fetch --all --prune 2>/dev/null || true
|
||||||
|
|
||||||
|
# Get highest number from ALL branches (not just matching short name)
|
||||||
|
local highest_branch=$(get_highest_from_branches)
|
||||||
|
|
||||||
|
# Get highest number from ALL specs (not just matching short name)
|
||||||
|
local highest_spec=$(get_highest_from_specs "$specs_dir")
|
||||||
|
|
||||||
|
# Take the maximum of both
|
||||||
|
local max_num=$highest_branch
|
||||||
|
if [ "$highest_spec" -gt "$max_num" ]; then
|
||||||
|
max_num=$highest_spec
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Return next number
|
||||||
|
echo $((max_num + 1))
|
||||||
|
}
|
||||||
|
|
||||||
|
# Function to clean and format a branch name
|
||||||
|
clean_branch_name() {
|
||||||
|
local name="$1"
|
||||||
|
echo "$name" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/-\+/-/g' | sed 's/^-//' | sed 's/-$//'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Resolve repository root. Prefer git information when available, but fall back
|
||||||
|
# to searching for repository markers so the workflow still functions in repositories that
|
||||||
|
# were initialised with --no-git.
|
||||||
|
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
|
||||||
|
if git rev-parse --show-toplevel >/dev/null 2>&1; then
|
||||||
|
REPO_ROOT=$(git rev-parse --show-toplevel)
|
||||||
|
HAS_GIT=true
|
||||||
|
else
|
||||||
|
REPO_ROOT="$(find_repo_root "$SCRIPT_DIR")"
|
||||||
|
if [ -z "$REPO_ROOT" ]; then
|
||||||
|
echo "Error: Could not determine repository root. Please run this script from within the repository." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
HAS_GIT=false
|
||||||
|
fi
|
||||||
|
|
||||||
|
cd "$REPO_ROOT"
|
||||||
|
|
||||||
|
SPECS_DIR="$REPO_ROOT/specs"
|
||||||
|
mkdir -p "$SPECS_DIR"
|
||||||
|
|
||||||
|
# Function to generate branch name with stop word filtering and length filtering
|
||||||
|
generate_branch_name() {
|
||||||
|
local description="$1"
|
||||||
|
|
||||||
|
# Common stop words to filter out
|
||||||
|
local stop_words="^(i|a|an|the|to|for|of|in|on|at|by|with|from|is|are|was|were|be|been|being|have|has|had|do|does|did|will|would|should|could|can|may|might|must|shall|this|that|these|those|my|your|our|their|want|need|add|get|set)$"
|
||||||
|
|
||||||
|
# Convert to lowercase and split into words
|
||||||
|
local clean_name=$(echo "$description" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/ /g')
|
||||||
|
|
||||||
|
# Filter words: remove stop words and words shorter than 3 chars (unless they're uppercase acronyms in original)
|
||||||
|
local meaningful_words=()
|
||||||
|
for word in $clean_name; do
|
||||||
|
# Skip empty words
|
||||||
|
[ -z "$word" ] && continue
|
||||||
|
|
||||||
|
# Keep words that are NOT stop words AND (length >= 3 OR are potential acronyms)
|
||||||
|
if ! echo "$word" | grep -qiE "$stop_words"; then
|
||||||
|
if [ ${#word} -ge 3 ]; then
|
||||||
|
meaningful_words+=("$word")
|
||||||
|
elif echo "$description" | grep -q "\b${word^^}\b"; then
|
||||||
|
# Keep short words if they appear as uppercase in original (likely acronyms)
|
||||||
|
meaningful_words+=("$word")
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# If we have meaningful words, use first 3-4 of them
|
||||||
|
if [ ${#meaningful_words[@]} -gt 0 ]; then
|
||||||
|
local max_words=3
|
||||||
|
if [ ${#meaningful_words[@]} -eq 4 ]; then max_words=4; fi
|
||||||
|
|
||||||
|
local result=""
|
||||||
|
local count=0
|
||||||
|
for word in "${meaningful_words[@]}"; do
|
||||||
|
if [ $count -ge $max_words ]; then break; fi
|
||||||
|
if [ -n "$result" ]; then result="$result-"; fi
|
||||||
|
result="$result$word"
|
||||||
|
count=$((count + 1))
|
||||||
|
done
|
||||||
|
echo "$result"
|
||||||
|
else
|
||||||
|
# Fallback to original logic if no meaningful words found
|
||||||
|
local cleaned=$(clean_branch_name "$description")
|
||||||
|
echo "$cleaned" | tr '-' '\n' | grep -v '^$' | head -3 | tr '\n' '-' | sed 's/-$//'
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Generate branch name
|
||||||
|
if [ -n "$SHORT_NAME" ]; then
|
||||||
|
# Use provided short name, just clean it up
|
||||||
|
BRANCH_SUFFIX=$(clean_branch_name "$SHORT_NAME")
|
||||||
|
else
|
||||||
|
# Generate from description with smart filtering
|
||||||
|
BRANCH_SUFFIX=$(generate_branch_name "$FEATURE_DESCRIPTION")
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Determine branch number
|
||||||
|
if [ -z "$BRANCH_NUMBER" ]; then
|
||||||
|
if [ "$HAS_GIT" = true ]; then
|
||||||
|
# Check existing branches on remotes
|
||||||
|
BRANCH_NUMBER=$(check_existing_branches "$SPECS_DIR")
|
||||||
|
else
|
||||||
|
# Fall back to local directory check
|
||||||
|
HIGHEST=$(get_highest_from_specs "$SPECS_DIR")
|
||||||
|
BRANCH_NUMBER=$((HIGHEST + 1))
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Force base-10 interpretation to prevent octal conversion (e.g., 010 → 8 in octal, but should be 10 in decimal)
|
||||||
|
FEATURE_NUM=$(printf "%03d" "$((10#$BRANCH_NUMBER))")
|
||||||
|
BRANCH_NAME="${FEATURE_NUM}-${BRANCH_SUFFIX}"
|
||||||
|
|
||||||
|
# GitHub enforces a 244-byte limit on branch names
|
||||||
|
# Validate and truncate if necessary
|
||||||
|
MAX_BRANCH_LENGTH=244
|
||||||
|
if [ ${#BRANCH_NAME} -gt $MAX_BRANCH_LENGTH ]; then
|
||||||
|
# Calculate how much we need to trim from suffix
|
||||||
|
# Account for: feature number (3) + hyphen (1) = 4 chars
|
||||||
|
MAX_SUFFIX_LENGTH=$((MAX_BRANCH_LENGTH - 4))
|
||||||
|
|
||||||
|
# Truncate suffix at word boundary if possible
|
||||||
|
TRUNCATED_SUFFIX=$(echo "$BRANCH_SUFFIX" | cut -c1-$MAX_SUFFIX_LENGTH)
|
||||||
|
# Remove trailing hyphen if truncation created one
|
||||||
|
TRUNCATED_SUFFIX=$(echo "$TRUNCATED_SUFFIX" | sed 's/-$//')
|
||||||
|
|
||||||
|
ORIGINAL_BRANCH_NAME="$BRANCH_NAME"
|
||||||
|
BRANCH_NAME="${FEATURE_NUM}-${TRUNCATED_SUFFIX}"
|
||||||
|
|
||||||
|
>&2 echo "[specify] Warning: Branch name exceeded GitHub's 244-byte limit"
|
||||||
|
>&2 echo "[specify] Original: $ORIGINAL_BRANCH_NAME (${#ORIGINAL_BRANCH_NAME} bytes)"
|
||||||
|
>&2 echo "[specify] Truncated to: $BRANCH_NAME (${#BRANCH_NAME} bytes)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$HAS_GIT" = true ]; then
|
||||||
|
git checkout -b "$BRANCH_NAME"
|
||||||
|
else
|
||||||
|
>&2 echo "[specify] Warning: Git repository not detected; skipped branch creation for $BRANCH_NAME"
|
||||||
|
fi
|
||||||
|
|
||||||
|
FEATURE_DIR="$SPECS_DIR/$BRANCH_NAME"
|
||||||
|
mkdir -p "$FEATURE_DIR"
|
||||||
|
|
||||||
|
TEMPLATE="$REPO_ROOT/.specify/templates/spec-template.md"
|
||||||
|
SPEC_FILE="$FEATURE_DIR/spec.md"
|
||||||
|
if [ -f "$TEMPLATE" ]; then cp "$TEMPLATE" "$SPEC_FILE"; else touch "$SPEC_FILE"; fi
|
||||||
|
|
||||||
|
# Set the SPECIFY_FEATURE environment variable for the current session
|
||||||
|
export SPECIFY_FEATURE="$BRANCH_NAME"
|
||||||
|
|
||||||
|
if $JSON_MODE; then
|
||||||
|
printf '{"BRANCH_NAME":"%s","SPEC_FILE":"%s","FEATURE_NUM":"%s"}\n' "$BRANCH_NAME" "$SPEC_FILE" "$FEATURE_NUM"
|
||||||
|
else
|
||||||
|
echo "BRANCH_NAME: $BRANCH_NAME"
|
||||||
|
echo "SPEC_FILE: $SPEC_FILE"
|
||||||
|
echo "FEATURE_NUM: $FEATURE_NUM"
|
||||||
|
echo "SPECIFY_FEATURE environment variable set to: $BRANCH_NAME"
|
||||||
|
fi
|
||||||
61
.specify/scripts/bash/setup-plan.sh
Executable file
61
.specify/scripts/bash/setup-plan.sh
Executable file
|
|
@ -0,0 +1,61 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Parse command line arguments
|
||||||
|
JSON_MODE=false
|
||||||
|
ARGS=()
|
||||||
|
|
||||||
|
for arg in "$@"; do
|
||||||
|
case "$arg" in
|
||||||
|
--json)
|
||||||
|
JSON_MODE=true
|
||||||
|
;;
|
||||||
|
--help|-h)
|
||||||
|
echo "Usage: $0 [--json]"
|
||||||
|
echo " --json Output results in JSON format"
|
||||||
|
echo " --help Show this help message"
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
ARGS+=("$arg")
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# Get script directory and load common functions
|
||||||
|
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
source "$SCRIPT_DIR/common.sh"
|
||||||
|
|
||||||
|
# Get all paths and variables from common functions
|
||||||
|
eval $(get_feature_paths)
|
||||||
|
|
||||||
|
# Check if we're on a proper feature branch (only for git repos)
|
||||||
|
check_feature_branch "$CURRENT_BRANCH" "$HAS_GIT" || exit 1
|
||||||
|
|
||||||
|
# Ensure the feature directory exists
|
||||||
|
mkdir -p "$FEATURE_DIR"
|
||||||
|
|
||||||
|
# Copy plan template if it exists
|
||||||
|
TEMPLATE="$REPO_ROOT/.specify/templates/plan-template.md"
|
||||||
|
if [[ -f "$TEMPLATE" ]]; then
|
||||||
|
cp "$TEMPLATE" "$IMPL_PLAN"
|
||||||
|
echo "Copied plan template to $IMPL_PLAN"
|
||||||
|
else
|
||||||
|
echo "Warning: Plan template not found at $TEMPLATE"
|
||||||
|
# Create a basic plan file if template doesn't exist
|
||||||
|
touch "$IMPL_PLAN"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Output results
|
||||||
|
if $JSON_MODE; then
|
||||||
|
printf '{"FEATURE_SPEC":"%s","IMPL_PLAN":"%s","SPECS_DIR":"%s","BRANCH":"%s","HAS_GIT":"%s"}\n' \
|
||||||
|
"$FEATURE_SPEC" "$IMPL_PLAN" "$FEATURE_DIR" "$CURRENT_BRANCH" "$HAS_GIT"
|
||||||
|
else
|
||||||
|
echo "FEATURE_SPEC: $FEATURE_SPEC"
|
||||||
|
echo "IMPL_PLAN: $IMPL_PLAN"
|
||||||
|
echo "SPECS_DIR: $FEATURE_DIR"
|
||||||
|
echo "BRANCH: $CURRENT_BRANCH"
|
||||||
|
echo "HAS_GIT: $HAS_GIT"
|
||||||
|
fi
|
||||||
|
|
||||||
799
.specify/scripts/bash/update-agent-context.sh
Executable file
799
.specify/scripts/bash/update-agent-context.sh
Executable file
|
|
@ -0,0 +1,799 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
# Update agent context files with information from plan.md
|
||||||
|
#
|
||||||
|
# This script maintains AI agent context files by parsing feature specifications
|
||||||
|
# and updating agent-specific configuration files with project information.
|
||||||
|
#
|
||||||
|
# MAIN FUNCTIONS:
|
||||||
|
# 1. Environment Validation
|
||||||
|
# - Verifies git repository structure and branch information
|
||||||
|
# - Checks for required plan.md files and templates
|
||||||
|
# - Validates file permissions and accessibility
|
||||||
|
#
|
||||||
|
# 2. Plan Data Extraction
|
||||||
|
# - Parses plan.md files to extract project metadata
|
||||||
|
# - Identifies language/version, frameworks, databases, and project types
|
||||||
|
# - Handles missing or incomplete specification data gracefully
|
||||||
|
#
|
||||||
|
# 3. Agent File Management
|
||||||
|
# - Creates new agent context files from templates when needed
|
||||||
|
# - Updates existing agent files with new project information
|
||||||
|
# - Preserves manual additions and custom configurations
|
||||||
|
# - Supports multiple AI agent formats and directory structures
|
||||||
|
#
|
||||||
|
# 4. Content Generation
|
||||||
|
# - Generates language-specific build/test commands
|
||||||
|
# - Creates appropriate project directory structures
|
||||||
|
# - Updates technology stacks and recent changes sections
|
||||||
|
# - Maintains consistent formatting and timestamps
|
||||||
|
#
|
||||||
|
# 5. Multi-Agent Support
|
||||||
|
# - Handles agent-specific file paths and naming conventions
|
||||||
|
# - Supports: Claude, Gemini, Copilot, Cursor, Qwen, opencode, Codex, Windsurf, Kilo Code, Auggie CLI, Roo Code, CodeBuddy CLI, Qoder CLI, Amp, SHAI, or Amazon Q Developer CLI
|
||||||
|
# - Can update single agents or all existing agent files
|
||||||
|
# - Creates default Claude file if no agent files exist
|
||||||
|
#
|
||||||
|
# Usage: ./update-agent-context.sh [agent_type]
|
||||||
|
# Agent types: claude|gemini|copilot|cursor-agent|qwen|opencode|codex|windsurf|kilocode|auggie|shai|q|bob|qoder
|
||||||
|
# Leave empty to update all existing agent files
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Enable strict error handling
|
||||||
|
set -u
|
||||||
|
set -o pipefail
|
||||||
|
|
||||||
|
#==============================================================================
|
||||||
|
# Configuration and Global Variables
|
||||||
|
#==============================================================================
|
||||||
|
|
||||||
|
# Get script directory and load common functions
|
||||||
|
SCRIPT_DIR="$(CDPATH="" cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
source "$SCRIPT_DIR/common.sh"
|
||||||
|
|
||||||
|
# Get all paths and variables from common functions
|
||||||
|
eval $(get_feature_paths)
|
||||||
|
|
||||||
|
NEW_PLAN="$IMPL_PLAN" # Alias for compatibility with existing code
|
||||||
|
AGENT_TYPE="${1:-}"
|
||||||
|
|
||||||
|
# Agent-specific file paths
|
||||||
|
CLAUDE_FILE="$REPO_ROOT/CLAUDE.md"
|
||||||
|
GEMINI_FILE="$REPO_ROOT/GEMINI.md"
|
||||||
|
COPILOT_FILE="$REPO_ROOT/.github/agents/copilot-instructions.md"
|
||||||
|
CURSOR_FILE="$REPO_ROOT/.cursor/rules/specify-rules.mdc"
|
||||||
|
QWEN_FILE="$REPO_ROOT/QWEN.md"
|
||||||
|
AGENTS_FILE="$REPO_ROOT/AGENTS.md"
|
||||||
|
WINDSURF_FILE="$REPO_ROOT/.windsurf/rules/specify-rules.md"
|
||||||
|
KILOCODE_FILE="$REPO_ROOT/.kilocode/rules/specify-rules.md"
|
||||||
|
AUGGIE_FILE="$REPO_ROOT/.augment/rules/specify-rules.md"
|
||||||
|
ROO_FILE="$REPO_ROOT/.roo/rules/specify-rules.md"
|
||||||
|
CODEBUDDY_FILE="$REPO_ROOT/CODEBUDDY.md"
|
||||||
|
QODER_FILE="$REPO_ROOT/QODER.md"
|
||||||
|
AMP_FILE="$REPO_ROOT/AGENTS.md"
|
||||||
|
SHAI_FILE="$REPO_ROOT/SHAI.md"
|
||||||
|
Q_FILE="$REPO_ROOT/AGENTS.md"
|
||||||
|
BOB_FILE="$REPO_ROOT/AGENTS.md"
|
||||||
|
|
||||||
|
# Template file
|
||||||
|
TEMPLATE_FILE="$REPO_ROOT/.specify/templates/agent-file-template.md"
|
||||||
|
|
||||||
|
# Global variables for parsed plan data
|
||||||
|
NEW_LANG=""
|
||||||
|
NEW_FRAMEWORK=""
|
||||||
|
NEW_DB=""
|
||||||
|
NEW_PROJECT_TYPE=""
|
||||||
|
|
||||||
|
#==============================================================================
|
||||||
|
# Utility Functions
|
||||||
|
#==============================================================================
|
||||||
|
|
||||||
|
log_info() {
|
||||||
|
echo "INFO: $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
log_success() {
|
||||||
|
echo "✓ $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
log_error() {
|
||||||
|
echo "ERROR: $1" >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
log_warning() {
|
||||||
|
echo "WARNING: $1" >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
# Cleanup function for temporary files
|
||||||
|
cleanup() {
|
||||||
|
local exit_code=$?
|
||||||
|
rm -f /tmp/agent_update_*_$$
|
||||||
|
rm -f /tmp/manual_additions_$$
|
||||||
|
exit $exit_code
|
||||||
|
}
|
||||||
|
|
||||||
|
# Set up cleanup trap
|
||||||
|
trap cleanup EXIT INT TERM
|
||||||
|
|
||||||
|
#==============================================================================
|
||||||
|
# Validation Functions
|
||||||
|
#==============================================================================
|
||||||
|
|
||||||
|
validate_environment() {
|
||||||
|
# Check if we have a current branch/feature (git or non-git)
|
||||||
|
if [[ -z "$CURRENT_BRANCH" ]]; then
|
||||||
|
log_error "Unable to determine current feature"
|
||||||
|
if [[ "$HAS_GIT" == "true" ]]; then
|
||||||
|
log_info "Make sure you're on a feature branch"
|
||||||
|
else
|
||||||
|
log_info "Set SPECIFY_FEATURE environment variable or create a feature first"
|
||||||
|
fi
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Check if plan.md exists
|
||||||
|
if [[ ! -f "$NEW_PLAN" ]]; then
|
||||||
|
log_error "No plan.md found at $NEW_PLAN"
|
||||||
|
log_info "Make sure you're working on a feature with a corresponding spec directory"
|
||||||
|
if [[ "$HAS_GIT" != "true" ]]; then
|
||||||
|
log_info "Use: export SPECIFY_FEATURE=your-feature-name or create a new feature first"
|
||||||
|
fi
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Check if template exists (needed for new files)
|
||||||
|
if [[ ! -f "$TEMPLATE_FILE" ]]; then
|
||||||
|
log_warning "Template file not found at $TEMPLATE_FILE"
|
||||||
|
log_warning "Creating new agent files will fail"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
#==============================================================================
|
||||||
|
# Plan Parsing Functions
|
||||||
|
#==============================================================================
|
||||||
|
|
||||||
|
extract_plan_field() {
|
||||||
|
local field_pattern="$1"
|
||||||
|
local plan_file="$2"
|
||||||
|
|
||||||
|
grep "^\*\*${field_pattern}\*\*: " "$plan_file" 2>/dev/null | \
|
||||||
|
head -1 | \
|
||||||
|
sed "s|^\*\*${field_pattern}\*\*: ||" | \
|
||||||
|
sed 's/^[ \t]*//;s/[ \t]*$//' | \
|
||||||
|
grep -v "NEEDS CLARIFICATION" | \
|
||||||
|
grep -v "^N/A$" || echo ""
|
||||||
|
}
|
||||||
|
|
||||||
|
parse_plan_data() {
|
||||||
|
local plan_file="$1"
|
||||||
|
|
||||||
|
if [[ ! -f "$plan_file" ]]; then
|
||||||
|
log_error "Plan file not found: $plan_file"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ! -r "$plan_file" ]]; then
|
||||||
|
log_error "Plan file is not readable: $plan_file"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
log_info "Parsing plan data from $plan_file"
|
||||||
|
|
||||||
|
NEW_LANG=$(extract_plan_field "Language/Version" "$plan_file")
|
||||||
|
NEW_FRAMEWORK=$(extract_plan_field "Primary Dependencies" "$plan_file")
|
||||||
|
NEW_DB=$(extract_plan_field "Storage" "$plan_file")
|
||||||
|
NEW_PROJECT_TYPE=$(extract_plan_field "Project Type" "$plan_file")
|
||||||
|
|
||||||
|
# Log what we found
|
||||||
|
if [[ -n "$NEW_LANG" ]]; then
|
||||||
|
log_info "Found language: $NEW_LANG"
|
||||||
|
else
|
||||||
|
log_warning "No language information found in plan"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -n "$NEW_FRAMEWORK" ]]; then
|
||||||
|
log_info "Found framework: $NEW_FRAMEWORK"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]]; then
|
||||||
|
log_info "Found database: $NEW_DB"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -n "$NEW_PROJECT_TYPE" ]]; then
|
||||||
|
log_info "Found project type: $NEW_PROJECT_TYPE"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
format_technology_stack() {
|
||||||
|
local lang="$1"
|
||||||
|
local framework="$2"
|
||||||
|
local parts=()
|
||||||
|
|
||||||
|
# Add non-empty parts
|
||||||
|
[[ -n "$lang" && "$lang" != "NEEDS CLARIFICATION" ]] && parts+=("$lang")
|
||||||
|
[[ -n "$framework" && "$framework" != "NEEDS CLARIFICATION" && "$framework" != "N/A" ]] && parts+=("$framework")
|
||||||
|
|
||||||
|
# Join with proper formatting
|
||||||
|
if [[ ${#parts[@]} -eq 0 ]]; then
|
||||||
|
echo ""
|
||||||
|
elif [[ ${#parts[@]} -eq 1 ]]; then
|
||||||
|
echo "${parts[0]}"
|
||||||
|
else
|
||||||
|
# Join multiple parts with " + "
|
||||||
|
local result="${parts[0]}"
|
||||||
|
for ((i=1; i<${#parts[@]}; i++)); do
|
||||||
|
result="$result + ${parts[i]}"
|
||||||
|
done
|
||||||
|
echo "$result"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
#==============================================================================
|
||||||
|
# Template and Content Generation Functions
|
||||||
|
#==============================================================================
|
||||||
|
|
||||||
|
get_project_structure() {
|
||||||
|
local project_type="$1"
|
||||||
|
|
||||||
|
if [[ "$project_type" == *"web"* ]]; then
|
||||||
|
echo "backend/\\nfrontend/\\ntests/"
|
||||||
|
else
|
||||||
|
echo "src/\\ntests/"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
get_commands_for_language() {
|
||||||
|
local lang="$1"
|
||||||
|
|
||||||
|
case "$lang" in
|
||||||
|
*"Python"*)
|
||||||
|
echo "cd src && pytest && ruff check ."
|
||||||
|
;;
|
||||||
|
*"Rust"*)
|
||||||
|
echo "cargo test && cargo clippy"
|
||||||
|
;;
|
||||||
|
*"JavaScript"*|*"TypeScript"*)
|
||||||
|
echo "npm test \\&\\& npm run lint"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "# Add commands for $lang"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
get_language_conventions() {
|
||||||
|
local lang="$1"
|
||||||
|
echo "$lang: Follow standard conventions"
|
||||||
|
}
|
||||||
|
|
||||||
|
create_new_agent_file() {
|
||||||
|
local target_file="$1"
|
||||||
|
local temp_file="$2"
|
||||||
|
local project_name="$3"
|
||||||
|
local current_date="$4"
|
||||||
|
|
||||||
|
if [[ ! -f "$TEMPLATE_FILE" ]]; then
|
||||||
|
log_error "Template not found at $TEMPLATE_FILE"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ! -r "$TEMPLATE_FILE" ]]; then
|
||||||
|
log_error "Template file is not readable: $TEMPLATE_FILE"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
log_info "Creating new agent context file from template..."
|
||||||
|
|
||||||
|
if ! cp "$TEMPLATE_FILE" "$temp_file"; then
|
||||||
|
log_error "Failed to copy template file"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Replace template placeholders
|
||||||
|
local project_structure
|
||||||
|
project_structure=$(get_project_structure "$NEW_PROJECT_TYPE")
|
||||||
|
|
||||||
|
local commands
|
||||||
|
commands=$(get_commands_for_language "$NEW_LANG")
|
||||||
|
|
||||||
|
local language_conventions
|
||||||
|
language_conventions=$(get_language_conventions "$NEW_LANG")
|
||||||
|
|
||||||
|
# Perform substitutions with error checking using safer approach
|
||||||
|
# Escape special characters for sed by using a different delimiter or escaping
|
||||||
|
local escaped_lang=$(printf '%s\n' "$NEW_LANG" | sed 's/[\[\.*^$()+{}|]/\\&/g')
|
||||||
|
local escaped_framework=$(printf '%s\n' "$NEW_FRAMEWORK" | sed 's/[\[\.*^$()+{}|]/\\&/g')
|
||||||
|
local escaped_branch=$(printf '%s\n' "$CURRENT_BRANCH" | sed 's/[\[\.*^$()+{}|]/\\&/g')
|
||||||
|
|
||||||
|
# Build technology stack and recent change strings conditionally
|
||||||
|
local tech_stack
|
||||||
|
if [[ -n "$escaped_lang" && -n "$escaped_framework" ]]; then
|
||||||
|
tech_stack="- $escaped_lang + $escaped_framework ($escaped_branch)"
|
||||||
|
elif [[ -n "$escaped_lang" ]]; then
|
||||||
|
tech_stack="- $escaped_lang ($escaped_branch)"
|
||||||
|
elif [[ -n "$escaped_framework" ]]; then
|
||||||
|
tech_stack="- $escaped_framework ($escaped_branch)"
|
||||||
|
else
|
||||||
|
tech_stack="- ($escaped_branch)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
local recent_change
|
||||||
|
if [[ -n "$escaped_lang" && -n "$escaped_framework" ]]; then
|
||||||
|
recent_change="- $escaped_branch: Added $escaped_lang + $escaped_framework"
|
||||||
|
elif [[ -n "$escaped_lang" ]]; then
|
||||||
|
recent_change="- $escaped_branch: Added $escaped_lang"
|
||||||
|
elif [[ -n "$escaped_framework" ]]; then
|
||||||
|
recent_change="- $escaped_branch: Added $escaped_framework"
|
||||||
|
else
|
||||||
|
recent_change="- $escaped_branch: Added"
|
||||||
|
fi
|
||||||
|
|
||||||
|
local substitutions=(
|
||||||
|
"s|\[PROJECT NAME\]|$project_name|"
|
||||||
|
"s|\[DATE\]|$current_date|"
|
||||||
|
"s|\[EXTRACTED FROM ALL PLAN.MD FILES\]|$tech_stack|"
|
||||||
|
"s|\[ACTUAL STRUCTURE FROM PLANS\]|$project_structure|g"
|
||||||
|
"s|\[ONLY COMMANDS FOR ACTIVE TECHNOLOGIES\]|$commands|"
|
||||||
|
"s|\[LANGUAGE-SPECIFIC, ONLY FOR LANGUAGES IN USE\]|$language_conventions|"
|
||||||
|
"s|\[LAST 3 FEATURES AND WHAT THEY ADDED\]|$recent_change|"
|
||||||
|
)
|
||||||
|
|
||||||
|
for substitution in "${substitutions[@]}"; do
|
||||||
|
if ! sed -i.bak -e "$substitution" "$temp_file"; then
|
||||||
|
log_error "Failed to perform substitution: $substitution"
|
||||||
|
rm -f "$temp_file" "$temp_file.bak"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# Convert \n sequences to actual newlines
|
||||||
|
newline=$(printf '\n')
|
||||||
|
sed -i.bak2 "s/\\\\n/${newline}/g" "$temp_file"
|
||||||
|
|
||||||
|
# Clean up backup files
|
||||||
|
rm -f "$temp_file.bak" "$temp_file.bak2"
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
update_existing_agent_file() {
|
||||||
|
local target_file="$1"
|
||||||
|
local current_date="$2"
|
||||||
|
|
||||||
|
log_info "Updating existing agent context file..."
|
||||||
|
|
||||||
|
# Use a single temporary file for atomic update
|
||||||
|
local temp_file
|
||||||
|
temp_file=$(mktemp) || {
|
||||||
|
log_error "Failed to create temporary file"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Process the file in one pass
|
||||||
|
local tech_stack=$(format_technology_stack "$NEW_LANG" "$NEW_FRAMEWORK")
|
||||||
|
local new_tech_entries=()
|
||||||
|
local new_change_entry=""
|
||||||
|
|
||||||
|
# Prepare new technology entries
|
||||||
|
if [[ -n "$tech_stack" ]] && ! grep -q "$tech_stack" "$target_file"; then
|
||||||
|
new_tech_entries+=("- $tech_stack ($CURRENT_BRANCH)")
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]] && [[ "$NEW_DB" != "NEEDS CLARIFICATION" ]] && ! grep -q "$NEW_DB" "$target_file"; then
|
||||||
|
new_tech_entries+=("- $NEW_DB ($CURRENT_BRANCH)")
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Prepare new change entry
|
||||||
|
if [[ -n "$tech_stack" ]]; then
|
||||||
|
new_change_entry="- $CURRENT_BRANCH: Added $tech_stack"
|
||||||
|
elif [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]] && [[ "$NEW_DB" != "NEEDS CLARIFICATION" ]]; then
|
||||||
|
new_change_entry="- $CURRENT_BRANCH: Added $NEW_DB"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Check if sections exist in the file
|
||||||
|
local has_active_technologies=0
|
||||||
|
local has_recent_changes=0
|
||||||
|
|
||||||
|
if grep -q "^## Active Technologies" "$target_file" 2>/dev/null; then
|
||||||
|
has_active_technologies=1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if grep -q "^## Recent Changes" "$target_file" 2>/dev/null; then
|
||||||
|
has_recent_changes=1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Process file line by line
|
||||||
|
local in_tech_section=false
|
||||||
|
local in_changes_section=false
|
||||||
|
local tech_entries_added=false
|
||||||
|
local changes_entries_added=false
|
||||||
|
local existing_changes_count=0
|
||||||
|
local file_ended=false
|
||||||
|
|
||||||
|
while IFS= read -r line || [[ -n "$line" ]]; do
|
||||||
|
# Handle Active Technologies section
|
||||||
|
if [[ "$line" == "## Active Technologies" ]]; then
|
||||||
|
echo "$line" >> "$temp_file"
|
||||||
|
in_tech_section=true
|
||||||
|
continue
|
||||||
|
elif [[ $in_tech_section == true ]] && [[ "$line" =~ ^##[[:space:]] ]]; then
|
||||||
|
# Add new tech entries before closing the section
|
||||||
|
if [[ $tech_entries_added == false ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then
|
||||||
|
printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file"
|
||||||
|
tech_entries_added=true
|
||||||
|
fi
|
||||||
|
echo "$line" >> "$temp_file"
|
||||||
|
in_tech_section=false
|
||||||
|
continue
|
||||||
|
elif [[ $in_tech_section == true ]] && [[ -z "$line" ]]; then
|
||||||
|
# Add new tech entries before empty line in tech section
|
||||||
|
if [[ $tech_entries_added == false ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then
|
||||||
|
printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file"
|
||||||
|
tech_entries_added=true
|
||||||
|
fi
|
||||||
|
echo "$line" >> "$temp_file"
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Handle Recent Changes section
|
||||||
|
if [[ "$line" == "## Recent Changes" ]]; then
|
||||||
|
echo "$line" >> "$temp_file"
|
||||||
|
# Add new change entry right after the heading
|
||||||
|
if [[ -n "$new_change_entry" ]]; then
|
||||||
|
echo "$new_change_entry" >> "$temp_file"
|
||||||
|
fi
|
||||||
|
in_changes_section=true
|
||||||
|
changes_entries_added=true
|
||||||
|
continue
|
||||||
|
elif [[ $in_changes_section == true ]] && [[ "$line" =~ ^##[[:space:]] ]]; then
|
||||||
|
echo "$line" >> "$temp_file"
|
||||||
|
in_changes_section=false
|
||||||
|
continue
|
||||||
|
elif [[ $in_changes_section == true ]] && [[ "$line" == "- "* ]]; then
|
||||||
|
# Keep only first 2 existing changes
|
||||||
|
if [[ $existing_changes_count -lt 2 ]]; then
|
||||||
|
echo "$line" >> "$temp_file"
|
||||||
|
((existing_changes_count++))
|
||||||
|
fi
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Update timestamp
|
||||||
|
if [[ "$line" =~ \*\*Last\ updated\*\*:.*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] ]]; then
|
||||||
|
echo "$line" | sed "s/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]/$current_date/" >> "$temp_file"
|
||||||
|
else
|
||||||
|
echo "$line" >> "$temp_file"
|
||||||
|
fi
|
||||||
|
done < "$target_file"
|
||||||
|
|
||||||
|
# Post-loop check: if we're still in the Active Technologies section and haven't added new entries
|
||||||
|
if [[ $in_tech_section == true ]] && [[ $tech_entries_added == false ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then
|
||||||
|
printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file"
|
||||||
|
tech_entries_added=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
# If sections don't exist, add them at the end of the file
|
||||||
|
if [[ $has_active_technologies -eq 0 ]] && [[ ${#new_tech_entries[@]} -gt 0 ]]; then
|
||||||
|
echo "" >> "$temp_file"
|
||||||
|
echo "## Active Technologies" >> "$temp_file"
|
||||||
|
printf '%s\n' "${new_tech_entries[@]}" >> "$temp_file"
|
||||||
|
tech_entries_added=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ $has_recent_changes -eq 0 ]] && [[ -n "$new_change_entry" ]]; then
|
||||||
|
echo "" >> "$temp_file"
|
||||||
|
echo "## Recent Changes" >> "$temp_file"
|
||||||
|
echo "$new_change_entry" >> "$temp_file"
|
||||||
|
changes_entries_added=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Move temp file to target atomically
|
||||||
|
if ! mv "$temp_file" "$target_file"; then
|
||||||
|
log_error "Failed to update target file"
|
||||||
|
rm -f "$temp_file"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
#==============================================================================
|
||||||
|
# Main Agent File Update Function
|
||||||
|
#==============================================================================
|
||||||
|
|
||||||
|
update_agent_file() {
|
||||||
|
local target_file="$1"
|
||||||
|
local agent_name="$2"
|
||||||
|
|
||||||
|
if [[ -z "$target_file" ]] || [[ -z "$agent_name" ]]; then
|
||||||
|
log_error "update_agent_file requires target_file and agent_name parameters"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
log_info "Updating $agent_name context file: $target_file"
|
||||||
|
|
||||||
|
local project_name
|
||||||
|
project_name=$(basename "$REPO_ROOT")
|
||||||
|
local current_date
|
||||||
|
current_date=$(date +%Y-%m-%d)
|
||||||
|
|
||||||
|
# Create directory if it doesn't exist
|
||||||
|
local target_dir
|
||||||
|
target_dir=$(dirname "$target_file")
|
||||||
|
if [[ ! -d "$target_dir" ]]; then
|
||||||
|
if ! mkdir -p "$target_dir"; then
|
||||||
|
log_error "Failed to create directory: $target_dir"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ! -f "$target_file" ]]; then
|
||||||
|
# Create new file from template
|
||||||
|
local temp_file
|
||||||
|
temp_file=$(mktemp) || {
|
||||||
|
log_error "Failed to create temporary file"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if create_new_agent_file "$target_file" "$temp_file" "$project_name" "$current_date"; then
|
||||||
|
if mv "$temp_file" "$target_file"; then
|
||||||
|
log_success "Created new $agent_name context file"
|
||||||
|
else
|
||||||
|
log_error "Failed to move temporary file to $target_file"
|
||||||
|
rm -f "$temp_file"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
log_error "Failed to create new agent file"
|
||||||
|
rm -f "$temp_file"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
# Update existing file
|
||||||
|
if [[ ! -r "$target_file" ]]; then
|
||||||
|
log_error "Cannot read existing file: $target_file"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ! -w "$target_file" ]]; then
|
||||||
|
log_error "Cannot write to existing file: $target_file"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if update_existing_agent_file "$target_file" "$current_date"; then
|
||||||
|
log_success "Updated existing $agent_name context file"
|
||||||
|
else
|
||||||
|
log_error "Failed to update existing agent file"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
#==============================================================================
|
||||||
|
# Agent Selection and Processing
|
||||||
|
#==============================================================================
|
||||||
|
|
||||||
|
update_specific_agent() {
|
||||||
|
local agent_type="$1"
|
||||||
|
|
||||||
|
case "$agent_type" in
|
||||||
|
claude)
|
||||||
|
update_agent_file "$CLAUDE_FILE" "Claude Code"
|
||||||
|
;;
|
||||||
|
gemini)
|
||||||
|
update_agent_file "$GEMINI_FILE" "Gemini CLI"
|
||||||
|
;;
|
||||||
|
copilot)
|
||||||
|
update_agent_file "$COPILOT_FILE" "GitHub Copilot"
|
||||||
|
;;
|
||||||
|
cursor-agent)
|
||||||
|
update_agent_file "$CURSOR_FILE" "Cursor IDE"
|
||||||
|
;;
|
||||||
|
qwen)
|
||||||
|
update_agent_file "$QWEN_FILE" "Qwen Code"
|
||||||
|
;;
|
||||||
|
opencode)
|
||||||
|
update_agent_file "$AGENTS_FILE" "opencode"
|
||||||
|
;;
|
||||||
|
codex)
|
||||||
|
update_agent_file "$AGENTS_FILE" "Codex CLI"
|
||||||
|
;;
|
||||||
|
windsurf)
|
||||||
|
update_agent_file "$WINDSURF_FILE" "Windsurf"
|
||||||
|
;;
|
||||||
|
kilocode)
|
||||||
|
update_agent_file "$KILOCODE_FILE" "Kilo Code"
|
||||||
|
;;
|
||||||
|
auggie)
|
||||||
|
update_agent_file "$AUGGIE_FILE" "Auggie CLI"
|
||||||
|
;;
|
||||||
|
roo)
|
||||||
|
update_agent_file "$ROO_FILE" "Roo Code"
|
||||||
|
;;
|
||||||
|
codebuddy)
|
||||||
|
update_agent_file "$CODEBUDDY_FILE" "CodeBuddy CLI"
|
||||||
|
;;
|
||||||
|
qoder)
|
||||||
|
update_agent_file "$QODER_FILE" "Qoder CLI"
|
||||||
|
;;
|
||||||
|
amp)
|
||||||
|
update_agent_file "$AMP_FILE" "Amp"
|
||||||
|
;;
|
||||||
|
shai)
|
||||||
|
update_agent_file "$SHAI_FILE" "SHAI"
|
||||||
|
;;
|
||||||
|
q)
|
||||||
|
update_agent_file "$Q_FILE" "Amazon Q Developer CLI"
|
||||||
|
;;
|
||||||
|
bob)
|
||||||
|
update_agent_file "$BOB_FILE" "IBM Bob"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
log_error "Unknown agent type '$agent_type'"
|
||||||
|
log_error "Expected: claude|gemini|copilot|cursor-agent|qwen|opencode|codex|windsurf|kilocode|auggie|roo|amp|shai|q|bob|qoder"
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
update_all_existing_agents() {
|
||||||
|
local found_agent=false
|
||||||
|
|
||||||
|
# Check each possible agent file and update if it exists
|
||||||
|
if [[ -f "$CLAUDE_FILE" ]]; then
|
||||||
|
update_agent_file "$CLAUDE_FILE" "Claude Code"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$GEMINI_FILE" ]]; then
|
||||||
|
update_agent_file "$GEMINI_FILE" "Gemini CLI"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$COPILOT_FILE" ]]; then
|
||||||
|
update_agent_file "$COPILOT_FILE" "GitHub Copilot"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$CURSOR_FILE" ]]; then
|
||||||
|
update_agent_file "$CURSOR_FILE" "Cursor IDE"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$QWEN_FILE" ]]; then
|
||||||
|
update_agent_file "$QWEN_FILE" "Qwen Code"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$AGENTS_FILE" ]]; then
|
||||||
|
update_agent_file "$AGENTS_FILE" "Codex/opencode"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$WINDSURF_FILE" ]]; then
|
||||||
|
update_agent_file "$WINDSURF_FILE" "Windsurf"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$KILOCODE_FILE" ]]; then
|
||||||
|
update_agent_file "$KILOCODE_FILE" "Kilo Code"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$AUGGIE_FILE" ]]; then
|
||||||
|
update_agent_file "$AUGGIE_FILE" "Auggie CLI"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$ROO_FILE" ]]; then
|
||||||
|
update_agent_file "$ROO_FILE" "Roo Code"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$CODEBUDDY_FILE" ]]; then
|
||||||
|
update_agent_file "$CODEBUDDY_FILE" "CodeBuddy CLI"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$SHAI_FILE" ]]; then
|
||||||
|
update_agent_file "$SHAI_FILE" "SHAI"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$QODER_FILE" ]]; then
|
||||||
|
update_agent_file "$QODER_FILE" "Qoder CLI"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$Q_FILE" ]]; then
|
||||||
|
update_agent_file "$Q_FILE" "Amazon Q Developer CLI"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -f "$BOB_FILE" ]]; then
|
||||||
|
update_agent_file "$BOB_FILE" "IBM Bob"
|
||||||
|
found_agent=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
# If no agent files exist, create a default Claude file
|
||||||
|
if [[ "$found_agent" == false ]]; then
|
||||||
|
log_info "No existing agent files found, creating default Claude file..."
|
||||||
|
update_agent_file "$CLAUDE_FILE" "Claude Code"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
print_summary() {
|
||||||
|
echo
|
||||||
|
log_info "Summary of changes:"
|
||||||
|
|
||||||
|
if [[ -n "$NEW_LANG" ]]; then
|
||||||
|
echo " - Added language: $NEW_LANG"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -n "$NEW_FRAMEWORK" ]]; then
|
||||||
|
echo " - Added framework: $NEW_FRAMEWORK"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -n "$NEW_DB" ]] && [[ "$NEW_DB" != "N/A" ]]; then
|
||||||
|
echo " - Added database: $NEW_DB"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
|
||||||
|
log_info "Usage: $0 [claude|gemini|copilot|cursor-agent|qwen|opencode|codex|windsurf|kilocode|auggie|codebuddy|shai|q|bob|qoder]"
|
||||||
|
}
|
||||||
|
|
||||||
|
#==============================================================================
|
||||||
|
# Main Execution
|
||||||
|
#==============================================================================
|
||||||
|
|
||||||
|
main() {
|
||||||
|
# Validate environment before proceeding
|
||||||
|
validate_environment
|
||||||
|
|
||||||
|
log_info "=== Updating agent context files for feature $CURRENT_BRANCH ==="
|
||||||
|
|
||||||
|
# Parse the plan file to extract project information
|
||||||
|
if ! parse_plan_data "$NEW_PLAN"; then
|
||||||
|
log_error "Failed to parse plan data"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Process based on agent type argument
|
||||||
|
local success=true
|
||||||
|
|
||||||
|
if [[ -z "$AGENT_TYPE" ]]; then
|
||||||
|
# No specific agent provided - update all existing agent files
|
||||||
|
log_info "No agent specified, updating all existing agent files..."
|
||||||
|
if ! update_all_existing_agents; then
|
||||||
|
success=false
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
# Specific agent provided - update only that agent
|
||||||
|
log_info "Updating specific agent: $AGENT_TYPE"
|
||||||
|
if ! update_specific_agent "$AGENT_TYPE"; then
|
||||||
|
success=false
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Print summary
|
||||||
|
print_summary
|
||||||
|
|
||||||
|
if [[ "$success" == true ]]; then
|
||||||
|
log_success "Agent context update completed successfully"
|
||||||
|
exit 0
|
||||||
|
else
|
||||||
|
log_error "Agent context update completed with errors"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Execute main function if script is run directly
|
||||||
|
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
||||||
|
main "$@"
|
||||||
|
fi
|
||||||
|
|
||||||
28
.specify/templates/agent-file-template.md
Normal file
28
.specify/templates/agent-file-template.md
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
# [PROJECT NAME] Development Guidelines
|
||||||
|
|
||||||
|
Auto-generated from all feature plans. Last updated: [DATE]
|
||||||
|
|
||||||
|
## Active Technologies
|
||||||
|
|
||||||
|
[EXTRACTED FROM ALL PLAN.MD FILES]
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```text
|
||||||
|
[ACTUAL STRUCTURE FROM PLANS]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
[ONLY COMMANDS FOR ACTIVE TECHNOLOGIES]
|
||||||
|
|
||||||
|
## Code Style
|
||||||
|
|
||||||
|
[LANGUAGE-SPECIFIC, ONLY FOR LANGUAGES IN USE]
|
||||||
|
|
||||||
|
## Recent Changes
|
||||||
|
|
||||||
|
[LAST 3 FEATURES AND WHAT THEY ADDED]
|
||||||
|
|
||||||
|
<!-- MANUAL ADDITIONS START -->
|
||||||
|
<!-- MANUAL ADDITIONS END -->
|
||||||
40
.specify/templates/checklist-template.md
Normal file
40
.specify/templates/checklist-template.md
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
# [CHECKLIST TYPE] Checklist: [FEATURE NAME]
|
||||||
|
|
||||||
|
**Purpose**: [Brief description of what this checklist covers]
|
||||||
|
**Created**: [DATE]
|
||||||
|
**Feature**: [Link to spec.md or relevant documentation]
|
||||||
|
|
||||||
|
**Note**: This checklist is generated by the `/speckit.checklist` command based on feature context and requirements.
|
||||||
|
|
||||||
|
<!--
|
||||||
|
============================================================================
|
||||||
|
IMPORTANT: The checklist items below are SAMPLE ITEMS for illustration only.
|
||||||
|
|
||||||
|
The /speckit.checklist command MUST replace these with actual items based on:
|
||||||
|
- User's specific checklist request
|
||||||
|
- Feature requirements from spec.md
|
||||||
|
- Technical context from plan.md
|
||||||
|
- Implementation details from tasks.md
|
||||||
|
|
||||||
|
DO NOT keep these sample items in the generated checklist file.
|
||||||
|
============================================================================
|
||||||
|
-->
|
||||||
|
|
||||||
|
## [Category 1]
|
||||||
|
|
||||||
|
- [ ] CHK001 First checklist item with clear action
|
||||||
|
- [ ] CHK002 Second checklist item
|
||||||
|
- [ ] CHK003 Third checklist item
|
||||||
|
|
||||||
|
## [Category 2]
|
||||||
|
|
||||||
|
- [ ] CHK004 Another category item
|
||||||
|
- [ ] CHK005 Item with specific criteria
|
||||||
|
- [ ] CHK006 Final item in this category
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- Check items off as completed: `[x]`
|
||||||
|
- Add comments or findings inline
|
||||||
|
- Link to relevant resources or documentation
|
||||||
|
- Items are numbered sequentially for easy reference
|
||||||
104
.specify/templates/plan-template.md
Normal file
104
.specify/templates/plan-template.md
Normal file
|
|
@ -0,0 +1,104 @@
|
||||||
|
# Implementation Plan: [FEATURE]
|
||||||
|
|
||||||
|
**Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link]
|
||||||
|
**Input**: Feature specification from `/specs/[###-feature-name]/spec.md`
|
||||||
|
|
||||||
|
**Note**: This template is filled in by the `/speckit.plan` command. See `.specify/templates/commands/plan.md` for the execution workflow.
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
[Extract from feature spec: primary requirement + technical approach from research]
|
||||||
|
|
||||||
|
## Technical Context
|
||||||
|
|
||||||
|
<!--
|
||||||
|
ACTION REQUIRED: Replace the content in this section with the technical details
|
||||||
|
for the project. The structure here is presented in advisory capacity to guide
|
||||||
|
the iteration process.
|
||||||
|
-->
|
||||||
|
|
||||||
|
**Language/Version**: [e.g., Python 3.11, Swift 5.9, Rust 1.75 or NEEDS CLARIFICATION]
|
||||||
|
**Primary Dependencies**: [e.g., FastAPI, UIKit, LLVM or NEEDS CLARIFICATION]
|
||||||
|
**Storage**: [if applicable, e.g., PostgreSQL, CoreData, files or N/A]
|
||||||
|
**Testing**: [e.g., pytest, XCTest, cargo test or NEEDS CLARIFICATION]
|
||||||
|
**Target Platform**: [e.g., Linux server, iOS 15+, WASM or NEEDS CLARIFICATION]
|
||||||
|
**Project Type**: [single/web/mobile - determines source structure]
|
||||||
|
**Performance Goals**: [domain-specific, e.g., 1000 req/s, 10k lines/sec, 60 fps or NEEDS CLARIFICATION]
|
||||||
|
**Constraints**: [domain-specific, e.g., <200ms p95, <100MB memory, offline-capable or NEEDS CLARIFICATION]
|
||||||
|
**Scale/Scope**: [domain-specific, e.g., 10k users, 1M LOC, 50 screens or NEEDS CLARIFICATION]
|
||||||
|
|
||||||
|
## Constitution Check
|
||||||
|
|
||||||
|
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
|
||||||
|
|
||||||
|
[Gates determined based on constitution file]
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
### Documentation (this feature)
|
||||||
|
|
||||||
|
```text
|
||||||
|
specs/[###-feature]/
|
||||||
|
├── plan.md # This file (/speckit.plan command output)
|
||||||
|
├── research.md # Phase 0 output (/speckit.plan command)
|
||||||
|
├── data-model.md # Phase 1 output (/speckit.plan command)
|
||||||
|
├── quickstart.md # Phase 1 output (/speckit.plan command)
|
||||||
|
├── contracts/ # Phase 1 output (/speckit.plan command)
|
||||||
|
└── tasks.md # Phase 2 output (/speckit.tasks command - NOT created by /speckit.plan)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Source Code (repository root)
|
||||||
|
<!--
|
||||||
|
ACTION REQUIRED: Replace the placeholder tree below with the concrete layout
|
||||||
|
for this feature. Delete unused options and expand the chosen structure with
|
||||||
|
real paths (e.g., apps/admin, packages/something). The delivered plan must
|
||||||
|
not include Option labels.
|
||||||
|
-->
|
||||||
|
|
||||||
|
```text
|
||||||
|
# [REMOVE IF UNUSED] Option 1: Single project (DEFAULT)
|
||||||
|
src/
|
||||||
|
├── models/
|
||||||
|
├── services/
|
||||||
|
├── cli/
|
||||||
|
└── lib/
|
||||||
|
|
||||||
|
tests/
|
||||||
|
├── contract/
|
||||||
|
├── integration/
|
||||||
|
└── unit/
|
||||||
|
|
||||||
|
# [REMOVE IF UNUSED] Option 2: Web application (when "frontend" + "backend" detected)
|
||||||
|
backend/
|
||||||
|
├── src/
|
||||||
|
│ ├── models/
|
||||||
|
│ ├── services/
|
||||||
|
│ └── api/
|
||||||
|
└── tests/
|
||||||
|
|
||||||
|
frontend/
|
||||||
|
├── src/
|
||||||
|
│ ├── components/
|
||||||
|
│ ├── pages/
|
||||||
|
│ └── services/
|
||||||
|
└── tests/
|
||||||
|
|
||||||
|
# [REMOVE IF UNUSED] Option 3: Mobile + API (when "iOS/Android" detected)
|
||||||
|
api/
|
||||||
|
└── [same as backend above]
|
||||||
|
|
||||||
|
ios/ or android/
|
||||||
|
└── [platform-specific structure: feature modules, UI flows, platform tests]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Structure Decision**: [Document the selected structure and reference the real
|
||||||
|
directories captured above]
|
||||||
|
|
||||||
|
## Complexity Tracking
|
||||||
|
|
||||||
|
> **Fill ONLY if Constitution Check has violations that must be justified**
|
||||||
|
|
||||||
|
| Violation | Why Needed | Simpler Alternative Rejected Because |
|
||||||
|
|-----------|------------|-------------------------------------|
|
||||||
|
| [e.g., 4th project] | [current need] | [why 3 projects insufficient] |
|
||||||
|
| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] |
|
||||||
115
.specify/templates/spec-template.md
Normal file
115
.specify/templates/spec-template.md
Normal file
|
|
@ -0,0 +1,115 @@
|
||||||
|
# Feature Specification: [FEATURE NAME]
|
||||||
|
|
||||||
|
**Feature Branch**: `[###-feature-name]`
|
||||||
|
**Created**: [DATE]
|
||||||
|
**Status**: Draft
|
||||||
|
**Input**: User description: "$ARGUMENTS"
|
||||||
|
|
||||||
|
## User Scenarios & Testing *(mandatory)*
|
||||||
|
|
||||||
|
<!--
|
||||||
|
IMPORTANT: User stories should be PRIORITIZED as user journeys ordered by importance.
|
||||||
|
Each user story/journey must be INDEPENDENTLY TESTABLE - meaning if you implement just ONE of them,
|
||||||
|
you should still have a viable MVP (Minimum Viable Product) that delivers value.
|
||||||
|
|
||||||
|
Assign priorities (P1, P2, P3, etc.) to each story, where P1 is the most critical.
|
||||||
|
Think of each story as a standalone slice of functionality that can be:
|
||||||
|
- Developed independently
|
||||||
|
- Tested independently
|
||||||
|
- Deployed independently
|
||||||
|
- Demonstrated to users independently
|
||||||
|
-->
|
||||||
|
|
||||||
|
### User Story 1 - [Brief Title] (Priority: P1)
|
||||||
|
|
||||||
|
[Describe this user journey in plain language]
|
||||||
|
|
||||||
|
**Why this priority**: [Explain the value and why it has this priority level]
|
||||||
|
|
||||||
|
**Independent Test**: [Describe how this can be tested independently - e.g., "Can be fully tested by [specific action] and delivers [specific value]"]
|
||||||
|
|
||||||
|
**Acceptance Scenarios**:
|
||||||
|
|
||||||
|
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
|
||||||
|
2. **Given** [initial state], **When** [action], **Then** [expected outcome]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### User Story 2 - [Brief Title] (Priority: P2)
|
||||||
|
|
||||||
|
[Describe this user journey in plain language]
|
||||||
|
|
||||||
|
**Why this priority**: [Explain the value and why it has this priority level]
|
||||||
|
|
||||||
|
**Independent Test**: [Describe how this can be tested independently]
|
||||||
|
|
||||||
|
**Acceptance Scenarios**:
|
||||||
|
|
||||||
|
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### User Story 3 - [Brief Title] (Priority: P3)
|
||||||
|
|
||||||
|
[Describe this user journey in plain language]
|
||||||
|
|
||||||
|
**Why this priority**: [Explain the value and why it has this priority level]
|
||||||
|
|
||||||
|
**Independent Test**: [Describe how this can be tested independently]
|
||||||
|
|
||||||
|
**Acceptance Scenarios**:
|
||||||
|
|
||||||
|
1. **Given** [initial state], **When** [action], **Then** [expected outcome]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
[Add more user stories as needed, each with an assigned priority]
|
||||||
|
|
||||||
|
### Edge Cases
|
||||||
|
|
||||||
|
<!--
|
||||||
|
ACTION REQUIRED: The content in this section represents placeholders.
|
||||||
|
Fill them out with the right edge cases.
|
||||||
|
-->
|
||||||
|
|
||||||
|
- What happens when [boundary condition]?
|
||||||
|
- How does system handle [error scenario]?
|
||||||
|
|
||||||
|
## Requirements *(mandatory)*
|
||||||
|
|
||||||
|
<!--
|
||||||
|
ACTION REQUIRED: The content in this section represents placeholders.
|
||||||
|
Fill them out with the right functional requirements.
|
||||||
|
-->
|
||||||
|
|
||||||
|
### Functional Requirements
|
||||||
|
|
||||||
|
- **FR-001**: System MUST [specific capability, e.g., "allow users to create accounts"]
|
||||||
|
- **FR-002**: System MUST [specific capability, e.g., "validate email addresses"]
|
||||||
|
- **FR-003**: Users MUST be able to [key interaction, e.g., "reset their password"]
|
||||||
|
- **FR-004**: System MUST [data requirement, e.g., "persist user preferences"]
|
||||||
|
- **FR-005**: System MUST [behavior, e.g., "log all security events"]
|
||||||
|
|
||||||
|
*Example of marking unclear requirements:*
|
||||||
|
|
||||||
|
- **FR-006**: System MUST authenticate users via [NEEDS CLARIFICATION: auth method not specified - email/password, SSO, OAuth?]
|
||||||
|
- **FR-007**: System MUST retain user data for [NEEDS CLARIFICATION: retention period not specified]
|
||||||
|
|
||||||
|
### Key Entities *(include if feature involves data)*
|
||||||
|
|
||||||
|
- **[Entity 1]**: [What it represents, key attributes without implementation]
|
||||||
|
- **[Entity 2]**: [What it represents, relationships to other entities]
|
||||||
|
|
||||||
|
## Success Criteria *(mandatory)*
|
||||||
|
|
||||||
|
<!--
|
||||||
|
ACTION REQUIRED: Define measurable success criteria.
|
||||||
|
These must be technology-agnostic and measurable.
|
||||||
|
-->
|
||||||
|
|
||||||
|
### Measurable Outcomes
|
||||||
|
|
||||||
|
- **SC-001**: [Measurable metric, e.g., "Users can complete account creation in under 2 minutes"]
|
||||||
|
- **SC-002**: [Measurable metric, e.g., "System handles 1000 concurrent users without degradation"]
|
||||||
|
- **SC-003**: [User satisfaction metric, e.g., "90% of users successfully complete primary task on first attempt"]
|
||||||
|
- **SC-004**: [Business metric, e.g., "Reduce support tickets related to [X] by 50%"]
|
||||||
251
.specify/templates/tasks-template.md
Normal file
251
.specify/templates/tasks-template.md
Normal file
|
|
@ -0,0 +1,251 @@
|
||||||
|
---
|
||||||
|
|
||||||
|
description: "Task list template for feature implementation"
|
||||||
|
---
|
||||||
|
|
||||||
|
# Tasks: [FEATURE NAME]
|
||||||
|
|
||||||
|
**Input**: Design documents from `/specs/[###-feature-name]/`
|
||||||
|
**Prerequisites**: plan.md (required), spec.md (required for user stories), research.md, data-model.md, contracts/
|
||||||
|
|
||||||
|
**Tests**: The examples below include test tasks. Tests are OPTIONAL - only include them if explicitly requested in the feature specification.
|
||||||
|
|
||||||
|
**Organization**: Tasks are grouped by user story to enable independent implementation and testing of each story.
|
||||||
|
|
||||||
|
## Format: `[ID] [P?] [Story] Description`
|
||||||
|
|
||||||
|
- **[P]**: Can run in parallel (different files, no dependencies)
|
||||||
|
- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3)
|
||||||
|
- Include exact file paths in descriptions
|
||||||
|
|
||||||
|
## Path Conventions
|
||||||
|
|
||||||
|
- **Single project**: `src/`, `tests/` at repository root
|
||||||
|
- **Web app**: `backend/src/`, `frontend/src/`
|
||||||
|
- **Mobile**: `api/src/`, `ios/src/` or `android/src/`
|
||||||
|
- Paths shown below assume single project - adjust based on plan.md structure
|
||||||
|
|
||||||
|
<!--
|
||||||
|
============================================================================
|
||||||
|
IMPORTANT: The tasks below are SAMPLE TASKS for illustration purposes only.
|
||||||
|
|
||||||
|
The /speckit.tasks command MUST replace these with actual tasks based on:
|
||||||
|
- User stories from spec.md (with their priorities P1, P2, P3...)
|
||||||
|
- Feature requirements from plan.md
|
||||||
|
- Entities from data-model.md
|
||||||
|
- Endpoints from contracts/
|
||||||
|
|
||||||
|
Tasks MUST be organized by user story so each story can be:
|
||||||
|
- Implemented independently
|
||||||
|
- Tested independently
|
||||||
|
- Delivered as an MVP increment
|
||||||
|
|
||||||
|
DO NOT keep these sample tasks in the generated tasks.md file.
|
||||||
|
============================================================================
|
||||||
|
-->
|
||||||
|
|
||||||
|
## Phase 1: Setup (Shared Infrastructure)
|
||||||
|
|
||||||
|
**Purpose**: Project initialization and basic structure
|
||||||
|
|
||||||
|
- [ ] T001 Create project structure per implementation plan
|
||||||
|
- [ ] T002 Initialize [language] project with [framework] dependencies
|
||||||
|
- [ ] T003 [P] Configure linting and formatting tools
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 2: Foundational (Blocking Prerequisites)
|
||||||
|
|
||||||
|
**Purpose**: Core infrastructure that MUST be complete before ANY user story can be implemented
|
||||||
|
|
||||||
|
**⚠️ CRITICAL**: No user story work can begin until this phase is complete
|
||||||
|
|
||||||
|
Examples of foundational tasks (adjust based on your project):
|
||||||
|
|
||||||
|
- [ ] T004 Setup database schema and migrations framework
|
||||||
|
- [ ] T005 [P] Implement authentication/authorization framework
|
||||||
|
- [ ] T006 [P] Setup API routing and middleware structure
|
||||||
|
- [ ] T007 Create base models/entities that all stories depend on
|
||||||
|
- [ ] T008 Configure error handling and logging infrastructure
|
||||||
|
- [ ] T009 Setup environment configuration management
|
||||||
|
|
||||||
|
**Checkpoint**: Foundation ready - user story implementation can now begin in parallel
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 3: User Story 1 - [Title] (Priority: P1) 🎯 MVP
|
||||||
|
|
||||||
|
**Goal**: [Brief description of what this story delivers]
|
||||||
|
|
||||||
|
**Independent Test**: [How to verify this story works on its own]
|
||||||
|
|
||||||
|
### Tests for User Story 1 (OPTIONAL - only if tests requested) ⚠️
|
||||||
|
|
||||||
|
> **NOTE: Write these tests FIRST, ensure they FAIL before implementation**
|
||||||
|
|
||||||
|
- [ ] T010 [P] [US1] Contract test for [endpoint] in tests/contract/test_[name].py
|
||||||
|
- [ ] T011 [P] [US1] Integration test for [user journey] in tests/integration/test_[name].py
|
||||||
|
|
||||||
|
### Implementation for User Story 1
|
||||||
|
|
||||||
|
- [ ] T012 [P] [US1] Create [Entity1] model in src/models/[entity1].py
|
||||||
|
- [ ] T013 [P] [US1] Create [Entity2] model in src/models/[entity2].py
|
||||||
|
- [ ] T014 [US1] Implement [Service] in src/services/[service].py (depends on T012, T013)
|
||||||
|
- [ ] T015 [US1] Implement [endpoint/feature] in src/[location]/[file].py
|
||||||
|
- [ ] T016 [US1] Add validation and error handling
|
||||||
|
- [ ] T017 [US1] Add logging for user story 1 operations
|
||||||
|
|
||||||
|
**Checkpoint**: At this point, User Story 1 should be fully functional and testable independently
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 4: User Story 2 - [Title] (Priority: P2)
|
||||||
|
|
||||||
|
**Goal**: [Brief description of what this story delivers]
|
||||||
|
|
||||||
|
**Independent Test**: [How to verify this story works on its own]
|
||||||
|
|
||||||
|
### Tests for User Story 2 (OPTIONAL - only if tests requested) ⚠️
|
||||||
|
|
||||||
|
- [ ] T018 [P] [US2] Contract test for [endpoint] in tests/contract/test_[name].py
|
||||||
|
- [ ] T019 [P] [US2] Integration test for [user journey] in tests/integration/test_[name].py
|
||||||
|
|
||||||
|
### Implementation for User Story 2
|
||||||
|
|
||||||
|
- [ ] T020 [P] [US2] Create [Entity] model in src/models/[entity].py
|
||||||
|
- [ ] T021 [US2] Implement [Service] in src/services/[service].py
|
||||||
|
- [ ] T022 [US2] Implement [endpoint/feature] in src/[location]/[file].py
|
||||||
|
- [ ] T023 [US2] Integrate with User Story 1 components (if needed)
|
||||||
|
|
||||||
|
**Checkpoint**: At this point, User Stories 1 AND 2 should both work independently
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 5: User Story 3 - [Title] (Priority: P3)
|
||||||
|
|
||||||
|
**Goal**: [Brief description of what this story delivers]
|
||||||
|
|
||||||
|
**Independent Test**: [How to verify this story works on its own]
|
||||||
|
|
||||||
|
### Tests for User Story 3 (OPTIONAL - only if tests requested) ⚠️
|
||||||
|
|
||||||
|
- [ ] T024 [P] [US3] Contract test for [endpoint] in tests/contract/test_[name].py
|
||||||
|
- [ ] T025 [P] [US3] Integration test for [user journey] in tests/integration/test_[name].py
|
||||||
|
|
||||||
|
### Implementation for User Story 3
|
||||||
|
|
||||||
|
- [ ] T026 [P] [US3] Create [Entity] model in src/models/[entity].py
|
||||||
|
- [ ] T027 [US3] Implement [Service] in src/services/[service].py
|
||||||
|
- [ ] T028 [US3] Implement [endpoint/feature] in src/[location]/[file].py
|
||||||
|
|
||||||
|
**Checkpoint**: All user stories should now be independently functional
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
[Add more user story phases as needed, following the same pattern]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase N: Polish & Cross-Cutting Concerns
|
||||||
|
|
||||||
|
**Purpose**: Improvements that affect multiple user stories
|
||||||
|
|
||||||
|
- [ ] TXXX [P] Documentation updates in docs/
|
||||||
|
- [ ] TXXX Code cleanup and refactoring
|
||||||
|
- [ ] TXXX Performance optimization across all stories
|
||||||
|
- [ ] TXXX [P] Additional unit tests (if requested) in tests/unit/
|
||||||
|
- [ ] TXXX Security hardening
|
||||||
|
- [ ] TXXX Run quickstart.md validation
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependencies & Execution Order
|
||||||
|
|
||||||
|
### Phase Dependencies
|
||||||
|
|
||||||
|
- **Setup (Phase 1)**: No dependencies - can start immediately
|
||||||
|
- **Foundational (Phase 2)**: Depends on Setup completion - BLOCKS all user stories
|
||||||
|
- **User Stories (Phase 3+)**: All depend on Foundational phase completion
|
||||||
|
- User stories can then proceed in parallel (if staffed)
|
||||||
|
- Or sequentially in priority order (P1 → P2 → P3)
|
||||||
|
- **Polish (Final Phase)**: Depends on all desired user stories being complete
|
||||||
|
|
||||||
|
### User Story Dependencies
|
||||||
|
|
||||||
|
- **User Story 1 (P1)**: Can start after Foundational (Phase 2) - No dependencies on other stories
|
||||||
|
- **User Story 2 (P2)**: Can start after Foundational (Phase 2) - May integrate with US1 but should be independently testable
|
||||||
|
- **User Story 3 (P3)**: Can start after Foundational (Phase 2) - May integrate with US1/US2 but should be independently testable
|
||||||
|
|
||||||
|
### Within Each User Story
|
||||||
|
|
||||||
|
- Tests (if included) MUST be written and FAIL before implementation
|
||||||
|
- Models before services
|
||||||
|
- Services before endpoints
|
||||||
|
- Core implementation before integration
|
||||||
|
- Story complete before moving to next priority
|
||||||
|
|
||||||
|
### Parallel Opportunities
|
||||||
|
|
||||||
|
- All Setup tasks marked [P] can run in parallel
|
||||||
|
- All Foundational tasks marked [P] can run in parallel (within Phase 2)
|
||||||
|
- Once Foundational phase completes, all user stories can start in parallel (if team capacity allows)
|
||||||
|
- All tests for a user story marked [P] can run in parallel
|
||||||
|
- Models within a story marked [P] can run in parallel
|
||||||
|
- Different user stories can be worked on in parallel by different team members
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Parallel Example: User Story 1
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Launch all tests for User Story 1 together (if tests requested):
|
||||||
|
Task: "Contract test for [endpoint] in tests/contract/test_[name].py"
|
||||||
|
Task: "Integration test for [user journey] in tests/integration/test_[name].py"
|
||||||
|
|
||||||
|
# Launch all models for User Story 1 together:
|
||||||
|
Task: "Create [Entity1] model in src/models/[entity1].py"
|
||||||
|
Task: "Create [Entity2] model in src/models/[entity2].py"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Implementation Strategy
|
||||||
|
|
||||||
|
### MVP First (User Story 1 Only)
|
||||||
|
|
||||||
|
1. Complete Phase 1: Setup
|
||||||
|
2. Complete Phase 2: Foundational (CRITICAL - blocks all stories)
|
||||||
|
3. Complete Phase 3: User Story 1
|
||||||
|
4. **STOP and VALIDATE**: Test User Story 1 independently
|
||||||
|
5. Deploy/demo if ready
|
||||||
|
|
||||||
|
### Incremental Delivery
|
||||||
|
|
||||||
|
1. Complete Setup + Foundational → Foundation ready
|
||||||
|
2. Add User Story 1 → Test independently → Deploy/Demo (MVP!)
|
||||||
|
3. Add User Story 2 → Test independently → Deploy/Demo
|
||||||
|
4. Add User Story 3 → Test independently → Deploy/Demo
|
||||||
|
5. Each story adds value without breaking previous stories
|
||||||
|
|
||||||
|
### Parallel Team Strategy
|
||||||
|
|
||||||
|
With multiple developers:
|
||||||
|
|
||||||
|
1. Team completes Setup + Foundational together
|
||||||
|
2. Once Foundational is done:
|
||||||
|
- Developer A: User Story 1
|
||||||
|
- Developer B: User Story 2
|
||||||
|
- Developer C: User Story 3
|
||||||
|
3. Stories complete and integrate independently
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- [P] tasks = different files, no dependencies
|
||||||
|
- [Story] label maps task to specific user story for traceability
|
||||||
|
- Each user story should be independently completable and testable
|
||||||
|
- Verify tests fail before implementing
|
||||||
|
- Commit after each task or logical group
|
||||||
|
- Stop at any checkpoint to validate story independently
|
||||||
|
- Avoid: vague tasks, same file conflicts, cross-story dependencies that break independence
|
||||||
201
libs/o-mem/LICENSE
Normal file
201
libs/o-mem/LICENSE
Normal file
|
|
@ -0,0 +1,201 @@
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
143
libs/o-mem/README.md
Normal file
143
libs/o-mem/README.md
Normal file
|
|
@ -0,0 +1,143 @@
|
||||||
|
# O-Mem: Omni Memory System for Personalized, Long Horizon, Self-Evolving Agents
|
||||||
|
|
||||||
|
[](LICENSE) [](https://www.python.org) [](https://arxiv.org/abs/2511.13593)
|
||||||
|
[](https://huggingface.co/papers/2511.13593)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<!-- [](https://youtu.be/...) -->
|
||||||
|
|
||||||
|
|
||||||
|
<div align="center">
|
||||||
|
<img src="./images/image1.png" width="80%" height="auto" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
📌 Current agent memory systems often rely on **semantic clustering and chunk-based retrieval**, which can:
|
||||||
|
|
||||||
|
- ❌ Miss contextually important but semantically distant information (e.g., health status affecting weekend plans)
|
||||||
|
- ❌ Introduce retrieval noise due to suboptimal grouping- ❌ Fail to capture evolving user characteristics over time**o-mem** addresses these issues by rethinking memory as an **active user modeling process**, not just passive storage. Inspired by personal informatics theory, o-mem continuously extracts and updates:
|
||||||
|
- 🔹 **User Persona Attributes** (e.g., preferences, habits, life stage)
|
||||||
|
- 🔹 **Event Records** (e.g., recent job change, travel plans)
|
||||||
|
- 🔹 **Topic-Indexed Messages** (for contextual grounding)
|
||||||
|
|
||||||
|
This enables **hierarchical, user-aware retrieval**: agents first reason about *who the user is*, then retrieve *what they said* — leading to more coherent, adaptive, and personalized responses.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 🚀 Key Features✅ **Dynamic User Profiling**> Automatically extract and update user attributes from ongoing interactions — no manual annotation needed.
|
||||||
|
|
||||||
|
✅ **Hierarchical Memory Structure**> Three-tier design:> - **Persona Layer**: Stable & evolving user traits> - **Event Layer**: Significant life/contextual events> - **Message Layer**: Topic-indexed raw dialog history✅ **User-Centric Retrieval**> Retrieve based on *user state* first, then *topic relevance* — reducing noise and improving coherence.
|
||||||
|
|
||||||
|
✅ **Interaction-Time Scaling**> Memory grows and adapts with each interaction — enabling true long-term personalization.
|
||||||
|
|
||||||
|
✅ **Evaluation Suite Included**> Benchmark scripts for:> - Persona-based QA (LoCoMo)> - Response selection (PERSONAMEM)> - In-depth report generation (Personalized Deep Research Bench)
|
||||||
|
|
||||||
|
✅ **Extensible & Modular**> Plug into any LLM agent pipeline via clean APIs. Easy to customize extraction rules or add new memory types.
|
||||||
|
|
||||||
|
## 🧩 Architecture
|
||||||
|
|
||||||
|
[Raw Interaction] ↓[Memory Writer] → [Extract: Attributes + Events]
|
||||||
|
↓[Update: Dynamic User Profile]
|
||||||
|
↓[Hierarchical Indexing]
|
||||||
|
↓[Retriever] ← [Query: "What would this user care about?"]
|
||||||
|
↓[Context-Aware Prompting] → [LLM Agent]
|
||||||
|
|
||||||
|
## 🔄O-Mem Workflow Visualization
|
||||||
|
|
||||||
|
<div align="center">
|
||||||
|
<img src="./images/workflow.png" width="80%" height="auto" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
## 🧩Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
memory_chain/
|
||||||
|
├── __init__.py # Package exports
|
||||||
|
├── memory.py # MemoryChain - main memory container
|
||||||
|
├── memory_manager.py # MemoryManager - high-level API
|
||||||
|
├── working_memory.py # Working Memory implementation
|
||||||
|
├── episodic_memory.py # Episodic Memory implementation
|
||||||
|
├── persona_memory.py # Persona Memory (active user profiling)
|
||||||
|
├── prompts.py # LLM prompt templates
|
||||||
|
└── utils.py # Utility functions
|
||||||
|
|
||||||
|
example_usage.py # Usage examples
|
||||||
|
config.yaml.example # Configuration template
|
||||||
|
requirements.txt # Dependencies
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🧠Memory Types
|
||||||
|
|
||||||
|
### Working Memory
|
||||||
|
- **Purpose**: Short-term storage for recent conversation
|
||||||
|
- **Capacity**: Fixed size queue (default: 20 messages)
|
||||||
|
- **Behavior**: Oldest messages overflow to Episodic Memory
|
||||||
|
|
||||||
|
### Episodic Memory
|
||||||
|
- **Purpose**: Long-term storage for events and topics
|
||||||
|
- **Features**:
|
||||||
|
- Topic clustering via semantic similarity
|
||||||
|
- Event-level and topic-level memories
|
||||||
|
- Attribute and fact extraction
|
||||||
|
|
||||||
|
### Persona Memory
|
||||||
|
- **Purpose**: Active user profiling and preferences
|
||||||
|
- **Contents**:
|
||||||
|
- Preferences (likes, dislikes, interests)
|
||||||
|
- Attributes (personality traits, facts)
|
||||||
|
- Dynamically updated user characteristics
|
||||||
|
|
||||||
|
## ⚙️Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# Copy and configure settings
|
||||||
|
cp config.yaml.example config.yaml
|
||||||
|
# Edit config.yaml with your OpenAI API key
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🚀Quick Start
|
||||||
|
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run full example
|
||||||
|
python example_usage.py
|
||||||
|
|
||||||
|
# Run simplified example
|
||||||
|
python example_usage.py simple
|
||||||
|
|
||||||
|
#Run test experiments for locomo benchmark with different arguments
|
||||||
|
python locomo_experiment_retrieval_optimize_ablation_study.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## ⚙️Configuration
|
||||||
|
|
||||||
|
Create a `config.yaml` file:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
model:
|
||||||
|
llm_model: "model name"
|
||||||
|
openai_api_key: "your-openai-api-key"
|
||||||
|
openai_base_url: "https://api.openai.com/v1"
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🧩 Community Support Note
|
||||||
|
|
||||||
|
We note that the performance of GPT-4.1 has recently degraded in preliminary observations, and the model is expected to be deprecated in the near future. Due to these changes, results obtained using GPT-4.1 may not be fully reproducible over time. For research purposes, especially for individuals or institutions with limited access to large language models, we are willing to share the original model outputs (e.g., inference logs, generated responses) upon request. We encourage careful interpretation of the experimental results in light of the evolving nature of commercial LLMs, and refer readers to the discussion in our technical report for guidance on result analysis and limitations.
|
||||||
|
|
||||||
|
## 📝 Citation
|
||||||
|
|
||||||
|
```
|
||||||
|
@article{wang2025omni,
|
||||||
|
title={Omni Memory System for Personalized, Long Horizon, Self-Evolving Agents},
|
||||||
|
author={Wang, Piaohong and Tian, Motong and Li, Jiaxian and Liang, Yuan and Wang, Yuqing and Chen, Qianben and Wang, Tiannan and Lu, Zhicong and Ma, Jiawei and Jiang, Yuchen Eleanor and others},
|
||||||
|
journal={arXiv preprint arXiv:2511.13593},
|
||||||
|
year={2025}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
9
libs/o-mem/config.yaml.example
Normal file
9
libs/o-mem/config.yaml.example
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
# Memory Chain Configuration Example
|
||||||
|
# ===================================
|
||||||
|
# Copy this file to config.yaml and fill in your settings
|
||||||
|
|
||||||
|
model:
|
||||||
|
llm_model: "model_name" # LLM model name
|
||||||
|
openai_api_key: "your-openai-api-key-here" # Your OpenAI API key
|
||||||
|
openai_base_url: "https://api.openai.com/v1" # OpenAI API base URL (change if using proxy)
|
||||||
|
|
||||||
481
libs/o-mem/example_usage.py
Normal file
481
libs/o-mem/example_usage.py
Normal file
|
|
@ -0,0 +1,481 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# coding=utf-8
|
||||||
|
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import yaml
|
||||||
|
import torch
|
||||||
|
from openai import AsyncOpenAI
|
||||||
|
from sentence_transformers import SentenceTransformer
|
||||||
|
from memory_chain import MemoryChain, MemoryManager
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== Configuration Class ====================
|
||||||
|
|
||||||
|
class MemoryConfig:
|
||||||
|
"""Memory system configuration"""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
working_memory_max_size: int = 20,
|
||||||
|
episodic_memory_refresh_rate: int = 5,
|
||||||
|
output_dir: str = "./memory_storage",
|
||||||
|
number_of_retrieval_pieces: int = 15, # Must be >= 10 (internal calculation uses top_k-9)
|
||||||
|
drop_threshold: float = 0.1,
|
||||||
|
):
|
||||||
|
self.working_memory_max_size = working_memory_max_size
|
||||||
|
self.episodic_memory_refresh_rate = episodic_memory_refresh_rate
|
||||||
|
self.output_dir = output_dir
|
||||||
|
self.number_of_retrieval_pieces = max(number_of_retrieval_pieces, 10) # Ensure at least 10
|
||||||
|
self.drop_threshold = drop_threshold
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== Main Usage Example ====================
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
"""
|
||||||
|
Memory Chain Usage Example
|
||||||
|
"""
|
||||||
|
|
||||||
|
# ========== 1. Configuration Parameters ==========
|
||||||
|
|
||||||
|
# Read config file (or set directly)
|
||||||
|
try:
|
||||||
|
with open('config.yaml', 'r') as file:
|
||||||
|
config = yaml.safe_load(file)
|
||||||
|
except FileNotFoundError:
|
||||||
|
# If no config file, use default configuration
|
||||||
|
config = {
|
||||||
|
"model": {
|
||||||
|
"llm_model": "gpt-4o-mini",
|
||||||
|
"openai_api_key": "your-api-key-here",
|
||||||
|
"openai_base_url": "https://api.openai.com/v1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize OpenAI client
|
||||||
|
client = AsyncOpenAI(
|
||||||
|
base_url=config["model"]["openai_base_url"],
|
||||||
|
api_key=config["model"]["openai_api_key"]
|
||||||
|
)
|
||||||
|
|
||||||
|
# Load Embedding model
|
||||||
|
print("Loading Embedding model...")
|
||||||
|
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||||
|
embedding_model = SentenceTransformer("all-MiniLM-L6-v2").to(device)
|
||||||
|
print(f"Embedding model loaded, using device: {device}")
|
||||||
|
|
||||||
|
# Memory system configuration
|
||||||
|
# Note: working_memory_max_size determines the working memory capacity
|
||||||
|
# When message count reaches this value, old messages are transferred to episodic memory
|
||||||
|
memory_config = MemoryConfig(
|
||||||
|
working_memory_max_size=5, # Max working memory capacity (small value to trigger memory transfer quickly)
|
||||||
|
episodic_memory_refresh_rate=3, # Episodic memory refresh rate
|
||||||
|
output_dir="./memory_storage", # Memory storage directory
|
||||||
|
number_of_retrieval_pieces=15, # Number of retrieval pieces
|
||||||
|
drop_threshold=0.1 # Similarity threshold
|
||||||
|
)
|
||||||
|
|
||||||
|
# Ensure storage directory exists
|
||||||
|
os.makedirs(memory_config.output_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# ========== 2. Initialize Memory System ==========
|
||||||
|
|
||||||
|
user_name = "Alice" # User name
|
||||||
|
agent_name = "Bob" # Agent/assistant name
|
||||||
|
memory_index = 0 # Memory index (for multi-session scenarios)
|
||||||
|
|
||||||
|
# Create MemoryChain (core memory system)
|
||||||
|
memory_system = MemoryChain(
|
||||||
|
memory_index=memory_index,
|
||||||
|
llm_model=config["model"]["llm_model"],
|
||||||
|
llm_client=client,
|
||||||
|
embedding_model=embedding_model,
|
||||||
|
user_name=user_name,
|
||||||
|
agent_name=agent_name,
|
||||||
|
cmd_args=memory_config,
|
||||||
|
args=config,
|
||||||
|
memory_dir=memory_config.output_dir
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create MemoryManager (memory manager, provides high-level API)
|
||||||
|
memory_manager = MemoryManager(
|
||||||
|
memory_index=memory_index,
|
||||||
|
memory_system=memory_system,
|
||||||
|
llm_model=config["model"]["llm_model"],
|
||||||
|
llm_client=client,
|
||||||
|
embedding_model=embedding_model,
|
||||||
|
user_name=user_name,
|
||||||
|
agent_name=agent_name,
|
||||||
|
cmd_args=memory_config,
|
||||||
|
args=config,
|
||||||
|
memory_dir=memory_config.output_dir
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"\n{'='*50}")
|
||||||
|
print("Memory system initialization complete!")
|
||||||
|
print(f"User: {user_name}, Agent: {agent_name}")
|
||||||
|
print(f"{'='*50}\n")
|
||||||
|
|
||||||
|
# ========== 3. Simulate Conversation and Store Memory ==========
|
||||||
|
|
||||||
|
# Simulated conversation data
|
||||||
|
# Note: Number of conversations must exceed working_memory_max_size to trigger memory transfer
|
||||||
|
conversations = [
|
||||||
|
{"speaker": user_name, "message": "I love playing basketball with my friends every weekend.", "timestamp": "2024-01-01 10:00:00"},
|
||||||
|
{"speaker": agent_name, "message": "That sounds great! Basketball is a wonderful way to stay active.", "timestamp": "2024-01-01 10:01:00"},
|
||||||
|
{"speaker": user_name, "message": "Yes! I've been playing for 5 years. My favorite team is the Lakers.", "timestamp": "2024-01-01 10:02:00"},
|
||||||
|
{"speaker": agent_name, "message": "The Lakers have a great history. Do you play any position specifically?", "timestamp": "2024-01-01 10:03:00"},
|
||||||
|
{"speaker": user_name, "message": "I usually play as a point guard. I also started learning guitar last month.", "timestamp": "2024-01-01 10:04:00"},
|
||||||
|
{"speaker": agent_name, "message": "Guitar is a lovely instrument! What kind of music do you want to play?", "timestamp": "2024-01-01 10:05:00"},
|
||||||
|
{"speaker": user_name, "message": "I'm into rock music. My favorite band is Coldplay.", "timestamp": "2024-01-01 10:06:00"},
|
||||||
|
{"speaker": agent_name, "message": "Coldplay has some amazing songs. Do you have a favorite album?", "timestamp": "2024-01-01 10:07:00"},
|
||||||
|
{"speaker": user_name, "message": "I really love 'A Rush of Blood to the Head'. The song 'The Scientist' is my favorite.", "timestamp": "2024-01-01 10:08:00"},
|
||||||
|
{"speaker": agent_name, "message": "That's a classic! Do you also enjoy attending live concerts?", "timestamp": "2024-01-01 10:09:00"},
|
||||||
|
{"speaker": user_name, "message": "Yes! I went to a Coldplay concert last year. It was an amazing experience.", "timestamp": "2024-01-01 10:10:00"},
|
||||||
|
{"speaker": agent_name, "message": "That must have been incredible! Live music is always so energizing.", "timestamp": "2024-01-01 10:11:00"},
|
||||||
|
{"speaker": user_name, "message": "Absolutely! I also enjoy cooking Italian food on weekends.", "timestamp": "2024-01-01 10:12:00"},
|
||||||
|
{"speaker": agent_name, "message": "Italian cuisine is delicious! What's your specialty dish?", "timestamp": "2024-01-01 10:13:00"},
|
||||||
|
{"speaker": user_name, "message": "I make a great homemade pasta with tomato sauce. My family loves it.", "timestamp": "2024-01-01 10:14:00"},
|
||||||
|
{"speaker": agent_name, "message": "That sounds delicious! Cooking for family is always special.", "timestamp": "2024-01-01 10:15:00"},
|
||||||
|
]
|
||||||
|
|
||||||
|
print("Processing conversations and building memory...")
|
||||||
|
print("-" * 50)
|
||||||
|
|
||||||
|
for index, conv in enumerate(conversations):
|
||||||
|
speaker = conv["speaker"]
|
||||||
|
message = conv["message"]
|
||||||
|
timestamp = conv["timestamp"]
|
||||||
|
user_speak = (speaker == user_name)
|
||||||
|
|
||||||
|
print(f"[{index}] {speaker}: {message}")
|
||||||
|
|
||||||
|
# Store message in memory system
|
||||||
|
await memory_manager.receive_message(
|
||||||
|
message=message,
|
||||||
|
client=client,
|
||||||
|
index=index,
|
||||||
|
timestamp=timestamp,
|
||||||
|
user_speak=user_speak
|
||||||
|
)
|
||||||
|
|
||||||
|
print("-" * 50)
|
||||||
|
print("Conversation processing complete!\n")
|
||||||
|
|
||||||
|
# ========== 4. Sync Memory Mappings (Important! Must be called before retrieval) ==========
|
||||||
|
|
||||||
|
print("Syncing memory mappings...")
|
||||||
|
# Sync messages from working_memory and episodic_memory to topic_message_dict
|
||||||
|
for message in list(memory_system.user_working_memory.working_memory_queue.queue) + memory_system.user_episodic_memory.episodic_memory_cache_list:
|
||||||
|
memory_system.user_topic_message_dict[message["topics"]] = [message["raw_message"], message["timestamp"]]
|
||||||
|
for message in list(memory_system.agent_working_memory.working_memory_queue.queue) + memory_system.agent_episodic_memory.episodic_memory_cache_list:
|
||||||
|
memory_system.agent_topic_message_dict[message["topics"]] = [message["raw_message"], message["timestamp"]]
|
||||||
|
|
||||||
|
# Generate memory detail map (for keyword retrieval)
|
||||||
|
memory_system.generate_memory_detail_map()
|
||||||
|
print("Memory mapping sync complete!\n")
|
||||||
|
|
||||||
|
# ========== 5. Update Persona Memory (Optional, call after conversation ends) ==========
|
||||||
|
|
||||||
|
print("Updating persona memory...")
|
||||||
|
await memory_system.user_persona_memory.update_preference_persona(
|
||||||
|
memory_system.user_episodic_memory.topic_episodic_memory_list
|
||||||
|
)
|
||||||
|
await memory_system.user_persona_memory.update_attribute_persona(
|
||||||
|
memory_system.user_episodic_memory.attribute_episodic_memory_dict
|
||||||
|
)
|
||||||
|
print("Persona memory update complete!\n")
|
||||||
|
|
||||||
|
# ========== 6. Memory Retrieval ==========
|
||||||
|
|
||||||
|
print("=" * 50)
|
||||||
|
print("Memory Retrieval Example")
|
||||||
|
print("=" * 50)
|
||||||
|
|
||||||
|
# Test questions
|
||||||
|
test_questions = [
|
||||||
|
f"What sport does {user_name} like?",
|
||||||
|
f"What instrument is {user_name} learning?",
|
||||||
|
f"What is {user_name}'s favorite band?",
|
||||||
|
]
|
||||||
|
|
||||||
|
for question in test_questions:
|
||||||
|
print(f"\nQuestion: {question}")
|
||||||
|
print("-" * 40)
|
||||||
|
|
||||||
|
# Retrieve relevant information from memory system
|
||||||
|
retrieval_result, retrieved_user, retrieved_agent, peak_mem, peak_mem_inc = \
|
||||||
|
memory_manager.retrieve_from_memory_soft_segmentation(
|
||||||
|
question=question,
|
||||||
|
topn=memory_config.number_of_retrieval_pieces,
|
||||||
|
drop_threshold=memory_config.drop_threshold
|
||||||
|
)
|
||||||
|
|
||||||
|
# Display retrieval results
|
||||||
|
print(f"Retrieved persona attributes: {retrieval_result.get('persona attributes', [])}")
|
||||||
|
print(f"Retrieved context messages: {retrieval_result.get('retrieved context messages', [])[:3]}")
|
||||||
|
|
||||||
|
# Generate answer
|
||||||
|
answer, tokens = await memory_manager.generate_system_response(
|
||||||
|
query=question,
|
||||||
|
restrieval_result=retrieval_result,
|
||||||
|
client=client,
|
||||||
|
speaker_a=retrieved_user,
|
||||||
|
speaker_b=retrieved_agent,
|
||||||
|
llm_model=config["model"]["llm_model"]
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"Generated answer: {answer}")
|
||||||
|
print(f"Tokens consumed: {tokens}")
|
||||||
|
|
||||||
|
print("\n" + "=" * 50)
|
||||||
|
print("Example run complete!")
|
||||||
|
print("=" * 50)
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== Simplified API Wrapper ====================
|
||||||
|
|
||||||
|
class SimpleMemory:
|
||||||
|
"""
|
||||||
|
Simplified memory system wrapper class
|
||||||
|
Provides simpler API for everyday use
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
user_name: str,
|
||||||
|
agent_name: str,
|
||||||
|
llm_model: str = "gpt-4o-mini",
|
||||||
|
api_key: str = None,
|
||||||
|
base_url: str = "https://api.openai.com/v1",
|
||||||
|
embedding_model_name: str = "all-MiniLM-L6-v2",
|
||||||
|
memory_dir: str = "./memory_storage",
|
||||||
|
):
|
||||||
|
self.user_name = user_name
|
||||||
|
self.agent_name = agent_name
|
||||||
|
self.llm_model = llm_model
|
||||||
|
self.memory_dir = memory_dir
|
||||||
|
self.message_index = 0
|
||||||
|
|
||||||
|
# Initialize client
|
||||||
|
self.client = AsyncOpenAI(base_url=base_url, api_key=api_key)
|
||||||
|
|
||||||
|
# Load Embedding model
|
||||||
|
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||||
|
self.embedding_model = SentenceTransformer(embedding_model_name).to(device)
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
self.config = {"model": {"llm_model": llm_model}}
|
||||||
|
self.cmd_args = MemoryConfig(
|
||||||
|
working_memory_max_size=5, # Same as main() for consistent behavior
|
||||||
|
episodic_memory_refresh_rate=3, # Same as main()
|
||||||
|
output_dir=memory_dir
|
||||||
|
)
|
||||||
|
|
||||||
|
os.makedirs(memory_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# Initialize memory system
|
||||||
|
self.memory_system = MemoryChain(
|
||||||
|
memory_index=0,
|
||||||
|
llm_model=llm_model,
|
||||||
|
llm_client=self.client,
|
||||||
|
embedding_model=self.embedding_model,
|
||||||
|
user_name=user_name,
|
||||||
|
agent_name=agent_name,
|
||||||
|
cmd_args=self.cmd_args,
|
||||||
|
args=self.config,
|
||||||
|
memory_dir=memory_dir
|
||||||
|
)
|
||||||
|
|
||||||
|
self.memory_manager = MemoryManager(
|
||||||
|
memory_index=0,
|
||||||
|
memory_system=self.memory_system,
|
||||||
|
llm_model=llm_model,
|
||||||
|
llm_client=self.client,
|
||||||
|
embedding_model=self.embedding_model,
|
||||||
|
user_name=user_name,
|
||||||
|
agent_name=agent_name,
|
||||||
|
cmd_args=self.cmd_args,
|
||||||
|
args=self.config,
|
||||||
|
memory_dir=memory_dir
|
||||||
|
)
|
||||||
|
|
||||||
|
async def add_message(self, message: str, is_user: bool = True, timestamp: str = None):
|
||||||
|
"""Add a message to memory"""
|
||||||
|
from datetime import datetime
|
||||||
|
if timestamp is None:
|
||||||
|
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
|
await self.memory_manager.receive_message(
|
||||||
|
message=message,
|
||||||
|
client=self.client,
|
||||||
|
index=self.message_index,
|
||||||
|
timestamp=timestamp,
|
||||||
|
user_speak=is_user
|
||||||
|
)
|
||||||
|
self.message_index += 1
|
||||||
|
|
||||||
|
async def query(self, question: str) -> str:
|
||||||
|
"""Query memory and generate answer"""
|
||||||
|
# Sync memory mappings
|
||||||
|
self._sync_memory_mappings()
|
||||||
|
|
||||||
|
result, user, agent, _, _ = self.memory_manager.retrieve_from_memory_soft_segmentation(
|
||||||
|
question=question,
|
||||||
|
topn=self.cmd_args.number_of_retrieval_pieces,
|
||||||
|
drop_threshold=self.cmd_args.drop_threshold
|
||||||
|
)
|
||||||
|
|
||||||
|
answer, _ = await self.memory_manager.generate_system_response(
|
||||||
|
query=question,
|
||||||
|
restrieval_result=result,
|
||||||
|
client=self.client,
|
||||||
|
speaker_a=user,
|
||||||
|
speaker_b=agent,
|
||||||
|
llm_model=self.llm_model
|
||||||
|
)
|
||||||
|
return answer
|
||||||
|
|
||||||
|
def _sync_memory_mappings(self):
|
||||||
|
"""Sync memory mappings (must be called before retrieval)"""
|
||||||
|
for message in list(self.memory_system.user_working_memory.working_memory_queue.queue) + self.memory_system.user_episodic_memory.episodic_memory_cache_list:
|
||||||
|
self.memory_system.user_topic_message_dict[message["topics"]] = [message["raw_message"], message["timestamp"]]
|
||||||
|
for message in list(self.memory_system.agent_working_memory.working_memory_queue.queue) + self.memory_system.agent_episodic_memory.episodic_memory_cache_list:
|
||||||
|
self.memory_system.agent_topic_message_dict[message["topics"]] = [message["raw_message"], message["timestamp"]]
|
||||||
|
self.memory_system.generate_memory_detail_map()
|
||||||
|
|
||||||
|
async def update_persona(self):
|
||||||
|
"""Update persona memory"""
|
||||||
|
# Sync memory mappings first
|
||||||
|
self._sync_memory_mappings()
|
||||||
|
|
||||||
|
await self.memory_system.user_persona_memory.update_preference_persona(
|
||||||
|
self.memory_system.user_episodic_memory.topic_episodic_memory_list
|
||||||
|
)
|
||||||
|
await self.memory_system.user_persona_memory.update_attribute_persona(
|
||||||
|
self.memory_system.user_episodic_memory.attribute_episodic_memory_dict
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== Simplified Usage Example ====================
|
||||||
|
|
||||||
|
async def simple_example():
|
||||||
|
"""Simplified API usage example - processes the same conversation as main()"""
|
||||||
|
|
||||||
|
print("\n" + "=" * 50)
|
||||||
|
print("Simplified API Usage Example")
|
||||||
|
print("=" * 50 + "\n")
|
||||||
|
|
||||||
|
# Read configuration
|
||||||
|
with open('config.yaml', 'r') as f:
|
||||||
|
config = yaml.safe_load(f)
|
||||||
|
|
||||||
|
user_name = "Alice"
|
||||||
|
agent_name = "Bob"
|
||||||
|
|
||||||
|
# Create simplified memory system
|
||||||
|
memory = SimpleMemory(
|
||||||
|
user_name=user_name,
|
||||||
|
agent_name=agent_name,
|
||||||
|
llm_model=config["model"]["llm_model"],
|
||||||
|
api_key=config["model"]["openai_api_key"],
|
||||||
|
base_url=config["model"]["openai_base_url"],
|
||||||
|
memory_dir="./memory_storage_simple", # Use different storage directory
|
||||||
|
)
|
||||||
|
|
||||||
|
# Simulated conversation data (same as main())
|
||||||
|
conversations = [
|
||||||
|
{"speaker": user_name, "message": "I love playing basketball with my friends every weekend.", "timestamp": "2024-01-01 10:00:00"},
|
||||||
|
{"speaker": agent_name, "message": "That sounds great! Basketball is a wonderful way to stay active.", "timestamp": "2024-01-01 10:01:00"},
|
||||||
|
{"speaker": user_name, "message": "Yes! I've been playing for 5 years. My favorite team is the Lakers.", "timestamp": "2024-01-01 10:02:00"},
|
||||||
|
{"speaker": agent_name, "message": "The Lakers have a great history. Do you play any position specifically?", "timestamp": "2024-01-01 10:03:00"},
|
||||||
|
{"speaker": user_name, "message": "I usually play as a point guard. I also started learning guitar last month.", "timestamp": "2024-01-01 10:04:00"},
|
||||||
|
{"speaker": agent_name, "message": "Guitar is a lovely instrument! What kind of music do you want to play?", "timestamp": "2024-01-01 10:05:00"},
|
||||||
|
{"speaker": user_name, "message": "I'm into rock music. My favorite band is Coldplay.", "timestamp": "2024-01-01 10:06:00"},
|
||||||
|
{"speaker": agent_name, "message": "Coldplay has some amazing songs. Do you have a favorite album?", "timestamp": "2024-01-01 10:07:00"},
|
||||||
|
{"speaker": user_name, "message": "I really love 'A Rush of Blood to the Head'. The song 'The Scientist' is my favorite.", "timestamp": "2024-01-01 10:08:00"},
|
||||||
|
{"speaker": agent_name, "message": "That's a classic! Do you also enjoy attending live concerts?", "timestamp": "2024-01-01 10:09:00"},
|
||||||
|
{"speaker": user_name, "message": "Yes! I went to a Coldplay concert last year. It was an amazing experience.", "timestamp": "2024-01-01 10:10:00"},
|
||||||
|
{"speaker": agent_name, "message": "That must have been incredible! Live music is always so energizing.", "timestamp": "2024-01-01 10:11:00"},
|
||||||
|
{"speaker": user_name, "message": "Absolutely! I also enjoy cooking Italian food on weekends.", "timestamp": "2024-01-01 10:12:00"},
|
||||||
|
{"speaker": agent_name, "message": "Italian cuisine is delicious! What's your specialty dish?", "timestamp": "2024-01-01 10:13:00"},
|
||||||
|
{"speaker": user_name, "message": "I make a great homemade pasta with tomato sauce. My family loves it.", "timestamp": "2024-01-01 10:14:00"},
|
||||||
|
{"speaker": agent_name, "message": "That sounds delicious! Cooking for family is always special.", "timestamp": "2024-01-01 10:15:00"},
|
||||||
|
]
|
||||||
|
|
||||||
|
# Add all conversations
|
||||||
|
print("Processing conversations and building memory...")
|
||||||
|
print("-" * 50)
|
||||||
|
|
||||||
|
for conv in conversations:
|
||||||
|
speaker = conv["speaker"]
|
||||||
|
message = conv["message"]
|
||||||
|
timestamp = conv["timestamp"]
|
||||||
|
is_user = (speaker == user_name)
|
||||||
|
|
||||||
|
print(f"{'[User]' if is_user else '[Agent]'} {speaker}: {message[:50]}...")
|
||||||
|
await memory.add_message(message, is_user=is_user, timestamp=timestamp)
|
||||||
|
|
||||||
|
print("-" * 50)
|
||||||
|
print("Conversation processing complete!\n")
|
||||||
|
|
||||||
|
# Update persona memory
|
||||||
|
print("Updating persona memory...")
|
||||||
|
await memory.update_persona()
|
||||||
|
print("Persona memory update complete!\n")
|
||||||
|
|
||||||
|
# Test questions
|
||||||
|
print("=" * 50)
|
||||||
|
print("Memory Retrieval Example")
|
||||||
|
print("=" * 50)
|
||||||
|
|
||||||
|
test_questions = [
|
||||||
|
f"What sport does {user_name} like?",
|
||||||
|
f"What instrument is {user_name} learning?",
|
||||||
|
f"What is {user_name}'s favorite band?",
|
||||||
|
]
|
||||||
|
|
||||||
|
for question in test_questions:
|
||||||
|
print(f"\nQuestion: {question}")
|
||||||
|
print("-" * 40)
|
||||||
|
answer = await memory.query(question)
|
||||||
|
print(f"Answer: {answer}")
|
||||||
|
|
||||||
|
print("\n" + "=" * 50)
|
||||||
|
print("Simplified example run complete!")
|
||||||
|
print("=" * 50)
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== Entry Point ====================
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import sys
|
||||||
|
|
||||||
|
if len(sys.argv) > 1 and sys.argv[1] == "simple":
|
||||||
|
# Run simplified example
|
||||||
|
print("Running simplified example...")
|
||||||
|
asyncio.run(simple_example())
|
||||||
|
else:
|
||||||
|
# Run full example (default)
|
||||||
|
print("Running full example...")
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
# Usage:
|
||||||
|
# python example_usage.py # Run full example
|
||||||
|
# python example_usage.py simple # Run simplified example
|
||||||
|
|
||||||
|
|
||||||
BIN
libs/o-mem/images/image1.png
Normal file
BIN
libs/o-mem/images/image1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 145 KiB |
BIN
libs/o-mem/images/workflow.png
Normal file
BIN
libs/o-mem/images/workflow.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 225 KiB |
66751
libs/o-mem/locomo10.json
Normal file
66751
libs/o-mem/locomo10.json
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,381 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# coding=utf-8
|
||||||
|
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
import json
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
import re
|
||||||
|
import openai
|
||||||
|
import time
|
||||||
|
import tiktoken
|
||||||
|
import os
|
||||||
|
import asyncio
|
||||||
|
import aiofiles
|
||||||
|
from tqdm.asyncio import tqdm_asyncio
|
||||||
|
from memory_chain import *
|
||||||
|
from openai import AsyncOpenAI
|
||||||
|
import yaml
|
||||||
|
import argparse
|
||||||
|
import torch
|
||||||
|
import time
|
||||||
|
from typing import List, Union, Dict
|
||||||
|
from concurrent.futures import ProcessPoolExecutor
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open('config.yaml', 'r') as file:
|
||||||
|
args = yaml.safe_load(file)
|
||||||
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
|
print('Error reading the config file')
|
||||||
|
client = AsyncOpenAI(base_url=args["model"]["openai_base_url"],api_key=args["model"]["openai_api_key"])
|
||||||
|
|
||||||
|
|
||||||
|
def get_timestamp():
|
||||||
|
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
|
||||||
|
|
||||||
|
class ParallelSentenceTransformer:
|
||||||
|
def __init__(self, model: SentenceTransformer):
|
||||||
|
self.model = model
|
||||||
|
# Enable DataParallel only in multi-GPU environment
|
||||||
|
if torch.cuda.device_count() > 1:
|
||||||
|
self.model = torch.nn.DataParallel(model)
|
||||||
|
print(f"Using {torch.cuda.device_count()} GPUs!")
|
||||||
|
else:
|
||||||
|
print("Using single GPU or CPU")
|
||||||
|
|
||||||
|
def encode(self, texts: Union[str, List[str]],
|
||||||
|
batch_size: int = 32,
|
||||||
|
convert_to_tensor: bool = True,
|
||||||
|
**kwargs) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
Multi-GPU friendly encoding method with automatic batching and cross-device processing.
|
||||||
|
Args:
|
||||||
|
texts: Input text (single string or list)
|
||||||
|
batch_size: Batch size per GPU
|
||||||
|
convert_to_tensor: Whether to return tensor
|
||||||
|
"""
|
||||||
|
# Normalize input format
|
||||||
|
if isinstance(texts, str):
|
||||||
|
texts = [texts]
|
||||||
|
|
||||||
|
# Get current device (primary GPU)
|
||||||
|
device = self.model.device_ids[0] if isinstance(self.model, torch.nn.DataParallel) \
|
||||||
|
else next(self.model.parameters()).device
|
||||||
|
|
||||||
|
# Batch processing (avoid single GPU memory overflow)
|
||||||
|
all_embeddings = []
|
||||||
|
for i in range(0, len(texts), batch_size):
|
||||||
|
batch = texts[i:i + batch_size]
|
||||||
|
|
||||||
|
# Tokenization (must be executed on primary GPU)
|
||||||
|
features = self.model.module.tokenize(batch) if hasattr(self.model, 'module') \
|
||||||
|
else self.model.tokenize(batch)
|
||||||
|
features = {k: v.to(device) for k, v in features.items()}
|
||||||
|
|
||||||
|
# Multi-GPU forward propagation
|
||||||
|
with torch.no_grad():
|
||||||
|
outputs = self.model(features)
|
||||||
|
embeddings = outputs['sentence_embedding']
|
||||||
|
all_embeddings.append(embeddings if convert_to_tensor else embeddings.cpu().numpy())
|
||||||
|
|
||||||
|
# Merge results
|
||||||
|
return torch.cat(all_embeddings, dim=0) if convert_to_tensor \
|
||||||
|
else np.concatenate(all_embeddings, axis=0)
|
||||||
|
|
||||||
|
print("Loading embedding model...")
|
||||||
|
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||||
|
embedding_model = ParallelSentenceTransformer(SentenceTransformer("all-MiniLM-L6-v2").to(device))
|
||||||
|
# path = 'your model'
|
||||||
|
# embedding_model = ParallelSentenceTransformer(SentenceTransformer(path).to(device))
|
||||||
|
async def update_user_profile_from_top_segment(mid_mem, long_mem, sample_id, client):
|
||||||
|
|
||||||
|
print("update the profiles of the users.")
|
||||||
|
|
||||||
|
async def generate_system_response_with_memx(query, short_mem, long_mem, retrieval_queue, long_konwledge, client, sample_id, speaker_a, speaker_b, meta_data,no_mtm,no_ltm,no_wm):
|
||||||
|
|
||||||
|
"""
|
||||||
|
These codes are referenced from memory os.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if no_wm == True:
|
||||||
|
history_text = ""
|
||||||
|
else:
|
||||||
|
history = short_mem.get_all()
|
||||||
|
history_text_list = [
|
||||||
|
f"{speaker_a}: {qa.get('user_input', '')}\n{speaker_b}: {qa.get('agent_response', '')}\nTime: ({qa.get('timestamp', '')})"
|
||||||
|
for qa in history]
|
||||||
|
|
||||||
|
if no_mtm == True:
|
||||||
|
retrieval_text = ""
|
||||||
|
else:
|
||||||
|
retrieval_text = "\n".join([
|
||||||
|
f"【Historical Memory】 {speaker_a}: {page.get('user_input', '')}\n{speaker_b}: {page.get('agent_response', '')}\nTime:({page.get('timestamp', '')})\nConversation chain overview:({page.get('meta_info', '')})\n"
|
||||||
|
for page in retrieval_queue])
|
||||||
|
|
||||||
|
if no_ltm == True:
|
||||||
|
user_profile_text = ""
|
||||||
|
else:
|
||||||
|
profile_obj = long_mem.get_user_profile(sample_id)
|
||||||
|
user_profile_text = str(profile_obj.get("data", "None")) if profile_obj else "None"
|
||||||
|
|
||||||
|
background = f"【User Profile】\n{user_profile_text}\n\n"
|
||||||
|
for kn in long_konwledge:
|
||||||
|
background += f"{kn['knowledge']}\n"
|
||||||
|
background = re.sub(r'(?i)\buser\b', speaker_a, background)
|
||||||
|
background= re.sub(r'(?i)\bassistant\b', speaker_b, background)
|
||||||
|
assistant_knowledge = long_mem.get_assistant_knowledge()
|
||||||
|
assistant_knowledge_text = "【Assistant Knowledge】\n"
|
||||||
|
for ak in assistant_knowledge:
|
||||||
|
assistant_knowledge_text += f"- {ak['knowledge']} ({ak['timestamp']})\n"
|
||||||
|
|
||||||
|
assistant_knowledge_text = re.sub(r'\bI\b', speaker_b, assistant_knowledge_text)
|
||||||
|
|
||||||
|
system_prompt = (
|
||||||
|
f"You are role-playing as {speaker_b} in a conversation with the user is playing is {speaker_a}. "
|
||||||
|
f"Here are some of your character traits and knowledge:\n{assistant_knowledge_text}\n"
|
||||||
|
f"Any content referring to 'User' in the prompt refers to {speaker_a}'s content, and any content referring to 'AI'or 'assiant' refers to {speaker_b}'s content."
|
||||||
|
f"Your task is to answer questions about {speaker_a} or {speaker_b} in an extremely concise manner.\n"
|
||||||
|
f"When the question is: \"What did the charity race raise awareness for?\", you should not answer in the form of: \"The charity race raised awareness for mental health.\" Instead, it should be: \"mental health\", as this is more concise."
|
||||||
|
)
|
||||||
|
|
||||||
|
user_prompt = (
|
||||||
|
f"<CONTEXT>\n"
|
||||||
|
f"Recent conversation between {speaker_a} and {speaker_b}:\n"
|
||||||
|
f"{history_text}\n\n"
|
||||||
|
f"<MEMORY>\n"
|
||||||
|
f"Relevant past conversations:\n"
|
||||||
|
f"{retrieval_text}\n\n"
|
||||||
|
f"<CHARACTER TRAITS>\n"
|
||||||
|
f"Characteristics of {speaker_a}:\n"
|
||||||
|
f"{background}\n\n"
|
||||||
|
f"the question is: {query}\n"
|
||||||
|
f"Your task is to answer questions about {speaker_a} or {speaker_b} in an extremely concise manner.\n"
|
||||||
|
f"Please only provide the content of the answer, without including 'answer:'\n"
|
||||||
|
f"For questions that require answering a date or time, strictly follow the format \"15 July 2023\" and provide a specific date whenever possible. For example, if you need to answer \"last year,\" give the specific year of last year rather than just saying \"last year.\" Only provide one year, date, or time, without any extra responses.\n"
|
||||||
|
f"If the question is about the duration, answer in the form of several years, months, or days.\n"
|
||||||
|
f"Generate answers primarily composed of concrete entities, such as Mentoring program, school speech, etc"
|
||||||
|
)
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": system_prompt},
|
||||||
|
{"role": "user", "content": user_prompt}
|
||||||
|
]
|
||||||
|
|
||||||
|
response = await client.chat_completion(model="gpt-4o-mini", messages=messages, temperature=0.7, max_tokens=2000)
|
||||||
|
return response, system_prompt, user_prompt
|
||||||
|
|
||||||
|
def process_conversation(conversation_data):
|
||||||
|
|
||||||
|
"""
|
||||||
|
These codes are referenced from memory os.
|
||||||
|
Process conversation data from locomo10 format into memory system format.
|
||||||
|
Handles both text-only and image-containing messages.
|
||||||
|
"""
|
||||||
|
|
||||||
|
processed = []
|
||||||
|
speaker_a = conversation_data["speaker_a"]
|
||||||
|
speaker_b = conversation_data["speaker_b"]
|
||||||
|
|
||||||
|
session_keys = [key for key in conversation_data.keys() if key.startswith("session_") and not key.endswith("_date_time")]
|
||||||
|
|
||||||
|
for session_key in session_keys:
|
||||||
|
|
||||||
|
timestamp_key = f"{session_key}_date_time"
|
||||||
|
timestamp = conversation_data.get(timestamp_key, "")
|
||||||
|
|
||||||
|
for dialog in conversation_data[session_key]:
|
||||||
|
|
||||||
|
speaker = dialog["speaker"]
|
||||||
|
text = dialog["text"]
|
||||||
|
|
||||||
|
if "blip_caption" in dialog and dialog["blip_caption"]:
|
||||||
|
text = f"{text} (image description: {dialog['blip_caption']})"
|
||||||
|
|
||||||
|
if speaker == speaker_a:
|
||||||
|
processed.append({speaker_a: text,"timestamp": timestamp})
|
||||||
|
else:
|
||||||
|
processed.append({speaker_b: text, "timestamp": timestamp})
|
||||||
|
|
||||||
|
return processed
|
||||||
|
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
def find_agent_memory_file(directory, idx):
|
||||||
|
|
||||||
|
pattern = re.compile(rf'^.*_agent_working_memory_{idx}\.json$')
|
||||||
|
for filename in os.listdir(directory):
|
||||||
|
if pattern.match(filename):
|
||||||
|
return os.path.join(directory,filename)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def find_user_memory_file(directory, idx):
|
||||||
|
|
||||||
|
pattern = re.compile(rf'^.*_user_working_memory_{idx}\.json$')
|
||||||
|
for filename in os.listdir(directory):
|
||||||
|
if pattern.match(filename):
|
||||||
|
return os.path.join(directory,filename)
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def run_locomo_experiment(idx,args,cmd_args,client):
|
||||||
|
|
||||||
|
os.makedirs("mem_tmp_loco_final", exist_ok=True)
|
||||||
|
try:
|
||||||
|
with open("locomo10.json", "r", encoding="utf-8") as f:
|
||||||
|
dataset = json.load(f)
|
||||||
|
except FileNotFoundError:
|
||||||
|
print("Error: locomo10.json file not found, please ensure it is in the current directory")
|
||||||
|
return
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error loading dataset: {e}")
|
||||||
|
return
|
||||||
|
|
||||||
|
output_file = cmd_args.response_output_dir+"/HippoIndex_results_"+str(idx)+".json"
|
||||||
|
results = []
|
||||||
|
total_samples = len(dataset)
|
||||||
|
sample = dataset[idx]
|
||||||
|
|
||||||
|
print(f"Processing sample {idx + 1}/{total_samples}: {sample.get('sample_id', 'unknown')}")
|
||||||
|
|
||||||
|
sample_id = sample.get("sample_id", "unknown_sample")
|
||||||
|
conversation_data = sample["conversation"]
|
||||||
|
qa_pairs = sample["qa"]
|
||||||
|
qa_count = len(qa_pairs)
|
||||||
|
processed_dialogs = process_conversation(conversation_data)
|
||||||
|
|
||||||
|
print(f"This sample has {len(processed_dialogs)} dialog turns")
|
||||||
|
print(f"This sample has {len(qa_pairs)} questions")
|
||||||
|
|
||||||
|
if not processed_dialogs:
|
||||||
|
print(f"Sample {sample_id} has no valid conversation data, skipping")
|
||||||
|
return
|
||||||
|
|
||||||
|
speaker_a = conversation_data["speaker_a"]
|
||||||
|
speaker_b = conversation_data["speaker_b"]
|
||||||
|
|
||||||
|
memory_dir = cmd_args.output_dir
|
||||||
|
|
||||||
|
memory_system = MemoryChain(memory_index=idx, llm_model=args["model"]["llm_model"],llm_client = client,embedding_model = embedding_model,
|
||||||
|
user_name= speaker_a, agent_name = speaker_b, cmd_args=cmd_args, args=args, memory_dir = memory_dir)
|
||||||
|
|
||||||
|
memory_manager = MemoryManager(memory_index=idx, memory_system=memory_system,llm_model=args["model"]["llm_model"],llm_client = client,
|
||||||
|
embedding_model = embedding_model,user_name= speaker_a, agent_name = speaker_b, cmd_args=cmd_args, args=args, memory_dir = memory_dir)
|
||||||
|
|
||||||
|
if cmd_args.use_all_memory_cache:
|
||||||
|
await memory_system.read_cache_memory(cmd_args.memory_cache_path)
|
||||||
|
memory_system.generate_memory_detail_map()
|
||||||
|
print("Memory system load cache memory finish")
|
||||||
|
# qa_count = len(qa_pairs)
|
||||||
|
else:
|
||||||
|
print("Stage 1: We indexing the memory base.")
|
||||||
|
for index,dialog in enumerate(processed_dialogs):
|
||||||
|
timestamp = get_timestamp()
|
||||||
|
if speaker_a in dialog:
|
||||||
|
user_speak = True
|
||||||
|
start_time = time.time()
|
||||||
|
await memory_manager.receive_message(message = dialog[speaker_a], client=client,index=index,timestamp=dialog["timestamp"], user_speak=user_speak)
|
||||||
|
end_time = time.time() # Record end time
|
||||||
|
elapsed = end_time - start_time # Calculate elapsed time (seconds)
|
||||||
|
print(f"Receive one new message took: {elapsed:.4f} seconds")
|
||||||
|
else:
|
||||||
|
user_speak = False
|
||||||
|
start_time = time.time()
|
||||||
|
await memory_manager.receive_message(message = dialog[speaker_b],client=client,index=index,timestamp=dialog["timestamp"],user_speak = user_speak)
|
||||||
|
end_time = time.time() # Record end time
|
||||||
|
elapsed = end_time - start_time # Calculate elapsed time (seconds)
|
||||||
|
print(f"Receive one new message took: {elapsed:.4f} seconds")
|
||||||
|
|
||||||
|
await memory_system.agent_persona_memory.update_preference_persona(memory_system.agent_episodic_memory.topic_episodic_memory_list)
|
||||||
|
await memory_system.agent_persona_memory.update_attribute_persona(memory_system.agent_episodic_memory.attribute_episodic_memory_dict)
|
||||||
|
await memory_system.user_persona_memory.update_preference_persona(memory_system.user_episodic_memory.topic_episodic_memory_list)
|
||||||
|
await memory_system.user_persona_memory.update_attribute_persona(memory_system.user_episodic_memory.attribute_episodic_memory_dict)
|
||||||
|
return
|
||||||
|
|
||||||
|
for qa_idx, qa in enumerate(qa_pairs):
|
||||||
|
|
||||||
|
start_time = time.time()
|
||||||
|
print(f"Processing QA {qa_idx + 1}/{qa_count}")
|
||||||
|
|
||||||
|
question = qa["question"]
|
||||||
|
original_answer = qa.get("answer", "")
|
||||||
|
category = qa["category"]
|
||||||
|
evidence = qa.get("evidence", "")
|
||||||
|
|
||||||
|
if(original_answer == ""):
|
||||||
|
# continue
|
||||||
|
original_answer = qa.get("adversarial_answer", "")
|
||||||
|
|
||||||
|
# retrieval_result, user_name, agent_name = memory_manager.retrieve_from_memory_soft_segmentation_v5(question,cmd_args.number_of_retrieval_pieces,cmd_args.drop_threshold)
|
||||||
|
retrieval_result, user_name, agent_name,peak_memory_number,peak_memory_number_increase = memory_manager.retrieve_from_memory_soft_segmentation(question,cmd_args.number_of_retrieval_pieces,cmd_args.drop_threshold)
|
||||||
|
# retrieval_result, user_name, agent_name,peak_memory_number,peak_memory_number_increase = memory_manager.retrieve_from_memory_soft_segmentation_v9_ablation_study(question,cmd_args.number_of_retrieval_pieces,cmd_args.drop_threshold)
|
||||||
|
answer,tokens_consumption = await memory_manager.generate_system_response(question,retrieval_result,client,user_name,agent_name,args["model"]["llm_model"])
|
||||||
|
end_time = time.time()
|
||||||
|
elapsed_time = end_time - start_time
|
||||||
|
|
||||||
|
|
||||||
|
results.append({"time":elapsed_time,"sample_id": sample_id,"user": user_name,"agent": agent_name,"question": question,"answer":answer,"reference_answer": original_answer,"category": category,
|
||||||
|
"evidence": evidence,"persona attributes":retrieval_result["persona attributes"],"fact scores":retrieval_result["fact scores"],"persona facts": retrieval_result["persona facts"],
|
||||||
|
"retrieved context messages":retrieval_result["retrieved context messages"],"fact recovery num":retrieval_result["recover facts num"],"ignored details keywords": retrieval_result["ignored_details_keywords"],
|
||||||
|
"ignored facts":retrieval_result["ignored_facts"],"keyword distribution dict":retrieval_result["keyword distribution dict"],"keyword message":retrieval_result["keyword message"],"original retrievals":retrieval_result["original context message"],"token consumption":tokens_consumption,
|
||||||
|
"peak memory":peak_memory_number,"peak_memory_number_increase":peak_memory_number_increase})
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(output_file, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(results, f, ensure_ascii=False, indent=2)
|
||||||
|
print(f"Sample {idx + 1} processing complete, results saved to {output_file}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error saving results: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
print(f"Final error saving results: {e}")
|
||||||
|
async def run_one(idx,args,cmd_args,client):
|
||||||
|
|
||||||
|
async with semaphore:
|
||||||
|
result = await run_locomo_experiment(idx=idx,args=args,cmd_args=cmd_args,client=client)
|
||||||
|
return result
|
||||||
|
|
||||||
|
semaphore = asyncio.Semaphore(10)
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description='Command line arguments')
|
||||||
|
parser.add_argument('--working_memory_max_size',type=int, default=20, help = 'the maximum size of the working memory')
|
||||||
|
parser.add_argument('--episodic_memory_refresh_rate',type=int, default=5, help = 'the rate ti refresh episodic memory')
|
||||||
|
parser.add_argument('--output_dir',type=str, default="./test_locomo") # 1. Memory generation directory
|
||||||
|
parser.add_argument('--response_output_dir',type=str, default="./responses_locomo") # 2. Results output
|
||||||
|
parser.add_argument('--use_all_memory_cache',type=bool, default=False) # 1.False(start generate mem) 2. True (start retireval)
|
||||||
|
parser.add_argument('--memory_cache_path',type=str, default="./test_locomo")
|
||||||
|
parser.add_argument('--message_understanding_cache',type=bool, default=False) # This is to save money and keep efficiency
|
||||||
|
parser.add_argument('--message_understanding_cache_path',type=str, default="./memory_cache")
|
||||||
|
parser.add_argument('--number_of_retrieval_pieces',type=int, default=10)
|
||||||
|
parser.add_argument('--drop_threshold',type=float, default=0.1)
|
||||||
|
cmd_args = parser.parse_args()
|
||||||
|
tasks = [run_one(idx=p_id, args = args, cmd_args=cmd_args, client=client) for p_id in range(10)]
|
||||||
|
|
||||||
|
import shutil
|
||||||
|
dir_path = cmd_args.output_dir
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
shutil.rmtree(cmd_args.response_output_dir)
|
||||||
|
except:
|
||||||
|
print("No target output folder.")
|
||||||
|
os.mkdir(cmd_args.response_output_dir)
|
||||||
|
|
||||||
|
results = await tqdm_asyncio.gather(*tasks, total=len(tasks))
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
20
libs/o-mem/memory_chain/__init__.py
Normal file
20
libs/o-mem/memory_chain/__init__.py
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# coding=utf-8
|
||||||
|
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
from .memory_manager import *
|
||||||
|
from .episodic_memory import *
|
||||||
|
from .working_memory import *
|
||||||
|
from .persona_memory import *
|
||||||
|
from .memory import *
|
||||||
273
libs/o-mem/memory_chain/episodic_memory.py
Normal file
273
libs/o-mem/memory_chain/episodic_memory.py
Normal file
|
|
@ -0,0 +1,273 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# coding=utf-8
|
||||||
|
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
import json
|
||||||
|
import numpy as np
|
||||||
|
from collections import deque
|
||||||
|
from .utils import *
|
||||||
|
from .prompts import *
|
||||||
|
from FlagEmbedding import FlagAutoModel
|
||||||
|
from sentence_transformers import SentenceTransformer
|
||||||
|
from itertools import combinations
|
||||||
|
from collections import defaultdict
|
||||||
|
import re
|
||||||
|
from collections import defaultdict
|
||||||
|
import re
|
||||||
|
from collections import OrderedDict
|
||||||
|
import random
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.WARNING) #
|
||||||
|
logging.getLogger("FlagEmbedding").setLevel(logging.CRITICAL + 1)
|
||||||
|
logging.getLogger("FlagEmbedding").propagate = False
|
||||||
|
|
||||||
|
class Episodic_Memory:
|
||||||
|
|
||||||
|
def __init__(self,event_episodic_memory_path,topic_episodic_memory_path,ep_cache_list_path ,attribute_episodic_memory_path,fact_episodic_memory_path,
|
||||||
|
user_id,client,llm_model, embedding_model,cmd_args, args):
|
||||||
|
|
||||||
|
self.user_id = user_id
|
||||||
|
self.client = client
|
||||||
|
self.model = llm_model
|
||||||
|
self.embedding_model = embedding_model
|
||||||
|
self.cmd_args = cmd_args
|
||||||
|
self.args = args
|
||||||
|
|
||||||
|
self.episodic_memory_cache_list = [] # Episodic memory cache for storing working memory.
|
||||||
|
self.event_episodic_memory_dict = {} # Episodic memory dictionary concerning different events (e.g., A note-taking experience)
|
||||||
|
self.topic_episodic_memory_list = [] # Episodic memory list concerning different event topics (e.g, multiple times of note-taking experience)
|
||||||
|
self.attribute_episodic_memory_dict = {} # Episodic memory list concerning different attributes of the user
|
||||||
|
self.fact_episodic_memory_dict = {} #Episodic memory list concerning different facts of the user
|
||||||
|
|
||||||
|
self.event_episodic_memory_path = event_episodic_memory_path
|
||||||
|
self.topic_episodic_memory_path = topic_episodic_memory_path
|
||||||
|
self.episodic_memory_cache_list_path = ep_cache_list_path
|
||||||
|
self.attribute_episodic_memory_path = attribute_episodic_memory_path
|
||||||
|
self.fact_episodic_memory_path = fact_episodic_memory_path
|
||||||
|
|
||||||
|
ensure_directory_exists(self.event_episodic_memory_path)
|
||||||
|
ensure_directory_exists(self.topic_episodic_memory_path)
|
||||||
|
ensure_directory_exists(self.episodic_memory_cache_list_path)
|
||||||
|
ensure_directory_exists(self.attribute_episodic_memory_path)
|
||||||
|
ensure_directory_exists(self.fact_episodic_memory_path)
|
||||||
|
|
||||||
|
async def evolve_event_episodic_memory(self,message_understanding,action,target):
|
||||||
|
|
||||||
|
self.episodic_memory_cache_list.append(message_understanding)
|
||||||
|
self._save_wm_cache_episodic_memory()
|
||||||
|
|
||||||
|
index = message_understanding["index"]
|
||||||
|
|
||||||
|
if action.upper() == "UPDATE" or action.upper() == "IGNORE":
|
||||||
|
self.event_episodic_memory_dict[target] += "The "+ str(index)+" round message: "+ message_understanding["emotions"]+"; "
|
||||||
|
if action.upper() == "ADD":
|
||||||
|
self.event_episodic_memory_dict[message_understanding["topics"]] = "The "+ str(index)+" round attitude: "+ message_understanding["emotions"]+"; "
|
||||||
|
|
||||||
|
self._save_event_episodic_memory()
|
||||||
|
|
||||||
|
async def evolve_fact_episodic_memory(self,message_understanding,action,target):
|
||||||
|
|
||||||
|
index = message_understanding["index"]
|
||||||
|
|
||||||
|
if action.upper() == "UPDATE" or action.upper() == "IGNORE":
|
||||||
|
self.fact_episodic_memory_dict[target] += "The "+ str(index)+" round fact: "+ message_understanding["fact"]+"; "
|
||||||
|
if action.upper() == "ADD":
|
||||||
|
self.fact_episodic_memory_dict[message_understanding["fact"]] = "The "+ str(index)+" round fact: "+ message_understanding["fact"]+"; "
|
||||||
|
|
||||||
|
self._save_fact_episodic_memory()
|
||||||
|
|
||||||
|
async def evolve_attr_episodic_memory(self,message_attribute,action,target,message_index):
|
||||||
|
|
||||||
|
index = message_index
|
||||||
|
|
||||||
|
if action.upper() == "UPDATE" or action.upper() == "IGNORE":
|
||||||
|
self.attribute_episodic_memory_dict[target] += "The "+ str(index)+" round attribute: "+ message_attribute +"; "
|
||||||
|
if action.upper() == "ADD":
|
||||||
|
self.attribute_episodic_memory_dict[message_attribute] = "The "+ str(index)+" round attribute: "+ message_attribute +"; "
|
||||||
|
|
||||||
|
self._save_attr_episodic_memory()
|
||||||
|
|
||||||
|
async def evolve_topic_episodic_memory(self):
|
||||||
|
|
||||||
|
self.topic_episodic_memory_list = []
|
||||||
|
event_episodic_memory_dict_keys = list(self.event_episodic_memory_dict.keys())
|
||||||
|
topic_clusters = self.cluster_related_topics(self.find_top_similar_keys(event_episodic_memory_dict_keys, self.embedding_model))
|
||||||
|
grouped_em_results = [] # Divide the episodic memory into groups.
|
||||||
|
|
||||||
|
for cluster in topic_clusters:
|
||||||
|
|
||||||
|
message = {}
|
||||||
|
for event_name in cluster:
|
||||||
|
message[event_name] = self.value_find_topic(self.episodic_memory_cache_list,event_name) # How to deal with this part ?
|
||||||
|
|
||||||
|
# print(message)
|
||||||
|
episodic_memory_merge_message = [{"role": "system", "content": Preference_Merge_System_PROMPT},{"role": "user", "content": Preference_Merge_User_PROMPT.format(Topic_Groups=str(message))}]
|
||||||
|
|
||||||
|
response = ""
|
||||||
|
while response == "":
|
||||||
|
try:
|
||||||
|
response = await self.client.chat.completions.create(model=self.model, messages = episodic_memory_merge_message, temperature = 0.3)
|
||||||
|
current_results = json.loads(response.choices[0].message.content)
|
||||||
|
for group_name in current_results["Grouped Topics"].keys():
|
||||||
|
current_dict_result = {}
|
||||||
|
current_dict_result["group_name"] = group_name
|
||||||
|
for event in current_results["Grouped Topics"][group_name]:
|
||||||
|
current_dict_result[event] = self.event_episodic_memory_dict[event]
|
||||||
|
pattern = r"The (\d+) round (?:attitude|message):.*?(Positive|Negative)"
|
||||||
|
result = {}
|
||||||
|
for key,value in current_dict_result.items():
|
||||||
|
matches = re.findall(pattern, str(value))
|
||||||
|
for round_num, attitude in matches:
|
||||||
|
result[int(round_num)] = attitude + " "+ self.value_find_index(self.episodic_memory_cache_list,str(round_num)) # 转为整数便于排序
|
||||||
|
sorted_result = OrderedDict(sorted(result.items()))
|
||||||
|
current_dict_result["Overall Attitude"]= sorted_result
|
||||||
|
self.topic_episodic_memory_list.append(current_dict_result)
|
||||||
|
except Exception as e:
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
response == ""
|
||||||
|
print(f"Error generating profile: {str(e)}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
self._save_topic_episodic_memory()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _save_event_episodic_memory(self):
|
||||||
|
|
||||||
|
with open(self.event_episodic_memory_path,'w') as f:
|
||||||
|
json.dump(self.event_episodic_memory_dict, f, indent=4)
|
||||||
|
|
||||||
|
def _save_fact_episodic_memory(self):
|
||||||
|
|
||||||
|
with open(self.fact_episodic_memory_path,'w') as f:
|
||||||
|
json.dump(self.fact_episodic_memory_dict, f, indent=4)
|
||||||
|
|
||||||
|
def _save_attr_episodic_memory(self):
|
||||||
|
|
||||||
|
with open(self.attribute_episodic_memory_path,'w') as f:
|
||||||
|
json.dump(self.attribute_episodic_memory_dict, f, indent=4)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _save_topic_episodic_memory(self):
|
||||||
|
|
||||||
|
with open(self.topic_episodic_memory_path,'w') as f:
|
||||||
|
json.dump(self.topic_episodic_memory_list, f, indent=4)
|
||||||
|
|
||||||
|
def _save_wm_cache_episodic_memory(self):
|
||||||
|
|
||||||
|
with open(self.episodic_memory_cache_list_path,'w') as f:
|
||||||
|
json.dump(self.episodic_memory_cache_list, f, indent=4)
|
||||||
|
|
||||||
|
def find_top_similar_keys(self,all_keys, embedding_model):
|
||||||
|
|
||||||
|
key_embeddings = embedding_model.encode(all_keys)
|
||||||
|
key_pairs = list(combinations(range(len(all_keys)), 2))
|
||||||
|
best_matches = {}
|
||||||
|
|
||||||
|
for i, j in key_pairs:
|
||||||
|
key1 = all_keys[i]
|
||||||
|
key2 = all_keys[j]
|
||||||
|
sim = float(key_embeddings[i] @ key_embeddings[j].T)
|
||||||
|
if key1 not in best_matches or sim > best_matches[key1]['similarity']:
|
||||||
|
best_matches[key1] = {'key1': key1, 'key2': key2, 'similarity': sim}
|
||||||
|
if key2 not in best_matches or sim > best_matches[key2]['similarity']:
|
||||||
|
best_matches[key2] = {'key1': key2, 'key2': key1, 'similarity': sim}
|
||||||
|
|
||||||
|
results = list(best_matches.values())
|
||||||
|
results.sort(key=lambda x: x['similarity'], reverse=True)
|
||||||
|
return results
|
||||||
|
|
||||||
|
def cluster_related_topics(self,data):
|
||||||
|
|
||||||
|
parent = {}
|
||||||
|
def find(node):
|
||||||
|
if parent[node] != node:
|
||||||
|
parent[node] = find(parent[node])
|
||||||
|
return parent[node]
|
||||||
|
def union(node1, node2):
|
||||||
|
root1 = find(node1)
|
||||||
|
root2 = find(node2)
|
||||||
|
if root1 != root2:
|
||||||
|
parent[root2] = root1
|
||||||
|
|
||||||
|
for item in data:
|
||||||
|
key1, key2 = item['key1'], item['key2']
|
||||||
|
if key1 not in parent:
|
||||||
|
parent[key1] = key1
|
||||||
|
if key2 not in parent:
|
||||||
|
parent[key2] = key2
|
||||||
|
|
||||||
|
for item in data:
|
||||||
|
key1, key2 = item['key1'], item['key2']
|
||||||
|
union(key1, key2)
|
||||||
|
|
||||||
|
clusters = defaultdict(list)
|
||||||
|
for node in parent:
|
||||||
|
clusters[find(node)].append(node)
|
||||||
|
|
||||||
|
result = [cluster for cluster in clusters.values() if len(cluster) > 1]
|
||||||
|
|
||||||
|
return result
|
||||||
|
def value_find_topic(self,dict_list,target_value):
|
||||||
|
|
||||||
|
for item in dict_list:
|
||||||
|
if item["topics"] == target_value:
|
||||||
|
return item["message"]
|
||||||
|
def value_find_index(self,dict_list,target_value):
|
||||||
|
|
||||||
|
for item in dict_list:
|
||||||
|
if item["index"] == target_value:
|
||||||
|
return item["message"]
|
||||||
|
|
||||||
|
for item in dict_list:
|
||||||
|
if item["index"] == int(target_value):
|
||||||
|
return item["message"]
|
||||||
|
|
||||||
|
|
||||||
|
def read_cache(self,topic_episodic_path,event_episodic_path,episodic_cache_path,fact_episodic_path,attr_episodic_path):
|
||||||
|
|
||||||
|
print(topic_episodic_path)
|
||||||
|
print(event_episodic_path)
|
||||||
|
print(episodic_cache_path)
|
||||||
|
print(fact_episodic_path)
|
||||||
|
print(attr_episodic_path)
|
||||||
|
|
||||||
|
with open(topic_episodic_path, 'r', encoding='utf-8') as f:
|
||||||
|
self.topic_episodic_memory_list = json.load(f)
|
||||||
|
|
||||||
|
with open(event_episodic_path,'r', encoding='utf-8') as f:
|
||||||
|
self.event_episodic_memory_dict = json.load(f)
|
||||||
|
|
||||||
|
with open(episodic_cache_path,'r', encoding='utf-8') as f:
|
||||||
|
self.episodic_memory_cache_list = json.load(f)
|
||||||
|
|
||||||
|
with open(fact_episodic_path,'r', encoding='utf-8') as f:
|
||||||
|
self.fact_episodic_memory_dict = json.load(f)
|
||||||
|
|
||||||
|
with open(attr_episodic_path,'r', encoding='utf-8') as f:
|
||||||
|
self.attribute_episodic_memory_dict = json.load(f)
|
||||||
|
|
||||||
|
self._save_event_episodic_memory()
|
||||||
|
self._save_topic_episodic_memory()
|
||||||
|
self._save_wm_cache_episodic_memory()
|
||||||
|
self._save_attr_episodic_memory()
|
||||||
|
self._save_fact_episodic_memory()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
596
libs/o-mem/memory_chain/memory.py
Normal file
596
libs/o-mem/memory_chain/memory.py
Normal file
|
|
@ -0,0 +1,596 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# coding=utf-8
|
||||||
|
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
from .utils import *
|
||||||
|
|
||||||
|
from .prompts import *
|
||||||
|
from .memory_manager import *
|
||||||
|
from .persona_memory import *
|
||||||
|
from .working_memory import *
|
||||||
|
from .memory_manager import *
|
||||||
|
from .episodic_memory import *
|
||||||
|
from datetime import datetime
|
||||||
|
import string
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
# Heat threshold for triggering profile/knowledge update from mid-term memory
|
||||||
|
H_PROFILE_UPDATE_THRESHOLD = 5.0
|
||||||
|
DEFAULT_ASSISTANT_ID = "default_assistant_profile"
|
||||||
|
|
||||||
|
def get_current_time():
|
||||||
|
now = datetime.now()
|
||||||
|
local_time_str = now.strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
return local_time_str
|
||||||
|
|
||||||
|
class MemoryChain:
|
||||||
|
|
||||||
|
def __init__(self,memory_index,llm_model,llm_client,embedding_model,user_name,agent_name,args,cmd_args,memory_dir):
|
||||||
|
|
||||||
|
|
||||||
|
self.idx = memory_index
|
||||||
|
self.args = args
|
||||||
|
self.cmd_args = cmd_args
|
||||||
|
self.client = llm_client
|
||||||
|
self.llm_model = llm_model
|
||||||
|
self.embedding_model = embedding_model
|
||||||
|
self.user_name = user_name
|
||||||
|
self.agent_name = agent_name
|
||||||
|
self.memory_dir = memory_dir
|
||||||
|
current_time = get_current_time()
|
||||||
|
|
||||||
|
self.user_topic_message_dict = {}
|
||||||
|
self.agent_topic_message_dict = {}
|
||||||
|
self.user_detail_dict = defaultdict(list)
|
||||||
|
self.agent_detail_dict = defaultdict(list)
|
||||||
|
|
||||||
|
|
||||||
|
print("The No."+str(self.idx)+" sample "+user_name+" and "+ agent_name+ "'s memory system has been established")
|
||||||
|
|
||||||
|
user_working_memory_path = os.path.join(self.memory_dir, "user_working_memory_"+str(self.idx)+".json") # User working memory
|
||||||
|
agent_working_memory_path = os.path.join(self.memory_dir, "agent_working_memory_"+str(self.idx)+".json") # Agent working memory
|
||||||
|
|
||||||
|
user_event_episodic_memory_path = os.path.join(self.memory_dir, "user_event_episodic_memory_"+str(self.idx)+".json")
|
||||||
|
agent_event_episodic_memory_path = os.path.join(self.memory_dir, "agent_event_episodic_memory_"+str(self.idx)+".json")
|
||||||
|
|
||||||
|
user_fact_episodic_memory_path = os.path.join(self.memory_dir, "user_fact_episodic_memory_"+str(self.idx)+".json")
|
||||||
|
agent_fact_episodic_memory_path = os.path.join(self.memory_dir, "agent_fact_episodic_memory_"+str(self.idx)+".json")
|
||||||
|
|
||||||
|
user_attribute_episodic_memory_path = os.path.join(self.memory_dir, "user_attribute_episodic_memory_"+str(self.idx)+".json")
|
||||||
|
agent_attribute_episodic_memory_path = os.path.join(self.memory_dir, "agent_attribute_episodic_memory_"+str(self.idx)+".json")
|
||||||
|
|
||||||
|
user_topic_episodic_memory_path = os.path.join(self.memory_dir, "user_topic_episodic_memory_"+str(self.idx)+".json")
|
||||||
|
agent_topic_episodic_memory_path = os.path.join(self.memory_dir, "agent_topic_episodic_memory_"+str(self.idx)+".json")
|
||||||
|
|
||||||
|
user_episodic_memory_wm_cache_path = os.path.join(self.memory_dir, "user_wm_cache_episodic_memory_"+str(self.idx)+".json")
|
||||||
|
agent_episodic_memory_wm_cache_path = os.path.join(self.memory_dir, "agent_wm_cache_episodic_memory_"+str(self.idx)+".json")
|
||||||
|
|
||||||
|
user_persona_memory_preference_path = os.path.join(self.memory_dir, "user_persona_memory_preference_"+str(self.idx)+".json")
|
||||||
|
agent_persona_memory_preference_path = os.path.join(self.memory_dir, "agent_persona_memory_preference_"+str(self.idx)+".json")
|
||||||
|
|
||||||
|
user_persona_memory_fact_path = os.path.join(self.memory_dir, "user_persona_memory_fact_"+str(self.idx)+".json")
|
||||||
|
agent_persona_memory_fact_path = os.path.join(self.memory_dir, "agent_persona_memory_fact_"+str(self.idx)+".json")
|
||||||
|
|
||||||
|
user_persona_memory_attr_path = os.path.join(self.memory_dir, "user_persona_memory_attr_"+str(self.idx)+".json")
|
||||||
|
agent_persona_memory_attr_path = os.path.join(self.memory_dir, "agent_persona_memory_attr_"+str(self.idx)+".json")
|
||||||
|
|
||||||
|
self.user_memory_detail_path = os.path.join(self.memory_dir, "user_detail_"+str(self.idx)+".json")
|
||||||
|
self.agent_memory_detail_path = os.path.join(self.memory_dir, "agent_detail_"+str(self.idx)+".json")
|
||||||
|
|
||||||
|
ensure_directory_exists(user_working_memory_path)
|
||||||
|
ensure_directory_exists(agent_working_memory_path)
|
||||||
|
ensure_directory_exists(user_event_episodic_memory_path)
|
||||||
|
ensure_directory_exists(agent_event_episodic_memory_path)
|
||||||
|
ensure_directory_exists(user_topic_episodic_memory_path)
|
||||||
|
ensure_directory_exists(agent_topic_episodic_memory_path)
|
||||||
|
ensure_directory_exists(user_episodic_memory_wm_cache_path)
|
||||||
|
ensure_directory_exists(agent_episodic_memory_wm_cache_path )
|
||||||
|
ensure_directory_exists(user_persona_memory_preference_path)
|
||||||
|
ensure_directory_exists(agent_persona_memory_preference_path)
|
||||||
|
ensure_directory_exists(user_persona_memory_fact_path)
|
||||||
|
ensure_directory_exists(agent_persona_memory_fact_path)
|
||||||
|
ensure_directory_exists(user_fact_episodic_memory_path)
|
||||||
|
ensure_directory_exists(user_attribute_episodic_memory_path)
|
||||||
|
ensure_directory_exists(agent_fact_episodic_memory_path )
|
||||||
|
ensure_directory_exists(agent_attribute_episodic_memory_path)
|
||||||
|
|
||||||
|
self.user_working_memory = Working_Memory(working_memory_path = user_working_memory_path, user_id = self.user_name, model=self.llm_model,
|
||||||
|
working_memory_max_size = cmd_args.working_memory_max_size, client=self.client,refresh_rate= cmd_args.episodic_memory_refresh_rate)
|
||||||
|
|
||||||
|
self.agent_working_memory = Working_Memory(working_memory_path = agent_working_memory_path, user_id = self.agent_name, model=self.llm_model,
|
||||||
|
working_memory_max_size = cmd_args.working_memory_max_size, client=self.client,refresh_rate= cmd_args.episodic_memory_refresh_rate)
|
||||||
|
|
||||||
|
self.user_episodic_memory = Episodic_Memory(event_episodic_memory_path = user_event_episodic_memory_path, topic_episodic_memory_path = user_topic_episodic_memory_path,
|
||||||
|
ep_cache_list_path = user_episodic_memory_wm_cache_path, user_id = user_name, client = self.client, llm_model = self.llm_model, embedding_model = self.embedding_model,
|
||||||
|
fact_episodic_memory_path = user_fact_episodic_memory_path,attribute_episodic_memory_path = user_attribute_episodic_memory_path,cmd_args = self.cmd_args, args = self.args)
|
||||||
|
|
||||||
|
self.agent_episodic_memory = Episodic_Memory(event_episodic_memory_path = agent_event_episodic_memory_path, topic_episodic_memory_path = agent_topic_episodic_memory_path,
|
||||||
|
ep_cache_list_path = agent_episodic_memory_wm_cache_path, user_id = agent_name, client = self.client, llm_model = self.llm_model, embedding_model = self.embedding_model,
|
||||||
|
fact_episodic_memory_path = agent_fact_episodic_memory_path,attribute_episodic_memory_path = agent_attribute_episodic_memory_path,cmd_args = self.cmd_args, args = self.args)
|
||||||
|
|
||||||
|
self.user_persona_memory = Persona_Memory(persona_memory_preference_path = user_persona_memory_preference_path, persona_memory_fact_path = user_persona_memory_fact_path,
|
||||||
|
user_id = self.user_name, llm_model=self.llm_model, client=self.client,init_persona_information="",embedding_model=self.embedding_model,
|
||||||
|
persona_memory_attr_path = user_persona_memory_attr_path)
|
||||||
|
|
||||||
|
self.agent_persona_memory = Persona_Memory(persona_memory_preference_path = agent_persona_memory_preference_path, persona_memory_fact_path = agent_persona_memory_fact_path,
|
||||||
|
user_id = self.agent_name, llm_model=self.llm_model, client=self.client,init_persona_information="",embedding_model=self.embedding_model,
|
||||||
|
persona_memory_attr_path = agent_persona_memory_attr_path)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
for message in list(self.user_working_memory.working_memory_queue.queue)+self.user_episodic_memory.episodic_memory_cache_list:
|
||||||
|
self.user_topic_message_dict[message["topics"]] = [message["raw_message"],message["timestamp"]]
|
||||||
|
|
||||||
|
for message in list(self.agent_working_memory.working_memory_queue.queue)+self.agent_episodic_memory.episodic_memory_cache_list:
|
||||||
|
self.agent_topic_message_dict[message["topics"]] = [message["raw_message"],message["timestamp"]]
|
||||||
|
|
||||||
|
def generate_memory_detail_map(self):
|
||||||
|
|
||||||
|
stop_words = {
|
||||||
|
'a', 'an', 'the', 'and', 'or', 'but', 'if', 'because', 'as', 'what',
|
||||||
|
'which', 'this', 'that', 'these', 'those', 'then', 'just', 'so', 'than',
|
||||||
|
'such', 'both', 'through', 'about', 'for', 'is', 'of', 'while', 'during',
|
||||||
|
'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under',
|
||||||
|
'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where',
|
||||||
|
'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most',
|
||||||
|
'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same',
|
||||||
|
'so', 'than', 'too', 'very', 'can', 'will', 'just', 'should', 'now',
|
||||||
|
'i', 'you', 'he', 'she', 'it', 'we', 'they', 'me', 'him', 'her',
|
||||||
|
'us', 'them', 'my', 'your', 'his', 'its', 'our', 'their', 'mine',
|
||||||
|
'yours', 'hers', 'ours', 'theirs', 'myself', 'yourself', 'himself',
|
||||||
|
'herself', 'itself', 'ourselves', 'yourselves', 'themselves',self.user_name,self.agent_name}
|
||||||
|
|
||||||
|
print("Generating Detail Map")
|
||||||
|
user_full_memory_list = [(message["index"],message["raw_message"]) for message in list(self.user_working_memory.working_memory_queue.queue) + self.user_episodic_memory.episodic_memory_cache_list]
|
||||||
|
agent_full_memory_list = [(message["index"],message["raw_message"]) for message in list(self.agent_working_memory.working_memory_queue.queue) + self.agent_episodic_memory.episodic_memory_cache_list]
|
||||||
|
|
||||||
|
# round = 0
|
||||||
|
for index,text in user_full_memory_list:
|
||||||
|
text = text.translate(str.maketrans('', '', string.punctuation))
|
||||||
|
word_list = text.split()
|
||||||
|
for word in word_list:
|
||||||
|
word = word.lower()
|
||||||
|
if word not in stop_words:
|
||||||
|
self.user_detail_dict[word].append(index)
|
||||||
|
|
||||||
|
for index,text in agent_full_memory_list:
|
||||||
|
text = text.translate(str.maketrans('', '', string.punctuation))
|
||||||
|
word_list = text.split()
|
||||||
|
for word in word_list:
|
||||||
|
word = word.lower()
|
||||||
|
if word not in stop_words:
|
||||||
|
self.agent_detail_dict[word].append(index)
|
||||||
|
|
||||||
|
with open(self.user_memory_detail_path, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump( self.user_detail_dict, f, ensure_ascii=False, indent=4)
|
||||||
|
|
||||||
|
with open(self.agent_memory_detail_path, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump( self.agent_detail_dict, f, ensure_ascii=False, indent=4)
|
||||||
|
|
||||||
|
def find_memory_file(self,directory, pattern):
|
||||||
|
|
||||||
|
regex = re.compile(f"{pattern}$")
|
||||||
|
for filename in os.listdir(directory):
|
||||||
|
if regex.search(filename):
|
||||||
|
return os.path.join(directory,filename)
|
||||||
|
return None
|
||||||
|
async def read_cache_memory(self, cache_memory_dir):
|
||||||
|
|
||||||
|
cache_user_working_memory_pattern = f"user_working_memory_{self.idx}.json"
|
||||||
|
cache_agent_working_memory_pattern = f"agent_working_memory_{self.idx}.json"
|
||||||
|
|
||||||
|
cache_user_topic_episodic_memory_pattern = f"user_topic_episodic_memory_{self.idx}.json"
|
||||||
|
cache_agent_topic_episodic_memory_pattern = f"agent_topic_episodic_memory_{self.idx}.json"
|
||||||
|
|
||||||
|
cache_user_event_episodic_memory_pattern = f"user_event_episodic_memory_{self.idx}.json"
|
||||||
|
cache_agent_event_episodic_memory_pattern = f"agent_event_episodic_memory_{self.idx}.json"
|
||||||
|
|
||||||
|
cache_user_fact_episodic_memory_pattern = f"user_fact_episodic_memory_{self.idx}.json"
|
||||||
|
cache_agent_fact_episodic_memory_pattern = f"agent_fact_episodic_memory_{self.idx}.json"
|
||||||
|
|
||||||
|
cache_user_attr_episodic_memory_pattern = f"user_attribute_episodic_memory_{self.idx}.json"
|
||||||
|
cache_agent_attr_episodic_memory_pattern = f"agent_attribute_episodic_memory_{self.idx}.json"
|
||||||
|
|
||||||
|
cache_user_wm_cache_episodic_memory_pattern = f"user_wm_cache_episodic_memory_{self.idx}.json"
|
||||||
|
cache_agent_wm_cache_episodic_memory_pattern = f"agent_wm_cache_episodic_memory_{self.idx}.json"
|
||||||
|
|
||||||
|
cache_user_preferences_persona_memory_pattern = f"user_persona_memory_preference_{self.idx}.json"
|
||||||
|
cache_agent_preferences_persona_memory_pattern = f"agent_persona_memory_preference_{self.idx}.json"
|
||||||
|
|
||||||
|
cache_user_attributes_persona_memory_pattern = f"user_persona_memory_attr_{self.idx}.json"
|
||||||
|
cache_agent_attributes_persona_memory_pattern = f"agent_persona_memory_attr_{self.idx}.json"
|
||||||
|
|
||||||
|
|
||||||
|
# fact_episodic_path,attr_episodic_path
|
||||||
|
|
||||||
|
self.user_working_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_user_working_memory_pattern))
|
||||||
|
self.agent_working_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_agent_working_memory_pattern))
|
||||||
|
|
||||||
|
self.user_episodic_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_user_topic_episodic_memory_pattern),self.find_memory_file(cache_memory_dir,
|
||||||
|
cache_user_event_episodic_memory_pattern),self.find_memory_file(cache_memory_dir,cache_user_wm_cache_episodic_memory_pattern),
|
||||||
|
self.find_memory_file(cache_memory_dir,cache_user_fact_episodic_memory_pattern),
|
||||||
|
self.find_memory_file(cache_memory_dir,cache_user_attr_episodic_memory_pattern))
|
||||||
|
|
||||||
|
self.agent_episodic_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_agent_topic_episodic_memory_pattern),self.find_memory_file(cache_memory_dir,
|
||||||
|
cache_agent_event_episodic_memory_pattern),self.find_memory_file(cache_memory_dir,cache_agent_wm_cache_episodic_memory_pattern),
|
||||||
|
self.find_memory_file(cache_memory_dir,cache_agent_fact_episodic_memory_pattern),
|
||||||
|
self.find_memory_file(cache_memory_dir,cache_agent_attr_episodic_memory_pattern))
|
||||||
|
|
||||||
|
self.user_persona_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_user_preferences_persona_memory_pattern),
|
||||||
|
self.find_memory_file(cache_memory_dir,cache_user_attributes_persona_memory_pattern))
|
||||||
|
|
||||||
|
self.agent_persona_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_agent_preferences_persona_memory_pattern),
|
||||||
|
self.find_memory_file(cache_memory_dir,cache_agent_attributes_persona_memory_pattern))
|
||||||
|
|
||||||
|
self.user_topic_message_dict = {}
|
||||||
|
self.agent_topic_message_dict = {}
|
||||||
|
|
||||||
|
for message in list(self.user_working_memory.working_memory_queue.queue)+self.user_episodic_memory.episodic_memory_cache_list:
|
||||||
|
self.user_topic_message_dict[message["topics"]] = [message["raw_message"],message["timestamp"]]
|
||||||
|
|
||||||
|
for message in list(self.agent_working_memory.working_memory_queue.queue)+self.agent_episodic_memory.episodic_memory_cache_list:
|
||||||
|
self.agent_topic_message_dict[message["topics"]] = [message["raw_message"],message["timestamp"]]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def receive_user_message(self,message,round_index,client,timestamp):
|
||||||
|
|
||||||
|
await self.user_memory_manager.understand_message(message,round_index,client)
|
||||||
|
|
||||||
|
async def receive_agent_message(self,message,round_index,client,timestamp):
|
||||||
|
|
||||||
|
await self.agent_memory_manager.understand_message(message,round_index,client)
|
||||||
|
|
||||||
|
async def receive_user_message_v2(self,previous_query,user_message,round_index,client):
|
||||||
|
|
||||||
|
await self.user_memory_manager.understand_message(message,round_index,client)
|
||||||
|
|
||||||
|
async def receive_agent_message_v2(self,previous_query, user_message,round_index,client):
|
||||||
|
|
||||||
|
await self.agent_memory_manager.understand_message(message,round_index,client)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def get_response_base_on_profile_reorganization(self,query,all_options):
|
||||||
|
|
||||||
|
"""
|
||||||
|
Generates a response to the user's query through reorganizing the latest profile.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print(f"Generating response for query: '{query[:50]}...'")
|
||||||
|
# raw_reorganized_user_profile_text, original_profile = self.personal_memory.reorganize_profile_base_on_query(query)
|
||||||
|
raw_reorganized_user_profile_text, original_profile = self.personal_memory.reorganize_profile_base_on_query_and_option(query,all_options)
|
||||||
|
reorganized_profile = f"【User Profile】\n{raw_reorganized_user_profile_text}"
|
||||||
|
|
||||||
|
system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT.format(background=reorganized_profile)
|
||||||
|
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(question= query,all_options=all_options)
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": system_prompt_text},
|
||||||
|
{"role": "user", "content": user_prompt_text}
|
||||||
|
]
|
||||||
|
|
||||||
|
response_content = self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=messages,
|
||||||
|
temperature=0.7,
|
||||||
|
max_tokens=1500 # As in original main
|
||||||
|
)
|
||||||
|
|
||||||
|
self.receive_message(query,self.user_id,"Question",self.client)
|
||||||
|
|
||||||
|
return response_content.choices[0].message.content, reorganized_profile, original_profile
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def get_response_base_on_profile(self,query,all_options):
|
||||||
|
|
||||||
|
"""
|
||||||
|
Generates a response to the user's query base on the latest profile.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print(f"Generating response for query: '{query[:50]}...'")
|
||||||
|
|
||||||
|
raw_user_profile_text = self.personal_memory.get_user_profile_data()
|
||||||
|
background_context = f"【User Profile】\n{raw_user_profile_text}"
|
||||||
|
system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
|
||||||
|
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(
|
||||||
|
background=background_context,
|
||||||
|
question= query,
|
||||||
|
all_options=all_options
|
||||||
|
)
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": system_prompt_text},
|
||||||
|
{"role": "user", "content": user_prompt_text}
|
||||||
|
]
|
||||||
|
|
||||||
|
response_content = self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=messages,
|
||||||
|
temperature=0.7,
|
||||||
|
max_tokens=1500 # As in original main
|
||||||
|
)
|
||||||
|
|
||||||
|
self.receive_message(query,self.user_id,"Question",self.client)
|
||||||
|
return response_content.choices[0].message.content, background_context
|
||||||
|
|
||||||
|
|
||||||
|
async def get_response_base_on_memx_profile(self,query,all_options):
|
||||||
|
|
||||||
|
"""
|
||||||
|
Generates a response to the user's query base on the latest profile.
|
||||||
|
"""
|
||||||
|
|
||||||
|
persona_profile = self.persona_memory.generate_preference_persona(self.episodic_memory.topic_episodic_memory_list)
|
||||||
|
|
||||||
|
|
||||||
|
system_prompt_text = GENERATE_SYSTEM_RESPONSE_MEMX_SYSTEM_PROMPT
|
||||||
|
user_prompt_text = GENERATE_SYSTEM_RESPONSE_MEMX_USER_PROMPT.format(
|
||||||
|
profile = persona_profile,
|
||||||
|
question= query,
|
||||||
|
all_options=all_options
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": system_prompt_text},
|
||||||
|
{"role": "user", "content": user_prompt_text}
|
||||||
|
]
|
||||||
|
|
||||||
|
response_content = await self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=messages,
|
||||||
|
temperature=0.7,
|
||||||
|
max_tokens=1500 # As in original main
|
||||||
|
)
|
||||||
|
|
||||||
|
return response_content.choices[0].message.content, persona_profile
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def get_response_base_on_profile(self,query,all_options):
|
||||||
|
|
||||||
|
"""
|
||||||
|
Generates a response to the user's query base on the profile.
|
||||||
|
"""
|
||||||
|
print(f"Generating response for query: '{query[:50]}...'")
|
||||||
|
|
||||||
|
# 1. Retrieve context
|
||||||
|
raw_user_profile_text = self.personal_memory.get_user_profile_data()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
background_context = f"【User Profile】\n{raw_user_profile_text}"
|
||||||
|
|
||||||
|
system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
|
||||||
|
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(
|
||||||
|
background=background_context,
|
||||||
|
question= query,
|
||||||
|
all_options=all_options
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": system_prompt_text},
|
||||||
|
{"role": "user", "content": user_prompt_text}
|
||||||
|
]
|
||||||
|
|
||||||
|
response_content = self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=messages,
|
||||||
|
temperature=0.7,
|
||||||
|
max_tokens=1500 # As in original main
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
self.receive_message(query,self.user_id,"Question",self.client)
|
||||||
|
return response_content.choices[0].message.content, background_context
|
||||||
|
|
||||||
|
def get_response_base_on_profile_v2(self,query,all_options):
|
||||||
|
|
||||||
|
"""
|
||||||
|
Generates a response to the user's query base on the profile.
|
||||||
|
"""
|
||||||
|
print(f"Generating response for query: '{query[:50]}...'")
|
||||||
|
|
||||||
|
# 1. Retrieve context
|
||||||
|
|
||||||
|
self.personal_memory.merge_user_trace_profile_into_user_preference_profile()
|
||||||
|
|
||||||
|
raw_user_profile_text = self.personal_memory.get_user_profile_data()
|
||||||
|
background_context = f"【User Profile】\n{raw_user_profile_text}"
|
||||||
|
|
||||||
|
# system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
|
||||||
|
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(
|
||||||
|
background=background_context,
|
||||||
|
question= query,
|
||||||
|
all_options=all_options)
|
||||||
|
|
||||||
|
messages = [{"role": "user", "content": user_prompt_text}]
|
||||||
|
|
||||||
|
# 2. Call LLM for response
|
||||||
|
# print("Memoryos: Calling LLM for final response generation...")
|
||||||
|
response_content = self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=messages,
|
||||||
|
temperature=0,
|
||||||
|
max_tokens=16000
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Add this interaction to memory
|
||||||
|
self.receive_message(query,self.user_id,"Question",self.client)
|
||||||
|
return response_content.choices[0].message.content, background_context
|
||||||
|
|
||||||
|
async def get_response_base_on_recent_message(self,query,all_options,working_memory):
|
||||||
|
|
||||||
|
"""
|
||||||
|
Generates a response to the user's query base on the profile.
|
||||||
|
"""
|
||||||
|
print(f"Generating response for query: '{query[:50]}...'")
|
||||||
|
|
||||||
|
# system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
|
||||||
|
|
||||||
|
system_prompt_text = GENERATE_SYSTEM_RESPONSE_ONLY_WM_SYSTEM_PROMPT
|
||||||
|
user_prompt_text = GENERATE_SYSTEM_RESPONSE_ONLY_WM_USER_PROMPT.format(messages= working_memory,question= query,all_options=all_options)
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": system_prompt_text},
|
||||||
|
{"role": "user", "content": user_prompt_text}
|
||||||
|
]
|
||||||
|
|
||||||
|
# 2. Call LLM for response
|
||||||
|
# print("Memoryos: Calling LLM for final response generation...")
|
||||||
|
response_content = await self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=messages,
|
||||||
|
temperature=0,
|
||||||
|
max_tokens=16000
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Add this interaction to memory
|
||||||
|
return response_content.choices[0].message.content
|
||||||
|
|
||||||
|
async def get_response_base_on_init_persona(self,query,all_options,init_persona):
|
||||||
|
|
||||||
|
"""
|
||||||
|
Generates a response to the user's query base on the profile.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print(f"Generating response for query: '{query[:50]}...'")
|
||||||
|
|
||||||
|
# system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
|
||||||
|
|
||||||
|
system_prompt_text = GENERATE_SYSTEM_RESPONSE_ONLY_WM_SYSTEM_PROMPT
|
||||||
|
user_prompt_text = GENERATE_SYSTEM_RESPONSE_ONLY_INIT_PROFILE_PROMPT.format(persona= init_persona,question= query,all_options=all_options)
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": system_prompt_text},
|
||||||
|
{"role": "user", "content": user_prompt_text}
|
||||||
|
]
|
||||||
|
|
||||||
|
# 2. Call LLM for response
|
||||||
|
# print("Memoryos: Calling LLM for final response generation...")
|
||||||
|
response_content = await self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=messages,
|
||||||
|
temperature=0,
|
||||||
|
max_tokens=16000
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Add this interaction to memory
|
||||||
|
return response_content.choices[0].message.content
|
||||||
|
|
||||||
|
|
||||||
|
def get_response_base_on_reorganized_profile(self,query,all_options,reorganzied_profile):
|
||||||
|
|
||||||
|
"""
|
||||||
|
Generates a response to the user's query base on the profile.
|
||||||
|
"""
|
||||||
|
print(f"Generating response for query: '{query[:50]}...'")
|
||||||
|
|
||||||
|
# 1. Retrieve context
|
||||||
|
|
||||||
|
raw_user_profile_text = str(reorganzied_profile)
|
||||||
|
background_context = f"【User Profile】\n{raw_user_profile_text}"
|
||||||
|
|
||||||
|
system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
|
||||||
|
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(
|
||||||
|
background=background_context,
|
||||||
|
question= query,
|
||||||
|
all_options=all_options
|
||||||
|
)
|
||||||
|
|
||||||
|
messages = [
|
||||||
|
{"role": "system", "content": system_prompt_text},
|
||||||
|
{"role": "user", "content": user_prompt_text}
|
||||||
|
]
|
||||||
|
|
||||||
|
# 2. Call LLM for response
|
||||||
|
# print("Memoryos: Calling LLM for final response generation...")
|
||||||
|
response_content = self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=messages,
|
||||||
|
temperature=0.7,
|
||||||
|
max_tokens=1500 # As in original main
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Add this interaction to memory
|
||||||
|
self.receive_message(query,self.user_id,"Question",self.client)
|
||||||
|
return response_content.choices[0].message.content, self.personal_memory.get_user_profile_data()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def reorganize_profile_base_on_message(self,message):
|
||||||
|
|
||||||
|
"""
|
||||||
|
Only extract the sections of the profile which are important for current user message as well as provide the reasons behind it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print(f"Reorganize the profile base on the user message: {message[:50]}...")
|
||||||
|
|
||||||
|
profile = self.personal_memory.latest_profile
|
||||||
|
system_prompt_text = Profile_Reorganization_SYSTEM_PROMPT
|
||||||
|
user_prompt_text = Profile_Reorganization_USER_PROMPT.format(Message = message,Profile = profile)
|
||||||
|
|
||||||
|
messages = [{"role": "system", "content": system_prompt_text},{"role": "user", "content": user_prompt_text}]
|
||||||
|
reorganized_profile = ""
|
||||||
|
|
||||||
|
while(reorganized_profile==""):
|
||||||
|
response = self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=messages,
|
||||||
|
temperature=0.7,
|
||||||
|
max_tokens=2000)
|
||||||
|
reorganized_profile = json.loads(response.choices[0].message.content)
|
||||||
|
|
||||||
|
print(reorganized_profile)
|
||||||
|
return reorganized_profile["relevant_profile"],reorganized_profile["summary"]
|
||||||
|
|
||||||
|
|
||||||
|
async def get_response_base_on_episodic_memory_retrieval(self,query,all_options):
|
||||||
|
|
||||||
|
"""
|
||||||
|
Generates a response to the user's query base on the latest profile.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# persona_profile = self.persona_memory.generate_preference_persona(self.episodic_memory.topic_episodic_memory_list)
|
||||||
|
experience = str(self.memory_manager.retrieve_episodic_memory(query))
|
||||||
|
system_prompt_text = GENERATE_SYSTEM_RESPONSE_EP_RAG_SYSTEM_PROMPT
|
||||||
|
user_prompt_text = GENERATE_SYSTEM_RESPONSE_EP_RAG_USER_PROMPT.format(experience = experience,question= query,all_options=all_options)
|
||||||
|
messages = [{"role": "system", "content": system_prompt_text},{"role": "user", "content": user_prompt_text}]
|
||||||
|
response_content = await self.client.chat.completions.create(model=self.model, messages=messages, temperature=0.7, max_tokens=1500)
|
||||||
|
|
||||||
|
# self.receive_message(query,self.user_id,"Question",self.client)
|
||||||
|
return response_content.choices[0].message.content, experience
|
||||||
1057
libs/o-mem/memory_chain/memory_manager.py
Normal file
1057
libs/o-mem/memory_chain/memory_manager.py
Normal file
File diff suppressed because it is too large
Load diff
224
libs/o-mem/memory_chain/persona_memory.py
Normal file
224
libs/o-mem/memory_chain/persona_memory.py
Normal file
|
|
@ -0,0 +1,224 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# coding=utf-8
|
||||||
|
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
import json
|
||||||
|
import numpy as np
|
||||||
|
# import faiss
|
||||||
|
from collections import deque
|
||||||
|
from .utils import *
|
||||||
|
from .prompts import *
|
||||||
|
from FlagEmbedding import FlagAutoModel
|
||||||
|
from sentence_transformers import SentenceTransformer
|
||||||
|
from itertools import combinations
|
||||||
|
from collections import defaultdict
|
||||||
|
import json
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
class Persona_Memory:
|
||||||
|
|
||||||
|
def __init__(self, persona_memory_preference_path, persona_memory_fact_path,persona_memory_attr_path,
|
||||||
|
user_id,llm_model,client,init_persona_information,embedding_model):
|
||||||
|
|
||||||
|
self.user_id = user_id
|
||||||
|
self.client = client
|
||||||
|
self.init_persona_information = init_persona_information
|
||||||
|
self.llm_model = llm_model
|
||||||
|
self.persona_memory_preference_path = persona_memory_preference_path
|
||||||
|
self.persona_memory_fact_path = persona_memory_fact_path
|
||||||
|
self.persona_memory_attr_path = persona_memory_attr_path
|
||||||
|
self.preference_persona = []
|
||||||
|
self.fact_persona = []
|
||||||
|
self.attr_persona = []
|
||||||
|
self.aspect_attribute_dict = {}
|
||||||
|
self.embedding_model = embedding_model
|
||||||
|
|
||||||
|
async def update_preference_persona(self, episodic_topic_memory_list):
|
||||||
|
|
||||||
|
episodic_memory_topic_list = [topic["group_name"] for topic in episodic_topic_memory_list]
|
||||||
|
topic_attitude_dict = {}
|
||||||
|
|
||||||
|
for topic in episodic_topic_memory_list:
|
||||||
|
topic_attitude_dict[topic["group_name"]] = topic["Overall Attitude"]
|
||||||
|
|
||||||
|
topic_clusters = self.cluster_related_topics(self.find_top_similar_keys(episodic_memory_topic_list, self.embedding_model))
|
||||||
|
persona_preference_results = []
|
||||||
|
|
||||||
|
for cluster in topic_clusters:
|
||||||
|
|
||||||
|
message = [{topic:topic_attitude_dict[topic]} for topic in cluster]
|
||||||
|
preference_generate_message = [{"role": "system", "content": Preference_Generate_System_PROMPT},{"role": "user", "content": Preference_Generate_User_PROMPT.format(Topic_Groups=str(message))}]
|
||||||
|
fact_generate_message = [{"role":"system"}]
|
||||||
|
|
||||||
|
response = ""
|
||||||
|
while response == "":
|
||||||
|
try:
|
||||||
|
response = await self.client.chat.completions.create(model=self.llm_model, messages = preference_generate_message, temperature = 0.3)
|
||||||
|
persona_preference = json.loads(response.choices[0].message.content)
|
||||||
|
persona_preference_results.append(persona_preference)
|
||||||
|
except Exception as e:
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
print("Error generating persona profile.")
|
||||||
|
print(f"Error generating profile: {str(e)}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
self.preference_persona = persona_preference_results
|
||||||
|
self._save_preference_persona()
|
||||||
|
|
||||||
|
async def update_attribute_persona(self, episodic_memory_attr_dict):
|
||||||
|
|
||||||
|
memory_attr_list = list(episodic_memory_attr_dict.keys())
|
||||||
|
attr_clusters = self.cluster_related_topics(self.find_top_similar_keys(memory_attr_list, self.embedding_model))
|
||||||
|
persona_attr_results = []
|
||||||
|
|
||||||
|
for cluster in attr_clusters:
|
||||||
|
|
||||||
|
print(str(cluster))
|
||||||
|
fact_generate_message = [{"role": "system", "content": Attribute_Merge_System_PROMPT_v2},{"role": "user", "content": Attribute_Merge_User_PROMPT.format(User_facts=str(cluster))}]
|
||||||
|
response = ""
|
||||||
|
while response == "":
|
||||||
|
try:
|
||||||
|
response = await self.client.chat.completions.create(model=self.llm_model, messages = fact_generate_message, temperature = 0.1)
|
||||||
|
persona_attr = json.loads(response.choices[0].message.content)
|
||||||
|
persona_attr["original attributes"] = cluster
|
||||||
|
persona_attr_results.append(persona_attr)
|
||||||
|
except Exception as e:
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
response == ""
|
||||||
|
print(f"Error generating profile: {str(e)}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
self.attr_persona = persona_attr_results
|
||||||
|
self._save_attr_persona()
|
||||||
|
|
||||||
|
def _save_preference_persona(self):
|
||||||
|
|
||||||
|
with open(self.persona_memory_preference_path, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(self.preference_persona, f, ensure_ascii=False, indent=4)
|
||||||
|
|
||||||
|
def _save_fact_persona(self):
|
||||||
|
|
||||||
|
with open(self.persona_memory_fact_path, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(self.fact_persona_description, f, ensure_ascii=False, indent=4)
|
||||||
|
|
||||||
|
def _save_attr_persona(self):
|
||||||
|
|
||||||
|
print("Generating aspect-attribute dictionary.")
|
||||||
|
for attr_group in self.attr_persona:
|
||||||
|
for key,value in attr_group["User Attributes"].items():
|
||||||
|
try:
|
||||||
|
if key in self.aspect_attribute_dict:
|
||||||
|
current = self.aspect_attribute_dict[key]
|
||||||
|
self.aspect_attribute_dict[key] = self.aspect_attribute_dict[key] + " " + value
|
||||||
|
else:
|
||||||
|
self.aspect_attribute_dict[key] = value
|
||||||
|
except:
|
||||||
|
print("Attribute Error")
|
||||||
|
print(key)
|
||||||
|
print(self.persona_memory_attr_path)
|
||||||
|
if key in self.aspect_attribute_dict:
|
||||||
|
current = self.aspect_attribute_dict[key]
|
||||||
|
self.aspect_attribute_dict[key] = str(self.aspect_attribute_dict[key]) + " " + str(value)
|
||||||
|
else:
|
||||||
|
self.aspect_attribute_dict[key] = value
|
||||||
|
|
||||||
|
|
||||||
|
with open(self.persona_memory_attr_path, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(self.attr_persona, f, ensure_ascii=False, indent=4)
|
||||||
|
|
||||||
|
|
||||||
|
def cluster_related_topics(self,data):
|
||||||
|
|
||||||
|
parent = {}
|
||||||
|
def find(node):
|
||||||
|
if parent[node] != node:
|
||||||
|
parent[node] = find(parent[node])
|
||||||
|
return parent[node]
|
||||||
|
def union(node1, node2):
|
||||||
|
root1 = find(node1)
|
||||||
|
root2 = find(node2)
|
||||||
|
if root1 != root2:
|
||||||
|
parent[root2] = root1
|
||||||
|
|
||||||
|
for item in data:
|
||||||
|
key1, key2 = item['key1'], item['key2']
|
||||||
|
if key1 not in parent:
|
||||||
|
parent[key1] = key1
|
||||||
|
if key2 not in parent:
|
||||||
|
parent[key2] = key2
|
||||||
|
|
||||||
|
for item in data:
|
||||||
|
key1, key2 = item['key1'], item['key2']
|
||||||
|
union(key1, key2)
|
||||||
|
|
||||||
|
clusters = defaultdict(list)
|
||||||
|
for node in parent:
|
||||||
|
clusters[find(node)].append(node)
|
||||||
|
|
||||||
|
result = [cluster for cluster in clusters.values() if len(cluster) > 1]
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
def find_top_similar_keys(self,all_keys, embedding_model):
|
||||||
|
|
||||||
|
key_embeddings = embedding_model.encode(all_keys)
|
||||||
|
key_pairs = list(combinations(range(len(all_keys)), 2))
|
||||||
|
best_matches = {}
|
||||||
|
|
||||||
|
for i, j in key_pairs:
|
||||||
|
key1 = all_keys[i]
|
||||||
|
key2 = all_keys[j]
|
||||||
|
sim = float(key_embeddings[i] @ key_embeddings[j].T)
|
||||||
|
if key1 not in best_matches or sim > best_matches[key1]['similarity']:
|
||||||
|
best_matches[key1] = {'key1': key1, 'key2': key2, 'similarity': sim}
|
||||||
|
if key2 not in best_matches or sim > best_matches[key2]['similarity']:
|
||||||
|
best_matches[key2] = {'key1': key2, 'key2': key1, 'similarity': sim}
|
||||||
|
|
||||||
|
results = list(best_matches.values())
|
||||||
|
results.sort(key=lambda x: x['similarity'], reverse=True)
|
||||||
|
return results
|
||||||
|
|
||||||
|
def read_cache(self,preference_memory_path,attr_memory_path):
|
||||||
|
|
||||||
|
with open(preference_memory_path,'r', encoding='utf-8') as f:
|
||||||
|
self.preference_persona = json.load(f)
|
||||||
|
|
||||||
|
with open(attr_memory_path,'r', encoding='utf-8') as f:
|
||||||
|
self.attr_persona = json.load(f)
|
||||||
|
|
||||||
|
self._save_preference_persona()
|
||||||
|
self._save_attr_persona()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
1043
libs/o-mem/memory_chain/prompts.py
Normal file
1043
libs/o-mem/memory_chain/prompts.py
Normal file
File diff suppressed because it is too large
Load diff
21
libs/o-mem/memory_chain/utils.py
Normal file
21
libs/o-mem/memory_chain/utils.py
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# coding=utf-8
|
||||||
|
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
import os
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_directory_exists(path):
|
||||||
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||||
|
|
||||||
99
libs/o-mem/memory_chain/working_memory.py
Normal file
99
libs/o-mem/memory_chain/working_memory.py
Normal file
|
|
@ -0,0 +1,99 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# coding=utf-8
|
||||||
|
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
import json
|
||||||
|
import numpy as np
|
||||||
|
from collections import deque
|
||||||
|
from .utils import *
|
||||||
|
from queue import Queue
|
||||||
|
import queue
|
||||||
|
|
||||||
|
class Working_Memory:
|
||||||
|
|
||||||
|
def __init__(self,working_memory_path ,user_id,model,working_memory_max_size,client,refresh_rate):
|
||||||
|
|
||||||
|
self.file_path = working_memory_path
|
||||||
|
self.user_id = user_id
|
||||||
|
self.model = model
|
||||||
|
self.working_memory_queue = Queue()
|
||||||
|
self.working_memory_max_size = working_memory_max_size
|
||||||
|
self.refresh_rate = refresh_rate
|
||||||
|
self.client = client
|
||||||
|
ensure_directory_exists(self.file_path)
|
||||||
|
|
||||||
|
def add_message_to_working_memory(self,raw_message,message,topics,emotions,reason,index,timestamp,fact,attribute):
|
||||||
|
|
||||||
|
self.working_memory_queue.put({"user_id":self.user_id,"raw_message":raw_message,"message":message,"topics":topics,"emotions":emotions,"reason":reason,"index":index,"timestamp":timestamp,"fact":fact,"attribue":attribute})
|
||||||
|
|
||||||
|
if (self.working_memory_queue.qsize() == self.working_memory_max_size):
|
||||||
|
is_full = True
|
||||||
|
else:
|
||||||
|
is_full = False
|
||||||
|
|
||||||
|
return is_full, self._save_working_memory()
|
||||||
|
|
||||||
|
def pop_oldest_wm(self):
|
||||||
|
|
||||||
|
return self.working_memory_queue.get()
|
||||||
|
|
||||||
|
def pop_oldest_working_memory(self):
|
||||||
|
|
||||||
|
popped_items = []
|
||||||
|
|
||||||
|
for _ in range(self.refresh_rate):
|
||||||
|
try:
|
||||||
|
item = self.working_memory_queue.get_nowait()
|
||||||
|
popped_items.append(item)
|
||||||
|
except queue.Empty:
|
||||||
|
break
|
||||||
|
|
||||||
|
return popped_items
|
||||||
|
|
||||||
|
|
||||||
|
def _save_working_memory(self):
|
||||||
|
temp_queue = queue.Queue()
|
||||||
|
temp_list = []
|
||||||
|
|
||||||
|
while not self.working_memory_queue.empty():
|
||||||
|
item = self.working_memory_queue.get()
|
||||||
|
temp_list.append(item)
|
||||||
|
temp_queue.put(item)
|
||||||
|
|
||||||
|
while not temp_queue.empty():
|
||||||
|
self.working_memory_queue.put(temp_queue.get())
|
||||||
|
|
||||||
|
with open(self.file_path, 'w') as f:
|
||||||
|
json.dump(temp_list, f, indent=2, sort_keys=True)
|
||||||
|
|
||||||
|
message_summary_list = [item["message"] for item in temp_list]
|
||||||
|
return message_summary_list
|
||||||
|
def read_cache(self,file_path):
|
||||||
|
|
||||||
|
print(file_path)
|
||||||
|
|
||||||
|
with open(file_path, 'r', encoding='utf-8') as f:
|
||||||
|
message_understanding_caches = json.load(f)
|
||||||
|
for message_understanding in message_understanding_caches:
|
||||||
|
self.working_memory_queue.put(message_understanding)
|
||||||
|
|
||||||
|
self._save_working_memory()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
20
libs/o-mem/requirements.txt
Normal file
20
libs/o-mem/requirements.txt
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
# Memory Chain - Dependencies
|
||||||
|
# ===========================
|
||||||
|
# Install with: pip install -r requirements.txt
|
||||||
|
|
||||||
|
# Core Dependencies
|
||||||
|
openai>=1.0.0 # OpenAI API client
|
||||||
|
torch>=2.8.0 # PyTorch deep learning framework
|
||||||
|
sentence-transformers>=2.2.0 # Sentence embedding models
|
||||||
|
numpy>=1.22.0 # Numerical computing
|
||||||
|
|
||||||
|
# Configuration & Utilities
|
||||||
|
pyyaml>=6.0 # YAML config file parsing
|
||||||
|
tqdm>=4.66.3 # Progress bars
|
||||||
|
aiofiles>=23.0.0 # Async file operations
|
||||||
|
|
||||||
|
# Optional Dependencies (for experiments)
|
||||||
|
tiktoken>=0.5.0 # OpenAI tokenizer
|
||||||
|
FlagEmbedding>=1.2.0 # BGE embedding models (optional, for custom embeddings)
|
||||||
|
scikit-learn>=1.0.0 # Machine learning utilities (cosine similarity)
|
||||||
|
|
||||||
Loading…
Reference in a new issue