From 1192eec1272865d146f470199ca63477ecf84f4a Mon Sep 17 00:00:00 2001 From: gaoyunlong <2785866137@qq.com> Date: Tue, 11 Aug 2026 22:57:32 +0800 Subject: [PATCH 1/2] docs(integrations): add copy-paste recipes for LlamaIndex/CrewAI/AutoGen/LangGraph --- README.md | 2 + examples/README.md | 8 + repo_pages/.vitepress/config.mts | 1 + repo_pages/guide/framework-integrations.md | 235 ++++++++++++++++++ repo_pages/zh/guide/framework-integrations.md | 235 ++++++++++++++++++ 5 files changed, 481 insertions(+) create mode 100644 repo_pages/guide/framework-integrations.md create mode 100644 repo_pages/zh/guide/framework-integrations.md diff --git a/README.md b/README.md index 5524178..1b14508 100644 --- a/README.md +++ b/README.md @@ -119,6 +119,8 @@ hebb agent-sync sync --dry-run # Preview historical session import Docker, one-line install, and source build: [Installation Guide](https://afx-team.github.io/hebb-mind/guide/installation.html). +Use **LlamaIndex, CrewAI, AutoGen, or LangGraph**? Paste a ~10-line snippet to give your agent Hebb Mind memory — [Python Framework Integrations](https://afx-team.github.io/hebb-mind/guide/framework-integrations.html). + ## 30-second Python SDK ```python diff --git a/examples/README.md b/examples/README.md index 11b3931..e6e3986 100644 --- a/examples/README.md +++ b/examples/README.md @@ -17,8 +17,13 @@ Want a chatbot that remembers across runs? ──→ 02_persistent_chat.py Want your AI coding agent to use Hebb Mind? ──→ 03_mcp_quickstart.md Want to see (or reproduce) benchmark numbers? ──→ 04_benchmarks_locomo.md Want to plug Hebb Mind into LangChain? ──→ 05_langchain_adapter.py (WIP) +Want LlamaIndex / CrewAI / AutoGen / LangGraph? ──→ Python framework integrations guide ``` +For LlamaIndex / CrewAI / AutoGen / LangGraph, paste a ~10-line snippet from the +[Python Framework Integrations guide](../repo_pages/guide/framework-integrations.md) +— it connects each framework to the shipped MCP / REST surfaces today. + ## Table of contents | # | File | What it shows | @@ -81,4 +86,7 @@ python examples/02_persistent_chat.py The audit (`reports/analysis/audit-examples.md`) lists the next examples we'd love to see: LangChain (#5 here is a starting skeleton), LlamaIndex, OpenAI Agents SDK, CrewAI, and a Jupyter walkthrough of the consolidation lifecycle. +Until the native adapters land, copy-paste recipes for LlamaIndex / CrewAI / +AutoGen / LangGraph live in the +[Python Framework Integrations guide](../repo_pages/guide/framework-integrations.md). PRs welcome — please keep each example self-contained and under ~200 lines. diff --git a/repo_pages/.vitepress/config.mts b/repo_pages/.vitepress/config.mts index 6550894..a70b89e 100644 --- a/repo_pages/.vitepress/config.mts +++ b/repo_pages/.vitepress/config.mts @@ -316,6 +316,7 @@ function guideSidebar(prefix = '') { { text: prefix ? 'Agent 同步' : 'Agent Sync', link: `${prefix}/guide/agent-sync` }, { text: prefix ? '导入 Agent 记忆' : 'Import Agent Memory', link: `${prefix}/guide/import` }, { text: prefix ? 'MCP 集成' : 'MCP Integration', link: `${prefix}/guide/mcp-integration` }, + { text: prefix ? 'Python 框架集成' : 'Python Framework Integrations', link: `${prefix}/guide/framework-integrations` }, { text: prefix ? 'Web 控制台' : 'Web Console', link: `${prefix}/guide/web-console` }, { text: prefix ? '从其他系统迁移' : 'Migration from mem0 / Letta / Zep', link: `${prefix}/guide/migration` }, ], diff --git a/repo_pages/guide/framework-integrations.md b/repo_pages/guide/framework-integrations.md new file mode 100644 index 0000000..1c11120 --- /dev/null +++ b/repo_pages/guide/framework-integrations.md @@ -0,0 +1,235 @@ +--- +description: "Connect LlamaIndex, CrewAI, AutoGen, and LangGraph to Hebb Mind in ~10 lines — copy-paste snippets that write and recall long-term agent memory over the hebb-mcp stdio server or the REST API." +--- + +# Use Hebb Mind from a Python Agent Framework + +Hebb Mind ships two surfaces that any Python agent framework can talk to **today** — no native adapter package required: + +- **MCP stdio server** (`hebb-mcp`) exposing the tools `write_memory`, `search_memory`, `consolidate`, and `ingest_conversation` (see [MCP Integration](./mcp-integration.md)). +- **REST API** at `http://localhost:8321` — `POST /api/v1/search` with `{"query": ..., "top_k": ...}` and `POST /api/v1/memories`. + +Each section below is a copy-paste recipe for one framework. Paste it, run it, and your agent can store and recall memories through Hebb Mind. + +::: tip Start the service first +Every snippet assumes the Hebb Mind background service is reachable at `http://localhost:8321`. If you haven't installed it yet: + +```bash +pipx install hebb-mind +hebb setup # first time only — picks the embedding model +hebb service install # registers the OS background service (no admin needed) +``` + +Verify it's up with: + +```bash +curl -X POST http://localhost:8321/api/v1/search \ + -H 'Content-Type: application/json' \ + -d '{"query":"ping","top_k":1}' +``` +::: + +::: tip Use the absolute path to `hebb-mcp` +The snippets below write `command="hebb-mcp"` for brevity. If the framework's MCP client doesn't inherit your shell `PATH` (GUI apps, some service managers), run `which hebb-mcp` (Windows: `where hebb-mcp`) and pass the **absolute path** as `command` — otherwise the server silently fails to start. +::: + +::: tip The agent needs an LLM +All four agent snippets rely on an LLM to decide when to call the memory tools. The examples use OpenAI (`OPENAI_API_KEY` in your environment); every framework also works with any OpenAI-compatible or local model (e.g. Ollama) — see each framework's docs. +::: + +--- + +## LlamaIndex + +LlamaIndex loads MCP servers through `llama-index-tools-mcp`. We connect to the `hebb-mcp` stdio server and convert its tools into LlamaIndex `FunctionTool`s — no LLM key needed to try it: + +```bash +pip install llama-index llama-index-tools-mcp +``` + +```python +import asyncio +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client +from llama_index.tools.mcp import McpToolSpec + +async def main(): + # 1. Launch hebb-mcp over stdio and load its tools + async with stdio_client(StdioServerParameters(command="hebb-mcp", args=[])) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + tools = await McpToolSpec(client=session).to_tool_list_async() + search = next(t for t in tools if t.metadata.name == "search_memory") + + # 2. Recall what Hebb Mind already knows about the user + print(await search.acall(query="What UI preferences does the user have?", top_k=5)) + +asyncio.run(main()) +``` + +To let an agent decide when to write/recall, hand the whole `tools` list to `FunctionCallingAgentWorker.from_tools(tools, llm=...).as_agent()` instead. + +Prefer REST? `POST /api/v1/search` returns `{"results": [{"memory": {...}, "score": ...}]}` — wrap the HTTP call in a `FunctionTool` for tool-calling agents, or in a small retriever to plug into a `RetrieverQueryEngine`. + +--- + +## CrewAI + +CrewAI loads MCP servers through `crewai-tools`' `MCPServerAdapter`. The `with` block starts `hebb-mcp`, yields its tools, and shuts the process down when the crew finishes: + +```bash +pip install crewai crewai-tools +``` + +```python +from crewai import Agent, Task, Crew +from crewai_tools import MCPServerAdapter +from mcp import StdioServerParameters + +# 1. Launch hebb-mcp over stdio; the with-block yields its tools +with MCPServerAdapter(StdioServerParameters(command="hebb-mcp", args=[])) as tools: + # 2. Give an agent the memory tools and run one recall task + agent = Agent( + role="Memory assistant", + goal="Recall the user's stored preferences from Hebb Mind", + backstory="A helpful agent backed by Hebb Mind long-term memory.", + tools=tools, + ) + crew = Crew(agents=[agent], tasks=[ + Task(description="What UI preferences does the user prefer?", + expected_output="A short sentence.", agent=agent), + ]) + print(crew.kickoff()) +``` + +Prefer REST? Call `POST /api/v1/memories` / `POST /api/v1/search` from a `crewai_tools.BaseTool` subclass — a `_run(query)` that does `requests.post` is all it takes. + +--- + +## AutoGen + +AutoGen **0.4+** discovers MCP servers with `mcp_server_tools`. We connect to `hebb-mcp` over stdio and attach the tools to an `AssistantAgent`: + +```bash +pip install "autogen-agentchat" "autogen-ext[mcp,openai]" +``` + +```python +import asyncio +from autogen_agentchat.agents import AssistantAgent +from autogen_ext.models.openai import OpenAIChatCompletionClient +from autogen_ext.tools.mcp import StdioServerParams, mcp_server_tools + +async def main(): + # 1. Discover the hebb-mcp tools over stdio + tools = await mcp_server_tools(StdioServerParams(command="hebb-mcp", args=[])) + + # 2. Attach them to an agent and run a recall task + agent = AssistantAgent( + "memory_assistant", + model_client=OpenAIChatCompletionClient(model="gpt-4o-mini"), + tools=tools, + ) + await agent.run(task="Search Hebb Mind for the user's UI preferences.") + +asyncio.run(main()) +``` + +::: warning AutoGen 0.2 vs 0.4+ +AutoGen 0.2 (legacy) and 0.4+ have **incompatible APIs** — the snippet above targets 0.4+ (`autogen-agentchat` / `autogen-ext`). On 0.2, use `autogen.ConversableAgent` with a `register_function` that calls the REST API instead. +::: + +--- + +## LangGraph + +LangGraph loads MCP tools through `langchain-mcp-adapters`. We connect to `hebb-mcp` over stdio and bind the tools into a prebuilt ReAct agent: + +```bash +pip install langgraph langchain-mcp-adapters langchain-openai +``` + +```python +import asyncio +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client +from langchain_mcp_adapters.tools import load_mcp_tools +from langchain_openai import ChatOpenAI +from langgraph.prebuilt import create_react_agent + +async def main(): + # 1. Launch hebb-mcp over stdio and load its tools + async with stdio_client(StdioServerParameters(command="hebb-mcp", args=[])) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + tools = await load_mcp_tools(session) + + # 2. Bind them into a ReAct agent and ask a question + agent = create_react_agent(ChatOpenAI(model="gpt-4o-mini"), tools) + result = await agent.ainvoke({"messages": [("user", "What UI preferences do you remember?")]}) + print(result["messages"][-1].content) + +asyncio.run(main()) +``` + +::: tip The LangChain skeleton is a separate follow-up +`examples/05_langchain_adapter.py` is a `NotImplementedError` skeleton for a native `BaseRetriever` / `BaseChatMessageHistory`. This page is the low-cost "paste a snippet" bridge; a native adapter is tracked separately. +::: + +--- + +## REST API alternative (no MCP client needed) + +If a framework's MCP adapter is missing or a version you use doesn't support it, the REST API is the fallback — it needs only `httpx` (or `requests`). This write + search round-trip works in any framework; wrap the two functions in the framework's function-tool class to give them to an agent: + +```python +import httpx + +BASE = "http://localhost:8321/api/v1" + +def remember(content: str, tags: list[str] | None = None) -> dict: + resp = httpx.post(f"{BASE}/memories", json={ + "content": content, "tags": tags or [], "importance_score": 7.5, + }) + resp.raise_for_status() + return resp.json() + +def recall(query: str, top_k: int = 5) -> list[str]: + resp = httpx.post(f"{BASE}/search", json={"query": query, "top_k": top_k}) + resp.raise_for_status() + return [hit["memory"]["content"] for hit in resp.json()["results"]] + +remember("User prefers dark mode and a compact layout", tags=["preference", "ui"]) +for content in recall("UI preferences"): + print(content) +``` + +## Which surface should I pick? + +| Framework | Lowest-friction path | Why | +|-----------|----------------------|-----| +| LlamaIndex | MCP (`McpToolSpec`) | First-class MCP client → `FunctionTool` flow | +| CrewAI | MCP (`MCPServerAdapter`) | `tools=[...]` on `Agent` is idiomatic | +| AutoGen 0.4+ | MCP (`mcp_server_tools`) | `StdioServerParams` is the supported loader | +| LangGraph | MCP (`load_mcp_tools`) | Tools bind straight into graph nodes | + +Reach for the **REST API** when a framework has no MCP adapter (or a version mismatch), or when you need the full response shape — `results` plus graph-expanded `related` — that the MCP tool collapses into a text summary. + +## How it works + +```mermaid +flowchart LR + subgraph Agent["Your framework agent"] + LI[LlamaIndex] + CA[CrewAI] + AG[AutoGen] + LG[LangGraph] + end + Agent -- stdio --> MCP[hebb-mcp MCP server] + Agent -- httpx / requests --> REST[REST API :8321] + MCP -- HTTP --> SRV[hebb service
localhost:8321] + REST --> SRV + SRV --> Store[Storage / Embedder / Hybrid Search / Tag graph] +``` + +The MCP server is a thin wrapper that translates tool calls into HTTP requests to the running Hebb Mind service — so both paths hit the same storage, embedding, and hybrid-search engine. diff --git a/repo_pages/zh/guide/framework-integrations.md b/repo_pages/zh/guide/framework-integrations.md new file mode 100644 index 0000000..7379f12 --- /dev/null +++ b/repo_pages/zh/guide/framework-integrations.md @@ -0,0 +1,235 @@ +--- +description: "用约 10 行代码把 LlamaIndex、CrewAI、AutoGen、LangGraph 接入 Hebb Mind——通过 hebb-mcp stdio 服务或 REST API 写入并召回长期记忆,复制即用。" +--- + +# 从 Python 智能体框架使用 Hebb Mind + +Hebb Mind 目前提供两条任何 Python 智能体框架都可以直接使用的接入面,无需等待原生适配器包: + +- **MCP stdio 服务**(`hebb-mcp`),暴露 `write_memory`、`search_memory`、`consolidate`、`ingest_conversation` 四个工具(参见 [MCP 集成](./mcp-integration.md))。 +- **REST API**(`http://localhost:8321`)——`POST /api/v1/search`(请求体 `{"query": ..., "top_k": ...}`)与 `POST /api/v1/memories`。 + +下面每个小节是一个框架的复制即用示例。粘贴运行后,你的智能体就能通过 Hebb Mind 存储与召回记忆。 + +::: tip 先启动服务 +所有示例都假设 Hebb Mind 后台服务运行在 `http://localhost:8321`。如果还没安装: + +```bash +pipx install hebb-mind +hebb setup # 首次使用 — 选择嵌入模型 +hebb service install # 注册系统后台服务(默认无需管理员权限) +``` + +用下面命令确认服务已就绪: + +```bash +curl -X POST http://localhost:8321/api/v1/search \ + -H 'Content-Type: application/json' \ + -d '{"query":"ping","top_k":1}' +``` +::: + +::: tip 使用 `hebb-mcp` 的绝对路径 +下面示例为简洁起见写的是 `command="hebb-mcp"`。如果框架的 MCP 客户端没有继承你的 shell `PATH`(GUI 应用、部分服务管理器),请先运行 `which hebb-mcp`(Windows:`where hebb-mcp`),把 **绝对路径** 填入 `command`——否则 MCP 服务会静默启动失败。 +::: + +::: tip 智能体需要一个 LLM +四个智能体示例都依赖 LLM 来决定何时调用记忆工具。示例使用 OpenAI(环境变量 `OPENAI_API_KEY`);各框架同样支持任意 OpenAI 兼容或本地模型(如 Ollama),详见各框架文档。 +::: + +--- + +## LlamaIndex + +LlamaIndex 通过 `llama-index-tools-mcp` 加载 MCP 服务。我们连接 `hebb-mcp` stdio 服务,把它的工具转换成 LlamaIndex 的 `FunctionTool`——这一步不需要 LLM key 即可体验: + +```bash +pip install llama-index llama-index-tools-mcp +``` + +```python +import asyncio +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client +from llama_index.tools.mcp import McpToolSpec + +async def main(): + # 1. 通过 stdio 启动 hebb-mcp 并加载其工具 + async with stdio_client(StdioServerParameters(command="hebb-mcp", args=[])) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + tools = await McpToolSpec(client=session).to_tool_list_async() + search = next(t for t in tools if t.metadata.name == "search_memory") + + # 2. 召回 Hebb Mind 已存储的关于用户的记忆 + print(await search.acall(query="What UI preferences does the user have?", top_k=5)) + +asyncio.run(main()) +``` + +如果想让智能体自行决定何时写入/召回,把整个 `tools` 列表交给 `FunctionCallingAgentWorker.from_tools(tools, llm=...).as_agent()` 即可。 + +倾向 REST?`POST /api/v1/search` 返回 `{"results": [{"memory": {...}, "score": ...}]}`——把 HTTP 调用包进一个 `FunctionTool`(供工具调用型智能体使用),或写一个轻量 retriever 接入 `RetrieverQueryEngine`。 + +--- + +## CrewAI + +CrewAI 通过 `crewai-tools` 的 `MCPServerAdapter` 加载 MCP 服务。`with` 块启动 `hebb-mcp`、产出工具列表,并在 crew 运行结束后关闭子进程: + +```bash +pip install crewai crewai-tools +``` + +```python +from crewai import Agent, Task, Crew +from crewai_tools import MCPServerAdapter +from mcp import StdioServerParameters + +# 1. 通过 stdio 启动 hebb-mcp;with 块产出其工具 +with MCPServerAdapter(StdioServerParameters(command="hebb-mcp", args=[])) as tools: + # 2. 把记忆工具交给一个 agent,运行一次召回任务 + agent = Agent( + role="Memory assistant", + goal="Recall the user's stored preferences from Hebb Mind", + backstory="A helpful agent backed by Hebb Mind long-term memory.", + tools=tools, + ) + crew = Crew(agents=[agent], tasks=[ + Task(description="What UI preferences does the user prefer?", + expected_output="A short sentence.", agent=agent), + ]) + print(crew.kickoff()) +``` + +倾向 REST?在 `crewai_tools.BaseTool` 子类里调用 `POST /api/v1/memories` / `POST /api/v1/search`——一个用 `requests.post` 的 `_run(query)` 就足够了。 + +--- + +## AutoGen + +AutoGen **0.4+** 用 `mcp_server_tools` 发现 MCP 服务。我们通过 stdio 连接 `hebb-mcp`,把工具挂到 `AssistantAgent` 上: + +```bash +pip install "autogen-agentchat" "autogen-ext[mcp,openai]" +``` + +```python +import asyncio +from autogen_agentchat.agents import AssistantAgent +from autogen_ext.models.openai import OpenAIChatCompletionClient +from autogen_ext.tools.mcp import StdioServerParams, mcp_server_tools + +async def main(): + # 1. 通过 stdio 发现 hebb-mcp 的工具 + tools = await mcp_server_tools(StdioServerParams(command="hebb-mcp", args=[])) + + # 2. 挂到 agent 上并运行一次召回任务 + agent = AssistantAgent( + "memory_assistant", + model_client=OpenAIChatCompletionClient(model="gpt-4o-mini"), + tools=tools, + ) + await agent.run(task="Search Hebb Mind for the user's UI preferences.") + +asyncio.run(main()) +``` + +::: warning AutoGen 0.2 与 0.4+ 的区别 +AutoGen 0.2(旧版)与 0.4+ 的 API **互不兼容**——上面的示例针对 0.4+(`autogen-agentchat` / `autogen-ext`)。0.2 请改用 `autogen.ConversableAgent`,通过 `register_function` 直接调用 REST API。 +::: + +--- + +## LangGraph + +LangGraph 通过 `langchain-mcp-adapters` 加载 MCP 工具。我们通过 stdio 连接 `hebb-mcp`,把工具绑定进预构建的 ReAct 智能体: + +```bash +pip install langgraph langchain-mcp-adapters langchain-openai +``` + +```python +import asyncio +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client +from langchain_mcp_adapters.tools import load_mcp_tools +from langchain_openai import ChatOpenAI +from langgraph.prebuilt import create_react_agent + +async def main(): + # 1. 通过 stdio 启动 hebb-mcp 并加载其工具 + async with stdio_client(StdioServerParameters(command="hebb-mcp", args=[])) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + tools = await load_mcp_tools(session) + + # 2. 绑定进 ReAct 智能体并提问 + agent = create_react_agent(ChatOpenAI(model="gpt-4o-mini"), tools) + result = await agent.ainvoke({"messages": [("user", "What UI preferences do you remember?")]}) + print(result["messages"][-1].content) + +asyncio.run(main()) +``` + +::: tip LangChain 骨架是另一项后续工作 +`examples/05_langchain_adapter.py` 是原生 `BaseRetriever` / `BaseChatMessageHistory` 适配器的 `NotImplementedError` 骨架。本页是低成本的"贴段代码就连上"方案;原生适配器单独跟踪。 +::: + +--- + +## REST API 备选方案(无需 MCP 客户端) + +如果框架缺少 MCP 适配器,或你使用的版本不支持,REST API 就是兜底方案——只需要 `httpx`(或 `requests`)。下面的写入 + 召回往返可在任意框架中使用;把两个函数包进框架的函数工具类,就能交给智能体: + +```python +import httpx + +BASE = "http://localhost:8321/api/v1" + +def remember(content: str, tags: list[str] | None = None) -> dict: + resp = httpx.post(f"{BASE}/memories", json={ + "content": content, "tags": tags or [], "importance_score": 7.5, + }) + resp.raise_for_status() + return resp.json() + +def recall(query: str, top_k: int = 5) -> list[str]: + resp = httpx.post(f"{BASE}/search", json={"query": query, "top_k": top_k}) + resp.raise_for_status() + return [hit["memory"]["content"] for hit in resp.json()["results"]] + +remember("User prefers dark mode and a compact layout", tags=["preference", "ui"]) +for content in recall("UI preferences"): + print(content) +``` + +## 该选哪条接入面? + +| 框架 | 摩擦最低的路径 | 原因 | +|------|----------------|------| +| LlamaIndex | MCP(`McpToolSpec`) | 一等公民的 MCP 客户端 → `FunctionTool` 流程 | +| CrewAI | MCP(`MCPServerAdapter`) | `Agent` 上的 `tools=[...]` 是最惯用写法 | +| AutoGen 0.4+ | MCP(`mcp_server_tools`) | `StdioServerParams` 是官方加载方式 | +| LangGraph | MCP(`load_mcp_tools`) | 工具直接绑定进图节点 | + +当框架没有 MCP 适配器(或版本不匹配),或需要完整响应结构——`results` 加上知识图谱扩展的 `related`,而 MCP 工具只返回文本摘要时——请改用 **REST API**。 + +## 工作原理 + +```mermaid +flowchart LR + subgraph Agent["你的框架智能体"] + LI[LlamaIndex] + CA[CrewAI] + AG[AutoGen] + LG[LangGraph] + end + Agent -- stdio --> MCP[hebb-mcp MCP 服务] + Agent -- httpx / requests --> REST[REST API :8321] + MCP -- HTTP --> SRV[hebb 服务
localhost:8321] + REST --> SRV + SRV --> Store[存储 / 嵌入 / 混合检索 / 标签图谱] +``` + +MCP 服务是一个薄封装:把工具调用翻译成对 Hebb Mind 服务的 HTTP 请求。两条路径最终都落在同一套存储、嵌入与混合检索引擎上。 From ab10dc447b302ac0e71d46dba23835d91b37345e Mon Sep 17 00:00:00 2001 From: gaoyunlong <2785866137@qq.com> Date: Tue, 11 Aug 2026 23:33:07 +0800 Subject: [PATCH 2/2] docs(integrations): address CodeRabbit review on framework-integrations guide - make the curl readiness check fail on HTTP 4xx/5xx (-f) - scope the LLM prerequisite tip to the agent snippets; LlamaIndex direct-call example needs no LLM key - translate natural-language strings in the zh page code snippets (queries, agent metadata, prompts); keep API identifiers unchanged - add explicit pip install httpx before the REST example (EN + zh parity) Closes #29 --- repo_pages/guide/framework-integrations.md | 12 +++++-- repo_pages/zh/guide/framework-integrations.md | 32 +++++++++++-------- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/repo_pages/guide/framework-integrations.md b/repo_pages/guide/framework-integrations.md index 1c11120..ffed3b3 100644 --- a/repo_pages/guide/framework-integrations.md +++ b/repo_pages/guide/framework-integrations.md @@ -23,7 +23,7 @@ hebb service install # registers the OS background service (no admin needed) Verify it's up with: ```bash -curl -X POST http://localhost:8321/api/v1/search \ +curl -f -X POST http://localhost:8321/api/v1/search \ -H 'Content-Type: application/json' \ -d '{"query":"ping","top_k":1}' ``` @@ -34,7 +34,7 @@ The snippets below write `command="hebb-mcp"` for brevity. If the framework's MC ::: ::: tip The agent needs an LLM -All four agent snippets rely on an LLM to decide when to call the memory tools. The examples use OpenAI (`OPENAI_API_KEY` in your environment); every framework also works with any OpenAI-compatible or local model (e.g. Ollama) — see each framework's docs. +The agent snippets (CrewAI, AutoGen, LangGraph) rely on an LLM to decide when to call the memory tools — the LlamaIndex snippet calls the tools directly and needs no LLM key. The examples use OpenAI (`OPENAI_API_KEY` in your environment); every framework also works with any OpenAI-compatible or local model (e.g. Ollama) — see each framework's docs. ::: --- @@ -180,7 +180,13 @@ asyncio.run(main()) ## REST API alternative (no MCP client needed) -If a framework's MCP adapter is missing or a version you use doesn't support it, the REST API is the fallback — it needs only `httpx` (or `requests`). This write + search round-trip works in any framework; wrap the two functions in the framework's function-tool class to give them to an agent: +If a framework's MCP adapter is missing or a version you use doesn't support it, the REST API is the fallback — it needs only `httpx` (or `requests`). Install it in the environment that runs the framework code: + +```bash +pip install httpx +``` + +This write + search round-trip works in any framework; wrap the two functions in the framework's function-tool class to give them to an agent: ```python import httpx diff --git a/repo_pages/zh/guide/framework-integrations.md b/repo_pages/zh/guide/framework-integrations.md index 7379f12..0f98dba 100644 --- a/repo_pages/zh/guide/framework-integrations.md +++ b/repo_pages/zh/guide/framework-integrations.md @@ -23,7 +23,7 @@ hebb service install # 注册系统后台服务(默认无需管理员权限 用下面命令确认服务已就绪: ```bash -curl -X POST http://localhost:8321/api/v1/search \ +curl -f -X POST http://localhost:8321/api/v1/search \ -H 'Content-Type: application/json' \ -d '{"query":"ping","top_k":1}' ``` @@ -34,7 +34,7 @@ curl -X POST http://localhost:8321/api/v1/search \ ::: ::: tip 智能体需要一个 LLM -四个智能体示例都依赖 LLM 来决定何时调用记忆工具。示例使用 OpenAI(环境变量 `OPENAI_API_KEY`);各框架同样支持任意 OpenAI 兼容或本地模型(如 Ollama),详见各框架文档。 +使用智能体的示例(CrewAI、AutoGen、LangGraph)依赖 LLM 来决定何时调用记忆工具——LlamaIndex 示例直接调用工具,不需要 LLM key。示例使用 OpenAI(环境变量 `OPENAI_API_KEY`);各框架同样支持任意 OpenAI 兼容或本地模型(如 Ollama),详见各框架文档。 ::: --- @@ -62,7 +62,7 @@ async def main(): search = next(t for t in tools if t.metadata.name == "search_memory") # 2. 召回 Hebb Mind 已存储的关于用户的记忆 - print(await search.acall(query="What UI preferences does the user have?", top_k=5)) + print(await search.acall(query="用户有哪些界面偏好?", top_k=5)) asyncio.run(main()) ``` @@ -90,14 +90,14 @@ from mcp import StdioServerParameters with MCPServerAdapter(StdioServerParameters(command="hebb-mcp", args=[])) as tools: # 2. 把记忆工具交给一个 agent,运行一次召回任务 agent = Agent( - role="Memory assistant", - goal="Recall the user's stored preferences from Hebb Mind", - backstory="A helpful agent backed by Hebb Mind long-term memory.", + role="记忆助手", + goal="从 Hebb Mind 召回用户已存储的偏好", + backstory="一个由 Hebb Mind 长期记忆支持的助手。", tools=tools, ) crew = Crew(agents=[agent], tasks=[ - Task(description="What UI preferences does the user prefer?", - expected_output="A short sentence.", agent=agent), + Task(description="用户偏好什么界面风格?", + expected_output="一句话。", agent=agent), ]) print(crew.kickoff()) ``` @@ -130,7 +130,7 @@ async def main(): model_client=OpenAIChatCompletionClient(model="gpt-4o-mini"), tools=tools, ) - await agent.run(task="Search Hebb Mind for the user's UI preferences.") + await agent.run(task="在 Hebb Mind 中搜索用户的界面偏好。") asyncio.run(main()) ``` @@ -166,7 +166,7 @@ async def main(): # 2. 绑定进 ReAct 智能体并提问 agent = create_react_agent(ChatOpenAI(model="gpt-4o-mini"), tools) - result = await agent.ainvoke({"messages": [("user", "What UI preferences do you remember?")]}) + result = await agent.ainvoke({"messages": [("user", "你记得用户有哪些界面偏好?")]}) print(result["messages"][-1].content) asyncio.run(main()) @@ -180,7 +180,13 @@ asyncio.run(main()) ## REST API 备选方案(无需 MCP 客户端) -如果框架缺少 MCP 适配器,或你使用的版本不支持,REST API 就是兜底方案——只需要 `httpx`(或 `requests`)。下面的写入 + 召回往返可在任意框架中使用;把两个函数包进框架的函数工具类,就能交给智能体: +如果框架缺少 MCP 适配器,或你使用的版本不支持,REST API 就是兜底方案——只需要 `httpx`(或 `requests`)。先在运行框架代码的环境中安装: + +```bash +pip install httpx +``` + +下面的写入 + 召回往返可在任意框架中使用;把两个函数包进框架的函数工具类,就能交给智能体: ```python import httpx @@ -199,8 +205,8 @@ def recall(query: str, top_k: int = 5) -> list[str]: resp.raise_for_status() return [hit["memory"]["content"] for hit in resp.json()["results"]] -remember("User prefers dark mode and a compact layout", tags=["preference", "ui"]) -for content in recall("UI preferences"): +remember("用户偏好深色模式和紧凑布局", tags=["preference", "ui"]) +for content in recall("界面偏好"): print(content) ```