LLM Notion集成
--- title: "LLM Notion集成" description: "全面解析大语言模型与Notion的集成方案,涵盖内容生成、数据库查询和页面自动化操作" tags: ["Notion", "LLM集成", "内容生成", "数据库", "自动化"] category: "llm" icon: "🧠"
LLM Notion集成
Notion是流行的全能型知识管理工具,集文档、数据库、看板和Wiki于一体。其开放的API使得大语言模型(LLM)能够无缝接入,实现内容自动生成、数据库智能查询和页面操作自动化。本文将从API对接、内容生成和数据库查询三个层面,详细介绍LLM与Notion的集成实践。
Notion API基础
Notion提供了RESTful API,支持对页面、数据库和块内容的CRUD操作。集成LLM的第一步是完成API认证和基础操作封装。
import os
import requests
import openai
NOTION_TOKEN = os.environ["NOTION_TOKEN"]
OPENAI_KEY = os.environ["OPENAI_API_KEY"]
headers = {
"Authorization": f"Bearer {NOTION_TOKEN}",
"Notion-Version": "2022-06-28",
"Content-Type": "application/json"
}
def get_page(page_id):
url = f"https://api.notion.com/v1/pages/{page_id}"
response = requests.get(url, headers=headers)
return response.json()
def get_block_children(block_id):
url = f"https://api.notion.com/v1/blocks/{block_id}/children"
response = requests.get(url, headers=headers)
return response.json()
def create_page(parent_id, title, content_blocks):
url = "https://api.notion.com/v1/pages"
payload = {
"parent": {"page_id": parent_id},
"properties": {
"title": [{"text": {"content": title}}]
},
"children": content_blocks
}
response = requests.post(url, headers=headers, json=payload)
return response.json()
Notion API的所有请求都需要携带Authorization头和Notion-Version头。页面和块操作通过不同的端点完成,其中块(Block)是Notion内容的基本单元,每个段落、标题、代码块都是一个Block。
LLM驱动的内容生成
利用LLM可以根据主题自动生成Notion页面内容,支持多种格式:文档、会议纪要、项目计划等。核心思路是构建结构化的Prompt,让LLM输出符合Notion Block格式的内容。
def generate_notion_content(topic, content_type="article"):
client = openai.OpenAI(api_key=OPENAI_KEY)
type_prompts = {
"article": "生成一篇结构清晰的技术文章,包含标题、引言、正文和总结。",
"meeting_notes": "生成会议纪要模板,包含议程、讨论要点、决策和行动项。",
"project_plan": "生成项目计划,包含目标、里程碑、任务分解和时间线。"
}
prompt = f"""{type_prompts.get(content_type, type_prompts['article'])}
主题:{topic}
请按以下JSON格式输出Notion Blocks:
[
{{"type": "heading_1", "text": "标题内容"}},
{{"type": "paragraph", "text": "段落内容"}},
{{"type": "bulleted_list_item", "text": "列表项"}},
{{"type": "code", "text": "代码内容", "language": "python"}}
]"""
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
max_tokens=2000,
response_format={"type": "json_object"}
)
blocks = parse_llm_blocks(response.choices[0].message.content)
return blocks
def parse_llm_blocks(llm_output):
import json
raw_blocks = json.loads(llm_output)
notion_blocks = []
for block in raw_blocks:
if block["type"] == "heading_1":
notion_blocks.append({
"object": "block",
"type": "heading_1",
"heading_1": {"rich_text": [{"type": "text", "text": {"content": block["text"]}}]}
})
elif block["type"] == "paragraph":
notion_blocks.append({
"object": "block",
"type": "paragraph",
"paragraph": {"rich_text": [{"type": "text", "text": {"content": block["text"]}}]}
})
elif block["type"] == "code":
notion_blocks.append({
"object": "block",
"type": "code",
"code": {
"rich_text": [{"type": "text", "text": {"content": block["text"]}}],
"language": block.get("language", "plain text")
}
})
return notion_blocks
通过generate_notion_content函数,可以指定主题和内容类型,让LLM自动生成符合Notion格式的内容。parse_llm_blocks函数负责将LLM输出的JSON转换为Notion API所需的Block格式。
数据库智能查询
Notion数据库支持丰富的属性类型和筛选条件。结合LLM可以实现自然语言查询,让用户用日常语言检索数据库内容。
def query_database(database_id, user_query):
client = openai.OpenAI(api_key=OPENAI_KEY)
schema = get_database_schema(database_id)
prompt = f"""根据以下Notion数据库结构,将用户查询转换为API筛选条件。
数据库属性:
{schema}
用户查询:{user_query}
请输出JSON格式的筛选条件:
{{
"filter": {{
"property": "属性名",
"filter_condition": "equals|contains|greater_than",
"value": "筛选值"
}},
"sorts": [{{"property": "排序属性", "direction": "ascending|descending"}}]
}}"""
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
response_format={"type": "json_object"}
)
filter_config = json.loads(response.choices[0].message.content)
url = f"https://api.notion.com/v1/databases/{database_id}/query"
payload = {"filter": filter_config["filter"], "sorts": filter_config.get("sorts", [])}
results = requests.post(url, headers=headers, json=payload).json()
return format_query_results(results["results"])
def get_database_schema(database_id):
url = f"https://api.notion.com/v1/databases/{database_id}"
response = requests.get(url, headers=headers).json()
schema = {}
for prop_name, prop_info in response["properties"].items():
schema[prop_name] = prop_info["type"]
return json.dumps(schema, ensure_ascii=False, indent=2)
自然语言查询系统的工作流程是:先获取数据库Schema,然后将用户自然语言描述转化为结构化的筛选条件,最后执行查询并格式化结果。这种方式大幅降低了使用门槛。
页面自动化操作
通过LLM驱动的自动化脚本,可以实现周期性的Notion页面维护:自动更新状态、生成周报、同步外部数据等。
from datetime import datetime
def auto_update_project_status(database_id):
projects = query_all_projects(database_id)
for project in projects:
status = project["status"]
progress = project["progress"]
deadline = project["deadline"]
days_left = (datetime.strptime(deadline, "%Y-%m-%d") - datetime.now()).days
prompt = f"""项目状态更新:
名称:{project['name']}
当前进度:{progress}
截止日期:{deadline}(剩余{days_left}天)
当前状态:{status}
请分析项目风险并建议下一步行动。"""
client = openai.OpenAI(api_key=OPENAI_KEY)
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
max_tokens=500
)
update_page(project["id"], {
"properties": {
"AI建议": {"rich_text": [{"text": {"content": response.choices[0].message.content}}]}
}
})
自动化脚本可以定期扫描项目数据库,为每个项目调用LLM分析风险并生成建议,然后将建议回写到Notion页面。这种闭环工作流大幅减少了人工维护的工作量。
总结
LLM与Notion的集成将知识管理提升到了智能化新高度。从内容自动生成到智能查询,再到自动化维护,LLM能力让Notion从静态工具变成了动态智能系统。开发者可以基于Notion API和LLM构建适合团队需求的自动化解决方案。