Spaces:
Paused
Paused
Download ai_engine.py from phanquocdat123/Ai_Agent: direct link, hf CLI and curl.
- Browser
- Download file 1.87 kB
-
https://huggingface.co/spaces/phanquocdat123/Ai_Agent/resolve/main/ai_engine.py
- Command line
-
hf download hf://spaces/phanquocdat123/Ai_Agent/ai_engine.py
-
curl -L -o ai_engine.py https://huggingface.co/spaces/phanquocdat123/Ai_Agent/resolve/main/ai_engine.py
1.87 kB
| import json | |
| import asyncio | |
| import config | |
| from google import genai | |
| client = genai.Client(api_key=config.GEMINI_API_KEY) | |
| # 1. Hàm này dùng để phân tích tin nhắn mới từ telegram | |
| async def analyze_intent(text): | |
| prompt = f"""Bạn là trợ lý Second Brain của Đạt. Hãy phân tích tin nhắn: '{text}' | |
| Trả về DUY NHẤT một chuỗi JSON (không markdown, không giải thích): | |
| {{"intent": "SAVE", "category": "tên_mục", "content": "nội_dung"}}, | |
| {{"intent": "LIST"}}, | |
| {{"intent": "VIEW", "category": "tên_mục"}}, | |
| {{"intent": "QUERY", "query": "từ_khóa"}}, | |
| {{"intent": "DELETE", "target": "từ_khóa"}}, | |
| {{"intent": "CHAT", "reply": "câu_trả_lời"}} | |
| """ | |
| def _call(): | |
| return client.models.generate_content(model=config.GEMINI_MODEL, contents=prompt) | |
| try: | |
| response = await asyncio.to_thread(_call) | |
| clean_json = response.text.replace("```json", "").replace("```", "").strip() | |
| return json.loads(clean_json) | |
| except: | |
| return {"intent": "CHAT", "reply": "Mình nghe đây, Đạt cần mình giúp gì?"} | |
| # 2. Hàm này dùng khi có dữ liệu từ DB (RAG) | |
| async def generate_with_context(query, context_data): | |
| prompt = f"""Bạn là trợ lý Second Brain của Đạt. | |
| Dưới đây là thông tin từ dữ liệu của Đạt: | |
| --- | |
| {context_data} | |
| --- | |
| Câu hỏi của Đạt: '{query}' | |
| Dựa vào thông tin trên và kiến thức của bạn, hãy trả lời câu hỏi của Đạt một cách tự nhiên. | |
| Nếu trong dữ liệu của Đạt không có, hãy tự trả lời bằng kiến thức của bạn.""" | |
| def _call(): | |
| return client.models.generate_content(model=config.GEMINI_MODEL, contents=prompt) | |
| response = await asyncio.to_thread(_call) | |
| return response.text |