qwen_agent/utils/prompt_loader.py
2025-10-22 00:45:32 +08:00

77 lines
2.5 KiB
Python
Raw 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
"""
System prompt loader utilities
"""
import os
def load_system_prompt(project_dir: str, language: str = None) -> str:
"""
优先使用项目目录的system_prompt没有才使用默认的system_prompt_default.md
Args:
project_dir: 项目目录路径
language: 语言代码,如 'zh', 'en', 'jp' 等(此参数将被忽略)
Returns:
str: 加载到的系统提示词内容,如果都未找到则返回空字符串
"""
system_prompt = None
# 1. 优先读取项目目录中的system_prompt
system_prompt_file = os.path.join(project_dir, "system_prompt.md")
if os.path.exists(system_prompt_file):
try:
with open(system_prompt_file, 'r', encoding='utf-8') as f:
system_prompt = f.read()
print(f"Using project-specific system prompt")
except Exception as e:
print(f"Failed to load project system prompt: {str(e)}")
system_prompt = None
# 2. 如果项目目录没有,使用默认提示词
if not system_prompt:
try:
default_prompt_file = os.path.join("prompt", "system_prompt_default.md")
with open(default_prompt_file, 'r', encoding='utf-8') as f:
system_prompt = f.read()
print(f"Using default system prompt from prompt folder")
except Exception as e:
print(f"Failed to load default system prompt: {str(e)}")
system_prompt = None
return system_prompt or ""
def get_available_prompt_languages() -> list:
"""
获取可用的提示词语言列表
Returns:
list: 可用语言代码列表,如 ['zh', 'en', 'jp']
"""
prompt_dir = "prompt"
available_languages = []
if os.path.exists(prompt_dir):
for filename in os.listdir(prompt_dir):
if filename.startswith("system_prompt_") and filename.endswith(".md"):
# 提取语言代码,如从 "system_prompt_zh.md" 中提取 "zh"
language = filename[len("system_prompt_"):-len(".md")]
available_languages.append(language)
return available_languages
def is_language_available(language: str) -> bool:
"""
检查指定语言的提示词是否可用
Args:
language: 语言代码
Returns:
bool: 如果可用返回True否则返回False
"""
prompt_file = os.path.join("prompt", f"system_prompt_{language}.md")
return os.path.exists(prompt_file)