关于 cognee
cognee 是面向使用 Cognee Python API 构建 Agent 记忆的技能,帮助将需求对应到存储、查询、丰富和管理知识图谱的工作流。
主要功能
- 01指导使用 remember 和 recall
- 02摄取文本、文件、URL 和代码库
- 03选择搜索策略
- 04用 NodeSets 限定记忆范围
- 05定义图模型和 DataPoint
- 06管理会话与反馈
适用场景
- 01为 Agent 添加持久记忆
- 02搜索知识图谱或文档
- 03按项目或用户划分记忆
- 04构建符合架构的图数据
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ topoteretes/ cognee --skill cognee安装后在 Claude Code 中输入/cognee确认已加载。
详细介绍
Cognee
当用户需要 Cognee 专用的 Python API 帮助,或需要将目标映射到合适的 Cognee 工作流时,使用此技能。
何时应用此技能
当用户想要使用 Cognee 执行以下任一操作时,应用此技能:
- 摄取文本、文件、URL、代码库或数据集
- 构建或重建知识图谱
- 搜索文档、文本块、摘要、三元组或图谱上下文
- 选择
SearchType - 使用
improve丰富现有图谱 - 定义自定义图谱提取模型或
DataPoint类型 - 运行自定义任务流水线
- 配置 LLM、图数据库、向量数据库或存储设置
- 使用
node_set/ NodeSets 为记忆添加标签和范围 - 为 Agent 构建可跨会话持久保存的记忆
- 创建反馈循环或自我改进的 Agent 工作流
- 使用时间提取、本体、Cypher 或自然语言图谱查询
- 管理数据集、会话、反馈、删除、更新或可视化
如果用户的意图是“将信息存入记忆并在之后查询”,优先使用 Cognee 的 记忆 API:remember -> recall(使用 improve 丰富内容,使用 forget 删除)。
核心工作流
import cognee
# Store: ingest + build the graph (+ improve, because self_improvement=True by default)
await cognee.remember(
"Your text, file path, URL, or list of inputs",
dataset_name="main",
)
# Query: recall picks a search strategy automatically (rule-based, no LLM call)
results = await cognee.recall("What are the key insights?", datasets=["main"])
for r in results:
print(r.source, r) # each result is tagged "graph" / "session" / ...
remember() 会运行 add() + cognify(),然后在底层运行 improve()。recall() 封装了
search(),并添加了路由、作为来源的会话记忆,以及带有 source 标签的结果。
默认指导
在帮助用户使用 Cognee 时:
- 除非用户明确要求高级配置,否则从最简单的可用方案开始。
- 优先使用记忆 API:
- 使用
remember(...)存储(摄取 + 构建图谱) - 使用
recall(...)查询 - 使用
improve(...)丰富或索引现有图谱,并将会话内容桥接到图谱中 - 使用
forget(...)删除
- 使用
- 将 Cognee API 视为异步 API。
- 当用户有多个来源时,使用
dataset_name/datasets整理工作。 - 当用户需要轻量级标签、项目范围、按用户划分的记忆区块或子图筛选时,使用
node_set。 - 只有当用户需要特定策略时,才向
recall()传入query_type=SearchType.X;否则让它自行路由。 - 仅在符合任务需求时推荐高级功能:
- 使用
session_id实现快速短期记忆和对话连续性 - 使用
graph_model=进行符合架构的提取,使用DataPoint类型直接插入 - 使用
extractor="gliner_demo"进行无需 LLM 的图谱提取 - 使用自定义流水线编排非默认任务
- 使用反馈循环改进检索
- 使用可视化工具检查图谱
- 使用
何时改用底层操作
add()、cognify() 和 search() 仍然提供支持;记忆 API 会调用它们。只有当
remember/recall 无法满足需求时,才使用这些操作:
cognify(datasets=["a", "b"])或datasets=None可一次处理多个数据集;remember()始终只针对一个数据集。- 对数据库中已有的数据重建图谱(例如调用
forget(memory_only=True)之后,或使用新的graph_model/ 本体时)只能通过cognify()完成;remember()始终会先运行add()。 search()将 Agent 的扩展参数作为一等参数(skills、tools、max_iter、code_query、node_type)接收,并返回原始SearchResult对象,而非带标签的字典。add()是暂存区:可先用它摄取数据,之后再运行cognify()。prune.prune_system(metadata=True)还会删除关系数据库(用户、ACL、数据集注册表);forget()不会触及这些内容。只有在完整清理测试环境时才使用 prune。
cognee.delete() 已弃用,建议改用 forget()。两个查询函数的完整对比见:docs/recall-vs-search.md。
常见任务
存储数据
remember() 接受文本、文件路径、URL、目录、git 代码库 URL、二进制流
或以上内容的列表。
await cognee.remember("notes.md", dataset_name="research")
await cognee.remember("https://example.com", dataset_name="research")
await cognee.remember(["paper.pdf", "summary.txt"], dataset_name="research")
当用户希望将数据归入逻辑记忆区块时,使用 node_set。
await cognee.remember(
"Customer prefers concise weekly summaries and Slack delivery.",
dataset_name="customer_success",
node_set=["preferences", "customer_123", "weekly_reports"],
)
有用的选项:
await cognee.remember(
"...",
dataset_name="research",
self_improvement=False, # skip the improve() stage (faster)
run_in_background=True, # return immediately; poll the pipeline status
chunk_size=1024,
custom_prompt="Extract companies, products, and partnerships.",
extractor="gliner_demo", # LLM-free extraction; needs cognee[gliner]
dry_run=True, # estimate LLM tokens/cost without ingesting
)
await cognee.remember("./my_repo", dataset_name="code") # code graph, no LLM
await cognee.remember("./skills", dataset_name="ops", content_type="skills") # SKILL.md playbooks
查询记忆
from cognee import SearchType
results = await cognee.recall("What changed in Q1 2024?", datasets=["research"], top_k=10)
# Pin a strategy when the user needs one
results = await cognee.recall(
"What changed in Q1 2024?",
query_type=SearchType.TEMPORAL,
datasets=["research"],
)
# Answers with evidence, or validated into a Pydantic model
results = await cognee.recall("...", include_references=True)
results = await cognee.recall("...", response_model=MyAnswerModel)
# Retrieval context only, no LLM completion (pin query_type here)
context = await cognee.recall("...", query_type=SearchType.GRAPH_COMPLETION, only_context=True)
使用 NodeSets 限定检索范围
当用户希望只搜索部分记忆(例如某个项目、客户、用户或工作流)时,请使用 NodeSets。
results = await cognee.recall(
"What are this customer's reporting preferences?",
datasets=["customer_success"],
node_name=["preferences", "customer_123"],
)
丰富现有图谱
当用户希望改进或扩展已构建的图谱,而不重新摄取数据时,请使用 improve()。不传入 session_ids 时,它只运行图谱级阶段(可选的冲突审核和全局上下文索引);传入后,它还会应用反馈权重、持久化会话问答,并将会话经验提炼到图谱中。
await cognee.improve(dataset="research")
await cognee.improve(dataset="research", session_ids=["chat_1"])
await cognee.improve(dataset="research", build_global_context_index=True)
删除数据
forget() 是唯一的删除入口。
await cognee.forget(data_id=data_id, dataset_id=dataset_id) # one document
await cognee.forget(dataset="research") # a dataset: raw data + graph + vectors
await cognee.forget(dataset="research", memory_only=True) # graph + vectors only, keep raw files
await cognee.forget(everything=True) # everything the current user owns
原位更新文档
await cognee.update(data_id=data_id, data="Updated content", dataset_id=dataset_id)
文档会保留其 data_id;只有编辑涉及的分块会重新提取。
创建特定领域的结构
将派生自 DataPoint 的 Pydantic 模型作为 graph_model 传入,大模型会填充该模型,而不是通用知识图谱:
from cognee.infrastructure.engine import DataPoint
class Person(DataPoint):
name: str
role: str
metadata: dict = {"index_fields": ["name"], "identity_fields": ["name"]}
class Company(DataPoint):
name: str
employs: list[Person] = [] # a DataPoint field becomes an edge named after the field
metadata: dict = {"index_fields": ["name"], "identity_fields": ["name"]}
await cognee.remember("...", dataset_name="org", graph_model=Company)
直接插入结构化 Python 对象,绕过文本提取:
from cognee.tasks.storage import add_data_points
await add_data_points([Person(name="Ada", role="Engineer")])
请参阅 examples/guides/custom_graph_model.py 和 examples/guides/custom_data_models.py。
运行自定义管道
当用户需要明确控制任务的执行顺序时,请使用 run_custom_pipeline(...)。
from cognee.modules.pipelines.tasks.task import Task
async def my_task(data):
return data
await cognee.run_custom_pipeline(
tasks=[Task(my_task)],
data="input",
dataset="research",
)
DataPoints
DataPoint 是 Cognee 中知识的基本单位。
当用户询问 Cognee 如何在内部表示结构化数据,或如何直接插入图对象时,请使用这一概念。
要点:
DataPoint是表示一个有意义信息单元的 Pydantic 模型。- 插入后,DataPoint 会成为图节点;包含其他 DataPoint 的字段会成为边。
metadata = {"index_fields": [...]}用于控制哪些字段会进行嵌入,以供语义搜索。metadata = {"identity_fields": [...]}会使节点 ID 保持确定性,因此重复插入时会合并,而不是重复创建。
当用户需要以下功能时,请使用 DataPoint:
- 符合架构的记忆
- 精确控制图结构
- 以编程方式创建关系
- 自定义领域实体,例如论文、客户、事件、政策、产品或工作流
对于非结构化文档,优先使用普通的 remember(...)。如果需要从文本中提取符合架构的数据,优先使用 graph_model=。如果用户已有结构化 Python 对象,优先使用 DataPoint 模型和 add_data_points(...)。
NodeSets
当用户需要轻量方式来标记、分组并限定记忆范围时,请使用 NodeSets。
NodeSet 最初是通过 node_set=[...] 传入 remember(...) 的标签列表;图谱构建完成后,这些标签会成为一等图节点,并且 recall(node_name=[...]) 会将检索范围限定为这些节点。
适用的 NodeSet 模式
- 按客户划分:
["customer_123"] - 按工作流划分:
["support_bot", "refund_flow"] - 按主题划分:
["contracts", "vendor_risk"] - 按环境划分:
["prod", "staging"] - 按用户记忆划分:
["user_42", "preferences"]
示例
await cognee.remember(
[
"Alice prefers terse answers and email follow-ups.",
"Alice escalates billing issues to finance first.",
"Bob prefers detailed technical explanations.",
],
dataset_name="agent_memory",
node_set=["crm", "user_profiles"],
)
results = await cognee.recall(
"How should I respond to Alice?",
datasets=["agent_memory"],
node_name=["crm", "user_profiles"],
)
当用户提出以下需求时,默认使用 NodeSets:
- “按客户限定记忆范围”
- “不创建单独的数据库,也能隔离不同项目”
- “让 Agent 只搜索自己的记忆”
- “按工作流或团队对事实进行分组”
SearchType 选择指南
省略 query_type 时,recall() 会自动路由。需要指定策略时,可从 cognee.SearchType 中选择(共 20 个值):
生成类型(由 LLM 撰写答案):
HYBRID_COMPLETION:文档片段加实体邻域;关闭路由时的默认选项GRAPH_COMPLETION:图遍历 + 生成;适用于通用图感知问答GRAPH_COMPLETION_COT:基于图上下文进行更深入的思维链推理GRAPH_COMPLETION_CONTEXT_EXTENSION:检索更广泛的图上下文GRAPH_COMPLETION_DECOMPOSITION:先将问题拆分为多个子查询GRAPH_SUMMARY_COMPLETION:图上下文 + 预先生成的摘要RAG_COMPLETION:对文档块进行传统 RAGTEMPORAL:具备时间感知能力的图搜索AGENTIC_COMPLETION:多步循环,可加载skills并调用tools
仅检索类型(不调用 LLM):
CHUNKS:对文本块进行语义检索CHUNKS_LEXICAL:精确词项 / 关键词(BM25)匹配SUMMARIES:预先生成的文档摘要SKILLS:发现 SKILL.md 操作手册(仅元数据;必须恰好有一个数据集)CODE:通过code_query执行确定性的代码图操作,如调用者、路径和影响分析
其他:
CYPHER:原始 Cypher,默认关闭(设置ALLOW_CYPHER_QUERY=true可启用;Postgres 演示图不支持)NATURAL_LANGUAGE:自然语言转图查询,默认关闭(同样通过ALLOW_CYPHER_QUERY=true标志启用)CODING_RULES:检索已存储的编码规则GRAPH_REPORT:图洞察报告(枢纽、跨来源链接、建议问题)FEELING_LUCKY:由 Cognee 自行选择
CLI 提供其中 10 种(cognee-cli recall --query-type);其余类型仅限 SDK 使用。
会话、反馈与自我改进
Cognee 有两个记忆层级:
- 永久记忆:不带
session_id调用remember(...)—— 知识图谱。 - 会话记忆:调用
remember(..., session_id=...)—— 快速会话缓存,写入时不调用 LLM。recall(..., session_id=...)会先搜索会话缓存,再回退到图谱。需要启用CACHING=true(默认值)。
# Short-term: store a turn in the session cache, recall it instantly
await cognee.remember("User wants weekly summaries on Fridays.", session_id="chat_1")
results = await cognee.recall("when does the user want summaries?", session_id="chat_1")
# Long-term: bridge the session into the permanent graph
await cognee.improve(dataset="main_dataset", session_ids=["chat_1"])
使用 self_improvement=True(默认值)调用 remember(..., session_id=...) 时,会在后台将内容同步至图谱,因此只有需要控制时机时才需显式调用 improve()。
反馈
反馈会附加到会话中的问答条目,之后由 improve() 纳入检索权重:
from cognee import FeedbackEntry
# Rate an earlier answer (qa_id is the entry_id returned by the remember() that stored it)
await cognee.remember(
FeedbackEntry(qa_id=qa_id, feedback_score=5, feedback_text="Captured the key themes."),
session_id="chat_1",
)
# Equivalent helper API
await cognee.session.add_feedback(session_id="chat_1", qa_id=qa_id, feedback_score=5)
history = await cognee.session.get_session(session_id="chat_1")
启用 AUTO_FEEDBACK=true(默认值)时,每轮已回答的对话也会通过一次结构化输出 LLM 调用分析隐式反馈。若要降低读取延迟,请设置 AUTO_FEEDBACK=false。
包装 Agent
@cognee.agent_memory 会将 Agent 函数的调用记录为会话轨迹,并在每次调用前召回上下文。请参阅 examples/guides/agent_memory_quickstart.py。
Agentic 工作流与反馈驱动的改进
将 Cognee 用作 Agent 系统的记忆层,通过更好的召回、更好地复用先前工作,以及更好地检索过去成功的行为来持续改进。
核心理念很简单:
- 保持 Agent 工作流本身不变
- 保持 提示词和工具不变
- 只改变 Agent 能够记住和检索的内容
“改进”来自 记忆复用和检索质量,而不是更改模型。
通用 Agent 循环
- 观察 — 捕获输入、事件、偏好、结果、错误和决策。
- 存储 — 使用
remember(...)存储这些内容;活动运行使用session_id,持久事实则不使用。 - 整理 — 使用数据集和 NodeSet,按客户、工作流、团队、Agent 或主题分隔记忆。
- 行动前检索 — 在规划、使用工具、综合信息或生成回复前调用
recall(...)。 - 收集反馈 — 使用
FeedbackEntry/session.add_feedback记录哪些做法有效、哪些无效。 - 整合 — 调用
improve(dataset, session_ids=[...]),将会话历史和经验转化为长期图记忆。 - 复用 — 后续运行可受益于更丰富的上下文和更充分的信息检索。
最简示例模式
import cognee
# 1) Store a durable observation
await cognee.remember(
"Customer 123 prefers concise status updates and Slack notifications.",
dataset_name="agent_memory",
node_set=["customer_123", "preferences", "support_agent"],
)
# 2) Recall before acting, inside a session
context = await cognee.recall(
"What should I know before replying to customer 123?",
datasets=["agent_memory"],
session_id="support-session-123",
)
# 3) Continue work in the same session
answer = await cognee.recall(
"Draft the best reply for customer 123.",
datasets=["agent_memory"],
session_id="support-session-123",
)
# 4) Consolidate the session into long-term memory later
await cognee.improve(dataset="agent_memory", session_ids=["support-session-123"])
最佳默认说明
如果用户询问 Cognee 如何帮助 Agent 随时间不断改进:
Cognee 让 Agent 记住更多有用信息,将这些信息整理成可搜索的图记忆,并在后续运行中复用以往成功的做法,从而不断改进。
配置帮助
当用户需要配置提供商或后端时,使用 Cognee 配置辅助工具或环境变量。
cognee.config.set_llm_provider("openai")
cognee.config.set_llm_model("gpt-5-mini")
cognee.config.set_llm_api_key("sk-...")
环境变量(.env):LLM_API_KEY、LLM_MODEL、LLM_PROVIDER、EMBEDDING_*、GRAPH_DATABASE_PROVIDER(默认使用 ladybug,也支持 neo4j、neptune、postgres_demo)、VECTOR_DB_PROVIDER(默认使用 lancedb,也支持 pgvector、turso)、DB_PROVIDER(默认使用 sqlite,也支持 postgres)、CACHE_BACKEND。如果只配置了 LLM 或嵌入模型,另一项将默认使用 OpenAI。
数据集和生命周期操作
datasets = await cognee.datasets.list_datasets()
data = await cognee.datasets.list_data(dataset_id)
await cognee.forget(dataset="research") # preferred over datasets.empty_dataset / delete_all
可视化
默认情况下,visualize_graph 会渲染一个范围受限的子图(种子节点及其 k 跳邻域,节点数上限为 max_nodes),而不是整个图。
# Default: bounded subgraph. Seed by a query, explicit ids, or a recall result;
# with none of those, the highest-degree nodes seed a representative view.
await cognee.visualize_graph("/path/to/output.html")
await cognee.visualize_graph("/path/to/output.html", query="What relates to Python?")
await cognee.visualize_graph("/path/to/output.html", seed_node_ids=["node-id-1"])
await cognee.visualize_graph("/path/to/output.html", recall_result=recall_output)
# Legacy whole-graph render.
await cognee.visualize_graph("/path/to/output.html", full=True)
await cognee.start_visualization_server(port=8080)
await cognee.start_ui()
上限:neighborhood_depth=2、neighborhood_seed_top_k=10、max_nodes=500。
请参阅 examples/guides/graph_visualization.py。
完全重置(仅用于测试)
forget(everything=True) 会删除用户的数据和记忆。若要同时删除用户、ACL 和数据集注册表,以彻底清理测试环境,请使用 prune:
await cognee.prune.prune_data()
await cognee.prune.prune_system(graph=True, vector=True, metadata=True, cache=True)
重要行为说明
- Cognee API 是异步的。
- 除非用户只需要某个底层阶段,否则优先使用remember -> recall(以及
improve、forget)。 - 如果用户以后可能需要限定范围的检索,请尽早使用
node_set。 - 使用
session_id存储短期记忆并保持对话连贯;使用improve(session_ids=...)将其永久保存。 - 只有在用户需要按架构提取信息时,才使用
graph_model=或DataPoint类型。 - 仅当配置中启用了 Cypher 查询时,才使用
CYPHER。 - 示例应保持精简且可运行。
避免过度复杂化
除非用户提出要求或问题显然需要,否则不要直接使用高级后端、本体配置或自定义管道。首先选择最精简且正确的 Cognee 方案,再逐步扩展。