Spaces:
Running
Running
Update tools_service.py
Browse files- tools_service.py +169 -204
tools_service.py
CHANGED
|
@@ -1,204 +1,169 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Tools Service for LLM Function Calling
|
| 3 |
-
HuggingFace-compatible với prompt engineering
|
| 4 |
-
"""
|
| 5 |
-
import httpx
|
| 6 |
-
from typing import List, Dict, Any, Optional
|
| 7 |
-
import json
|
| 8 |
-
import asyncio
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
""
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
"
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
"
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
}
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
"short_description": event.get("shortDescription"),
|
| 171 |
-
"start_time": event.get("startTimeEventTime"),
|
| 172 |
-
"end_time": event.get("endTimeEventTime"),
|
| 173 |
-
"start_sale": event.get("startTicketSaleTime"),
|
| 174 |
-
"end_sale": event.get("endTicketSaleTime"),
|
| 175 |
-
"location": location, # Full nested structure
|
| 176 |
-
"contact": {
|
| 177 |
-
"email": event.get("publicContactEmail"),
|
| 178 |
-
"phone": event.get("publicContactPhone"),
|
| 179 |
-
"website": event.get("website")
|
| 180 |
-
},
|
| 181 |
-
"capacity": event.get("capacity"),
|
| 182 |
-
"hashtags": event.get("hashtags", [])
|
| 183 |
-
}
|
| 184 |
-
|
| 185 |
-
print(f"Successfully extracted event data for: {event.get('eventName')}")
|
| 186 |
-
print(f"=== API CALL COMPLETE ===")
|
| 187 |
-
return result
|
| 188 |
-
|
| 189 |
-
except httpx.HTTPStatusError as e:
|
| 190 |
-
return {
|
| 191 |
-
"success": False,
|
| 192 |
-
"error": f"HTTP {e.response.status_code}",
|
| 193 |
-
"message": f"API trả về lỗi khi truy vấn sự kiện {event_code}"
|
| 194 |
-
}
|
| 195 |
-
except Exception as e:
|
| 196 |
-
return {
|
| 197 |
-
"success": False,
|
| 198 |
-
"error": str(e),
|
| 199 |
-
"message": "Không thể kết nối đến API để lấy thông tin sự kiện"
|
| 200 |
-
}
|
| 201 |
-
|
| 202 |
-
async def close(self):
|
| 203 |
-
"""Close HTTP client"""
|
| 204 |
-
await self.client.aclose()
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tools Service for LLM Function Calling
|
| 3 |
+
HuggingFace-compatible với prompt engineering
|
| 4 |
+
"""
|
| 5 |
+
import httpx
|
| 6 |
+
from typing import List, Dict, Any, Optional
|
| 7 |
+
import json
|
| 8 |
+
import asyncio
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ToolsService:
|
| 12 |
+
"""
|
| 13 |
+
Manages external API tools that LLM can call via prompt engineering
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
def __init__(self, base_url: str = "https://hoalacrent.io.vn/api/v0"):
|
| 17 |
+
self.base_url = base_url
|
| 18 |
+
self.client = httpx.AsyncClient(timeout=10.0)
|
| 19 |
+
|
| 20 |
+
def get_tools_definition(self) -> List[Dict]:
|
| 21 |
+
"""
|
| 22 |
+
Return list of tool definitions (OpenAI format style)
|
| 23 |
+
Used for constructing system prompt
|
| 24 |
+
"""
|
| 25 |
+
return [
|
| 26 |
+
{
|
| 27 |
+
"name": "search_events",
|
| 28 |
+
"description": "Tìm kiếm sự kiện phù hợp theo từ khóa, vibe, hoặc thời gian.",
|
| 29 |
+
"parameters": {
|
| 30 |
+
"type": "object",
|
| 31 |
+
"properties": {
|
| 32 |
+
"query": {"type": "string", "description": "Từ khóa tìm kiếm (VD: 'nhạc rock', 'hài kịch')"},
|
| 33 |
+
"vibe": {"type": "string", "description": "Vibe/Mood (VD: 'chill', 'sôi động', 'hẹn hò')"},
|
| 34 |
+
"time": {"type": "string", "description": "Thời gian (VD: 'cuối tuần này', 'tối nay')"}
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"name": "get_event_details",
|
| 40 |
+
"description": "Lấy thông tin chi tiết (giá, địa điểm, thời gian) của sự kiện.",
|
| 41 |
+
"parameters": {
|
| 42 |
+
"type": "object",
|
| 43 |
+
"properties": {
|
| 44 |
+
"event_id": {"type": "string", "description": "ID của sự kiện (MongoDB ID)"}
|
| 45 |
+
},
|
| 46 |
+
"required": ["event_id"]
|
| 47 |
+
}
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"name": "get_purchased_events",
|
| 51 |
+
"description": "Kiểm tra lịch sử các sự kiện user đã mua vé hoặc tham gia.",
|
| 52 |
+
"parameters": {
|
| 53 |
+
"type": "object",
|
| 54 |
+
"properties": {
|
| 55 |
+
"user_id": {"type": "string", "description": "ID của user"}
|
| 56 |
+
},
|
| 57 |
+
"required": ["user_id"]
|
| 58 |
+
}
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"name": "save_feedback",
|
| 62 |
+
"description": "Lưu đánh giá/feedback của user về sự kiện.",
|
| 63 |
+
"parameters": {
|
| 64 |
+
"type": "object",
|
| 65 |
+
"properties": {
|
| 66 |
+
"event_id": {"type": "string", "description": "ID sự kiện"},
|
| 67 |
+
"rating": {"type": "integer", "description": "Số sao đánh giá (1-5)"},
|
| 68 |
+
"comment": {"type": "string", "description": "Nội dung nhận xét"}
|
| 69 |
+
},
|
| 70 |
+
"required": ["event_id", "rating"]
|
| 71 |
+
}
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"name": "save_lead",
|
| 75 |
+
"description": "Lưu thông tin khách hàng quan tâm (Lead).",
|
| 76 |
+
"parameters": {
|
| 77 |
+
"type": "object",
|
| 78 |
+
"properties": {
|
| 79 |
+
"email": {"type": "string"},
|
| 80 |
+
"phone": {"type": "string"},
|
| 81 |
+
"interest": {"type": "string"}
|
| 82 |
+
}
|
| 83 |
+
}
|
| 84 |
+
}
|
| 85 |
+
]
|
| 86 |
+
|
| 87 |
+
async def execute_tool(self, tool_name: str, arguments: Dict) -> Any:
|
| 88 |
+
"""
|
| 89 |
+
Execute a tool by name with arguments
|
| 90 |
+
"""
|
| 91 |
+
print(f"🔧 Executing Tool: {tool_name} with args: {arguments}")
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
if tool_name == "get_event_details":
|
| 95 |
+
return await self._get_event_details(arguments.get("event_id") or arguments.get("event_code"))
|
| 96 |
+
|
| 97 |
+
elif tool_name == "get_purchased_events":
|
| 98 |
+
return await self._get_purchased_events(arguments.get("user_id"))
|
| 99 |
+
|
| 100 |
+
elif tool_name == "save_feedback":
|
| 101 |
+
return await self._save_feedback(
|
| 102 |
+
arguments.get("event_id"),
|
| 103 |
+
arguments.get("rating"),
|
| 104 |
+
arguments.get("comment")
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
elif tool_name == "search_events":
|
| 108 |
+
# Note: This usually requires RAG service, so we return a special signal
|
| 109 |
+
# The Agent Service will handle RAG search
|
| 110 |
+
return {"action": "run_rag_search", "query": arguments}
|
| 111 |
+
|
| 112 |
+
elif tool_name == "save_lead":
|
| 113 |
+
# Placeholder for lead saving
|
| 114 |
+
return {"success": True, "message": "Lead saved successfully"}
|
| 115 |
+
|
| 116 |
+
else:
|
| 117 |
+
return {"error": f"Unknown tool: {tool_name}"}
|
| 118 |
+
|
| 119 |
+
except Exception as e:
|
| 120 |
+
print(f"⚠️ Tool Execution Error: {e}")
|
| 121 |
+
return {"error": str(e)}
|
| 122 |
+
|
| 123 |
+
async def _get_event_details(self, event_id: str) -> Dict:
|
| 124 |
+
"""Call API to get event details"""
|
| 125 |
+
if not event_id:
|
| 126 |
+
return {"error": "Missing event_id"}
|
| 127 |
+
|
| 128 |
+
try:
|
| 129 |
+
url = f"{self.base_url}/event/get-event-by-id"
|
| 130 |
+
|
| 131 |
+
response = await self.client.get(url, params={"id": event_id})
|
| 132 |
+
if response.status_code == 200:
|
| 133 |
+
data = response.json()
|
| 134 |
+
if data.get("success"):
|
| 135 |
+
return data.get("data")
|
| 136 |
+
return {"error": "Event not found", "details": response.text}
|
| 137 |
+
except Exception as e:
|
| 138 |
+
return {"error": str(e)}
|
| 139 |
+
|
| 140 |
+
async def _get_purchased_events(self, user_id: str) -> List[Dict]:
|
| 141 |
+
"""Call API to get purchased events for user"""
|
| 142 |
+
if not user_id:
|
| 143 |
+
return []
|
| 144 |
+
|
| 145 |
+
try:
|
| 146 |
+
url = f"{self.base_url}/event/get-purchase-event-by-user-id/{user_id}"
|
| 147 |
+
print(f"🔍 Calling API: {url}")
|
| 148 |
+
|
| 149 |
+
response = await self.client.get(url)
|
| 150 |
+
if response.status_code == 200:
|
| 151 |
+
data = response.json()
|
| 152 |
+
# API returns {data: [...]}
|
| 153 |
+
return data.get("data", [])
|
| 154 |
+
|
| 155 |
+
print(f"⚠️ API Error: {response.status_code} - {response.text}")
|
| 156 |
+
return []
|
| 157 |
+
except Exception as e:
|
| 158 |
+
print(f"⚠️ API Exception: {e}")
|
| 159 |
+
return []
|
| 160 |
+
|
| 161 |
+
async def _save_feedback(self, event_id: str, rating: int, comment: str) -> Dict:
|
| 162 |
+
"""Save feedback (Mock or Real API)"""
|
| 163 |
+
# TODO: Implement real API call when available
|
| 164 |
+
print(f"📝 Saving Feedback: Event={event_id}, Rating={rating}, Comment={comment}")
|
| 165 |
+
return {"success": True, "message": "Feedback recorded"}
|
| 166 |
+
|
| 167 |
+
async def close(self):
|
| 168 |
+
"""Close HTTP client"""
|
| 169 |
+
await self.client.aclose()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|