Download app.py from muzsang/Notion: direct link, hf CLI and curl.
- Browser
- Download file 21.3 kB
-
https://huggingface.co/spaces/muzsang/Notion/resolve/541e1ea5be292056fdbeb9bddba87d2e5e660430/app.py
- Command line
-
hf download hf://spaces/muzsang/Notion@541e1ea5be292056fdbeb9bddba87d2e5e660430/app.py
-
curl -L -o app.py https://huggingface.co/spaces/muzsang/Notion/resolve/541e1ea5be292056fdbeb9bddba87d2e5e660430/app.py
21.3 kB
| import os | |
| import requests | |
| import json | |
| import uuid | |
| import logging | |
| import time | |
| from datetime import datetime | |
| from flask import Flask, request, jsonify, Response | |
| from functools import wraps | |
| # 设置日志 | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format='%(asctime)s - %(levelname)s - %(message)s', | |
| handlers=[ | |
| logging.StreamHandler() | |
| ] | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Notion AI 模型列表 | |
| NOTION_MODELS = { | |
| "openai-gpt-4.1": "GPT-4.1", | |
| "anthropic-sonnet-4": "Claude Sonnet 4", | |
| "anthropic-opus-4": "Claude Opus 4", | |
| "anthropic-sonnet-3.7": "Claude 3.7 Sonnet" | |
| } | |
| # 全局配置 | |
| class Config: | |
| # 从环境变量读取认证信息 | |
| NOTION_COOKIE = os.environ.get('NOTION_COOKIE', '') | |
| NOTION_SPACE_ID = os.environ.get('NOTION_SPACE_ID', '') | |
| NOTION_USER_ID = os.environ.get('NOTION_USER_ID', '') | |
| NOTION_SPACE_VIEW_ID = os.environ.get('NOTION_SPACE_VIEW_ID', '') | |
| USER_AGENT = os.environ.get('USER_AGENT', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0') | |
| # API URL | |
| NOTION_API_URL = os.environ.get('NOTION_API_URL', '<https://www.notion.so/api/v3/runInferenceTranscript>') | |
| # 默认模型 | |
| DEFAULT_MODEL = os.environ.get('DEFAULT_MODEL', 'anthropic-opus-4') | |
| # 超时设置 | |
| REQUEST_TIMEOUT = int(os.environ.get('REQUEST_TIMEOUT', 120)) | |
| # 服务器设置 | |
| HOST = os.environ.get('HOST', '0.0.0.0') | |
| PORT = int(os.environ.get('PORT', 7860)) # HF Spaces 使用 7860 端口 | |
| # 默认用户名和工作空间名 | |
| DEFAULT_USER_NAME = os.environ.get('DEFAULT_USER_NAME', 'Niigata') | |
| DEFAULT_SPACE_NAME = os.environ.get('DEFAULT_SPACE_NAME', 'Linux Do') | |
| # API 密钥认证 | |
| API_KEYS = os.environ.get('API_KEYS', '').split(',') | |
| REQUIRE_API_KEY = os.environ.get('REQUIRE_API_KEY', 'true').lower() == 'true' | |
| # 保存对话历史的类 | |
| class ConversationManager: | |
| def __init__(self): | |
| # 存储所有对话,键为会话ID | |
| self.conversations = {} | |
| def create_conversation(self, conversation_id=None): | |
| """创建新的对话,返回对话ID""" | |
| if conversation_id is None: | |
| conversation_id = str(uuid.uuid4()) | |
| self.conversations[conversation_id] = { | |
| "trace_id": str(uuid.uuid4()), | |
| "messages": [], | |
| "system_prompt": "你是一个乐于助人的AI助手。", # 默认系统提示词 | |
| "model": Config.DEFAULT_MODEL, | |
| "use_websearch": True | |
| } | |
| return conversation_id | |
| def get_conversation(self, conversation_id): | |
| """获取指定ID的对话,如果不存在则创建""" | |
| if conversation_id not in self.conversations: | |
| conversation_id = self.create_conversation(conversation_id) | |
| return self.conversations[conversation_id] | |
| def add_message(self, conversation_id, role, content): | |
| """添加消息到对话历史""" | |
| conversation = self.get_conversation(conversation_id) | |
| message = { | |
| "id": str(uuid.uuid4()), | |
| "role": role, | |
| "content": content, | |
| "timestamp": datetime.now().astimezone().isoformat(timespec='milliseconds') | |
| } | |
| conversation["messages"].append(message) | |
| return message | |
| def set_system_prompt(self, conversation_id, system_prompt): | |
| """设置系统提示词""" | |
| conversation = self.get_conversation(conversation_id) | |
| conversation["system_prompt"] = system_prompt if system_prompt else "你是一个乐于助人的AI助手。" | |
| return conversation | |
| def set_model(self, conversation_id, model): | |
| """设置模型""" | |
| if model not in NOTION_MODELS: | |
| raise ValueError(f"不支持的模型: {model}") | |
| conversation = self.get_conversation(conversation_id) | |
| conversation["model"] = model | |
| return conversation | |
| def get_transcript(self, conversation_id): | |
| """获取用于Notion API的transcript数组""" | |
| conversation = self.get_conversation(conversation_id) | |
| current_datetime_iso = datetime.now().astimezone().isoformat(timespec='milliseconds') | |
| # 构建基本transcript | |
| transcript = [ | |
| # 配置 | |
| { | |
| "id": str(uuid.uuid4()), | |
| "type": "config", | |
| "value": { | |
| "type": "markdown-chat", | |
| "model": conversation["model"], | |
| "useWebsearch": conversation.get("use_websearch", True) | |
| } | |
| } | |
| ] | |
| # 构建完整的context信息 - 关键修复点 | |
| system_prompt = conversation["system_prompt"] | |
| full_user_name = f"{Config.DEFAULT_USER_NAME}\\n\\nNote: {system_prompt}" | |
| # 获取用户ID,如果没有设置则从space_id中提取 | |
| user_id = Config.NOTION_USER_ID | |
| if not user_id and Config.NOTION_SPACE_ID: | |
| # 尝试从cookie中提取user_id | |
| if 'notion_user_id=' in Config.NOTION_COOKIE: | |
| user_id = Config.NOTION_COOKIE.split('notion_user_id=')[1].split(';')[0] | |
| else: | |
| user_id = "unknown" | |
| space_view_id = Config.NOTION_SPACE_VIEW_ID or Config.NOTION_SPACE_ID | |
| transcript.append({ | |
| "id": str(uuid.uuid4()), | |
| "type": "context", | |
| "value": { | |
| "timezone": "Asia/Shanghai", | |
| "userName": full_user_name, | |
| "userId": user_id, | |
| "spaceName": Config.DEFAULT_SPACE_NAME, | |
| "spaceId": Config.NOTION_SPACE_ID, | |
| "spaceViewId": space_view_id, | |
| "currentDatetime": current_datetime_iso, | |
| "surface": "api_call" | |
| } | |
| }) | |
| # 添加agent-integration - 关键修复点 | |
| transcript.append({ | |
| "id": str(uuid.uuid4()), | |
| "recordPointers": [], | |
| "type": "agent-integration" | |
| }) | |
| # 添加对话历史 | |
| for msg in conversation["messages"]: | |
| if msg["role"] == "user": | |
| transcript.append({ | |
| "id": msg["id"], | |
| "type": "user", | |
| "value": [[msg["content"]]], | |
| "userId": user_id, | |
| "createdAt": msg.get("timestamp", current_datetime_iso) | |
| }) | |
| elif msg["role"] == "assistant": | |
| transcript.append({ | |
| "id": msg["id"], | |
| "type": "markdown-chat", # 修复:使用正确的类型 | |
| "value": msg["content"], | |
| "traceId": conversation["trace_id"] | |
| }) | |
| return transcript | |
| def delete_conversation(self, conversation_id): | |
| """删除对话""" | |
| if conversation_id in self.conversations: | |
| del self.conversations[conversation_id] | |
| return True | |
| return False | |
| # Notion API 调用类 | |
| class NotionAIClient: | |
| def get_headers(): | |
| """获取请求头""" | |
| # 获取用户ID用于active user header | |
| user_id = Config.NOTION_USER_ID | |
| if not user_id and 'notion_user_id=' in Config.NOTION_COOKIE: | |
| user_id = Config.NOTION_COOKIE.split('notion_user_id=')[1].split(';')[0] | |
| return { | |
| 'User-Agent': Config.USER_AGENT, | |
| 'Accept': 'application/x-ndjson', | |
| 'Content-Type': 'application/json', | |
| 'Cookie': Config.NOTION_COOKIE, | |
| 'notion-audit-log-platform': 'web', | |
| 'notion-client-version': '23.13.0.3598', | |
| 'origin': '<https://www.notion.so>', | |
| 'referer': '<https://www.notion.so/>', | |
| 'x-notion-active-user-header': user_id or '', | |
| 'x-notion-space-id': Config.NOTION_SPACE_ID | |
| } | |
| def get_request_body(conversation_id, conversation_manager): | |
| """构建请求体""" | |
| conversation = conversation_manager.get_conversation(conversation_id) | |
| # 修复:构建完整的请求体 | |
| body = { | |
| "traceId": conversation["trace_id"], | |
| "spaceId": Config.NOTION_SPACE_ID, | |
| "transcript": conversation_manager.get_transcript(conversation_id), | |
| "threadId": conversation_id, | |
| "createThread": True, | |
| "generateTitle": True, | |
| "saveAllThreadOperations": True | |
| } | |
| # 添加threadParentPointer | |
| if Config.NOTION_SPACE_ID: | |
| body["threadParentPointer"] = { | |
| "table": "space", | |
| "id": Config.NOTION_SPACE_ID, | |
| "spaceId": Config.NOTION_SPACE_ID | |
| } | |
| return body | |
| def generate_completion(conversation_id, conversation_manager, stream=True): | |
| """生成回复""" | |
| headers = NotionAIClient.get_headers() | |
| body = NotionAIClient.get_request_body(conversation_id, conversation_manager) | |
| logger.info(f"发送请求到 Notion API,对话ID: {conversation_id}") | |
| logger.debug(f"请求体: {json.dumps(body, ensure_ascii=False)}") | |
| try: | |
| # 修复:移除有问题的 proxies 参数 | |
| response = requests.post( | |
| Config.NOTION_API_URL, | |
| headers=headers, | |
| json=body, | |
| stream=stream, | |
| timeout=Config.REQUEST_TIMEOUT | |
| ) | |
| if response.status_code != 200: | |
| logger.error(f"请求失败,状态码: {response.status_code}") | |
| logger.error(f"响应内容: {response.text}") | |
| return None | |
| # 如果不是流式响应,直接返回完整内容 | |
| if not stream: | |
| return NotionAIClient.parse_response(response.text) | |
| # 处理流式响应 | |
| return response | |
| except Exception as e: | |
| logger.error(f"请求出错: {str(e)}") | |
| return None | |
| def parse_response(response_text): | |
| """解析响应""" | |
| full_response = "" | |
| # 处理流式响应的每一行 | |
| for line in response_text.split('\\n'): | |
| line = line.strip() | |
| if not line: | |
| continue | |
| try: | |
| json_obj = json.loads(line) | |
| # 修复:正确解析markdown-chat类型的响应 | |
| if isinstance(json_obj, dict) and json_obj.get('type') == 'markdown-chat' and 'value' in json_obj: | |
| content = json_obj.get('value', '') | |
| full_response += content | |
| except json.JSONDecodeError: | |
| pass | |
| return full_response | |
| # 创建Flask应用 | |
| app = Flask(__name__) | |
| conversation_manager = ConversationManager() | |
| # API密钥验证装饰器 | |
| def require_api_key(f): | |
| def decorated_function(*args, **kwargs): | |
| if not Config.REQUIRE_API_KEY: | |
| return f(*args, **kwargs) | |
| api_key = request.headers.get('Authorization') | |
| if api_key: | |
| # 移除可能的"Bearer "前缀 | |
| api_key = api_key.replace('Bearer ', '') | |
| if not api_key or (Config.API_KEYS and api_key not in Config.API_KEYS): | |
| return jsonify({ | |
| "error": { | |
| "message": "Invalid API key", | |
| "type": "invalid_request_error", | |
| "code": "invalid_api_key" | |
| } | |
| }), 401 | |
| return f(*args, **kwargs) | |
| return decorated_function | |
| # 首页路由 | |
| def index(): | |
| return """ | |
| <html> | |
| <head> | |
| <title>Notion AI API (OpenAI Compatible)</title> | |
| <style> | |
| body { | |
| font-family: Arial, sans-serif; | |
| max-width: 800px; | |
| margin: 0 auto; | |
| padding: 20px; | |
| line-height: 1.6; | |
| } | |
| h1 { | |
| color: #333; | |
| border-bottom: 1px solid #eee; | |
| padding-bottom: 10px; | |
| } | |
| h2 { | |
| color: #444; | |
| margin-top: 30px; | |
| } | |
| code { | |
| background: #f4f4f4; | |
| padding: 2px 5px; | |
| border-radius: 3px; | |
| } | |
| pre { | |
| background: #f4f4f4; | |
| padding: 15px; | |
| border-radius: 5px; | |
| overflow-x: auto; | |
| } | |
| .endpoint { | |
| margin-top: 20px; | |
| background: #f9f9f9; | |
| padding: 15px; | |
| border-left: 4px solid #007bff; | |
| } | |
| .models { | |
| display: flex; | |
| flex-wrap: wrap; | |
| gap: 10px; | |
| margin-top: 10px; | |
| } | |
| .model { | |
| background: #e9f5ff; | |
| padding: 8px 12px; | |
| border-radius: 4px; | |
| font-family: monospace; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <h1>Notion AI API (OpenAI Compatible)</h1> | |
| <p>这是一个将Notion AI转换为OpenAI兼容格式的API服务。</p> | |
| <h2>可用模型</h2> | |
| <div class="models"> | |
| <div class="model">openai-gpt-4.1</div> | |
| <div class="model">anthropic-sonnet-4</div> | |
| <div class="model">anthropic-opus-4</div> | |
| <div class="model">anthropic-sonnet-3.7</div> | |
| </div> | |
| <h2>API端点</h2> | |
| <div class="endpoint"> | |
| <h3>列出模型</h3> | |
| <code>GET /v1/models</code> | |
| <p>获取所有可用模型的列表。</p> | |
| </div> | |
| <div class="endpoint"> | |
| <h3>创建聊天完成</h3> | |
| <code>POST /v1/chat/completions</code> | |
| <p>创建一个聊天完成请求。</p> | |
| <pre> | |
| { | |
| "model": "anthropic-opus-4", | |
| "messages": [ | |
| {"role": "system", "content": "You are a helpful assistant."}, | |
| {"role": "user", "content": "Hello, who are you?"} | |
| ], | |
| "stream": false | |
| } | |
| </pre> | |
| </div> | |
| <h2>认证</h2> | |
| <p>请在请求头中添加API密钥:</p> | |
| <pre>Authorization: Bearer your_api_key</pre> | |
| <h2>使用示例</h2> | |
| <pre> | |
| curl -X POST <https://your-space-name.hf.space/v1/chat/completions> \\\\ | |
| -H "Content-Type: application/json" \\\\ | |
| -H "Authorization: Bearer your_api_key" \\\\ | |
| -d '{ | |
| "model": "anthropic-opus-4", | |
| "messages": [ | |
| {"role": "system", "content": "You are a helpful assistant."}, | |
| {"role": "user", "content": "Hello, who are you?"} | |
| ] | |
| }' | |
| </pre> | |
| </body> | |
| </html> | |
| """ | |
| # 健康检查端点 | |
| def health_check(): | |
| if not Config.NOTION_COOKIE or not Config.NOTION_SPACE_ID: | |
| return jsonify({ | |
| "status": "warning", | |
| "message": "Missing Notion credentials", | |
| "details": { | |
| "cookie": bool(Config.NOTION_COOKIE), | |
| "space_id": bool(Config.NOTION_SPACE_ID) | |
| } | |
| }), 200 | |
| return jsonify({ | |
| "status": "ok", | |
| "version": "1.0.0", | |
| "models": list(NOTION_MODELS.keys()) | |
| }), 200 | |
| # OpenAI 兼容的模型列表接口 | |
| def list_models(): | |
| models = [] | |
| for model_id, model_name in NOTION_MODELS.items(): | |
| models.append({ | |
| "id": model_id, | |
| "object": "model", | |
| "created": int(time.time()), | |
| "owned_by": "notion", | |
| "permission": [], | |
| "root": model_id, | |
| "parent": None | |
| }) | |
| return jsonify({ | |
| "object": "list", | |
| "data": models | |
| }) | |
| # OpenAI 兼容的聊天完成接口 | |
| def create_chat_completion(): | |
| try: | |
| data = request.json | |
| # 解析请求参数 | |
| model = data.get('model', Config.DEFAULT_MODEL) | |
| messages = data.get('messages', []) | |
| stream = data.get('stream', False) | |
| conversation_id = data.get('conversation_id', str(uuid.uuid4())) | |
| # 验证模型 | |
| if model not in NOTION_MODELS: | |
| return jsonify({ | |
| "error": { | |
| "message": f"Model {model} does not exist", | |
| "type": "invalid_request_error", | |
| "code": "model_not_found" | |
| } | |
| }), 404 | |
| # 设置模型 | |
| conversation_manager.set_model(conversation_id, model) | |
| # 处理消息 | |
| system_message = None | |
| for msg in messages: | |
| role = msg.get('role') | |
| content = msg.get('content', '') | |
| if role == 'system': | |
| system_message = content | |
| elif role in ['user', 'assistant']: | |
| conversation_manager.add_message(conversation_id, role, content) | |
| # 设置系统提示 | |
| conversation_manager.set_system_prompt(conversation_id, system_message) | |
| # 生成回复 | |
| if stream: | |
| def generate(): | |
| response = NotionAIClient.generate_completion(conversation_id, conversation_manager, stream=True) | |
| if not response: | |
| yield f"data: {json.dumps({'error': 'Failed to generate completion'})}\\n\\n" | |
| return | |
| # 发送开始标记 | |
| yield f"data: {json.dumps({'id': conversation_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': model, 'choices': [{'index': 0, 'delta': {'role': 'assistant'}, 'finish_reason': None}]})}\\n\\n" | |
| full_response = "" | |
| for chunk in response.iter_content(chunk_size=1024): | |
| if chunk: | |
| try: | |
| chunk_str = chunk.decode('utf-8', errors='replace') | |
| # 处理每一行 | |
| for line in chunk_str.split('\\n'): | |
| line = line.strip() | |
| if not line: | |
| continue | |
| try: | |
| json_obj = json.loads(line) | |
| if isinstance(json_obj, dict) and json_obj.get('type') == 'markdown-chat' and 'value' in json_obj: | |
| content = json_obj.get('value', '') | |
| full_response += content | |
| # 发送内容块 | |
| yield f"data: {json.dumps({'id': conversation_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': model, 'choices': [{'index': 0, 'delta': {'content': content}, 'finish_reason': None}]})}\\n\\n" | |
| except json.JSONDecodeError: | |
| pass | |
| except Exception as e: | |
| logger.warning(f"处理响应块时出错: {str(e)}") | |
| # 保存AI回复到对话历史 | |
| if full_response: | |
| conversation_manager.add_message(conversation_id, "assistant", full_response) | |
| # 发送结束标记 | |
| yield f"data: {json.dumps({'id': conversation_id, 'object': 'chat.completion.chunk', 'created': int(time.time()), 'model': model, 'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}]})}\\n\\n" | |
| yield "data: [DONE]\\n\\n" | |
| return Response( | |
| generate(), | |
| mimetype='text/event-stream', | |
| headers={'Cache-Control': 'no-cache', 'Connection': 'keep-alive'} | |
| ) | |
| else: | |
| response = NotionAIClient.generate_completion(conversation_id, conversation_manager, stream=False) | |
| if not response: | |
| return jsonify({ | |
| "error": { | |
| "message": "Failed to generate completion", | |
| "type": "server_error", | |
| "code": "internal_error" | |
| } | |
| }), 500 | |
| # 保存AI回复到对话历史 | |
| conversation_manager.add_message(conversation_id, "assistant", response) | |
| return jsonify({ | |
| "id": conversation_id, | |
| "object": "chat.completion", | |
| "created": int(time.time()), | |
| "model": model, | |
| "choices": [ | |
| { | |
| "index": 0, | |
| "message": { | |
| "role": "assistant", | |
| "content": response | |
| }, | |
| "finish_reason": "stop" | |
| } | |
| ], | |
| "usage": { | |
| "prompt_tokens": -1, # 无法准确计算 | |
| "completion_tokens": -1, # 无法准确计算 | |
| "total_tokens": -1 # 无法准确计算 | |
| } | |
| }) | |
| except Exception as e: | |
| logger.error(f"处理请求时出错: {str(e)}", exc_info=True) | |
| return jsonify({ | |
| "error": { | |
| "message": str(e), | |
| "type": "server_error", | |
| "code": "internal_error" | |
| } | |
| }), 500 | |
| # 添加一个测试端点来检查系统提示词设置 | |
| def debug_conversation(conversation_id): | |
| try: | |
| conversation = conversation_manager.get_conversation(conversation_id) | |
| return jsonify(conversation) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| # 主函数 | |
| if __name__ == "__main__": | |
| # 检查必要的环境变量 | |
| if not Config.NOTION_COOKIE or not Config.NOTION_SPACE_ID: | |
| logger.warning("警告: 未设置 NOTION_COOKIE 或 NOTION_SPACE_ID 环境变量") | |
| # 启动应用 | |
| app.run(host=Config.HOST, port=Config.PORT) | |