document_builder.py 1.5 KB

123456789101112131415161718192021222324252627282930
  1. from __future__ import annotations
  2. import hashlib
  3. import json
  4. from typing import Any
  5. SECRET_KEYS = {"password", "credentials", "api_key", "token", "authorization", "connection_string"}
  6. def _safe(value: Any, key: str = "") -> Any:
  7. if key.lower() in SECRET_KEYS:
  8. return "[redacted]"
  9. if isinstance(value, dict):
  10. return {k: _safe(v, k) for k, v in sorted(value.items()) if k not in {"updated_at", "created_at"}}
  11. if isinstance(value, list):
  12. items = [_safe(item) for item in value]
  13. return sorted(items, key=lambda item: json.dumps(item, sort_keys=True, ensure_ascii=False))
  14. return value
  15. def build_document(object_type: str, source: dict[str, Any]) -> dict[str, Any]:
  16. uid = source.get("uid")
  17. if not uid:
  18. raise ValueError("governance object uid is required")
  19. safe = _safe(source)
  20. content = json.dumps({"object_type": object_type, "source": safe}, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
  21. return {"object_type": object_type, "object_uid": uid, "object_version": int(source.get("version", 1)), "object_name": source.get("name_zh") or source.get("name") or uid, "business_domain_uid": source.get("business_domain_uid"), "content": content, "content_hash": hashlib.sha256(content.encode()).hexdigest(), "source_updated_at": source.get("updated_at")}
  22. def chunk_document(content: str, max_chars: int = 1200) -> list[str]:
  23. return [content[index:index + max_chars] for index in range(0, len(content), max_chars)] or [""]