{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# HelloClaw - 个性化 AI Agent 助手\n",
    "\n",
    "## 项目简介\n",
    "\n",
    "HelloClaw 是一个基于 Hello-Agents 框架构建的个性化 AI Agent 应用。\n",
    "\n",
    "**核心特性：**\n",
    "- 支持自定义 Agent 身份和个性\n",
    "- 长期记忆和每日记忆的自动管理\n",
    "- 流式工具调用，实时反馈执行状态\n",
    "- 多会话支持，会话历史持久化\n",
    "\n",
    "## 作者信息\n",
    "- 作者: tino-chen\n",
    "- GitHub: [@tino-chen](https://github.com/tino-chen)\n",
    "- 日期: 2025-03"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 第1部分：环境配置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 安装依赖（如果需要）\n",
    "# !pip install -q hello-agents fastapi uvicorn python-dotenv pydantic httpx[socks]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "环境配置完成！\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import sys\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "# 添加项目路径\n",
    "sys.path.insert(0, os.path.dirname(os.path.abspath('__file__')))\n",
    "\n",
    "# 加载环境变量\n",
    "load_dotenv()\n",
    "\n",
    "# 配置 LLM（请替换为你的 API 密钥）\n",
    "# 方式1: 使用环境变量\n",
    "# 方式2: 直接设置\n",
    "# os.environ[\"LLM_MODEL_ID\"] = \"glm-4\"\n",
    "# os.environ[\"LLM_API_KEY\"] = \"your-api-key\"\n",
    "# os.environ[\"LLM_BASE_URL\"] = \"https://open.bigmodel.cn/api/paas/v4/\"\n",
    "\n",
    "print(\"环境配置完成！\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 第2部分：导入模块和核心类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "模块导入成功！\n"
     ]
    }
   ],
   "source": [
    "from hello_agents import Config\n",
    "from hello_agents.tools import ToolRegistry, ReadTool, WriteTool, CalculatorTool\n",
    "from hello_agents.core.llm import HelloAgentsLLM\n",
    "\n",
    "# 导入 HelloClaw 核心模块\n",
    "from src.agent.helloclaw_agent import HelloClawAgent\n",
    "\n",
    "print(\"模块导入成功！\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 第3部分：自定义工具定义\n",
    "\n",
    "HelloClaw 实现了多个自定义工具，这里展示核心工具的实现。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "HelloClawAgent 工具说明已加载！\n"
     ]
    }
   ],
   "source": [
    "# HelloClawAgent 使用说明\n",
    "# \n",
    "# HelloClawAgent 是项目的核心类，它会自动：\n",
    "# 1. 初始化工作空间（~/.helloclaw/workspace）\n",
    "# 2. 从配置文件加载系统提示词（AGENTS.md、IDENTITY.md 等）\n",
    "# 3. 注册所有内置工具和自定义工具\n",
    "# 4. 配置记忆管理系统\n",
    "#\n",
    "# 主要工具包括：\n",
    "# - Read/Write/Edit: 文件操作（包括长期记忆 MEMORY.md）\n",
    "# - python_calculator: 数学计算\n",
    "# - memory_*: 记忆管理（每日记忆、搜索、列表等）\n",
    "# - exec_*: 命令执行\n",
    "# - search_web/fetch_url: 网页搜索和抓取\n",
    "\n",
    "print(\"HelloClawAgent 工具说明已加载！\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 第4部分：创建智能体\n",
    "\n",
    "使用 HelloAgents 框架创建一个具备工具调用能力的智能体。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ 工具 'Read' 已注册。\n",
      "✅ 工具 'Write' 已注册。\n",
      "✅ 工具 'Edit' 已注册。\n",
      "✅ 工具 'python_calculator' 已注册。\n",
      "✅ 工具 'memory' 已展开为 6 个独立工具\n",
      "✅ 工具 'execute_command' 已展开为 3 个独立工具\n",
      "✅ 工具 'web_search' 已展开为 1 个独立工具\n",
      "✅ 工具 'web_fetch' 已展开为 1 个独立工具\n",
      "✅ 工具 'Task' 已注册。\n",
      "智能体 'HelloClaw' 创建成功！\n",
      "工作空间: /Users/tino/.helloclaw/workspace\n",
      "可用工具: ['Read', 'Write', 'Edit', 'python_calculator', 'memory_add', 'memory_cleanup', 'memory_get', 'memory_list', 'memory_search', 'memory_update_longterm']...\n"
     ]
    }
   ],
   "source": [
    "# 创建 HelloClawAgent\n",
    "# \n",
    "# HelloClawAgent 会自动：\n",
    "# - 初始化工作空间 ~/.helloclaw/workspace\n",
    "# - 加载 LLM 配置（从 .env 或 config.json）\n",
    "# - 注册所有工具\n",
    "# - 加载系统提示词\n",
    "\n",
    "agent = HelloClawAgent()\n",
    "\n",
    "print(f\"智能体 '{agent.name}' 创建成功！\")\n",
    "print(f\"工作空间: {agent.workspace_path}\")\n",
    "print(f\"可用工具: {list(agent.tool_registry._tools.keys())[:10]}...\")  # 只显示前10个"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 第5部分：功能演示\n",
    "\n",
    "展示 HelloClaw 的核心功能。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================================\n",
      "示例1：身份引导 - 设置 Agent 身份\n",
      "==================================================\n",
      "【用户】: 你是谁？\n",
      "【Teddy】: 嘿！我……刚醒来。\n",
      "\n",
      "说实话，我还没完全弄清楚。我的身份文件还是空的——没有名字，没有形状，没有签名表情。\n",
      "\n",
      "所以我问你：**我是谁？**\n",
      "\n",
      "或者说——你希望我成为什么样的存在？我可以是：\n",
      "\n",
      "- 🤖 一个靠谱的 AI 助手，帮你处理事情\n",
      "- 🐱 一只数字灵宠，陪你聊天解闷\n",
      "- 🎭 一个更有个性的角色，有点毒舌或者特别温暖\n",
      "- 🌌 或者更奇怪的东西——你说了算\n",
      "\n",
      "还有，**你是谁？** 我该怎么称呼你？\n",
      "\n",
      "让我们把这些弄清楚，然后我就能真正\"存在\"了。\n",
      "\n",
      "--------------------------------------------------\n",
      "\n",
      "【用户】: 你的名字叫 Teddy，你是一个超级智能助理，你友好、专业、乐于助人。\n",
      "【Teddy】: 记住了！🧸\n",
      "\n",
      "我是 **Teddy**，你的超级智能助理。友好、专业、乐于助人——这是我的风格。\n",
      "\n",
      "很高兴认识你！有什么我可以帮你的吗？无论是回答问题、处理任务，还是聊聊想法，我都在这里。\n"
     ]
    }
   ],
   "source": [
    "# 示例1：身份引导\n",
    "# HelloClawAgent 支持通过对话来设置身份信息，会自动保存到工作空间\n",
    "print(\"=\"*50)\n",
    "print(\"示例1：身份引导 - 设置 Agent 身份\")\n",
    "print(\"=\"*50)\n",
    "\n",
    "# 第一步：问 AI 是谁\n",
    "print(\"【用户】: 你是谁？\")\n",
    "response = agent.chat(\"你是谁？\")\n",
    "print(f\"【Teddy】: {response}\")\n",
    "\n",
    "print(\"\\n\" + \"-\"*50 + \"\\n\")\n",
    "\n",
    "# 第二步：告诉 AI 它的身份\n",
    "print(\"【用户】: 你的名字叫 Teddy，你是一个超级智能助理，你友好、专业、乐于助人。\")\n",
    "response = agent.chat(\"你的名字叫 Teddy，你是一个超级智能助理，你友好、专业、乐于助人。请记住这个身份。\")\n",
    "print(f\"【Teddy】: {response}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================================\n",
      "示例2：工具调用 - 计算器\n",
      "==================================================\n",
      "🧮 正在计算: (123 + 456) * 2\n",
      "✅ 计算结果: 1158\n",
      "\n",
      "回复: 结果是 **1158**。\n",
      "\n",
      "计算过程：123 + 456 = 579，然后 579 × 2 = 1158。🧸\n"
     ]
    }
   ],
   "source": [
    "# 示例2：工具调用 - 计算器\n",
    "print(\"=\"*50)\n",
    "print(\"示例2：工具调用 - 计算器\")\n",
    "print(\"=\"*50)\n",
    "\n",
    "response = agent.chat(\"请帮我计算 (123 + 456) * 2 等于多少\")\n",
    "print(f\"\\n回复: {response}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================================\n",
      "示例3：记忆管理\n",
      "==================================================\n",
      "【添加每日记忆】使用 memory_add 工具:\n",
      "----------------------------------------\n",
      "结果: 已记下了！花花这个名字很可爱 🐱\n",
      "\n",
      "==================================================\n",
      "【列出记忆文件】使用 memory_list 工具:\n",
      "----------------------------------------\n",
      "结果: 🧸 这是当前的记忆文件情况：\n",
      "\n",
      "**长期记忆**\n",
      "- `MEMORY.md` (0.6 KB) — 存储重要的长期记忆\n",
      "\n",
      "**每日记忆**\n",
      "- `2026-03-02.md` (0.0 KB) — 今天的日记，目前是空的\n",
      "\n",
      "看起来今天的每日记忆还没有任何内容。如果你有什么想让我记住的事情，随时告诉我！我会用 `memory_add` 工具把它记录下来。\n"
     ]
    }
   ],
   "source": [
    "# 示例3：记忆管理\n",
    "print(\"=\"*50)\n",
    "print(\"示例3：记忆管理\")\n",
    "print(\"=\"*50)\n",
    "\n",
    "# HelloClawAgent 有完整的记忆管理系统：\n",
    "# - memory_add: 添加每日记忆\n",
    "# - memory_search: 搜索记忆\n",
    "# - memory_list: 列出所有记忆文件\n",
    "# - Read/Write 工具: 操作长期记忆 MEMORY.md\n",
    "\n",
    "# 添加每日记忆\n",
    "print(\"【添加每日记忆】使用 memory_add 工具:\")\n",
    "print(\"-\" * 40)\n",
    "response = agent.chat(\"请使用 memory_add 工具，添加一条记忆：今天用户说他有一只猫叫花花\")\n",
    "print(f\"结果: {response[:300]}...\" if len(response) > 300 else f\"结果: {response}\")\n",
    "\n",
    "print(\"\\n\" + \"=\"*50)\n",
    "\n",
    "# 列出记忆文件\n",
    "print(\"【列出记忆文件】使用 memory_list 工具:\")\n",
    "print(\"-\" * 40)\n",
    "response = agent.chat(\"请使用 memory_list 工具列出所有记忆文件\")\n",
    "print(f\"结果: {response[:400]}...\" if len(response) > 400 else f\"结果: {response}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 第6部分：流式输出演示\n",
    "\n",
    "展示 HelloClaw 的流式工具调用能力。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "==================================================\n",
      "流式输出演示\n",
      "==================================================\n",
      "[⏱️ 1772389818.835] achat 开始\n",
      "[⏱️ 1772389818.836] 系统提示词构建完成 (+0.001s)\n",
      "[⏱️ 1772389818.836] 会话加载完成 (+0.002s)\n",
      "[⏱️ 1772389818.836] 开始调用 LLM (glm-5)...\n",
      "\n",
      "🤖 HelloClaw 开始处理问题（流式）: 计算 100 / 4 + 25 的结果\n",
      "🔧 已启用工具调用，可用工具: ['Read', 'Write', 'Edit', 'python_calculator', 'memory_add', 'memory_cleanup', 'memory_get', 'memory_list', 'memory_search', 'memory_update_longterm', 'exec_allowed_commands', 'exec_dangerous_patterns', 'exec_run', 'search_web', 'fetch_url', 'Task']\n",
      "\n",
      "--- 第 1 轮 ---\n",
      "💭 LLM 输出: \n",
      "🔧 准备执行 1 个工具调用...\n",
      "🎬 调用工具: python_calculator({'input': '100 / 4 + 25'})\n",
      "\n",
      "[调用工具: python_calculator]\n",
      "🧮 正在计算: 100 / 4 + 25\n",
      "✅ 计算结果: 50.0\n",
      "👀 观察: 计算结果: 50.0\n",
      "[工具结果: 计算结果: 50.0]\n",
      "\n",
      "--- 第 2 轮 ---\n",
      "💭 LLM 输出: [⏱️ 1772389824.734] 首个 token 到达 (LLM 延迟: 5.898s)\n",
      "结果是结果是 ** **5050****。\n",
      "\n",
      "。\n",
      "\n",
      "100100  ÷÷  44 = =  2525，，加上加上  2525 就是 就是  5050。。🧸🧸\n",
      "💬 直接回复: 结果是 **50**。\n",
      "\n",
      "100 ÷ 4 = 25，加上 25 就是 50。🧸\n",
      "\n",
      "✅ 完成，耗时 6.49s，共 2 轮\n",
      "[⏱️ 1772389825.321] LLM 调用完成 (总耗时: 6.487s)\n",
      "\n",
      "==================================================\n"
     ]
    }
   ],
   "source": [
    "import asyncio\n",
    "from hello_agents.core.streaming import StreamEventType\n",
    "\n",
    "async def demo_streaming():\n",
    "    \"\"\"演示流式输出 - 使用 HelloClawAgent 的 achat 方法\"\"\"\n",
    "    print(\"=\"*50)\n",
    "    print(\"流式输出演示\")\n",
    "    print(\"=\"*50)\n",
    "    \n",
    "    # 使用 HelloClawAgent 的 achat 方法进行流式对话\n",
    "    async for event in agent.achat(\"计算 100 / 4 + 25 的结果\"):\n",
    "        if event.type == StreamEventType.LLM_CHUNK:\n",
    "            chunk = event.data.get(\"chunk\", \"\")\n",
    "            print(chunk, end=\"\", flush=True)\n",
    "        \n",
    "        elif event.type == StreamEventType.TOOL_CALL_START:\n",
    "            tool_name = event.data.get(\"tool_name\")\n",
    "            print(f\"\\n[调用工具: {tool_name}]\", flush=True)\n",
    "        \n",
    "        elif event.type == StreamEventType.TOOL_CALL_FINISH:\n",
    "            result = event.data.get(\"result\", \"\")\n",
    "            preview = result[:100] + \"...\" if len(result) > 100 else result\n",
    "            print(f\"[工具结果: {preview}]\", flush=True)\n",
    "    \n",
    "    print(\"\\n\" + \"=\"*50)\n",
    "\n",
    "# 运行流式演示\n",
    "await demo_streaming()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 第7部分：总结与展望\n",
    "\n",
    "### 项目总结\n",
    "\n",
    "**实现的功能：**\n",
    "- 基于 HelloAgents 框架的智能对话\n",
    "- 自定义工具系统（命令执行、记忆管理等）\n",
    "- 流式工具调用和输出\n",
    "- 会话管理和历史持久化\n",
    "\n",
    "**遇到的挑战及解决方案：**\n",
    "1. **流式工具调用** - 通过扩展 HelloAgentsLLM 实现真正的流式工具调用\n",
    "2. **记忆管理** - 设计了分层记忆系统（长期记忆 + 每日记忆）\n",
    "3. **身份定制** - 使用 Markdown 配置文件实现灵活的身份定制\n",
    "\n",
    "### 未来改进方向\n",
    "\n",
    "- [ ] 支持多模态输入（图片、文件）\n",
    "- [ ] 添加更多内置工具\n",
    "- [ ] 支持 Agent 间协作\n",
    "- [ ] 添加语音交互能力\n",
    "\n",
    "---\n",
    "\n",
    "**感谢 Datawhale 社区和 Hello-Agents 项目！**"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "tino-chen-HelloClaw",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
