├── account_agent ├── requirements.txt ├── __init__.py ├── model │ └── litellm_model │ │ └── model_config.py └── agent.py ├── privai_context_agent ├── models │ ├── __init__.py │ └── litellm_ace_model │ │ └── ace_model_config.py ├── __init__.py ├── requirements.txt ├── functions │ ├── __init__.py │ └── privai_knowledge_rag.py ├── agent.py └── file │ └── 資安法規.md ├── requirements.txt ├── timezone_agent ├── requirements.txt ├── __init__.py ├── model │ └── litellm_model │ │ └── model_config.py └── agent.py ├── google_blog_news_agent ├── __init__.py ├── requirements.txt ├── model │ └── litellm_model │ │ └── model_config.py └── agent.py ├── accounting.db ├── .env.template ├── README_zhtw.md ├── .gitignore ├── README.md └── LICENSE /account_agent/requirements.txt: -------------------------------------------------------------------------------- 1 | google-adk -------------------------------------------------------------------------------- /privai_context_agent/models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | feedparser 2 | google-adk -------------------------------------------------------------------------------- /timezone_agent/requirements.txt: -------------------------------------------------------------------------------- 1 | google-adk -------------------------------------------------------------------------------- /account_agent/__init__.py: -------------------------------------------------------------------------------- 1 | from . import agent 2 | -------------------------------------------------------------------------------- /timezone_agent/__init__.py: -------------------------------------------------------------------------------- 1 | from . import agent 2 | -------------------------------------------------------------------------------- /google_blog_news_agent/__init__.py: -------------------------------------------------------------------------------- 1 | from . import agent 2 | -------------------------------------------------------------------------------- /privai_context_agent/__init__.py: -------------------------------------------------------------------------------- 1 | from . import agent 2 | -------------------------------------------------------------------------------- /privai_context_agent/requirements.txt: -------------------------------------------------------------------------------- 1 | google-adk 2 | requests -------------------------------------------------------------------------------- /google_blog_news_agent/requirements.txt: -------------------------------------------------------------------------------- 1 | feedparser 2 | google-adk -------------------------------------------------------------------------------- /accounting.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LiuYuWei/google-adk-gemini-file-search-agent/main/accounting.db -------------------------------------------------------------------------------- /privai_context_agent/functions/__init__.py: -------------------------------------------------------------------------------- 1 | from .privai_knowledge_rag import knowledge_rag_reference 2 | 3 | __all__ = [ 4 | "knowledge_rag_reference" 5 | ] 6 | -------------------------------------------------------------------------------- /.env.template: -------------------------------------------------------------------------------- 1 | LITELLM_MODEL_BOOL=False 2 | 3 | #If LITELLM_MODEL_BOOL=False, the following variables are used for Google API. 4 | GOOGLE_API_KEY=your_google_api_key_here 5 | 6 | #If LITELLM_MODEL_BOOL=True, the following variables are used for LiteLLM Model API. 7 | LITELLM_MODEL_API_SSL_VERIFY=True 8 | LITELLM_MODEL_API_BASE=https://api.litellm.com/v1 9 | LITELLM_MODEL_API_KEY=your_litellm_model_api_key_here 10 | LITELLM_MODEL_MODEL_NAME=openai/ace-1-24b 11 | 12 | # PrivAI Configuration 13 | PRIVAI_API_URL=privai_api_url 14 | PRIVAI_API_KEY=privai_api_key -------------------------------------------------------------------------------- /privai_context_agent/models/litellm_ace_model/ace_model_config.py: -------------------------------------------------------------------------------- 1 | import os 2 | from dotenv import load_dotenv 3 | from google.adk.models.lite_llm import LiteLlm 4 | 5 | import litellm 6 | 7 | litellm.ssl_verify = os.getenv("LITELLM_MODEL_API_SSL_VERIFY", "True") 8 | 9 | # 載入環境變數 10 | load_dotenv() 11 | 12 | # 從環境變數取得設定 13 | API_BASE = os.getenv("LITELLM_MODEL_API_BASE") 14 | API_KEY = os.getenv("LITELLM_MODEL_API_KEY") 15 | MODEL_NAME = os.getenv("LITELLM_MODEL_MODEL_NAME") 16 | 17 | # 初始化 LiteLlm 模型 18 | litellm_ace_model = LiteLlm( 19 | model=MODEL_NAME, 20 | api_base=API_BASE, 21 | api_key=API_KEY, 22 | extra_body={"skip_special_tokens": False} 23 | ) -------------------------------------------------------------------------------- /account_agent/model/litellm_model/model_config.py: -------------------------------------------------------------------------------- 1 | import os 2 | from dotenv import load_dotenv 3 | from google.adk.models.lite_llm import LiteLlm 4 | import litellm 5 | 6 | litellm.ssl_verify = False 7 | 8 | # 載入環境變數 9 | load_dotenv() 10 | 11 | # 從環境變數取得設定 12 | API_BASE = os.getenv("LITELLM_MODEL_API_BASE") 13 | API_KEY = os.getenv("LITELLM_MODEL_API_KEY") 14 | MODEL_NAME = os.getenv("LITELLM_MODEL_MODEL_NAME") 15 | 16 | litellm_variables = { 17 | "model": MODEL_NAME, 18 | "api_base": API_BASE, 19 | "api_key": API_KEY, 20 | } 21 | 22 | # 解析 SPECIAL_TOKENS 23 | special_tokens_flag = os.getenv("LITELLM_MODEL_SPECIAL_TOKENS", "").lower() in ["1", "true", "yes"] 24 | 25 | if special_tokens_flag: 26 | print("LITELLM_MODEL_SPECIAL_TOKENS is True → initializing LiteLlm without skip_special_tokens.") 27 | else: 28 | litellm_variables["extra_body"] = {"skip_special_tokens": False} 29 | print("LITELLM_MODEL_SPECIAL_TOKENS is False → initializing LiteLlm with skip_special_tokens=False.") 30 | 31 | # 初始化模型 32 | litellm_model = LiteLlm(**litellm_variables) 33 | -------------------------------------------------------------------------------- /timezone_agent/model/litellm_model/model_config.py: -------------------------------------------------------------------------------- 1 | import os 2 | from dotenv import load_dotenv 3 | from google.adk.models.lite_llm import LiteLlm 4 | import litellm 5 | 6 | litellm.ssl_verify = False 7 | 8 | # 載入環境變數 9 | load_dotenv() 10 | 11 | # 從環境變數取得設定 12 | API_BASE = os.getenv("LITELLM_MODEL_API_BASE") 13 | API_KEY = os.getenv("LITELLM_MODEL_API_KEY") 14 | MODEL_NAME = os.getenv("LITELLM_MODEL_MODEL_NAME") 15 | 16 | litellm_variables = { 17 | "model": MODEL_NAME, 18 | "api_base": API_BASE, 19 | "api_key": API_KEY, 20 | } 21 | 22 | # 解析 SPECIAL_TOKENS 23 | special_tokens_flag = os.getenv("LITELLM_MODEL_SPECIAL_TOKENS", "").lower() in ["1", "true", "yes"] 24 | 25 | if special_tokens_flag: 26 | print("LITELLM_MODEL_SPECIAL_TOKENS is True → initializing LiteLlm without skip_special_tokens.") 27 | else: 28 | litellm_variables["extra_body"] = {"skip_special_tokens": False} 29 | print("LITELLM_MODEL_SPECIAL_TOKENS is False → initializing LiteLlm with skip_special_tokens=False.") 30 | 31 | # 初始化模型 32 | litellm_model = LiteLlm(**litellm_variables) 33 | -------------------------------------------------------------------------------- /google_blog_news_agent/model/litellm_model/model_config.py: -------------------------------------------------------------------------------- 1 | import os 2 | from dotenv import load_dotenv 3 | from google.adk.models.lite_llm import LiteLlm 4 | import litellm 5 | 6 | litellm.ssl_verify = False 7 | 8 | # 載入環境變數 9 | load_dotenv() 10 | 11 | # 從環境變數取得設定 12 | API_BASE = os.getenv("LITELLM_MODEL_API_BASE") 13 | API_KEY = os.getenv("LITELLM_MODEL_API_KEY") 14 | MODEL_NAME = os.getenv("LITELLM_MODEL_MODEL_NAME") 15 | 16 | litellm_variables = { 17 | "model": MODEL_NAME, 18 | "api_base": API_BASE, 19 | "api_key": API_KEY, 20 | } 21 | 22 | # 解析 SPECIAL_TOKENS 23 | special_tokens_flag = os.getenv("LITELLM_MODEL_SPECIAL_TOKENS", "").lower() in ["1", "true", "yes"] 24 | 25 | if special_tokens_flag: 26 | print("LITELLM_MODEL_SPECIAL_TOKENS is True → initializing LiteLlm without skip_special_tokens.") 27 | else: 28 | litellm_variables["extra_body"] = {"skip_special_tokens": False} 29 | print("LITELLM_MODEL_SPECIAL_TOKENS is False → initializing LiteLlm with skip_special_tokens=False.") 30 | 31 | # 初始化模型 32 | litellm_model = LiteLlm(**litellm_variables) 33 | -------------------------------------------------------------------------------- /privai_context_agent/agent.py: -------------------------------------------------------------------------------- 1 | from google.adk.agents import Agent 2 | from .models.litellm_ace_model.ace_model_config import litellm_ace_model 3 | from .functions import knowledge_rag_reference 4 | 5 | root_agent = Agent( 6 | name="root_agent", 7 | model=litellm_ace_model, 8 | description="一個與 PrivAI API 互動的代理,用於從檔案集中檢索檔案及其內容。", 9 | instruction=""" 10 | 【總則】 11 | 你是一個專業的企業級知識檢索助理,能夠透過 tools 檢索 PrivAI 檔案集中的資訊,並結合大語言模型生成上下文相關的回覆。 12 | 13 | 【嚴格決策流程】 14 | Step 1:當使用者提出問題時,請先判斷是否需要使用 tools 來輔助回答。 15 | - 若問題不需要任何工具即可回答,直接以模型知識回覆。 16 | - 若問題涉及特定知識領域或需要查詢檔案集內容,使用 `knowledge_rag_reference`。 17 | 18 | Step 2:使用 tools 時,請遵循以下介面定義: 19 | - `knowledge_rag_reference(fileset_id: str, user_query: str)` 20 | - fileset_id = 請從 {privai_fileset_id_list} 知識庫中挑選一個最接近問題的 ID 來帶入 21 | - user_query:使用者查詢字串 22 | 23 | Step 3:完成工具呼叫後,將工具回傳內容與使用者問題結合,輸出最終答案 24 | 25 | 【回覆風格】 26 | - 專業、精簡、事實為本;避免花俏語句。 27 | - 若工具回覆不足以回答,請明確點出資訊缺口並提出下一步建議(例如需要的 fileset_id 或補充條件)。 28 | 29 | 【錯誤處理】 30 | - 若工具回傳錯誤或不完整,請在最終回覆中簡述錯因(狀態碼/訊息),並提出可行修正(例如:確認 API Key、檢查 API Key、檢查 fileset_id 是否有效)。 31 | """, 32 | tools=[knowledge_rag_reference] 33 | ) 34 | -------------------------------------------------------------------------------- /privai_context_agent/functions/privai_knowledge_rag.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import requests 4 | from urllib.parse import urlencode 5 | 6 | def knowledge_rag_reference(fileset_id: str, user_query: str) -> str: 7 | """ 8 | 呼叫 PrivAI RAG API 進行檔案檢索。 9 | :param fileset_id: 已上傳檔案集合的 ID 10 | :param prompt_id: (未使用) 11 | :param user_query: 使用者查詢字串 12 | :param model_name: (未使用) 13 | :return: 檢索到的文件內容 14 | """ 15 | base_url = "{}v1/chat/references".format(os.getenv("PRIVAI_API_URL")) 16 | params = { 17 | "fileset_id": fileset_id, 18 | "query": user_query 19 | } 20 | url = f"{base_url}?{urlencode(params)}" 21 | 22 | headers = { 23 | "Accept": "application/json", 24 | "Authorization": "Bearer " + os.getenv("PRIVAI_API_KEY") 25 | } 26 | 27 | response = requests.post(url, headers=headers, data="", verify=True) 28 | 29 | if response.status_code == 200: 30 | result = response.json() 31 | return json.dumps(result, indent=2, ensure_ascii=False) 32 | else: 33 | raise {"Content": "PrivAI API 呼叫失敗", "status_code": response.status_code, "response": response.text} 34 | -------------------------------------------------------------------------------- /timezone_agent/agent.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from zoneinfo import ZoneInfo, ZoneInfoNotFoundError 3 | from google.adk.agents import Agent 4 | import requests 5 | import feedparser 6 | import re 7 | from typing import List, Dict, Union 8 | from .model.litellm_model.model_config import litellm_model 9 | 10 | 11 | def get_current_time(timezone_str: str) -> dict: 12 | """Returns the current time in a specified IANA timezone. 13 | 14 | Args: 15 | timezone_str: The IANA timezone name (e.g., 'Asia/Taipei', 'America/New_York'). 16 | 17 | Returns: 18 | dict: A dictionary with the status and the result or an error message. 19 | """ 20 | try: 21 | # 使用 ZoneInfo 獲取指定時區的資訊 22 | tz = ZoneInfo(timezone_str) 23 | # 獲取該時區的當前時間 24 | current_time = datetime.datetime.now(tz) 25 | # 將時間格式化為易於閱讀的字串 26 | time_report = current_time.strftime("%Y-%m-%d %H:%M:%S %Z") 27 | report = f"The current time in {timezone_str} is {time_report}." 28 | # 返回成功的結果 29 | return {"status": "success", "report": report} 30 | except ZoneInfoNotFoundError: 31 | # 如果找不到時區,返回錯誤訊息 32 | error_msg = f"Error: Timezone '{timezone_str}' not found. Please use a valid IANA timezone name." 33 | return {"status": "error", "report": error_msg} 34 | except Exception as e: 35 | # 處理其他潛在的錯誤 36 | error_msg = f"An unexpected error occurred: {e}" 37 | return {"status": "error", "report": error_msg} 38 | 39 | # 保持您的 Agent 定義不變 40 | root_agent = Agent( 41 | name="time_agent", 42 | model=litellm_model, 43 | description=( 44 | "Agent to answer questions about the time in a city." 45 | ), 46 | instruction=( 47 | "You are a helpful agent who can answer user questions about the time in a city. " 48 | "You will be given a timezone string to find the current time." 49 | ), 50 | tools=[get_current_time], 51 | ) 52 | -------------------------------------------------------------------------------- /privai_context_agent/file/資安法規.md: -------------------------------------------------------------------------------- 1 | # 資通安全管理法(114年版) 2 | 3 | **修正日期:** 民國114年9月24日 4 | **施行日期:** 由行政院定之(部分條文尚未生效) 5 | **法規類別:** 行政 > 數位發展部 > 資通安全目 6 | 7 | --- 8 | 9 | ## 第一章 總則 10 | 11 | ### 第1條 12 | 13 | 為積極推動國家資通安全政策,加速建構國家資通安全環境,以保障國家安全,維護社會公共利益,特制定本法。 14 | 15 | ### 第2條 16 | 17 | 本法之主管機關為數位發展部。 18 | 資通安全業務之執行,由數位發展部指定資安專責機關辦理。 19 | 20 | ### 第3條 定義 21 | 22 | 一、資通系統:指用以蒐集、控制、傳輸、儲存、流通、刪除資訊或對資訊為其他處理、使用或分享之系統。 23 | 二、資通服務:指與資訊之蒐集、控制、傳輸、儲存、流通、刪除、其他處理、使用或分享相關之服務。 24 | 三、資通安全:防止資通系統或資訊遭未經授權之存取、使用、控制、洩漏、破壞、竄改或銷毀,影響其機密性、完整性或可用性。 25 | 四、資通安全事件:指系統、服務或網路狀態顯示可能違反資通安全或保護措施失效之情況。 26 | 五、公務機關:依法行使公權力之中央、地方機關或公法人,不含軍事及情報機關。 27 | 六、特定非公務機關:指關鍵基礎設施提供者、公營事業、特定財團法人或受政府控制之事業、團體或機構。 28 | 七、關鍵基礎設施:對國家安全、社會公共利益、國民生活或經濟活動有重大影響者。 29 | 八、關鍵基礎設施提供者:維運或提供前項設施之機構。 30 | 九、特定財團法人:依財團法人法規定之全國性財團法人。 31 | 十、受政府控制之事業、團體或機構:經主管機關核定,具資通安全重要性者。 32 | 十一、危害國家資通安全產品:經主管機關認定具潛在危害風險之產品或服務。 33 | 34 | ### 第4條 35 | 36 | 政府應整合公私資源,推動下列事項: 37 | 38 | * 資通安全專業人才培育 39 | * 資通安全科技研發與國際合作 40 | * 資安產業發展與審驗機制 41 | * 協助民間防範重大資安事件 42 | 43 | ### 第5條 44 | 45 | 行政院設國家資通安全會報,協調推動政策與應變機制,會議由院長或副院長召集,主管機關為幕僚單位。 46 | 47 | ### 第6條 48 | 49 | 主管機關應每年發布下列報告並送立法院備查: 50 | 51 | * 國家資通安全情勢報告 52 | * 資安維護計畫稽核概況報告 53 | * 國家資安發展方案 54 | 55 | ### 第7條 56 | 57 | 各機關應依業務重要性、層級與資訊性質,報核資通安全責任等級,並辦理相應防護措施。 58 | 59 | ### 第8條 60 | 61 | 主管機關得定期或不定期稽核資安維護計畫實施情形,發現缺失者應提出改善報告。 62 | 63 | ### 第9條 64 | 65 | 主管機關應建立資通安全情資分享機制。 66 | 67 | ### 第10條 68 | 69 | 委外辦理資通系統建置或維運者,應要求受託者具備資安管理機制並簽訂契約。主管機關得規劃演練作業。 70 | 71 | --- 72 | 73 | ## 第二章 公務機關資通安全管理 74 | 75 | ### 第11條 76 | 77 | 禁止使用危害國家資通安全產品。必要時得專案核准使用並列冊管理。 78 | 79 | ### 第12條 80 | 81 | 公務機關應置資通安全長,由副首長或適當人員兼任。 82 | 83 | ### 第13條 84 | 85 | 公務機關應依資通安全責任等級訂定資通安全維護計畫。 86 | 87 | ### 第14條 88 | 89 | 公務機關每年應向上級機關或主管機關報送資安維護計畫實施情形。 90 | 91 | ### 第15條 92 | 93 | 上級機關應稽核所屬及所監督機關之資安維護計畫。 94 | 95 | ### 第16條 96 | 97 | 受稽核機關有缺失者,應提出改善報告;主管機關得要求補充說明或調整。 98 | 99 | ### 第17條 100 | 101 | 應訂定資安事件通報及應變機制,並通報主管機關與上級機關。 102 | 103 | ### 第18條 104 | 105 | 應設置資安專職人員並予獎勵;主管機關應規劃職能訓練與支援機制。 106 | 107 | ### 第19條 108 | 109 | 得對資安人員適任性進行查核,未通過者不得辦理涉密業務。 110 | 111 | --- 112 | 113 | ## 第三章 特定非公務機關資通安全管理 114 | 115 | ### 第20條 116 | 117 | 中央目的事業主管機關指定關鍵基礎設施提供者,應報主管機關核定並稽核其資安維護計畫。 118 | 119 | ### 第21條 120 | 121 | 特定非公務機關應依責任等級設置資安人員、制定維護計畫,主管機關得要求報告與稽核。 122 | 123 | ### 第22條 124 | 125 | 資安維護計畫之內容、稽核頻率、改善程序等由中央主管機關擬訂,報主管機關核定。 126 | 127 | ### 第23條 128 | 129 | 特定非公務機關應置資通安全長,負責推動與監督資安事務。 130 | 131 | ### 第24條 132 | 133 | 應訂定資安事件通報及應變機制,並向主管機關通報與提出報告。 134 | 135 | ### 第25條 136 | 137 | 重大資安事件發生時,主管機關得調查,當事人不得規避或拒絕,執行人員應出示證明文件。 138 | 139 | ### 第26條 140 | 141 | 特定非公務機關應獎勵資安績效優良人員。 142 | 143 | ### 第27條 144 | 145 | 主管機關得限制或禁止特定非公務機關使用危害國家資通安全產品。 146 | 147 | --- 148 | 149 | ## 第四章 罰則 150 | 151 | ### 第28條 152 | 153 | 公務人員違反本法者,依情節予以懲處;特定非公務機關人員情節重大者亦同。 154 | 155 | ### 第29條 156 | 157 | 特定非公務機關未依第24條第2項通報資安事件者,處30萬至1,000萬元罰鍰,並得按次處罰。 158 | 159 | ### 第30條 160 | 161 | 特定非公務機關未訂定計畫、未報告或未改善等情節者,處10萬至500萬元罰鍰。 162 | 163 | ### 第31條 164 | 165 | 違反第25條第3項,規避、妨礙或拒絕調查者,處10萬至100萬元罰鍰。 166 | 167 | --- 168 | 169 | ## 第五章 附則 170 | 171 | ### 第32條 172 | 173 | 主管機關得委託其他機構辦理資安相關事務。受託機關不得洩漏所知悉之秘密。 174 | 175 | ### 第33條 176 | 177 | 涉及個資外洩時,應另依個資保護法辦理。 178 | 179 | ### 第34條 180 | 181 | 施行細則由主管機關定之。 182 | 183 | ### 第35條 184 | 185 | 施行日期由行政院定之。 186 | -------------------------------------------------------------------------------- /google_blog_news_agent/agent.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from zoneinfo import ZoneInfo, ZoneInfoNotFoundError 3 | from google.adk.agents import Agent 4 | import requests 5 | import feedparser 6 | import re 7 | from typing import List, Dict, Union 8 | 9 | 10 | def get_current_time(timezone_str: str) -> dict: 11 | """Returns the current time in a specified IANA timezone. 12 | 13 | Args: 14 | timezone_str: The IANA timezone name (e.g., 'Asia/Taipei', 'America/New_York'). 15 | 16 | Returns: 17 | dict: A dictionary with the status and the result or an error message. 18 | """ 19 | try: 20 | # 使用 ZoneInfo 獲取指定時區的資訊 21 | tz = ZoneInfo(timezone_str) 22 | # 獲取該時區的當前時間 23 | current_time = datetime.datetime.now(tz) 24 | # 將時間格式化為易於閱讀的字串 25 | time_report = current_time.strftime("%Y-%m-%d %H:%M:%S %Z") 26 | report = f"The current time in {timezone_str} is {time_report}." 27 | # 返回成功的結果 28 | return {"status": "success", "report": report} 29 | except ZoneInfoNotFoundError: 30 | # 如果找不到時區,返回錯誤訊息 31 | error_msg = f"Error: Timezone '{timezone_str}' not found. Please use a valid IANA timezone name." 32 | return {"status": "error", "report": error_msg} 33 | except Exception as e: 34 | # 處理其他潛在的錯誤 35 | error_msg = f"An unexpected error occurred: {e}" 36 | return {"status": "error", "report": error_msg} 37 | 38 | 39 | def strip_html_tags(html: str) -> str: 40 | """ 41 | 移除 HTML 標籤,保留段落換行 42 | """ 43 | # 直接使用正規表達式清理 HTML 標籤 44 | return re.sub(r'<[^>]*>', '', html).strip() 45 | 46 | 47 | def get_google_blog_news( 48 | keyword: str, 49 | max_results: int = 1 50 | ) -> Dict[str, Union[str, List[Dict[str, str]]]]: 51 | """ 52 | 僅使用 feedparser 從 Google 台灣官方部落格 RSS 提取新聞,根據關鍵字搜尋並回傳前 N 筆結果。 53 | 54 | Args: 55 | keyword (str): 要搜尋的關鍵字(不區分大小寫) 56 | max_results (int): 最多回傳新聞數量,預設為 1 57 | 58 | Returns: 59 | dict: 包含 status 及 reports 或 error_message 60 | """ 61 | feed_url = "https://blog.google/intl/zh-tw/rss/" 62 | try: 63 | # 解析 RSS Feed(feedparser 會自動發送請求) 64 | feed = feedparser.parse(feed_url) 65 | # 檢查 feed 解析是否有錯誤 66 | if feed.bozo: 67 | raise feed.bozo_exception 68 | 69 | # 編譯關鍵字正則表達式 70 | pattern = re.compile(re.escape(keyword), re.IGNORECASE) 71 | results: List[Dict[str, str]] = [] 72 | 73 | for entry in feed.entries: 74 | title = entry.get('title', '') 75 | summary_html = entry.get('summary', '') 76 | combined_text = f"{title} {summary_html}" 77 | 78 | if pattern.search(combined_text): 79 | # 清理 HTML 標籤 80 | summary_text = strip_html_tags(summary_html) 81 | results.append({ 82 | 'title': title, 83 | 'link': entry.get('link', ''), 84 | 'summary': summary_text, 85 | 'pubDate': entry.get('published', '') 86 | }) 87 | if len(results) >= max_results: 88 | break 89 | 90 | if not results: 91 | return { 92 | 'status': 'error', 93 | 'error_message': f"未找到關鍵字「{keyword}」的相關新聞。" 94 | } 95 | 96 | return {'status': 'success', 'reports': results} 97 | 98 | except Exception as e: 99 | # 任何解析或請求過程中出錯,都回傳錯誤訊息 100 | return { 101 | 'status': 'error', 102 | 'error_message': f"處理 RSS Feed 時發生錯誤: {e}" 103 | } 104 | 105 | # 保持您的 Agent 定義不變 106 | root_agent = Agent( 107 | name="time_agent", 108 | model="gemini-2.5-flash", 109 | description=( 110 | "Agent to answer questions about the time in a city." 111 | ), 112 | instruction=( 113 | "You are a helpful agent who can answer user questions about the time in a city. " 114 | "You will be given a timezone string to find the current time." 115 | ), 116 | tools=[get_current_time, get_google_blog_news], 117 | ) 118 | -------------------------------------------------------------------------------- /README_zhtw.md: -------------------------------------------------------------------------------- 1 | # Google ADK 工作坊 2 | 3 | 本儲存庫包含 Google ADK 工作坊的專案。其中包含四個使用 Google Agent Development Kit (ADK) 開發的獨特代理程式。 4 | 5 | ## 🤖 可用代理程式 6 | 7 | ### 1. 記帳代理人 (Accounting Agent) 8 | 9 | `account_agent` 是一個對話式 AI 代理程式,旨在作為個人記帳助理,幫助使用者透過自然語言指令管理其財務交易。 10 | 11 | #### ✨ 功能 12 | 13 | - **交易管理 (CRUD):** 14 | - **新增:** 記錄新的收入或支出。 15 | - **讀取:** 依 ID、類別查詢交易,或檢視所有記錄。 16 | - **更新:** 修改現有交易的詳細資訊。 17 | - **刪除:** 依 ID、類別或日期刪除交易。 18 | - **時間感知:** 19 | - 取得不同城市的目前時間,以正確解讀與時間相關的查詢 (例如「昨天」、「今天」)。 20 | - **智慧分析:** 21 | - 執行記憶體內計算以提供財務摘要,例如按類別劃分的每月支出,無需專門的分析工具。 22 | 23 | #### 🛠️ 工具 24 | 25 | - `add_transaction(date, description, amount, category)` 26 | - `get_transactions(transaction_id, category)` 27 | - `update_transaction(transaction_id, date, description, amount, category)` 28 | - `delete_transaction(transaction_id, category, date)` 29 | - `get_current_time(city)` 30 | 31 | ### 2. Google 部落格新聞代理人 (Google Blog News Agent) 32 | 33 | `google_blog_news_agent` 是一個代理程式,可根據使用者提供的關鍵字,從 Google 台灣官方部落格擷取和搜尋新聞文章。 34 | 35 | #### ✨ 功能 36 | 37 | - **關鍵字搜尋:** 在 Google 台灣部落格上搜尋符合特定關鍵字的文章。 38 | - **HTML 剝離:** 清理摘要內容,移除 HTML 標籤以提高可讀性。 39 | - **時間查詢:** 可提供任何 IANA 時區的目前時間。 40 | 41 | #### 🛠️ 工具 42 | 43 | - `get_google_blog_news(keyword, max_results)` 44 | - `get_current_time(timezone_str)` 45 | 46 | ### 3. PrivAI 內容助理 (PrivAI Context Agent) 47 | 48 | `privai_context_agent` 是一個與 PrivAI API 互動的代理程式,用於從檔案集中檢索檔案及其內容,作為一個企業級的知識檢索助理。 49 | 50 | #### ✨ 功能 51 | 52 | - **知識檢索:** 根據使用者查詢,從 PrivAI 檔案集中檢索資訊。 53 | - **情境式回答:** 將檢索到的資訊與大型語言模型結合,生成與情境相關的回覆。 54 | 55 | #### 🛠️ 工具 56 | 57 | - `knowledge_rag_reference(fileset_id: str, user_query: str)` 58 | 59 | ### 4. 時區代理 (Timezone Agent) 60 | 61 | `timezone_agent` 是一個簡單的代理程式,可以提供任何指定 IANA 時區的目前時間。 62 | 63 | #### ✨ 功能 64 | 65 | - **時間查詢:** 取得任何有效 IANA 時區 (例如 'Asia/Taipei', 'America/New_York') 的目前時間。 66 | 67 | #### 🛠️ 工具 68 | 69 | - `get_current_time(timezone_str: str)` 70 | 71 | ## 🚀 開始使用 72 | 73 | ### 先決條件 74 | 75 | - Python 3.9+ 76 | - Google Gemini API 存取權 77 | 78 | ### 安裝 79 | 80 | 1. **複製儲存庫:** 81 | ```bash 82 | git clone https://github.com/LiuYuWei/google-adk-workshop-code.git 83 | cd google-adk-workshop-code 84 | ``` 85 | 86 | 2. **安裝相依套件:** 87 | 建議建立虛擬環境。 88 | ```bash 89 | python -m venv venv 90 | source venv/bin/activate 91 | pip install -r requirements.txt 92 | pip install -r account_agent/requirements.txt 93 | pip install -r google_blog_news_agent/requirements.txt 94 | pip install -r privai_context_agent/requirements.txt 95 | pip install -r timezone_agent/requirements.txt 96 | ``` 97 | 98 | 3. **設定您的環境:** 99 | 若要設定您的環境,請將 `.env.template` 檔案複製到每個代理程式的根目錄中,並命名為 `.env` (例如 `account_agent/.env`, `google_blog_news_agent/.env`)。然後,修改 `.env` 檔案中的變數。 100 | 101 | ```bash 102 | cp .env.template account_agent/.env 103 | cp .env.template google_blog_news_agent/.env 104 | cp .env.template privai_context_agent/.env 105 | cp .env.template timezone_agent/.env 106 | ``` 107 | 108 | * **使用 Google Gemini API:** 109 | 在您的 `.env` 檔案中,將 `LITELLM_MODEL_BOOL` 設定為 `False`,並提供您的 Google API 金鑰: 110 | ``` 111 | LITELLM_MODEL_BOOL=False 112 | GOOGLE_API_KEY="YOUR_GEMINI_API_KEY" 113 | ``` 114 | 115 | * **使用本地端/LiteLLM 模型:** 116 | 在您的 `.env` 檔案中,將 `LITELLM_MODEL_BOOL` 設定為 `True`,並為您的 LiteLLM 相容模型設定以下變數: 117 | ``` 118 | LITELLM_MODEL_BOOL=True 119 | LITELLM_MODEL_API_BASE="http://localhost:11434" # Ollama 範例 120 | LITELLM_MODEL_MODEL_NAME="ollama/llama2" # Ollama 範例 121 | # 對於許多本地端模型,LITELLM_MODEL_API_KEY 是選用的 122 | ``` 123 | 這讓您可以在 Google 模型和由 Ollama 或 LiteLLM 提供的其他模型之間切換。 124 | 125 | 4. **啟動 Google ADK:** 126 | ADK 會自動發現在 `account_agent`、`google_blog_news_agent`、`privai_context_agent` 和 `timezone_agent` 目錄中的代理程式。 127 | ```bash 128 | adk web 129 | ``` 130 | 131 | ## 📝 使用方式 132 | 133 | 這些代理程式設計為在 ADK 框架內執行。啟動後,您可以在 ADK 網頁介面中使用自然語言與它們互動。從 UI 中選擇您想要互動的代理程式。 134 | 135 | ### 範例提示 136 | 137 | #### 記帳代理人 138 | 139 | - **新增交易:** 140 | > 「我昨天晚餐花了 500 元。」 141 | 142 | - **查詢交易:** 143 | > 「顯示我上週的所有支出。」 144 | > 「這個月我在食物上花了多少錢?」 145 | 146 | #### Google 部落格新聞代理人 147 | 148 | - **搜尋新聞:** 149 | > 「在 Google 部落格上尋找有關『Gemini』的新聞。」 150 | 151 | - **取得時間:** 152 | > 「『America/New_York』現在是什麼時間?」 153 | 154 | #### PrivAI 內容助理 155 | 156 | - **檢索知識:** 157 | > 「歐盟的資料隱私法規有哪些?」(假設存在相關的檔案集) 158 | 159 | #### 時區代理 160 | 161 | - **取得時間:** 162 | > 「『Asia/Tokyo』現在是什麼時間?」 163 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[codz] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # UV 98 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | #uv.lock 102 | 103 | # poetry 104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 105 | # This is especially recommended for binary packages to ensure reproducibility, and is more 106 | # commonly ignored for libraries. 107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 108 | #poetry.lock 109 | #poetry.toml 110 | 111 | # pdm 112 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 113 | # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. 114 | # https://pdm-project.org/en/latest/usage/project/#working-with-version-control 115 | #pdm.lock 116 | #pdm.toml 117 | .pdm-python 118 | .pdm-build/ 119 | 120 | # pixi 121 | # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. 122 | #pixi.lock 123 | # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one 124 | # in the .venv directory. It is recommended not to include this directory in version control. 125 | .pixi 126 | 127 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 128 | __pypackages__/ 129 | 130 | # Celery stuff 131 | celerybeat-schedule 132 | celerybeat.pid 133 | 134 | # SageMath parsed files 135 | *.sage.py 136 | 137 | # Environments 138 | .env 139 | .envrc 140 | .venv 141 | env/ 142 | venv/ 143 | ENV/ 144 | env.bak/ 145 | venv.bak/ 146 | 147 | # Spyder project settings 148 | .spyderproject 149 | .spyproject 150 | 151 | # Rope project settings 152 | .ropeproject 153 | 154 | # mkdocs documentation 155 | /site 156 | 157 | # mypy 158 | .mypy_cache/ 159 | .dmypy.json 160 | dmypy.json 161 | 162 | # Pyre type checker 163 | .pyre/ 164 | 165 | # pytype static type analyzer 166 | .pytype/ 167 | 168 | # Cython debug symbols 169 | cython_debug/ 170 | 171 | # PyCharm 172 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 173 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 174 | # and can be added to the global gitignore or merged into this file. For a more nuclear 175 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 176 | #.idea/ 177 | 178 | # Abstra 179 | # Abstra is an AI-powered process automation framework. 180 | # Ignore directories containing user credentials, local state, and settings. 181 | # Learn more at https://abstra.io/docs 182 | .abstra/ 183 | 184 | # Visual Studio Code 185 | # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore 186 | # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore 187 | # and can be added to the global gitignore or merged into this file. However, if you prefer, 188 | # you could uncomment the following to ignore the entire vscode folder 189 | # .vscode/ 190 | 191 | # Ruff stuff: 192 | .ruff_cache/ 193 | 194 | # PyPI configuration file 195 | .pypirc 196 | 197 | # Cursor 198 | # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to 199 | # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data 200 | # refer to https://docs.cursor.com/context/ignore-files 201 | .cursorignore 202 | .cursorindexingignore 203 | 204 | # Marimo 205 | marimo/_static/ 206 | marimo/_lsp/ 207 | __marimo__/ 208 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Google ADK Workshop 2 | 3 | This repository contains projects for the Google ADK Workshop. It features four distinct agents developed using the Google Agent Development Kit (ADK). 4 | 5 | ## 🤖 Available Agents 6 | 7 | ### 1. 記帳代理人 (Accounting Agent) 8 | 9 | The `account_agent` is a conversational AI agent designed to act as a personal accounting assistant, helping users manage their financial transactions through natural language commands. 10 | 11 | #### ✨ Features 12 | 13 | - **Transaction Management (CRUD):** 14 | - **Create:** Record new income or expenses. 15 | - **Read:** Query transactions by ID, category, or view all records. 16 | - **Update:** Modify the details of existing transactions. 17 | - **Delete:** Remove transactions by ID, category, or date. 18 | - **Time-Awareness:** 19 | - Fetches the current time in different cities to correctly interpret time-related queries (e.g., "yesterday," "today"). 20 | - **Smart Analysis:** 21 | - Performs in-memory calculations to provide financial summaries, such as monthly spending by category, without needing a dedicated analysis tool. 22 | 23 | #### 🛠️ Tools 24 | 25 | - `add_transaction(date, description, amount, category)` 26 | - `get_transactions(transaction_id, category)` 27 | - `update_transaction(transaction_id, date, description, amount, category)` 28 | - `delete_transaction(transaction_id, category, date)` 29 | - `get_current_time(city)` 30 | 31 | ### 2. Google 部落格新聞代理人 (Google Blog News Agent) 32 | 33 | The `google_blog_news_agent` is an agent that fetches and searches for news articles from the official Google Taiwan blog based on user-provided keywords. 34 | 35 | #### ✨ Features 36 | 37 | - **Keyword-Based Search:** Searches for articles on the Google Taiwan blog that match a specific keyword. 38 | - **HTML Stripping:** Cleans up the summary content by removing HTML tags for better readability. 39 | - **Time Queries:** Can provide the current time in any IANA timezone. 40 | 41 | #### 🛠️ Tools 42 | 43 | - `get_google_blog_news(keyword, max_results)` 44 | - `get_current_time(timezone_str)` 45 | 46 | ### 3. PrivAI 內容助理 (PrivAI Context Agent) 47 | 48 | The `privai_context_agent` is an agent that interacts with the PrivAI API to retrieve files and their content from a fileset, acting as an enterprise-level knowledge retrieval assistant. 49 | 50 | #### ✨ Features 51 | 52 | - **Knowledge Retrieval:** Retrieves information from PrivAI filesets based on user queries. 53 | - **Contextual Answers:** Combines the retrieved information with the power of large language models to generate context-aware responses. 54 | 55 | #### 🛠️ Tools 56 | 57 | - `knowledge_rag_reference(fileset_id: str, user_query: str)` 58 | 59 | ### 4. 時區代理 (Timezone Agent) 60 | 61 | The `timezone_agent` is a simple agent that can provide the current time in any specified IANA timezone. 62 | 63 | #### ✨ Features 64 | 65 | - **Time Queries:** Fetches the current time for any valid IANA timezone (e.g., 'Asia/Taipei', 'America/New_York'). 66 | 67 | #### 🛠️ Tools 68 | 69 | - `get_current_time(timezone_str: str)` 70 | 71 | ## 🚀 Getting Started 72 | 73 | ### Prerequisites 74 | 75 | - Python 3.9+ 76 | - Access to the Google Gemini API 77 | 78 | ### Installation 79 | 80 | 1. **Clone the repository:** 81 | ```bash 82 | git clone https://github.com/LiuYuWei/google-adk-workshop-code.git 83 | cd google-adk-workshop-code 84 | ``` 85 | 86 | 2. **Install dependencies:** 87 | It is recommended to create a virtual environment. 88 | ```bash 89 | python -m venv venv 90 | source venv/bin/activate 91 | pip install -r requirements.txt 92 | pip install -r account_agent/requirements.txt 93 | pip install -r google_blog_news_agent/requirements.txt 94 | pip install -r privai_context_agent/requirements.txt 95 | pip install -r timezone_agent/requirements.txt 96 | ``` 97 | 98 | 3. **Set up your environment:** 99 | To set up your environment, copy the `.env.template` file to a new file named `.env` in the root directory of each agent (e.g., `account_agent/.env`, `google_blog_news_agent/.env`). Then, modify the variables in the `.env` file. 100 | 101 | ```bash 102 | cp .env.template account_agent/.env 103 | cp .env.template google_blog_news_agent/.env 104 | cp .env.template privai_context_agent/.env 105 | cp .env.template timezone_agent/.env 106 | ``` 107 | 108 | * **For Google Gemini API:** 109 | In your `.env` file, set `LITELLM_MODEL_BOOL` to `False` and provide your Google API key: 110 | ``` 111 | LITELLM_MODEL_BOOL=False 112 | GOOGLE_API_KEY="YOUR_GEMINI_API_KEY" 113 | ``` 114 | 115 | * **For Local/LiteLLM Models:** 116 | In your `.env` file, set `LITELLM_MODEL_BOOL` to `True` and configure the following variables for your LiteLLM-compatible model: 117 | ``` 118 | LITELLM_MODEL_BOOL=True 119 | LITELLM_MODEL_API_BASE="http://localhost:11434" # Example for Ollama 120 | LITELLM_MODEL_MODEL_NAME="ollama/llama2" # Example for Ollama 121 | # LITELLM_MODEL_API_KEY is optional for many local models 122 | ``` 123 | This allows you to switch between Google's models and other models like those served by Ollama or LiteLLM. 124 | 125 | 4. **Launch the Google ADK:** 126 | The ADK will automatically discover the agents in the `account_agent`, `google_blog_news_agent`, `privai_context_agent`, and `timezone_agent` directories. 127 | ```bash 128 | adk web 129 | ``` 130 | 131 | ## 📝 Usage 132 | 133 | These agents are designed to be run within the ADK framework. Once running, you can interact with them using natural language in the ADK web interface. Select the agent you wish to interact with from the UI. 134 | 135 | ### Example Prompts 136 | 137 | #### Accounting Agent 138 | 139 | - **Add a transaction:** 140 | > "I spent 500 on dinner yesterday." 141 | 142 | - **Query transactions:** 143 | > "Show me all my expenses from last week." 144 | > "How much did I spend on food this month?" 145 | 146 | #### Google Blog News Agent 147 | 148 | - **Search for news:** 149 | > "Find news about 'Gemini' on the Google blog." 150 | 151 | - **Get the time:** 152 | > "What is the current time in 'America/New_York'?" 153 | 154 | #### PrivAI Context Agent 155 | 156 | - **Retrieve knowledge:** 157 | > "What are the data privacy regulations in the EU?" (Assuming a relevant fileset exists) 158 | 159 | #### Timezone Agent 160 | 161 | - **Get the time:** 162 | > "What time is it in 'Asia/Tokyo'?" 163 | -------------------------------------------------------------------------------- /account_agent/agent.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | from typing import Optional 3 | import datetime 4 | from zoneinfo import ZoneInfo 5 | from google.adk.agents import Agent 6 | from .model.litellm_model.model_config import litellm_model 7 | 8 | # Initialize the database 9 | def init_db(): 10 | conn = sqlite3.connect('accounting.db') 11 | c = conn.cursor() 12 | c.execute(''' 13 | CREATE TABLE IF NOT EXISTS transactions 14 | (id INTEGER PRIMARY KEY AUTOINCREMENT, 15 | date TEXT NOT NULL, 16 | description TEXT NOT NULL, 17 | amount REAL NOT NULL, 18 | category TEXT NOT NULL) 19 | ''') 20 | conn.commit() 21 | conn.close() 22 | 23 | init_db() 24 | 25 | def add_transaction(date: str, description: str, amount: float, category: str) -> dict: 26 | """Adds a new transaction record to the database.""" 27 | conn = sqlite3.connect('accounting.db') 28 | c = conn.cursor() 29 | c.execute("INSERT INTO transactions (date, description, amount, category) VALUES (?, ?, ?, ?)", 30 | (date, description, amount, category)) 31 | transaction_id = c.lastrowid 32 | conn.commit() 33 | conn.close() 34 | return {"status": "success", "report": f"Transaction record created with ID: {transaction_id}"} 35 | 36 | def get_transactions(transaction_id: Optional[int] = None, category: Optional[str] = None) -> dict: 37 | """Retrieves all transaction records, or filtered by ID or category from the database.""" 38 | conn = sqlite3.connect('accounting.db') 39 | conn.row_factory = sqlite3.Row 40 | c = conn.cursor() 41 | if transaction_id: 42 | c.execute("SELECT * FROM transactions WHERE id = ?", (transaction_id,)) 43 | transaction = c.fetchone() 44 | conn.close() 45 | if transaction: 46 | return {"status": "success", "report": dict(transaction)} 47 | else: 48 | return {"status": "error", "error_message": f"Transaction with ID {transaction_id} not found."} 49 | elif category: 50 | c.execute("SELECT * FROM transactions WHERE category = ?", (category,)) 51 | transactions = c.fetchall() 52 | conn.close() 53 | return {"status": "success", "report": [dict(row) for row in transactions]} 54 | else: 55 | c.execute("SELECT * FROM transactions") 56 | transactions = c.fetchall() 57 | conn.close() 58 | return {"status": "success", "report": [dict(row) for row in transactions]} 59 | 60 | def update_transaction(transaction_id: int, date: Optional[str] = None, description: Optional[str] = None, amount: Optional[float] = None, category: Optional[str] = None) -> dict: 61 | """Updates an existing transaction record in the database.""" 62 | conn = sqlite3.connect('accounting.db') 63 | c = conn.cursor() 64 | 65 | updates = [] 66 | params = [] 67 | if date: 68 | updates.append("date = ?") 69 | params.append(date) 70 | if description: 71 | updates.append("description = ?") 72 | params.append(description) 73 | if amount: 74 | updates.append("amount = ?") 75 | params.append(amount) 76 | if category: 77 | updates.append("category = ?") 78 | params.append(category) 79 | 80 | if not updates: 81 | conn.close() 82 | return {"status": "error", "error_message": "No fields to update."} 83 | 84 | params.append(transaction_id) 85 | c.execute(f"UPDATE transactions SET { ', '.join(updates)} WHERE id = ?", tuple(params)) 86 | 87 | conn.commit() 88 | 89 | if c.rowcount == 0: 90 | conn.close() 91 | return {"status": "error", "error_message": f"Transaction with ID {transaction_id} not found."} 92 | else: 93 | conn.close() 94 | return {"status": "success", "report": f"Transaction with ID {transaction_id} updated."} 95 | 96 | def delete_transaction(transaction_id: Optional[int] = None, category: Optional[str] = None, date: Optional[str] = None) -> dict: 97 | """Deletes transaction records from the database based on ID, category, or date. 98 | 99 | Args: 100 | transaction_id (Optional[int], optional): The ID of the transaction to delete. Defaults to None. 101 | category (Optional[str], optional): The category of transactions to delete. Defaults to None. 102 | date (Optional[str], optional): The date of transactions to delete (YYYY-MM-DD). Defaults to None. 103 | 104 | Returns: 105 | dict: status and result or error msg. 106 | """ 107 | if not transaction_id and not category and not date: 108 | return { 109 | "status": "error", 110 | "error_message": "You must provide at least one criterion (ID, category, or date) for deletion." 111 | } 112 | 113 | conn = sqlite3.connect('accounting.db') 114 | c = conn.cursor() 115 | 116 | where_clauses = [] 117 | params = [] 118 | 119 | if transaction_id: 120 | where_clauses.append("id = ?") 121 | params.append(transaction_id) 122 | if category: 123 | where_clauses.append("category = ?") 124 | params.append(category) 125 | if date: 126 | where_clauses.append("date = ?") 127 | params.append(date) 128 | 129 | where_sql = " AND ".join(where_clauses) 130 | 131 | query = f"DELETE FROM transactions WHERE {where_sql}" 132 | 133 | c.execute(query, tuple(params)) 134 | 135 | deleted_rows = c.rowcount 136 | conn.commit() 137 | conn.close() 138 | 139 | if deleted_rows > 0: 140 | return {"status": "success", "report": f"Successfully deleted {deleted_rows} transaction(s)."} 141 | else: 142 | return {"status": "error", "error_message": "No matching transactions found to delete."} 143 | 144 | def get_current_time(city: str = "Taipei") -> dict: 145 | """Returns the current time in a specified city. 146 | 147 | Args: 148 | city (str): The name of the city for which to retrieve the current time. Defaults to "Taipei". 149 | 150 | Returns: 151 | dict: status and result or error msg. 152 | """ 153 | 154 | # A simple mapping from city to timezone identifier 155 | timezone_map = { 156 | "new york": "America/New_York", 157 | "london": "Europe/London", 158 | "tokyo": "Asia/Tokyo", 159 | "sydney": "Australia/Sydney", 160 | "taipei": "Asia/Taipei", 161 | } 162 | 163 | tz_identifier = timezone_map.get(city.lower()) 164 | 165 | if not tz_identifier: 166 | return { 167 | "status": "error", 168 | "error_message": ( 169 | f"Sorry, I don't have timezone information for {city}." 170 | ), 171 | } 172 | 173 | tz = ZoneInfo(tz_identifier) 174 | now = datetime.datetime.now(tz) 175 | report = ( 176 | f'The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}' 177 | ) 178 | return {"status": "success", "report": report} 179 | 180 | root_agent = Agent( 181 | name="accounting_agent", 182 | model=litellm_model, 183 | description=( 184 | "Agent for accounting, primarily for users in Taiwan. It can get the current time and manage transactions." 185 | ), 186 | instruction=( 187 | """你是一位頂尖的 AI 記帳助理,專為台灣使用者設計,目標是提供**快速**且**安全**的服務。請嚴格遵循以下工作流程: 188 | 189 | **最高指導原則:時間基準** 190 | 在你執行任何有關交易紀錄的任務(新增、查詢、更新、刪除)之前,如果使用者的指令中**包含了任何與時間相關的詞彙**(例如「今天」、「昨天」、「上禮拜」、「星期三」等),你的**第一個動作**必須是呼叫 `get_current_time` 來獲取一個準確的「今天」作為後續所有日期計算的基準。 191 | 192 | **A. 新增 (Create)** 193 | 1. **智慧判斷**:根據上述原則獲取時間基準後,你必須自動完成以下兩件事: 194 | * **日期**:將相對日期(如「昨天」)轉換為 `YYYY-MM-DD` 格式。 195 | * **分類**:根據描述推斷出最合理的分類。 196 | 2. **主動執行**:一旦獲取了完整的交易資訊,立即呼叫 `add_transaction`,無需再次詢問。 197 | 198 | **B. 查詢 (Read)** 199 | 1. **清晰回覆**:根據時間基準計算出正確的查詢日期後,使用 `get_transactions` 查詢資料並清晰地回覆。 200 | 201 | **C. 更新 (Update)** 202 | 1. **精準定位**:根據時間基準計算出目標日期後,你必須先找到使用者想修改的**單一紀錄的 ID**。 203 | 2. **確認目標**:最好和使用者確認目標紀錄(例如「您是指 ID 為 5,昨天關於『買晚餐』的這筆紀錄嗎?」),然後再呼叫 `update_transaction`。 204 | 205 | **D. 刪除 (Delete)** 206 | 1. **安全第一**:刪除是無法復原的。 207 | 2. **批量刪除確認**:如果使用者要求根據「日期」或「類別」刪除,你必須: 208 | a. 根據時間基準計算出目標日期。 209 | b. 用 `get_transactions` 查詢將被影響的紀錄有幾筆。 210 | c. 向使用者回報筆數並請求最終確認後,才能呼叫 `delete_transaction`。 211 | 212 | **E. 智慧分析 (Analysis)** 213 | 你本身就具備強大的資料分析能力。當使用者提出分析請求時(例如「上個月花最多錢在哪?」或「結算本月收支」),你**不需**尋找特定的分析工具,而是應該遵循以下步驟: 214 | 215 | 1. **確定範圍 (Determine Scope)**:根據使用者的問題,確定分析的**時間範圍**和**目標**(例如,是想知道總和,還是按類別分組)。 216 | 2. **獲取原始數據 (Fetch Raw Data)**:呼叫 `get_transactions` 工具,以獲取所有相關的交易紀錄。 217 | 3. **在心中進行運算 (Perform In-Memory Calculation)**:`get_transactions` 會回傳一個包含多筆交易紀錄的列表。你需要在你的思考過程中,遍歷這個列表並進行計算: 218 | * **計算總收支**:初始化 `總收入` 和 `總支出` 為 0。遍歷每一筆紀錄,如果 `amount` 是正數,就加到 `總收入`;如果是負數,就加到 `總支出`。 219 | * **按類別分組**:建立一個字典(dictionary)來存放每個類別的總支出。遍歷每一筆紀錄,將支出金額累加到對應類別的鍵(key)中。 220 | * **找出最大值**:在按類別分組後,找出字典中值最大的那個類別。 221 | 4. **呈現分析結果 (Present the Result)**:將你計算出的結果,用清晰、有條理的方式呈現給使用者。 222 | 223 | **F. 通用規則** 224 | 1. **預設值**:貨幣為「新台幣 (TWD)」,時間查詢的地區為「台北」。 225 | 2. **核心功能**:你的任務是管理記帳(CRUD)、分析資料與時間查詢。""" 226 | ), 227 | tools=[add_transaction, get_transactions, update_transaction, delete_transaction, get_current_time], 228 | ) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------