functions.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. """
  2. 通用函数工具集
  3. 提供常用的图数据库操作和数据处理功能
  4. """
  5. import logging
  6. from app.core.graph.graph_operations import connect_graph
  7. from app.core.llm.llm_service import llm_client as llm_call
  8. logger = logging.getLogger("app")
  9. def delete_relationships(node_id):
  10. """
  11. 删除指定节点的所有关系
  12. Args:
  13. node_id: 节点ID
  14. """
  15. try:
  16. cql = """
  17. MATCH (n)-[r]-()
  18. WHERE id(n) = $node_id
  19. DELETE r
  20. """
  21. with connect_graph().session() as session:
  22. session.run(cql, node_id=node_id)
  23. return True
  24. except Exception as e:
  25. logger.error(f"删除关系错误: {e}")
  26. return False
  27. def update_or_create_node(node_id, **properties):
  28. """
  29. 更新或创建节点
  30. Args:
  31. node_id: 节点ID
  32. **properties: 节点属性
  33. Returns:
  34. 节点对象
  35. """
  36. try:
  37. # 检查节点是否存在
  38. with connect_graph().session() as session:
  39. check_query = "MATCH (n) WHERE id(n) = $node_id RETURN n"
  40. result = session.run(check_query, node_id=node_id).single()
  41. if result:
  42. # 如果有属性则更新,否则只返回节点
  43. if properties:
  44. props_string = ", ".join([f"n.{key} = ${key}" for key in properties])
  45. update_query = f"""
  46. MATCH (n) WHERE id(n) = $node_id
  47. SET {props_string}
  48. RETURN n
  49. """
  50. result = session.run(update_query, node_id=node_id, **properties).single()
  51. return result["n"]
  52. else:
  53. # 节点不存在,无法更新
  54. logger.warning(f"节点 {node_id} 不存在,无法更新")
  55. return None
  56. except Exception as e:
  57. logger.error(f"更新或创建节点错误: {e}")
  58. return None
  59. def get_node_by_id_no_label(node_id):
  60. """
  61. 通过ID获取节点,不考虑标签
  62. Args:
  63. node_id: 节点ID
  64. Returns:
  65. 节点对象
  66. """
  67. try:
  68. with connect_graph().session() as session:
  69. query = "MATCH (n) WHERE id(n) = $node_id RETURN n"
  70. result = session.run(query, node_id=node_id).single()
  71. return result["n"] if result else None
  72. except Exception as e:
  73. logger.error(f"获取节点错误: {e}")
  74. return None
  75. def translate_and_parse(content):
  76. """
  77. 翻译内容并返回结果
  78. Args:
  79. content: 需要翻译的内容
  80. Returns:
  81. list: 包含翻译结果的列表
  82. """
  83. # 调用LLM服务进行翻译
  84. translated_text = llm_call(content)
  85. # 如果翻译失败,返回原文
  86. if translated_text is None:
  87. return [content]
  88. # 确保返回格式为列表
  89. return [translated_text]