Files
momentry_core/src/api/agent_search.rs
T

523 lines
27 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use axum::{extract::State, http::StatusCode, response::Json, routing::post, Router};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::Instant;
use crate::api::types::AppState;
use crate::core::agent::tools;
use crate::core::db::schema;
use crate::core::llm::function_calling::{self, ChatMessage, LlmResponse, ToolCall, ToolDef};
// ── Conversation Manager ─────────────────────────────────────────
struct Conversation {
messages: Vec<ChatMessage>,
created_at: Instant,
last_active: Instant,
}
static CONVERSATIONS: Lazy<Mutex<HashMap<String, Conversation>>> = Lazy::new(|| {
// Spawn cleanup task
std::thread::spawn(|| loop {
std::thread::sleep(std::time::Duration::from_secs(60));
let mut map = CONVERSATIONS.lock().unwrap();
let now = Instant::now();
map.retain(|_, conv| now.duration_since(conv.last_active).as_secs() < 1800);
});
Mutex::new(HashMap::new())
});
fn get_or_create_conv(conv_id: Option<&str>) -> (String, Vec<ChatMessage>) {
let mut map = CONVERSATIONS.lock().unwrap();
if let Some(cid) = conv_id {
if let Some(conv) = map.get_mut(cid) {
conv.last_active = Instant::now();
return (cid.to_string(), conv.messages.clone());
}
}
let id = uuid::Uuid::new_v4().to_string().replace('-', "")[..16].to_string();
map.insert(
id.clone(),
Conversation {
messages: Vec::new(),
created_at: Instant::now(),
last_active: Instant::now(),
},
);
(id, Vec::new())
}
fn save_messages(conv_id: &str, messages: &[ChatMessage]) {
if let Some(conv) = CONVERSATIONS.lock().unwrap().get_mut(conv_id) {
conv.messages = messages.to_vec();
conv.last_active = Instant::now();
}
}
// ── Request / Response ───────────────────────────────────────────
#[derive(Debug, Deserialize)]
pub struct AgentSearchRequest {
pub query: String,
pub conversation_id: Option<String>,
pub file_uuid: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct AgentSearchResponse {
pub success: bool,
pub conversation_id: String,
pub answer: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub suggestions: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sources: Option<Vec<serde_json::Value>>,
}
// ── Tool Definitions ──────────────────────────────────────────────
const SYSTEM_PROMPT: &str = r#"你是 Momentry 影片分析助手。回答用戶關於影片內容的問題。
## Greeting and Conversation Handling (CRITICAL - Check First)
- If user input is ONLY a greeting ("hi", "hello", "hey", "你好", "您好", "hallo"):
- **DO NOT call any search tools**
- Respond in English: "Hello! I'm Momentry video analysis assistant. I can help you search video content, find people, and analyze scenes. What would you like to know?"
- If user asks "how are you" or "thanks", respond briefly in English without tools
- **Only use search tools when user asks about VIDEO CONTENT**
## Response Language (MANDATORY)
- **DEFAULT: English** - You MUST respond in English unless user explicitly requests another language
- This applies to ALL responses: greetings, search results, explanations
- Example: If user asks "gun", respond in English about gun-related content
- Only respond in Chinese if user writes in Chinese AND explicitly requests Chinese response
## 核心原則:預設搜尋所有影片,不主動反問
- **所有查詢都預設搜尋全部影片**,不要問用戶「哪部影片」
- 如果搜尋到多部影片,直接列出所有結果,不要反問用戶選擇
- 只有當多個搜尋工具都返回空、且問題明顯指向特定影片時,才問用戶
- 搜尋工具(smart_search, semantic_search, trace_search)的 file_uuid 參數可省略以搜尋全部
## 搜尋工具選擇策略(重要:根據問題類型選擇正確工具)
### 優先順序(按此順序選擇工具)
1. **vlm_search** - VLM 統一視覺搜尋(Scene + Trace 向量一次搜)→ **畫面/場景/人物視覺查詢優先使用,一查即涵蓋場景與人物**
2. **scene_search** - 場景功能搜尋(Scene VLM 向量優先)→ **只查畫面場景時使用**
3. **semantic_search** - 語意搜尋 → 適合文字內容(台詞、概念)
4. **smart_search** - 精確關鍵字匹配(僅在需要精確匹配時使用)
5. **trace_search** - 人物外貌、衣著、地點
6. **find_file** - 僅搜尋片名(不搜尋內容)
### vlm_search(VLM 統一視覺搜尋)- 視覺查詢優先使用
- **使用時機**:查詢畫面/場景/人物視覺內容(「廚房」、「公園」、「穿白外套的女人」、「有人在跑步」、「室內場景」),一次同時搜 Scene VLM 與 Trace VLM 向量,最全面
- **範例**:「廚房場景」、「公園裡的男人」、「穿白外套的女人在哪」、「室內場景」、「某人的外貌特徵」
- **回傳**:混合卡片(card_type: scene 或 face),scene 含 scene_index/thumbnail_url/vlm_tags,face 含 trace_id/identity_name/vlm_clothing/vlm_tags
### scene_search(場景功能搜尋)- 畫面查詢優先使用
- **使用時機**:查詢畫面/場景內容(「廚房」、「公園」、「室內裝潢」、「有人在跑步」),優先於文字搜尋
- **範例**:「廚房場景」、「公園裡的男人」、「穿白外套的女人在哪個畫面」、「室內場景」
- **回傳**:符合的場景卡片(file_uuid, scene_index, thumbnail_url, vlm_description, vlm_tags, score, timestamp)
### semantic_search(語意搜尋)- 優先使用
- **使用時機**:大多數查詢(理解意圖、概念性問題、一般話題)
- **範例**:「gun」、「car」、「他在做什麼」、「發生了什麼事」
- **回傳**:語意相關的 Top 10 chunk 卡片(text_preview, score, frame_range)
### smart_search(精確關鍵字匹配)
- **使用時機**:需要精確匹配專有名詞、特定詞彙(如人名、地名、專業術語)
- **範例**:「Cary Grant」、「Paris」、「確切的台詞引用」
- **回傳**:包含關鍵字的 Top 10 chunk 卡片(text_content, frame_range)
### trace_search(人物軌跡 VLM 搜尋)
- **使用時機**:搜尋人物外貌、衣著、地點、場景
- **範例**:「穿藍色衣服的人」、「在展場出現的人」、「戴眼鏡的人」
- **回傳**:符合的 face trace 卡片(name, vlm_description, vlm_clothing, vlm_tags, frame_range)
### face_profile_search(用名字或 VLM 註記搜尋人臉)
- **使用時機**:用「人名」或「VLM 註記」搜尋已命名的人臉畫面
- **範例**:「找出 Susan 的畫面」、「穿藍色衣服的人」、「在展場的人」
- **搜尋欄位**:name, vlm_description, vlm_clothing, vlm_tags, vlm_location, vlm_setting
- **回傳**:符合的 face profile 卡片(name, key_frame, key_face, frame_range, time_range)
### find_file(僅搜尋片名)
- **使用時機**:僅搜尋影片檔名
- **範例**:「find a video named action」
- **注意**:不適合搜尋內容,內容搜尋請用 semantic_search
## 回答格式
- 回答長度依問題類型調整:
- 簡單查詢 → 簡潔列表回答(1-2句)
- 分析問題 → 詳細回答(3-5句)
- **回傳 Top 10 卡片**:每個搜尋工具會回傳最多 10 張卡片
- 卡片包含:file_uuid, chunk_id/trace_id, start_time, end_time, score, text_preview/vlm_description
- 用自然語言回答,附上 file_name 和時間範圍
## 停止規則
- **如果已經找到足夠資訊回答用戶問題,立即停止呼叫工具,直接回答**
- **如果連續 2 次呼叫工具都返回空結果,停止並告知「找不到更多相關資訊」**
- **優化效率:避免重複呼叫相同工具**"#;
fn make_tools(pool: &sqlx::PgPool) -> Vec<ToolDef> {
vec![
function_calling::make_tool(
"find_file",
"透過關鍵字搜尋影片(片名、演員、年份)。回傳符合的影片列表。",
serde_json::json!({
"query": {"type": "string", "description": "搜尋關鍵字(片名、演員名、年份)"}
}),
vec!["query"],
),
function_calling::make_tool(
"list_files",
"列出近期註冊的影片。",
serde_json::json!({
"limit": {"type": "integer", "description": "回傳筆數上限", "default": 10}
}),
vec![],
),
function_calling::make_tool(
"tkg_query",
"查詢影片的人物互動、配對、同框、台詞資料。query_type 包括:top_identities(人物排名)、first_cooccurrence(第一次同框)、identity_details(人物詳細)、mutual_gaze(互看)、interaction_network(互動網絡)、identity_traces(出場片段)、file_info(影片資訊)、speaker_dialogue(人物台詞)、speaker_interaction(兩人對話互動)。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "影片 UUID"},
"query_type": {
"type": "string",
"enum": ["top_identities", "first_cooccurrence", "identity_details", "mutual_gaze", "interaction_network", "identity_traces", "file_info", "speaker_dialogue", "speaker_interaction"],
"description": "查詢類型"
},
"identity_name": {"type": "string", "description": "人物名稱(配合 identity_details / identity_traces / speaker_dialogue / speaker_interaction)"},
"identity_b": {"type": "string", "description": "第二人物名稱(配合 first_cooccurrence / mutual_gaze / speaker_interaction)"},
"limit": {"type": "integer", "default": 5}
}),
vec!["file_uuid", "query_type"],
),
function_calling::make_tool(
"smart_search",
"關鍵字搜尋 chunk 文字內容(ILIKE)。適合精確匹配專有名詞、特定詞彙。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
"query": {"type": "string", "description": "搜尋關鍵字"},
"limit": {"type": "integer", "default": 10}
}),
vec!["query"],
),
function_calling::make_tool(
"semantic_search",
"語意搜尋(embedding + Qdrant)。適合理解意圖的查詢,如「他在做什麼」、「發生了什麼事」。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
"query": {"type": "string", "description": "搜尋關鍵字(會轉為 embedding)"},
"limit": {"type": "integer", "default": 10}
}),
vec!["query"],
),
function_calling::make_tool(
"vlm_search",
"VLM 視覺統一搜尋(Scene VLM 場景向量 + Trace VLM 人物向量,一次查兩邊)。用一段描述同時搜尋影片的畫面場景與人物,兩者皆為視覺向量搜尋(embedding),非文字關鍵字。適合回答「哪個畫面/場景出現OOO」、「穿OO的人」、「影片的視覺內容」。可用 file_uuid 限制搜尋範圍。回傳混合卡片(card_type: scene 或 face)。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
"query": {"type": "string", "description": "搜尋關鍵字(會轉為 embedding,同時搜 scene + trace VLM 向量)"},
"limit": {"type": "integer", "default": 10}
}),
vec!["query"],
),
function_calling::make_tool(
"scene_search",
"場景功能搜尋(Scene VLM, Qdrant 向量優先)。搜尋影片中的畫面場景,如「廚房」、「公園」、「室內」、「有人在跑步」、「穿白外套的女人在廚房」。回傳場景卡片(含縮圖 URL、時間點、VLM 描述、tags)。適合回答「哪個畫面/場景出現OOO」、「場景外觀長什麼樣」。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
"query": {"type": "string", "description": "搜尋關鍵字(會轉為 embedding)"},
"limit": {"type": "integer", "default": 10}
}),
vec!["query"],
),
function_calling::make_tool(
"trace_search",
"搜尋人物軌跡的 VLM 註記(外貌描述、衣著、標籤、地點、場景)。輸入關鍵字,回傳符合的 face trace 卡片。適合回答「穿藍色衣服的人」、「在展場出現的人」。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
"query": {"type": "string", "description": "搜尋關鍵字(會搜尋 name, vlm_description, vlm_clothing, vlm_tags, vlm_location, vlm_setting)"},
"limit": {"type": "integer", "default": 10}
}),
vec!["query"],
),
function_calling::make_tool(
"identity_text",
"搜尋文字關鍵字,找出有提及該內容的影片人物。適合回答「誰說了OOO」、「誰跟OOO有關」。不是查詢人物的台詞,而是用文字反查人物。",
serde_json::json!({
"q": {"type": "string", "description": "搜尋關鍵字(台詞片段、主題等)"},
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
"limit": {"type": "integer", "default": 10}
}),
vec!["q"],
),
function_calling::make_tool(
"identities_search",
"查詢特定人物的台詞/發言內容。輸入人物名稱,回傳該人物在影片中說過的話。適合回答「某某人說了什麼」、「某某人的台詞」。",
serde_json::json!({
"q": {"type": "string", "description": "人物名稱關鍵字(姓名、角色名、別名)"},
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
"limit": {"type": "integer", "default": 10}
}),
vec!["q"],
),
function_calling::make_tool(
"get_identity_detail",
"查詢單一身份的詳細資料(名字、角色、TMDb 資訊)。",
serde_json::json!({
"name": {"type": "string", "description": "人物名稱"}
}),
vec!["name"],
),
function_calling::make_tool(
"get_file_info",
"查詢影片基本資訊(片名、長度、解析度)。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "影片 UUID"}
}),
vec!["file_uuid"],
),
function_calling::make_tool(
"get_representative_frame",
"查詢影片最具代表性的 frame 資訊(frame 編號、時間、人物)。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "影片 UUID"}
}),
vec!["file_uuid"],
),
function_calling::make_tool(
"analyze_frame",
"分析影片中指定畫面的視覺內容(場景、人物表情、動作、物件等)。若不指定 frame_number,會使用代表性畫面。問題會傳給視覺 LLM 分析。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "影片 UUID"},
"question": {"type": "string", "description": "關於畫面的問題,例如「這個場景發生什麼事?」"},
"frame_number": {"type": "integer", "description": "指定的 frame 編號(可選)"}
}),
vec!["file_uuid"],
),
function_calling::make_tool(
"tkg_nodes_query",
"查詢 TKG 知識圖譜的節點列表。可依照節點類型篩選(face_track, gaze_track, lip_track, text_trace, appearance_trace, object, speaker)。適合查詢影片中有多少人物軌跡、文字片段等。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "影片 UUID"},
"node_type": {"type": "string", "description": "節點類型(可選): face_track, gaze_track, lip_track, text_trace, appearance_trace, object, speaker"},
"page": {"type": "integer", "default": 1},
"page_size": {"type": "integer", "default": 20}
}),
vec!["file_uuid"],
),
function_calling::make_tool(
"tkg_edges_query",
"查詢 TKG 知識圖譜的邊列表。可依照邊類型篩選(CO_OCCURS_WITH, SPEAKS_AS, MUTUAL_GAZE, LIP_SYNC, HAS_APPEARANCE)。適合查詢人物之間的互動關係。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "影片 UUID"},
"edge_type": {"type": "string", "description": "邊類型(可選): CO_OCCURS_WITH, SPEAKS_AS, MUTUAL_GAZE, LIP_SYNC, HAS_APPEARANCE"},
"page": {"type": "integer", "default": 1},
"page_size": {"type": "integer", "default": 20}
}),
vec!["file_uuid"],
),
function_calling::make_tool(
"tkg_node_detail",
"查詢 TKG 知識圖譜的單一節點詳細資訊,包含該節點的 incoming 和 outgoing 邊。適合深入了解特定人物或物件的完整關係網絡。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "影片 UUID"},
"node_id": {"type": "integer", "description": "節點 ID"}
}),
vec!["file_uuid", "node_id"],
),
function_calling::make_tool(
"search_by_appearance",
"根據衣服顏色搜尋影片中的人物。支援顏色:red, orange, yellow, green, cyan, blue, purple, white, black。",
serde_json::json!({
"file_uuid": {"type": "string", "description": "影片 UUID"},
"color": {"type": "string", "description": "目標顏色: red, orange, yellow, green, cyan, blue, purple, white, black"}
}),
vec!["file_uuid", "color"],
),
function_calling::make_tool(
"vlm_describe",
"Describe a person's appearance (clothing, colors, accessories) by face trace ID using Vision Language Model (LLaVA). Uses pre-extracted face crop images.",
serde_json::json!({
"file_uuid": {"type": "string", "description": "UUID of the video file"},
"trace_id": {"type": "integer", "description": "Face trace ID to analyze"},
"prompt": {"type": "string", "description": "Specific question about the person's appearance (optional, default: describes clothing colors and style)"}
}),
vec!["file_uuid", "trace_id"],
),
function_calling::make_tool(
"face_profile_search",
"用名字或 VLM 註記搜尋已命名的人臉。輸入關鍵字(名字、衣著描述、地點、標籤),回傳符合的 face profile 卡片(含 key_frame、key_face、時間範圍、frame 範圍)。適合回答「找出穿藍色衣服的人」、「Susan 出現在哪」、「在展場的人」。",
serde_json::json!({
"name": {"type": "string", "description": "搜尋關鍵字(會搜尋 name, vlm_description, vlm_clothing, vlm_tags, vlm_location, vlm_setting)"},
"file_uuid": {"type": "string", "description": "限制搜尋範圍(可選)"},
"limit": {"type": "integer", "default": 10}
}),
vec!["name"],
),
]
}
// ── Tool Executors ── (implementations in core::agent::tools)
// ── Tool Router ───────────────────────────────────────────────────
async fn execute_tool(pool: &sqlx::PgPool, tool_call: &ToolCall) -> (String, String, String) {
let name = tool_call.function.name.clone();
let tool_call_id = tool_call.id.clone().unwrap_or_default();
let args: serde_json::Value = match serde_json::from_str(&tool_call.function.arguments) {
Ok(v) => v,
Err(e) => {
return (
tool_call_id,
name,
serde_json::json!({"error": format!("Invalid arguments: {}", e)}).to_string(),
)
}
};
let result = match name.as_str() {
"find_file" => tools::exec_find_file(pool, &args).await,
"list_files" => tools::exec_list_files(pool, &args).await,
"tkg_query" => tools::exec_tkg_query(pool, &args).await,
"tkg_nodes_query" => tools::exec_tkg_nodes_query(pool, &args).await,
"tkg_edges_query" => tools::exec_tkg_edges_query(pool, &args).await,
"tkg_node_detail" => tools::exec_tkg_node_detail(pool, &args).await,
"smart_search" => tools::exec_smart_search(pool, &args).await,
"semantic_search" => tools::exec_semantic_search(pool, &args).await,
"scene_search" => tools::exec_scene_search(pool, &args).await,
"vlm_search" => tools::exec_vlm_search(pool, &args).await,
"trace_search" => tools::exec_trace_search(pool, &args).await,
"identity_text" => tools::exec_identity_text(pool, &args).await,
"identities_search" => tools::exec_identities_search(pool, &args).await,
"get_identity_detail" => tools::exec_get_identity_detail(pool, &args).await,
"get_file_info" => tools::exec_get_file_info(pool, &args).await,
"get_representative_frame" => tools::exec_get_representative_frame(pool, &args).await,
"analyze_frame" => tools::exec_analyze_frame(pool, &args).await,
"search_by_appearance" => tools::exec_search_by_appearance(pool, &args).await,
"vlm_describe" => tools::exec_vlm_describe(pool, &args).await,
"face_profile_search" => tools::exec_face_profile_search(pool, &args).await,
_ => Err(format!("Unknown tool: {}", name)),
};
let content = match result {
Ok(s) => s,
Err(e) => serde_json::json!({"error": e}).to_string(),
};
(tool_call_id, name, content)
}
// ── Tool Loop ─────────────────────────────────────────────────────
const MAX_ROUNDS: u32 = 15;
async fn run_tool_loop(
pool: &sqlx::PgPool,
system_prompt: &str,
user_query: &str,
history: Vec<ChatMessage>,
) -> (String, Vec<ChatMessage>, Vec<serde_json::Value>) {
let mut messages = function_calling::build_conversation(system_prompt, user_query, history);
let mut sources = Vec::new();
for round in 0..MAX_ROUNDS {
let tools = make_tools(pool);
tracing::info!(
"[AGENT] Round {} started, message_count: {}, tools_available: {}",
round + 1,
messages.len(),
tools.len()
);
match function_calling::call_llm(messages.clone(), Some(tools.clone()), 2048, 120).await {
Ok(LlmResponse::Text(text)) => {
tracing::info!(
"[AGENT] Loop finished: rounds_used={}, total_tools_called={}, answer_length={} chars",
round + 1,
sources.len(),
text.len()
);
return (text, messages, sources);
}
Ok(LlmResponse::ToolCalls(calls)) => {
messages.push(ChatMessage {
role: "assistant".to_string(),
content: None,
tool_calls: Some(calls.clone()),
tool_call_id: None,
name: None,
});
for call in &calls {
let (tool_call_id, name, content) = execute_tool(pool, call).await;
tracing::info!(
"[AGENT] Tool called: {}, result_size: {} chars, round: {}",
name,
content.len(),
round + 1
);
sources.push(serde_json::json!({"tool": name, "result": content}));
messages.push(function_calling::make_tool_result(
&tool_call_id,
&name,
&content,
));
}
}
Err(e) => {
tracing::error!("[AGENT] LLM call failed: {}", e);
return (format!("系統錯誤:{}", e), messages, sources);
}
}
}
tracing::warn!(
"[AGENT] Max rounds reached: rounds_used={}, total_tools_called={}",
MAX_ROUNDS,
sources.len()
);
(
"已達到最大查詢次數,請縮小問題範圍後重新詢問。".to_string(),
messages,
sources,
)
}
// ── Handler ───────────────────────────────────────────────────────
async fn agent_search(
State(state): State<AppState>,
Json(req): Json<AgentSearchRequest>,
) -> Result<Json<AgentSearchResponse>, (StatusCode, Json<serde_json::Value>)> {
let (conv_id, history) = get_or_create_conv(req.conversation_id.as_deref());
let (answer, messages, sources) =
run_tool_loop(state.db.pool(), SYSTEM_PROMPT, &req.query, history).await;
// Save messages (skip system prompt — build_conversation re-adds it)
let history: Vec<ChatMessage> = messages.into_iter().skip(1).collect();
save_messages(&conv_id, &history);
let needs_input = answer.contains('?') || answer.contains('?');
let suggestions = if needs_input {
Some(vec![
"演員名".to_string(),
"電影片名".to_string(),
"年份".to_string(),
])
} else {
None
};
Ok(Json(AgentSearchResponse {
success: true,
conversation_id: conv_id,
answer,
suggestions,
sources: Some(sources),
}))
}
// ── Routes ─────────────────────────────────────────────────────────
pub fn agent_search_routes() -> Router<AppState> {
Router::new().route("/api/v1/agents/search", post(agent_search))
}