You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
4.0 KiB

5 months ago
# -*- coding: utf-8 -*-
5 months ago
import re
5 months ago
import time
5 months ago
from typing import Iterator, Tuple
5 months ago
from openai import OpenAI
from openai.types.chat import ChatCompletionChunk
5 months ago
from Config import *
5 months ago
class KnowledgeGraph:
5 months ago
def __init__(self, shiti_content: str):
self.shiti_content = shiti_content
self.client = OpenAI(api_key=HW_API_KEY, base_url=HW_API_URL)
5 months ago
5 months ago
def _generate_stream(self) -> Iterator[ChatCompletionChunk]:
5 months ago
"""流式生成内容"""
5 months ago
system_prompt = '''回答以下内容:
1. 这道题目有哪些知识点哪些能力点
2. 生成Neo4j 5.26.2的插入语句'''
return self.client.chat.completions.create(
5 months ago
model=MODEL_NAME,
5 months ago
messages=[
{"role": "system", "content": system_prompt},
5 months ago
{"role": "user", "content": self.shiti_content}
5 months ago
],
stream=True,
5 months ago
timeout=300
5 months ago
)
5 months ago
def _extract_cypher(self, content: str) -> str:
"""从内容中提取Cypher语句修正版"""
# 匹配包含cypher的代码块支持可选语言声明
pattern = r"```(?:cypher)?\n(.*?)```"
matches = re.findall(pattern, content, re.DOTALL)
processed = []
for block in matches:
# 清理每行:移除注释和首尾空格
cleaned_lines = []
for line in block.split('\n'):
line = line.split('//')[0].strip() # 移除行尾注释
if line: # 保留非空行
cleaned_lines.append(line)
if cleaned_lines:
processed.append('\n'.join(cleaned_lines))
return ';\n\n'.join(processed) if processed else ""
def run(self) -> Tuple[bool, str, str]:
"""执行生成流程返回状态、完整内容、Cypher语句"""
5 months ago
start_time = time.time()
spinner = ['', '', '', '', '', '', '', '', '', '']
content_buffer = []
5 months ago
cypher_script = ""
5 months ago
try:
print(f"🚀 开始生成知识点和能力点的总结和插入语句")
5 months ago
stream = self._generate_stream()
5 months ago
5 months ago
for idx, chunk in enumerate(stream):
5 months ago
print(f"\r{spinner[idx % 10]} 生成中({int(time.time() - start_time)}秒)", end="")
5 months ago
if chunk.choices and chunk.choices[0].delta.content:
content_chunk = chunk.choices[0].delta.content
content_buffer.append(content_chunk)
if len(content_buffer) == 1:
print("\n\n📝 内容生成开始:")
print(content_chunk, end="", flush=True)
5 months ago
if content_buffer:
5 months ago
full_content = ''.join(content_buffer)
5 months ago
cypher_script = self._extract_cypher(full_content)
5 months ago
print(f"\n\n✅ 生成成功!耗时 {int(time.time() - start_time)}")
5 months ago
print("\n================ 完整结果 ================")
print(full_content)
5 months ago
print("\n================ Cypher语句 ===============")
print(cypher_script if cypher_script else "未检测到Cypher语句")
print("==========================================")
return True, full_content, cypher_script
return False, "", ""
5 months ago
except Exception as e:
print(f"\n\n❌ 生成失败:{str(e)}")
5 months ago
return False, str(e), ""
5 months ago
if __name__ == '__main__':
5 months ago
shiti_content = '''
5 months ago
下面是一道小学三年级的数学题目巧求周长
把7个完全相同的小长方形拼成如图的样子已知每个小长方形的长是10厘米则拼成的大长方形的周长是多少厘米
'''
5 months ago
kg = KnowledgeGraph(shiti_content)
5 months ago
success, result, cypher = kg.run()
5 months ago
5 months ago
if success and cypher:
with open("knowledge_graph.cypher", "w", encoding="utf-8") as f:
f.write(cypher)
print("\nCypher语句已保存至 knowledge_graph.cypher")