iT邦幫忙

2025 iThome 鐵人賽

DAY 15
0

讓 AI 擁有工具使用能力 — SystemTools 類別設計深度解析 (2)

在上一篇,我們了解了 LangChain Agent 系統的整體架構。今天,我們要深入探討整個智能助手的核心:SystemTools 類別

這個類別就像是 AI 的「雙手」,讓它能夠真正地操作電腦、處理檔案、生成內容。


功能簡介

SystemTools 類別是智能助手的工具庫,包含:

  • 多種智能工具:涵蓋檔案處理、應用程式控制、內容生成等功能
  • API 整合機制:與本地 API 服務器無縫對接
  • 狀態管理系統:追蹤內容生成、分析結果、檔案上傳等狀態
  • 錯誤處理機制:完善的異常處理和用戶回饋

核心程式碼解析

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)

工具分類與功能

1. 應用程式控制工具

開啟小畫家

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}"

設計特色:

  • 統一的 API 調用模式
  • 完善的錯誤處理機制
  • 詳細的除錯日誌記錄

2. Word 文件操作工具群

Word 開啟工具

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)

智能特色:

  • 防重複機制:使用時間戳避免頻繁調用
  • 智能內容選擇:自動選擇最新的可用內容
  • 多來源整合:支援分析結果、生成內容、上傳檔案

3. 內容管理系統

內容狀態檢查工具

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 "操作剛執行過,請稍候..."

工具間的協作機制

智能內容流轉

  1. 生成階段:generate_content_tool 創建內容並記錄時間戳
  2. 狀態檢查:check_available_content_tool 顯示可用內容
  3. 寫入階段:write_generated_to_word_tool 自動選擇最新內容
  4. 儲存階段:save_word_tool 完成檔案保存

檔案處理流程

  1. 上傳階段:upload_file_tool 上傳並解析檔案
  2. 分析階段:analyze_file_content_tool 使用專家模式分析
  3. 結果保存:自動保存分析結果供後續使用
  4. 輸出階段:可將分析結果寫入 Word 或其他格式

上一篇
DAY 14
下一篇
DAY 16
系列文
我的 AI 助手開發16
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言