Skip to main content

TiMEM Python SDK - Time-based Memory Management and Rule Learning toolkit | TiMEM Python SDK - 时间记忆管理与规则学习工具包

Project description

TiMEM Python SDK

Time-based Memory Management and Rule Learning Toolkit

TiMEM SDK 是一个强大的 Python 客户端库,用于与 TiMEM Engine API 交互,提供记忆管理、通用规则学习和用户画像计算等功能。

特性

  • 通用规则学习:从场景/结果中学习可复用规则
  • 规则召回:基于场景、上下文、标签和过滤条件召回相关规则
  • 记忆管理:支持 L1-L5 分层记忆的增删改查
  • 用户画像:从 L5 级别记忆计算用户画像
  • 同步/异步支持:完整的同步和异步 API 封装
  • 批量操作:支持批量记忆写入提升效率
  • 自动重试:内置请求重试机制保证可靠性

安装

pip install timem-ai

或从源码安装:

git clone https://github.com/TiMEM-AI/timem-sdk-python.git
cd timem-sdk-python
pip install -e .

快速开始

规则学习门面与 Memory 保持同样的导出风格:Rules / AsyncRules 是正式类名,rules / async_rules 是小写快捷别名。

from timem import Rules, AsyncRules, rules, async_rules

同步客户端

from timem import Rules, TiMEMClient

# 1. 规则学习:从单条场景/结果学习通用规则
rules = Rules(
    api_key="your-api-key",
    base_url="http://localhost:8001",
)

learned = rules.learn(
    situation_text="候选人项目经历影响力描述比较笼统",
    outcome_text="要求补充量化指标和个人贡献边界",
    attributes={"scene": "resume_review", "role": "backend"},
    suggested_tags=["resume", "project_impact"],
    user_id="user-123",
    agent_id="hire",
)
print(learned["rule_id"])

# 2. 规则召回:根据当前场景召回相关规则
recalled = rules.recall(
    situation_text="评估 Python 后端候选人的项目经历",
    context_text="候选人只写了负责系统开发,缺少指标和业务结果",
    mode="auto",
    filters={"role": "backend"},
    top_k=5,
    user_id="user-123",
    agent_id="hire",
)
print(f"Recalled {recalled['count']} rules")

# 3. 添加记忆
client = TiMEMClient(api_key="your-api-key", base_url="http://localhost:8001")
memory = client.add_memory(
    user_id=12345,
    domain="aicv",
    content={
        "type": "interaction",
        "action": "resume_analysis",
        "context": {"job": "软件工程师"},
    },
    layer_type="L1",
    tags=["resume", "analysis"],
)

异步客户端

import asyncio
from timem import AsyncRules, AsyncTiMEMClient

async def main():
    async with AsyncRules(api_key="your-api-key", base_url="http://localhost:8001") as rules:
        learned = await rules.learn(
            situation_text="候选人项目经历影响力描述比较笼统",
            outcome_text="要求补充量化指标和个人贡献边界",
            suggested_tags=["resume", "project_impact"],
            user_id="user-123",
            agent_id="hire",
        )

        recalled = await rules.recall(
            situation_text="评估 Python 后端候选人的项目经历",
            context_text="候选人只写了负责系统开发,缺少指标和业务结果",
            mode="auto",
            top_k=5,
            user_id="user-123",
            agent_id="hire",
        )

    async with AsyncTiMEMClient(api_key="your-api-key", base_url="http://localhost:8001") as client:
        memories = [
            {"user_id": 12345, "domain": "aicv", "content": {"action": "view_job", "job_id": 1}},
            {"user_id": 12345, "domain": "aicv", "content": {"action": "apply_job", "job_id": 1}},
        ]
        results = await client.batch_add_memories(memories)

asyncio.run(main())

API 文档

通用规则学习

Rules.learn() / TiMEMClient.learn_rule()

从单条场景/结果中学习一条可复用规则。

rules.learn(
    situation_text="场景描述",
    outcome_text="这次应沉淀下来的处理经验",
    attributes={"scene": "resume_review"},
    suggested_tags=["resume"],
    user_id="default",
    agent_id="default",
)

Rules.recall() / TiMEMClient.recall_rules()

根据当前场景召回相关规则。

rules.recall(
    situation_text="当前待判断场景",
    context_text="更长的上下文材料",
    mode="auto",
    tags_hint=["resume"],
    filters={"scene": "resume_review"},
    top_k=5,
)

记忆管理

add_memory()

添加记忆到 TiMEM 系统

参数:

  • user_id (int): 用户ID
  • domain (str): 业务领域
  • content (Dict): 记忆内容
  • layer_type (str): 记忆层级(L1-L5),默认 "L1"
  • tags (List[str], optional): 标签
  • keywords (List[str], optional): 关键词

返回: 创建的记忆信息

search_memory()

搜索记忆

参数:

  • user_id (int, optional): 用户ID过滤
  • domain (str, optional): 领域过滤
  • layer_type (str, optional): 层级过滤
  • tags (List[str], optional): 标签过滤
  • keywords (List[str], optional): 关键词过滤
  • limit (int): 返回数量,默认 20
  • offset (int): 分页偏移,默认 0

返回: 搜索结果和记忆列表

用户画像

compute_profile()

从 L5 级别记忆计算用户画像

参数:

  • user_id (int): 用户ID
  • domain (str): 业务领域
  • source_memory_ids (List[str], optional): 指定记忆ID

返回: 计算的画像信息

get_profile()

获取用户画像

参数:

  • user_id (int): 用户ID
  • domain (str): 业务领域

返回: 用户画像信息

search_users()

根据画像特征搜索用户

参数:

  • criteria (Dict): 搜索条件(如偏好、行为模式)
  • domain (str, optional): 领域过滤
  • limit (int): 返回数量,默认 20

返回: 匹配的用户列表

异步批量操作

batch_add_memories()

并发添加多条记忆

async with AsyncTiMEMClient(api_key="your-key") as client:
    memories = [
        {"user_id": 1, "domain": "aicv", "content": {...}},
        {"user_id": 2, "domain": "aicv", "content": {...}}
    ]
    results = await client.batch_add_memories(memories)

异常处理

from timem import Rules, TiMEMError, AuthenticationError, APIError, ValidationError

try:
    rules = Rules(api_key="your-key")
    result = rules.learn(situation_text="场景", outcome_text="经验")
except ValidationError as e:
    print(f"验证错误: {e}")
except AuthenticationError as e:
    print(f"认证失败: {e}")
except APIError as e:
    print(f"API错误 [{e.status_code}]: {e}")
except TiMEMError as e:
    print(f"TiMEM错误: {e}")

配置选项

client = TiMEMClient(
    api_key="your-api-key",
    base_url="http://localhost:8001",  # TiMEM Engine URL
    timeout=60.0,                       # 请求超时(秒)
)

async_client = AsyncTiMEMClient(
    api_key="your-api-key",
    base_url="http://localhost:8001",
    timeout=60.0,
    max_retries=3,                      # 最大重试次数
    retry_delay=1.0,                    # 重试延迟(秒)
)

开发指南

安装开发依赖

pip install -r requirements-dev.txt

运行测试

pytest tests/

构建发布

python -m build
python -m twine upload dist/*

架构说明

TiMEM SDK 遵循以下设计原则:

  1. 简洁接口:规则学习通过 Rules.learn() / learn_rule() 显式表达场景和结果
  2. 智能召回:基于场景、标签、过滤条件和上下文召回相关规则
  3. 分层记忆:支持 L1-L5 五层记忆管理
  4. 异步优先:充分利用异步编程提升性能
  5. 容错设计:自动重试和异常处理

许可证

MIT License

联系我们

更新日志

v0.1.0 (2025-10-18)

  • ✨ 初始版本发布
  • ✨ 支持通用规则学习(Rules/AsyncRules)
  • ✨ 支持记忆管理(Add/Search/Update/Delete)
  • ✨ 支持用户画像计算
  • ✨ 完整的同步/异步 API
  • ✨ 批量操作支持

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

timem_ai-0.1.7.tar.gz (56.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

timem_ai-0.1.7-py3-none-any.whl (55.7 kB view details)

Uploaded Python 3

File details

Details for the file timem_ai-0.1.7.tar.gz.

File metadata

  • Download URL: timem_ai-0.1.7.tar.gz
  • Upload date:
  • Size: 56.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for timem_ai-0.1.7.tar.gz
Algorithm Hash digest
SHA256 cd52a84f6d13689e5fe90c2ae5d9ae752883d9adb53c5be68a9838dde1690d51
MD5 e2148ce388f194016967e33d1580b114
BLAKE2b-256 0306f9a36712490f598ccc33141737ef88bc8713349baaa1558c652a4f6963f1

See more details on using hashes here.

File details

Details for the file timem_ai-0.1.7-py3-none-any.whl.

File metadata

  • Download URL: timem_ai-0.1.7-py3-none-any.whl
  • Upload date:
  • Size: 55.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for timem_ai-0.1.7-py3-none-any.whl
Algorithm Hash digest
SHA256 4b453fccbca341a44cc564c307cf549bce143029e0ddf7c3bd0ccb816a5ef969
MD5 4fb0f6e626a50ffeb0e062c7a92717a4
BLAKE2b-256 651d46573a2e1ce0386493ead05ea64d8651501a1b76b0caa9bcccfc40668578

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page