关于 neo4j-genai-plugin-skill
neo4j-genai-plugin-skill 为 Neo4j 用户提供在 Cypher 查询中使用 GenAI 插件的参考,涵盖嵌入、文本生成、结构化输出、聊天与文本分块。它适合希望在图数据查询和处理中调用 LLM、而不另建 Python 流程的场景。
主要功能
- 01在 Cypher 中生成文本嵌入
- 02批量处理嵌入并调用 LLM
- 03生成结构化输出与聚合摘要
- 04在 Cypher 中维护聊天会话
- 05统计 Token 并按限制分块
适用场景
- 01导入时为节点或文本块生成嵌入
- 02在查询中生成文本摘要
- 03从图数据提取结构化字段
- 04按 Token 限制切分长文本
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ neo4j-contrib/ neo4j-skills --skill neo4j-genai-plugin-skill安装后在 Claude Code 中输入/neo4j-genai-plugin-skill确认已加载。
附带文件README.mdreferences/providers.md
详细介绍
适用场景
- 在 Cypher 中生成嵌入,无需外部 Python(
ai.text.embed()) - 在数据摄取期间对节点/文本块进行批量嵌入(
ai.text.embedBatch()) - 直接在 Cypher 中调用大模型进行补全或 GraphRAG(
ai.text.completion()) - 在 Cypher 中从大模型提取结构化 JSON 映射(
ai.text.structuredCompletion()) - 汇总分组行中的大模型摘要(
ai.text.aggregateCompletion()) - 在 Cypher 中使用有状态聊天会话(
ai.text.chat()) - 统计 Token 数量,或按 Token 限制对文本分块(
ai.text.tokenCount()、ai.text.chunkByTokenLimit())
不适用场景
- 基于 Python 的 GraphRAG 工作流(VectorCypherRetriever、HybridCypherRetriever)→
neo4j-graphrag-skill - 创建向量索引/kNN 搜索/SEARCH 子句 →
neo4j-vector-index-skill - GDS 嵌入(FastRP、Node2Vec)→
neo4j-gds-skill - 全文/关键词搜索 →
neo4j-cypher-skill
先决条件
所有 ai.* 函数都需要 CYPHER 25。有两种启用方式:
// Per-query prefix (self-managed, no admin rights needed):
CYPHER 25 MATCH (n:Chunk) ...
// Per-database default (admin; applies to all sessions):
ALTER DATABASE neo4j SET DEFAULT LANGUAGE CYPHER 25
安装:
- Aura:默认启用 GenAI 插件,无需操作
- 自管理 JAR:将插件 JAR 复制到
plugins/目录 - Docker:
--env NEO4J_PLUGINS='["genai"]'
提供商配置速查
所有 ai.text.* 函数都接受作为最后一个参数的 configuration :: MAP。
| 提供商字符串 | 必需的键 | 备注 |
|---|---|---|
'openai' | token、model | token = OpenAI API 密钥 |
'azure-openai' | token、resource、model | token = OAuth2 bearer;resource = Azure 资源名称 |
'vertexai' | model、project、region、token 或 apiKey | publisher 默认为 'google' |
'bedrock-titan' | model、region、accessKeyId、secretAccessKey | 仅用于嵌入 |
'bedrock-nova' | model、region、accessKeyId、secretAccessKey | 仅用于补全 |
所有提供商均可选:vendorOptions :: MAP 用于传递提供商专属的额外选项(例如,OpenAI 的 { dimensions: 1024 })。
❌ 切勿将 API 密钥字面量硬编码。✅ 始终使用通过驱动程序参数字典传入的 $param。
完整的提供商配置表 → references/providers.md
嵌入
单个嵌入 [2025.11]
CYPHER 25
MATCH (c:Chunk)
WHERE c.embedding IS NULL
WITH c
CALL {
WITH c
SET c.embedding = ai.text.embed(c.text, 'openai', {
token: $openaiKey,
model: 'text-embedding-3-small'
})
} IN TRANSACTIONS OF 500 ROWS
ai.text.embed() 返回 VECTOR,可直接存储并在向量索引中查询。
批量嵌入过程 [2025.11]
CYPHER 25
MATCH (c:Chunk) WHERE c.embedding IS NULL
WITH collect(c) AS chunks
UNWIND chunks AS c
WITH c.text AS text, c AS node
CALL ai.text.embedBatch(text, 'openai', { token: $openaiKey, model: 'text-embedding-3-small' })
YIELD index, resource, vector
MATCH (c:Chunk {text: resource})
SET c.embedding = vector
过程签名:CALL ai.text.embedBatch(resource, provider, config) YIELD index, resource, vector
列出已配置的嵌入提供商
CYPHER 25
CALL ai.text.embed.providers()
YIELD name, requiredConfigType, optionalConfigType, defaultConfig
RETURN name, requiredConfigType
文本补全 [2025.11]
CYPHER 25
RETURN ai.text.completion(
'Summarize: ' + $text,
'openai',
{ token: $openaiKey, model: 'gpt-4o-mini' }
) AS summary
返回 STRING。
聚合补全——跨行汇总 [2026.03]
CYPHER 25
MATCH (c:Chunk)-[:PART_OF]->(a:Article {id: $articleId})
RETURN ai.text.aggregateCompletion(
c.text,
'Summarize the following article chunks in 3 sentences',
'openai',
{ token: $openaiKey, model: 'gpt-4o-mini' }
) AS summary
value 参数 = 输入大模型的每行 STRING。对于非字符串值,使用 toString()。
纯 Cypher GraphRAG 模式
嵌入问题 → 向量搜索 → 图遍历 → 大模型补全——全部在一个 Cypher 查询中完成:
CYPHER 25
WITH ai.text.embed($question, 'openai', { token: $openaiKey, model: 'text-embedding-3-small' }) AS qEmbedding
MATCH (chunk:Chunk)
SEARCH chunk IN (VECTOR INDEX chunk_embedding FOR qEmbedding LIMIT 10) SCORE AS score
// SEARCH preferred on 2026.x; db.index.vector.queryNodes() deprecated 2026.04 — SEARCH syntax → neo4j-vector-index-skill
MATCH (chunk)<-[:HAS_CHUNK]-(article:Article)
OPTIONAL MATCH path = shortestPath((article)-[*..3]-(other:Article))
WITH chunk, article, collect(DISTINCT other.title) AS related, score
ORDER BY score DESC LIMIT 5
WITH collect(chunk.text + '\n[Source: ' + article.title + ']') AS context, $question AS question
RETURN ai.text.completion(
'Answer based on context:\n' + reduce(s='', c IN context | s + c + '\n') + '\nQuestion: ' + question,
'openai',
{ token: $openaiKey, model: 'gpt-4o-mini' }
) AS answer
关键见解(Bergman):种子节点之间的最短路径能够揭示仅从直接邻居无法看到的关系。
结构化输出 [2026.02]
返回 MAP,可直接存储为节点属性,或在下游 Cypher 中使用。
CYPHER 25
MATCH (p:Product {id: $productId})
WITH p,
ai.text.structuredCompletion(
'Extract key attributes from: ' + p.description,
{
type: 'object',
properties: {
category: { type: 'string' },
tags: { type: 'array', items: { type: 'string' } },
priceRange: { type: 'string', enum: ['budget', 'mid', 'premium'] }
},
required: ['category', 'tags', 'priceRange'],
additionalProperties: false
},
'openai',
{ token: $openaiKey, model: 'gpt-4o-mini' }
) AS extracted
SET p.category = extracted.category,
p.priceRange = extracted.priceRange
WITH p, extracted.tags AS tags
UNWIND tags AS tag
MERGE (t:Tag {name: tag})
MERGE (p)-[:TAGGED]->(t)
聚合结构化补全——从多行中提取 [2026.03]
CYPHER 25
MATCH (:User {id: $userId})-[:ORDERED]->(o:Order)-[:CONTAINS]->(p:Product)
RETURN ai.text.aggregateStructuredCompletion(
p.name + ': ' + p.category,
'Build a shopping profile for this user',
{
type: 'object',
properties: {
preferredCategories: { type: 'array', items: { type: 'string' } },
spendingTier: { type: 'string', enum: ['economy', 'standard', 'premium'] }
},
required: ['preferredCategories', 'spendingTier']
},
'openai',
{ token: $openaiKey, model: 'gpt-4o-mini' }
) AS profile
聊天 [2025.12]
仅支持 openai 和 azure-openai 提供商。
// Start new conversation (chatId = null → new session)
CYPHER 25
WITH ai.text.chat(
'Hello, who are you?',
null,
'openai',
{ token: $openaiKey, model: 'gpt-4o-mini' }
) AS result
RETURN result.message AS reply, result.chatId AS sessionId
// Continue conversation (pass returned chatId)
CYPHER 25
WITH ai.text.chat(
'What did I just ask you?',
$chatId,
'openai',
{ token: $openaiKey, model: 'gpt-4o-mini' }
) AS result
RETURN result.message AS reply, result.chatId AS sessionId
返回 MAP { message: STRING, chatId: STRING }。保存 chatId 以继续会话。
Tokenization & 分块 [2026.04]
// Count tokens before sending to LLM
CYPHER 25
RETURN ai.text.tokenCount($text, 'openai', { token: $openaiKey, model: 'gpt-4o-mini' }) AS tokenCount
// Chunk text by token limit (no external dependencies)
CYPHER 25
UNWIND ai.text.chunkByTokenLimit($longText, 512, 'gpt-4', 50) AS chunk
MERGE (c:Chunk { text: chunk })
// List providers supporting tokenCount
CYPHER 25
CALL ai.text.tokenCount.providers() YIELD name, requiredConfigType
RETURN name, requiredConfigType
签名:
ai.text.tokenCount(input, provider, configuration = {}) :: INTEGER— 由 provider 驱动的分词器;使用 provider 配置(token/model)。'openai'使用本地分词器(不调用 API);'Bedrock'和'VertexAI'会进行免费 API 调用。ai.text.chunkByTokenLimit(input, limit, model = 'gpt-4', overlap = 0) :: LIST<STRING>— 根据model选择本地 OpenAI 分词器;不调用 provider,无需token。按换行符、空格,然后按 token 数量进行分块。将limit设为低于 provider 上限的值,为提示词开销留出空间。
ai.text.embedBatch [2026.04] 支持 maxBatchSize(配置键),用于限制每次 API 请求的数据量 — 'openai' 和 'azure-openai' 的默认值为 8192;'vertexai' 没有默认值(如果遇到 token 上限错误,请设置此值)。
写入门控
SET node.embedding = ai.text.embed(...) 和 SET node.* = ai.text.structuredCompletion(...) 会写入图中。
批量写入前:
- 先统计节点数:
MATCH (c:Chunk) WHERE c.embedding IS NULL RETURN count(c) - 批处理前,先用一个测试节点验证配置
- 对于超过 1000 个节点的批次,使用
CALL { ... } IN TRANSACTIONS OF 500 ROWS - 执行前必须获得明确确认
已弃用 — 请勿使用
| 旧函数 | 替代项 |
|---|---|
genai.vector.encode() [已弃用] | ai.text.embed() |
genai.vector.encodeBatch() [已弃用] | CALL ai.text.embedBatch() |
genai.vector.listEncodingProviders() [已弃用] | CALL ai.text.embed.providers() |
常见错误
| 错误 | 原因 | 修复方法 |
|---|---|---|
Unknown function 'ai.text.embed' | 缺少 CYPHER 25 前缀或未安装插件 | 添加 CYPHER 25 前缀;确认已安装插件 |
Cypher version not supported | 在 Neo4j < 5.20 上使用 CYPHER 25,或缺少插件 | 升级 Neo4j;确保已加载 GenAI 插件 |
Configuration key 'token' missing | Provider 配置映射不完整 | 检查该 provider 的必需键(见上表) |
null returned from embed | 模型名称错误或 provider 身份验证失败 | 单独测试 RETURN ai.text.embed('test', 'openai', {token:$k, model:'text-embedding-3-small'}) |
Unsupported provider | Provider 字符串拼写错误(区分大小写,使用小写) | 使用 'openai' 而非 'OpenAI';运行 CALL ai.text.embed.providers() |
ai.text.chat fails on VertexAI | Chat 仅支持 openai/azure-openai | 使用 openai/azure-openai 进行 chat |
检查清单
- 每个 ai.text.* 查询都带有
CYPHER 25前缀 - 已安装 GenAI 插件(Aura:自动安装;自托管:将 JAR 放入 plugins/)
- API 密钥作为
$param传入,绝不使用字面字符串 - 在配置中明确指定
model键(不使用静默默认值) - Provider 字符串使用小写(
'openai'、'vertexai'、'bedrock-titan') - 批量写入使用
IN TRANSACTIONS OF 500 ROWS;先统计目标节点数 - 已将
genai.vector.encode()替换为ai.text.embed()[2025.11+] - Chat 会话:保存返回的
chatId以便继续会话;仅支持 openai/azure-openai - 结构化输出架构使用
additionalProperties: false,以防止生成幻觉键
参考资料
- 完整的 provider 配置 — 各 provider 的所有必需/可选键
- 官方文档
- API 参考