HazardInspector/lib/get_prompt.py

54 lines
2.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
将Markdown格式提示词转换为AI推理可用格式换行替换为\n转义符)
"""
import os
def get_prompt(md_path):
"""
转换Markdown格式提示词为AI推理可用格式
:param input_content: 输入内容md文件路径 或 md文本字符串
:param is_file: 是否为文件路径True文件路径False直接传入md文本
:param output_file: 输出文件路径(可选,指定则保存结果到文件)
:return: 转换后的AI可用提示词字符串
"""
try:
# 1. 获取原始md内容
# 校验文件是否存在
if not os.path.exists(md_path):
raise FileNotFoundError(f"找不到指定的Markdown文件{md_path}")
# 读取md文件指定utf-8编码避免中文乱码
with open(md_path, 'r', encoding='utf-8') as f:
md_content = f.read()
# 2. 核心转换:将可视化换行(\r\n 或 \n替换为转义换行符 \n
# 先统一处理Windows换行符 \r\n 为 Unix换行符 \n
# ai_prompt = md_content.replace('\r\n', '\n')
# 可选如果需要将连续换行压缩为单个换行避免AI识别多余空行解开下面注释
# import re
# ai_prompt = re.sub(r'\n{2,}', '\n\n', ai_prompt)
# 3. 可选保留Markdown关键格式的轻微优化避免转义破坏md语法
# 例如:保留代码块、标题、列表的格式,仅转换内容中的换行
# 此处无需额外处理,\n本身就可以被大多数AI包括Kimi识别为md换行
# 5. 返回转换后的提示词
return md_content
except Exception as e:
print(f"转换过程中出现错误:{e}")
return None
from datetime import datetime
def _current_time_str():
return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 示例用法
if __name__ == "__main__":
md_file_path = "./提示词 v2.md"
prompt = get_prompt(md_file_path)
if prompt:
print(f"[{_current_time_str()}][获取提示词] 转换成功AI可用提示词如下")
print(prompt)