qwen_agent/utils/prompt_loader.py
朱潮 1f81bef8c6 Squashed commits: various improvements and refactoring
🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-19 22:02:25 +08:00

92 lines
3.2 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项目目录 > 对应语言的提示词 > 默认提示词
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. 如果项目目录没有尝试根据language参数选择对应的system_prompt
if not system_prompt and language:
# 构建prompt文件路径
prompt_file = os.path.join("prompt", f"system_prompt_{language}.md")
if os.path.exists(prompt_file):
try:
with open(prompt_file, 'r', encoding='utf-8') as f:
system_prompt = f.read()
print(f"Loaded system prompt for language: {language}")
except Exception as e:
print(f"Failed to load system prompt for language {language}: {str(e)}")
system_prompt = None
else:
print(f"System prompt file not found for language: {language}")
# 3. 如果项目目录和对应语言的提示词都没有,使用默认提示词
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)