在上一篇,我們了解了 LangChain Agent 系統的整體架構。今天,我們要深入探討整個智能助手的核心:SystemTools 類別。
這個類別就像是 AI 的「雙手」,讓它能夠真正地操作電腦、處理檔案、生成內容。
SystemTools 類別是智能助手的工具庫,包含:
class SystemTools:
def __init__(self, app_instance=None):
self.opencc_converter = OpenCC('s2t') # 繁體中文轉換器
self.app_instance = app_instance # 引用主應用程式實例
# 初始化 Gemini 用於內容生成
api_key = os.environ.get("GEMINI_API_KEY") or (
getattr(app_instance, "gemini_llm", None) and
getattr(app_instance.gemini_llm, "api_key", None)
)
if not api_key:
raise RuntimeError("未找到 GEMINI_API_KEY。請設定環境變數後再執行。")
genai.configure(api_key=api_key)
model_name = os.environ.get("GEMINI_MODEL") or "models/gemini-2.5-flash"
self.content_model = genai.GenerativeModel(model_name)
def open_paint_tool(self, input_text: str) -> str:
"""開啟小畫家應用程式"""
print(f"[DEBUG] ===== open_paint_tool 被調用了! =====")
print(f"[DEBUG] 準備調用API: {LOCAL_API_BASE}/open-paint")
try:
response = requests.post(f"{LOCAL_API_BASE}/open-paint")
response.raise_for_status()
result = response.json()
return result["message"]
except requests.exceptions.ConnectionError:
return "錯誤:無法連線到本地 API 服務。請確認伺服器已啟動。"
except Exception as e:
return f"開啟小畫家時發生錯誤: {e}"
設計特色:
def open_word_tool(self, content: str) -> str:
"""開啟 Word 並輸入指定內容"""
# 使用統一的時間檢查機制防重複
import time
current_time = time.time()
if hasattr(self, '_last_word_operation_time'):
time_diff = current_time - self._last_word_operation_time
if time_diff < 1.5:
return "Word剛開啟過,請稍候..."
# 智能內容來源判斷
if not content.strip():
latest_time = 0
latest_content = ""
# 檢查分析結果
if (hasattr(self.app_instance, 'last_analysis_result') and
self.app_instance.last_analysis_result.strip()):
analysis_time = getattr(self.app_instance, 'last_analysis_time', 0)
if analysis_time > latest_time:
latest_content = self.app_instance.last_analysis_result
# 檢查生成內容...
# 檢查上傳檔案...
if latest_content:
content = latest_content
return self._actually_open_word(content)
智能特色:
def check_available_content_tool(self, input_text: str = "") -> str:
"""檢查當前可用的內容狀態"""
status_info = []
latest_time = 0
latest_type = ""
# 檢查生成內容
if (hasattr(self.app_instance, 'last_generated_content') and
self.app_instance.last_generated_content.strip()):
gen_time = getattr(self.app_instance, 'last_generated_time', 0)
content_preview = self.app_instance.last_generated_content[:100]
status_info.append(f"生成內容: {len(content)}字符 (預覽: {content_preview}...)")
if gen_time > latest_time:
latest_time = gen_time
latest_type = "生成內容"
# 檢查分析結果...
# 檢查上傳檔案...
if not status_info:
return "目前沒有可用的內容。請先生成內容、分析檔案或上傳檔案。"
result = "當前可用內容狀態:\n\n" + "\n".join(status_info)
if latest_type:
result += f"\n\n最新內容: {latest_type}"
return result
1. 時間戳狀態管理
# 保存內容時記錄時間戳
if self.app_instance:
import time
self.app_instance.last_generated_content = content
self.app_instance.last_generated_time = time.time()
2. 防重複執行機制
# 時間檢查防重複
current_time = time.time()
if hasattr(self, '_last_operation_time'):
time_diff = current_time - self._last_operation_time
if time_diff < 1.5:
return "操作剛執行過,請稍候..."