"""飞书知识库服务 - 读取知识空间文档内容供大模型分析引用""" import json import subprocess import os # lark-cli 完整路径 LARK_CLI = r"C:\Users\qinyi\.trae-cn\plugins\trae-remote-official\lark\1.0.3\bin\lark-cli.exe" if not os.path.exists(LARK_CLI): LARK_CLI = "lark-cli" # 单篇文档内容最大长度(字符),避免 token 超限 MAX_DOC_CONTENT_LEN = 8000 # 知识库上下文总最大长度(字符) MAX_CONTEXT_TOTAL_LEN = 50000 def _run_lark(args: list[str], cwd: str = None) -> dict: """执行 lark-cli 命令并返回 JSON 结果""" cmd = [LARK_CLI] + args + ["--as", "user", "--format", "json"] result = subprocess.run(cmd, capture_output=True, text=True, timeout=60, cwd=cwd) if result.returncode != 0: err = json.loads(result.stderr) if result.stderr else {"error": result.stderr} msg = err.get('error', {}).get('message', str(err)) raise Exception(f"lark-cli 调用失败: {msg}") return json.loads(result.stdout) def list_spaces() -> list[dict]: """列出所有可访问的知识空间""" data = _run_lark(["wiki", "+space-list"]) spaces = [] for s in data.get("data", {}).get("spaces", []): spaces.append({ "space_id": s.get("space_id", ""), "name": s.get("name", ""), "description": s.get("description", ""), "space_type": s.get("space_type", ""), "visibility": s.get("visibility", "") }) return spaces def list_nodes(space_id: str, parent_token: str = "") -> list[dict]: """列出知识空间下的节点(支持递归获取子节点)""" args = ["wiki", "+node-list", "--space-id", space_id] if parent_token: args.append("--parent-node-token") args.append(parent_token) data = _run_lark(args) nodes = [] for n in data.get("data", {}).get("nodes", []): node = { "node_token": n.get("node_token", ""), "obj_token": n.get("obj_token", ""), "obj_type": n.get("obj_type", ""), "title": n.get("title", ""), "has_child": n.get("has_child", False), "parent_node_token": n.get("parent_node_token", ""), "space_id": space_id } nodes.append(node) # 递归获取子节点 if node["has_child"]: try: children = list_nodes(space_id, node["node_token"]) nodes.extend(children) except Exception: pass # 子节点获取失败不影响主流程 return nodes def fetch_doc_content(obj_token: str) -> str: """获取飞书文档内容(markdown格式)""" try: data = _run_lark([ "docs", "+fetch", "--doc", obj_token, "--doc-format", "markdown", "--scope", "full" ]) content = data.get("data", {}).get("document", {}).get("content", "") if len(content) > MAX_DOC_CONTENT_LEN: content = content[:MAX_DOC_CONTENT_LEN] + "\n...(内容过长已截断)" return content except Exception: return "" def build_knowledge_context(space_ids: list[str]) -> str: """根据选中的知识空间ID列表,构建知识库上下文文本供大模型引用""" if not space_ids: return "" all_docs = [] total_len = 0 for space_id in space_ids: try: nodes = list_nodes(space_id) for node in nodes: if total_len >= MAX_CONTEXT_TOTAL_LEN: break # 只读取 docx 类型的文档 if node.get("obj_type") != "docx": continue title = node.get("title", "未命名") content = fetch_doc_content(node["obj_token"]) if content and len(content.strip()) > 20: # 过滤掉太短的模板内容 doc_text = f"### {title}\n{content}" remaining = MAX_CONTEXT_TOTAL_LEN - total_len if len(doc_text) > remaining: doc_text = doc_text[:remaining] + "\n...(内容已截断)" all_docs.append(doc_text) total_len += len(doc_text) except Exception: continue if total_len >= MAX_CONTEXT_TOTAL_LEN: break if not all_docs: return "" context = "## 知识库参考材料\n以下是与本次审计相关的制度、规范和指南,请在分析时参考引用:\n\n" context += "\n\n---\n\n".join(all_docs) return context