> ## Content Index
> Fetch the complete content index at: https://www.hubwiz.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# Context Fabric：智能体缺失的层
- URL: https://www.hubwiz.com/blog/context-fabric-the-missing-layer-of-ai-agents/
- Published: 2026-07-21T01:21:12.000Z
- Updated: 2026-10-13T14:45:07.000Z
- Description: 为什么你迄今构建的每一个 AI 智能体都在悄悄失忆——以及该怎么办
- Author: admin
- Tags: AGENT, #Import 2026-10-14 14:41

如果你在 2025–2026 年间花过任何时间用 AI 智能体做开发，你大概撞上了所有人都撞过的那堵墙。你的智能体在 demo 里跑得漂亮。深入到真实工作流才三步，它就忘了两回合前做的一个决定，用错误的参数调用了工具——因为它弄丢了*为什么*要调用它，或者信心十足地做了件违反某条没人告诉过它的策略的事——因为根本没地方放那条信息。

这不是模型的问题。GPT-5、Claude、Gemini——这些旗舰模型能力都极其强。问题出在架构上。我们一直用养金鱼的方式构建智能体：一个没有长期记忆的大脑，每隔几秒就被丢进一个新的池塘，却指望它表现得像记得整片海洋。

> **Context Fabric（上下文织物）** *同一个当前的受治理的*

让我们把它好好拆开——它是什么，为什么突然紧迫，以及究竟该如何从周末的爱好项目一路构建到企业级部署。

## 1、外行版解释

想象你雇了一个才华横溢的新员工。他是个天才——但每一天，他都是带着完全失忆来上班的。他不记得项目、客户的偏好、公司的规矩，甚至不记得自己昨天干了什么。每天早上，你都得在开工前，用一次仓促的简报，把一切从头讲一遍。

那就是 LLM。它在调用之间没有记忆。它对你具体处境所"知道"的一切，每次都必须塞进它的上下文窗口——也就是你发给它的那段文本。

现在换一种想象：这个员工有一本全公司都在往里写的共享笔记。里面有组织架构图、客户历史、当前项目状态、合规规则，以及每一个之前碰过这个任务的其他员工（或其他智能体）留下的备注。在他做任何事之前，先瞄一眼这本笔记。做完之后，再把它更新。

> **Context Fabric**

## 2、实践者版解释

Context Fabric 是一个**语义的、持续更新的层，它统一了四类上下文**，使得任何一个智能体，在工作流的任意一点，都能检索到对当前任务连贯、及时、有策略意识的画面：

1. **数据上下文**——来自你各系统的运营与分析数据（CRM、ERP、数据库、工单、文档）
2. **流程上下文**——本工作流里已经发生了什么、做了哪些决定、还有什么待办
3. **领域/业务上下文**——本体、业务规则、定义（"'高风险客户'到底指什么？"）
4. **治理上下文**——谁被允许看什么、哪些动作需要审批、哪些可审计

从技术上说，它通常由以下组合构建而成：

- 一个**知识图谱**或**本体层**（实体、关系、业务含义）
- 一个用于非结构化/语义检索的**向量库**（RAG）
- 一个**共享记忆存储**（跨会话的短期工作记忆 + 长期情景记忆）
- 一个**策略/治理引擎**（访问控制、合规约束，表达为可强制执行的规则，而非仅仅是提示词指令）
- 一个**编排/检索层**，按需把上述所有内容中正确的那一片，组装进每个智能体的上下文窗口

> **这不是"多走几步的 RAG"。** *意义*

## 3、为什么这突然紧迫

过去一年里，三件事同时发生了变化：

**1\. 智能体已经自主到危险的地步。** 一个答错问题的聊天机器人只是烦人。一个基于陈旧或不完整上下文、自主执行电汇、修改客户记录、或把代码推上生产的智能体，则是一个负债。当企业从"AI 辅助人"转向"AI 独立行动"，上下文失败的代价就从尴尬升级成了昂贵。

**2\. 多智能体系统成了默认架构。** 一旦你拥有不止一个智能体——一个规划者、一个研究者、一个执行者——你就有了协调问题。每个智能体的输出是下一个智能体的输入。如果它们不共享一致的上下文，错误就会沿着链路静默地叠加放大。Salesforce、微软，以及大多数企业级 AI 平台，过去一年里都发布了某种版本的"共享上下文层"，正是因为在规模化下，客户不断报告这种确切的失败模式。

**3\. 合规追了上来。** 监管者和内部风险团队现在期望 AI 的决策可解释、可审计。"是 LLM 决定做 X 的"在金融、医疗或任何受监管行业，都不是一个能接受的答案。Context Fabric 给了你一条纸迹：智能体被展示了什么上下文、哪条规则被触发、它为什么那样行动。

> **上下文工程曾经是个提示词技巧。现在它是基础设施。**

## 4、如何构建：从外行到专家

下面是三个实现层级。选一个匹配你当前所处阶段的，把其余的当作你的路线图。

### 4.1 爱好者：会话记忆 + 简单检索

这是入门点：给你的智能体跨会话的持久记忆，以及基础的语义检索。暂时还没有治理层——只是先止住失忆。

```python
# pip install langchain langchain-anthropic langchain-community chromadb
from langchain_anthropic import ChatAnthropic
from langchain.memory import ConversationSummaryBufferMemory
from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain.chains import ConversationalRetrievalChain
llm = ChatAnthropic(model="claude-sonnet-4-6")
# Working memory: summarizes older turns instead of dropping them
memory = ConversationSummaryBufferMemory(
    llm=llm, max_token_limit=2000, return_messages=True
)
# A minimal "context store" - your business documents, ontology notes, policies
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
vectorstore = Chroma(collection_name="context_fabric_v0", embedding_function=embeddings)
chain = ConversationalRetrievalChain.from_llm(
    llm=llm,
    retriever=vectorstore.as_retriever(search_kwargs={"k": 5}),
    memory=memory,
)
response = chain.invoke({"question": "What's the current status of the Acme renewal?"})
print(response["answer"])

```

这是一个*玩具级*的织物——但它教给了核心习惯：把"智能体此刻被告知什么"与"智能体能访问什么"分开，并让后者持久化。

### 4.2 中级：一个真正的语义层（图谱 + 向量 + 工作记忆）

这里我们加上一个实体/关系层，于是上下文不再是"相似的文本块"，而是被解析出的业务含义，并且我们把短期记忆和长期记忆分开。

```python
# pip install langchain langgraph neo4j langchain-anthropic
from langchain_anthropic import ChatAnthropic
from langgraph.graph import StateGraph, END
from neo4j import GraphDatabase
from typing import TypedDict, List
llm = ChatAnthropic(model="claude-sonnet-4-6")
graph_db = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
class AgentState(TypedDict):
    task: str
    entities: List[dict]
    working_memory: List[str]
    context_object: dict
def resolve_entities(state: AgentState) -> AgentState:
    """Pull related entities + business rules from the knowledge graph."""
    with graph_db.session() as session:
        result = session.run("""
            MATCH (c:Customer)-[:HAS_CASE]->(case:Case)
            WHERE case.task_id = $task_id
            OPTIONAL MATCH (c)-[:SUBJECT_TO]->(policy:Policy)
            RETURN c, case, collect(policy.name) as policies
        """, task_id=state["task"])
        rows = [dict(r) for r in result]
    state["entities"] = rows
    return state
def assemble_context(state: AgentState) -> AgentState:
    """This is the heart of the fabric: merge graph facts, memory,
    and governance rules into one coherent object for the agent."""
    state["context_object"] = {
        "entities": state["entities"],
        "recent_decisions": state["working_memory"][-10:],
        "applicable_policies": [p for e in state["entities"] for p in e.get("policies", [])],
    }
    return state
def run_agent(state: AgentState) -> AgentState:
    prompt = f"""You are acting within a governed context.
Context object: {state['context_object']}
Task: {state['task']}
Only act within the applicable_policies listed above."""
    answer = llm.invoke(prompt)
    state["working_memory"].append(answer.content)
    return state
workflow = StateGraph(AgentState)
workflow.add_node("resolve_entities", resolve_entities)
workflow.add_node("assemble_context", assemble_context)
workflow.add_node("run_agent", run_agent)
workflow.set_entry_point("resolve_entities")
workflow.add_edge("resolve_entities", "assemble_context")
workflow.add_edge("assemble_context", "run_agent")
workflow.add_edge("run_agent", END)
app = workflow.compile()

```

注意这个形态：**解析 → 组装 → 行动**。这个三步模式——拉取结构化的真相，把它与记忆和策略合并，*然后*才交给 LLM——就是织物模式的一个缩影。大多数生产失败，发生在团队从"原始数据"直接跳到"LLM 提示词"、跳过了组装这一步的时候。

### 4.3 专家：带 MCP + 治理强制的企业级 Context Fabric

在生产规模下，你不会希望每个智能体各自去查你的图数据库、各自重新实现一遍策略逻辑。你把这个织物作为一个**服务**暴露出来，用一套标准协议——越来越多地，那就是 **Model Context Protocol（MCP，模型上下文协议）**——并且你把治理做成强制的运行时约束，而不是提示词里的建议。

```python
# A minimal MCP server exposing the Context Fabric as a tool
# pip install mcp
from mcp.server.fastmcp import FastMCP
from typing import Optional
mcp = FastMCP("context-fabric")
@mcp.tool()
def get_context(entity_id: str, task_type: str, requesting_agent_id: str) -> dict:
    """
    Returns a governed context object for a given entity and task.
    This is the single entry point every agent uses - no agent
    queries raw data stores directly.
    """
    entity = fetch_entity_from_graph(entity_id)
    policies = fetch_applicable_policies(entity, task_type)
    memory = fetch_working_memory(entity_id)
    # Governance enforcement happens HERE, in code - not in a prompt
    if not agent_is_authorized(requesting_agent_id, policies):
        raise PermissionError(f"Agent {requesting_agent_id} lacks access for {task_type}")
    context_object = {
        "entity": redact_fields(entity, policies),   # field-level redaction
        "policies": policies,
        "recent_history": memory[-20:],
        "lineage": build_lineage_trace(entity_id),    # for auditability
    }
    log_context_access(entity_id, requesting_agent_id, task_type)  # audit trail
    return context_object
@mcp.tool()
def write_decision(entity_id: str, agent_id: str, decision: str, rationale: str) -> bool:
    """Every agent decision is written BACK into the fabric, enriching it
    for the next agent in the chain - this is what makes it a fabric,
    not a one-way lookup."""
    return append_to_graph(entity_id, agent_id, decision, rationale)
if __name__ == "__main__":
    mcp.run()

```

任何一个智能体——Claude、一个 LangGraph 工作流、一个自定义编排器——都可以像连接一个日历或数据库工具那样连接这个 MCP 服务器。织物变成了你组织里每个智能体共享的基础设施，而不是复制在每个智能体内部的逻辑。

这一层级与其他层级的区别在于三件事：

- **强制，而非指令。** 策略是在代码里检查的（`agent_is_authorized`），所以一个巧妙的提示注入无法说服智能体违背一条合规规则——这条规则压根不在提示词里。
- **写回。** 决策流回织物，于是下一个智能体（或人）看到的是一幅被充实过、最新的画面——这闭合了回路，也让它是"自我改进"的，而非静态的。
- **血缘与审计。** 每一次上下文访问都被记录下"展示了什么、为什么"，满足了监管日益要求的那项可解释性。

## 5、常见陷阱

- **把它当成"只是个更大的 RAG"。** 如果你的检索步骤返回的是原始片段，而不是被解析出的实体 + 关系 + 策略，那你建的是一个搜索引擎，不是织物。
- **把治理放进提示词。** "请不要分享 PII" 不是一种控制。字段级脱敏和代码里的授权检查才是。
- **没有写回循环。** 一个智能体只*读*不写的织物，在任何多步工作流里都会立刻过时。
- **第一天就过度工程。** 从层级 1 起步，在一个工作流上验证这个模式，再升级。大多数在这里失败的团队，在连一个能用的智能体都还没投产之前，就试图去构建层级 3 的架构。

## 6、结束语

LLM 从来不是瓶颈。瓶颈始终是*围绕它的东西*——它被允许知道什么、何时知道、在什么样的规则之下。Context Fabric 不过是一种坦承：上下文是基础设施，而不是事后塞进提示词模板里的念头。

---

原文链接: [Context Fabric: The Missing Layer Your Agentic AI Actually Needs](https://medium.com/@dewasheesh.rana/context-fabric-the-missing-layer-your-agentic-ai-actually-needs-7c4fdca5bf94?ref=hubwiz.com)

汇智网翻译整理，转载请标明出处

> **这是「Agent / MCP」专题的一部分。**完整地图见：[Agent / MCP / 自动化完全指南](https://www.hubwiz.com/blog/agent-stack/)