Spaces:
Build error
Build error
Download src/api/mod.rs from LuckyMod/intentforge: direct link, hf CLI and curl.
- Browser
- Download file 59.5 kB
-
https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/api/mod.rs
- Command line
-
hf download hf://spaces/LuckyMod/intentforge/src/api/mod.rs
-
curl -L -o mod.rs https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/api/mod.rs
59.5 kB
#![allow(dead_code)]
//! HTTP API module for IntentForge v2
//!
//! Provides REST endpoints for crawling, searching, and health checks
//! using axum web framework.
use axum::{
extract::{Path, Query, Request, State},
http::{HeaderMap, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use std::time::Instant;
use crate::metrics::Metrics;
use crate::AppState;
/// Count phrase-aware significant term hits in a text.
/// Phrase matches count as 2 hits each; individual terms that are part of a matched phrase are skipped.
fn count_phrase_aware_hits<S: AsRef<str>>(
combined: &str,
phrase_terms: &[String],
significant_terms: &[S],
) -> usize {
let phrase_hits = phrase_terms
.iter()
.filter(|p| combined.contains(p.as_str()))
.count();
let individual_hits = significant_terms
.iter()
.filter(|t| {
let t_str = t.as_ref();
let in_phrase = phrase_terms.iter().any(|p| p.contains(t_str));
if in_phrase {
return false;
}
combined.contains(t_str)
})
.count();
phrase_hits * 2 + individual_hits
}
/// Helper to hash a string for ID generation
fn hash_string(s: &str) -> String {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
s.hash(&mut hasher);
format!("{:x}", hasher.finish())
}
/// Shared API state wrapping the app state with metrics
pub struct ApiState {
pub app: Arc<AppState>,
pub metrics: Metrics,
}
/// Query parameters for search endpoint
#[derive(Debug, Deserialize)]
pub struct SearchParams {
pub q: String,
#[serde(default = "default_limit")]
pub limit: usize,
#[serde(default = "default_offset")]
pub offset: usize,
pub filter: Option<String>,
pub category: Option<String>,
pub media_type: Option<String>,
pub semantic_ratio: Option<f32>,
}
fn default_limit() -> usize {
15
}
fn default_offset() -> usize {
0
}
/// Search result item
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SearchResult {
pub id: String,
pub title: String,
pub url: String,
pub description: Option<String>,
pub category: String,
pub source: String,
pub media_type: String,
pub thumbnail_url: Option<String>,
pub intent_score: f32,
pub relevance_score: f32,
pub commercial_score: f32,
pub spam_score: f32,
}
/// Search response
#[derive(Debug, Serialize, Deserialize)]
pub struct SearchResponse {
pub query: String,
pub results: Vec<SearchResult>,
pub total: usize,
pub latency_ms: u64,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub message: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
#[serde(default)]
pub intent_scores: Vec<crate::intent_classifier::GroupScore>,
#[serde(default)]
pub self_improving: bool,
}
/// Query parameters for news/images/videos endpoints
#[derive(Debug, Deserialize)]
pub struct MediaSearchParams {
pub q: String,
#[serde(default = "default_limit")]
pub limit: usize,
pub category: Option<String>,
pub location: Option<String>,
}
/// News result item
#[derive(Debug, Serialize, Clone)]
pub struct NewsResult {
pub title: String,
pub url: String,
pub description: String,
pub source: String,
pub published_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub thumbnail_url: Option<String>,
}
/// News search response
#[derive(Debug, Serialize)]
pub struct NewsResponse {
pub query: String,
pub results: Vec<NewsResult>,
pub total: usize,
pub latency_ms: u64,
pub sources: Vec<String>,
}
/// Image result item
#[derive(Debug, Serialize, Clone)]
pub struct ImageResult {
pub id: String,
pub title: String,
pub url: String,
pub source: String,
pub category: String,
pub intent_score: f32,
pub relevance_score: f32,
#[serde(skip_serializing_if = "Option::is_none")]
pub thumbnail_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub alt_text: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub photographer: Option<String>,
pub width: Option<u32>,
pub height: Option<u32>,
pub avg_color: Option<String>,
}
/// Image search response
#[derive(Debug, Serialize)]
pub struct ImageResponse {
pub query: String,
pub results: Vec<ImageResult>,
pub total: usize,
pub latency_ms: u64,
pub sources: Vec<String>,
}
/// Video result item
#[derive(Debug, Serialize, Clone)]
pub struct VideoResult {
pub id: String,
pub title: String,
pub url: String,
pub source: String,
pub description: Option<String>,
pub intent_score: f32,
pub relevance_score: f32,
#[serde(skip_serializing_if = "Option::is_none")]
pub thumbnail_url: Option<String>,
pub duration_secs: Option<u32>,
pub view_count: Option<u64>,
pub channel: Option<String>,
pub published_at: Option<String>,
}
/// Video search response
#[derive(Debug, Serialize)]
pub struct VideoResponse {
pub query: String,
pub results: Vec<VideoResult>,
pub total: usize,
pub latency_ms: u64,
pub sources: Vec<String>,
}
/// Crawl parameters
#[derive(Debug, Deserialize)]
pub struct CrawlParams {
pub url: String,
}
/// Crawl response
#[derive(Debug, Serialize)]
pub struct CrawlResponse {
pub url: String,
pub title: String,
pub content_length: usize,
pub success: bool,
pub latency_ms: u64,
pub error: Option<String>,
}
/// Batch crawl request
#[derive(Debug, Deserialize)]
pub struct BatchCrawlRequest {
pub urls: Vec<String>,
}
/// Discovery enqueue request
#[derive(Debug, Deserialize)]
pub struct DiscoveryEnqueueRequest {
pub url: String,
#[serde(default)]
pub category: Option<String>,
#[serde(default = "default_priority")]
pub priority: u32,
}
fn default_priority() -> u32 {
5
}
/// Discovery enqueue response
#[derive(Debug, Serialize)]
pub struct DiscoveryEnqueueResponse {
pub url: String,
pub enqueued: bool,
pub error: Option<String>,
}
async fn auth_middleware(
State(state): State<Arc<ApiState>>,
headers: HeaderMap,
request: Request,
next: Next,
) -> Response {
// If no API key is configured, allow all requests (for dev/local)
let expected_key = match &state.app.config.api_key {
Some(k) if !k.is_empty() => k,
_ => return next.run(request).await,
};
let api_key = headers.get("X-API-Key").and_then(|h| h.to_str().ok());
match api_key {
Some(key) if key == expected_key => next.run(request).await,
_ => {
tracing::warn!("Unauthorized access attempt from {:?}", request.uri());
(
StatusCode::UNAUTHORIZED,
Json(serde_json::json!({ "error": "Unauthorized" })),
)
.into_response()
}
}
}
/// Initialize the API router
pub fn create_router(state: Arc<ApiState>) -> Router {
let public_routes = Router::new()
.route("/health", get(health_handler))
.route("/metrics", get(metrics_handler));
let protected_routes = Router::new()
.route("/search", get(search_handler))
.route("/meta", get(meta_search_handler))
.route("/news", get(news_handler))
.route("/images", get(images_handler))
.route("/videos", get(videos_handler))
.route("/crawl", get(crawl_single_handler))
.route("/crawl/batch", post(crawl_batch_handler))
.route("/content/:id", get(get_full_content_handler))
.route("/discovery/status", get(discovery_status_handler))
.route("/discovery/enqueue", post(discovery_enqueue_handler))
.route("/admin/reindex-scores", post(reindex_scores_handler))
.layer(middleware::from_fn_with_state(
state.clone(),
auth_middleware,
));
Router::new()
.merge(public_routes)
.merge(protected_routes)
.with_state(state)
}
/// Health check endpoint
async fn health_handler() -> impl IntoResponse {
(StatusCode::OK, Json(serde_json::json!({"status": "ok"})))
}
/// Validate filter string to prevent injection attacks
fn validate_filter(filter: &str) -> Result<(), (StatusCode, String)> {
if filter.contains('\0') {
return Err((
StatusCode::BAD_REQUEST,
"Invalid filter: contains null bytes".to_string(),
));
}
let dangerous_patterns = [
"DROP TABLE",
"DELETE FROM",
"UPDATE SET",
"INSERT INTO",
"ALTER TABLE",
"CREATE TABLE",
"EXEC ",
"--",
];
let upper_filter = filter.to_uppercase();
for pattern in dangerous_patterns {
if upper_filter.contains(pattern) {
return Err((
StatusCode::BAD_REQUEST,
"Invalid filter: contains dangerous pattern".to_string(),
));
}
}
Ok(())
}
/// Query expansion and rewriting
fn rewrite_query(
query: &str,
config: &crate::query_expansion::QueryExpansionConfig,
) -> (String, Vec<String>) {
let expansion = crate::query_expansion::expand_query(query, config);
let mut auto_filters = Vec::new();
let lower = query.to_lowercase();
if !(lower.contains("buy") || lower.contains("price") || lower.contains("discount")) {
auto_filters.push("commercial_score < 0.7".to_string());
}
auto_filters.push("spam_score < 0.5".to_string());
(expansion.expanded, auto_filters)
}
/// Search endpoint - hybrid semantic + keyword search
async fn search_handler(
State(state): State<Arc<ApiState>>,
Query(params): Query<SearchParams>,
) -> impl IntoResponse {
let start = Instant::now();
state.metrics.search_requests_total.inc();
// Validate empty query
if params.q.trim().is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(SearchResponse {
query: params.q.clone(),
total: 0,
results: vec![],
latency_ms: start.elapsed().as_millis() as u64,
message: Some("Query cannot be empty".to_string()),
intent_scores: vec![],
self_improving: false,
}),
)
.into_response();
}
// Check response cache (only quality responses are cached)
let cache_key = format!("search_cache:{}", params.q.to_lowercase().trim());
if let Ok(Some(cached)) = state.app.redis.get_json::<SearchResponse>(&cache_key).await {
tracing::info!(
"Cache HIT for '{}' ({} results)",
params.q,
cached.results.len()
);
return (StatusCode::OK, Json(cached)).into_response();
}
let (expanded_query, auto_filters) =
rewrite_query(¶ms.q, &state.app.query_expansion_config);
let mut filter_parts = Vec::new();
if let Some(f) = ¶ms.filter {
if let Err((status, msg)) = validate_filter(f) {
return (
status,
Json(SearchResponse {
query: params.q.clone(),
total: 0,
results: vec![],
latency_ms: start.elapsed().as_millis() as u64,
message: Some(msg),
intent_scores: vec![],
self_improving: false,
}),
)
.into_response();
}
filter_parts.push(format!("({})", f));
}
for af in auto_filters {
filter_parts.push(af);
}
if let Some(category) = ¶ms.category {
filter_parts.push(format!("category = \"{}\"", category));
}
if let Some(media_type) = ¶ms.media_type {
filter_parts.push(format!("media_type = \"{}\"", media_type));
}
let final_filter = if filter_parts.is_empty() {
if params.media_type.is_none() {
Some("media_type = \"text\"".to_string())
} else {
None
}
} else {
Some(filter_parts.join(" AND "))
};
let _semantic_ratio = params
.semantic_ratio
.unwrap_or(state.app.config.meilisearch.semantic_ratio);
// --- DYNAMIC INTENT CLASSIFICATION (no hardcoded keywords) ---
let intent_scores = state
.app
.intent_classifier
.classify_with_scores(¶ms.q, None);
let primary_intent = intent_scores.first().map(|g| g.primary_intent.clone());
let primary_intent_score = intent_scores.first().map(|g| g.score).unwrap_or(0.0);
let primary = primary_intent
.clone()
.unwrap_or(crate::intent_classifier::QueryIntent::General);
// Extract query keywords for term matching
let query_terms: Vec<String> = params
.q
.to_lowercase()
.split_whitespace()
.filter(|w| w.len() > 2)
.map(|w| w.to_string())
.collect();
// Stop words that don't carry query-specific meaning
let stop_words: HashSet<&str> = [
"the", "and", "for", "with", "from", "that", "this", "what", "how", "are", "was", "were",
"been", "being", "have", "has", "had", "does", "did", "will", "would", "could", "should",
"may", "might", "can", "not", "but", "yet", "also", "just", "than", "then", "too", "very",
"best", "top", "most", "more", "about", "into", "some", "any", "all", "who", "which",
"when", "where", "why", "use", "using", "used",
]
.iter()
.copied()
.collect();
// Significant terms: content-bearing words that discriminate this query
let significant_terms: Vec<&String> = query_terms
.iter()
.filter(|t| !stop_words.contains(t.as_str()))
.collect();
let has_significant_terms = !significant_terms.is_empty();
// Known compound terms that should be matched as phrases
let compound_terms: Vec<(&str, &str)> = vec![
("machine", "learning"),
("deep", "learning"),
("reinforcement", "learning"),
("neural", "network"),
("natural", "language"),
("computer", "vision"),
("data", "science"),
("cloud", "computing"),
("web", "development"),
("async", "programming"),
("binary", "search"),
("linked", "list"),
("hash", "table"),
("red", "black"),
("dynamic", "programming"),
("zero", "knowledge"),
("state", "locking"),
("full", "text"),
("black", "pine"),
("reward", "shaping"),
("cold", "ferment"),
("pressure", "profiling"),
("pod", "affinity"),
("helm", "chart"),
("near", "duplicate"),
("sourdough", "starter"),
("knife", "sharpening"),
("espresso", "machine"),
("ground", "plane"),
];
let mut phrase_terms: Vec<String> = Vec::new();
let sig_words: Vec<&str> = query_terms.iter().map(|s| s.as_str()).collect();
for window in sig_words.windows(2) {
let pair = (window[0], window[1]);
if compound_terms
.iter()
.any(|&(a, b)| a == pair.0 && b == pair.1)
{
phrase_terms.push(format!("{} {}", pair.0, pair.1));
}
}
// Effective sig count: each phrase replaces 2 individual terms with 1 phrase unit
let effective_sig_count = significant_terms.len().saturating_sub(phrase_terms.len());
let min_sig_required = if effective_sig_count <= 1 {
1
} else if effective_sig_count == 2 {
2
} else {
effective_sig_count.div_ceil(2)
};
// PHASE 1: Fast local index search (<1 second target)
let q_local = expanded_query.clone();
let filter_local = final_filter.clone();
let local_res = state
.app
.indexer
.search(&q_local, filter_local.as_deref(), Some(50))
.await
.unwrap_or_default();
// Pre-filter obvious garbage
let valid_docs: Vec<_> = local_res
.iter()
.filter(|doc| {
let title_low = doc.title.to_lowercase();
!(title_low.contains("just a moment")
|| title_low.contains("cloudflare")
|| doc.title.trim().is_empty())
})
.collect();
// Batch alignment boost for all valid documents
let combined_texts: Vec<String> = valid_docs
.iter()
.map(|doc| {
let title_low = doc.title.to_lowercase();
let desc_low = doc.description.as_deref().unwrap_or("").to_lowercase();
format!("{} {}", title_low, desc_low)
})
.collect();
let combined_refs: Vec<&str> = combined_texts.iter().map(|s| s.as_str()).collect();
let alignments = if primary == crate::intent_classifier::QueryIntent::General {
vec![1.0; combined_refs.len()]
} else {
state
.app
.intent_classifier
.calculate_alignment_boost_batch(&primary, &combined_refs)
};
let mut local_results: Vec<SearchResult> = Vec::new();
let mut local_urls = HashSet::new();
for (idx, doc) in valid_docs.iter().enumerate() {
let combined = &combined_texts[idx];
let alignment = alignments[idx];
if alignment < 0.2 {
continue;
}
// Significant term overlap (phrase-aware)
let sig_hits = count_phrase_aware_hits(combined, &phrase_terms, &significant_terms);
// Require minimum significant term coverage to pass
if has_significant_terms && sig_hits < min_sig_required {
continue;
}
// Score based on significant term coverage + alignment
let term_relevance = if !has_significant_terms {
0.5
} else {
sig_hits as f32 / significant_terms.len() as f32
};
let alignment_norm = (alignment / 1.2).min(1.0);
let computed_intent = (term_relevance * 0.7 + alignment_norm * 0.3).clamp(0.0, 1.0);
let intent_score = computed_intent.max(doc.intent_score * 0.7);
if !local_urls.contains(&doc.url) {
local_results.push(SearchResult {
id: doc.id.clone(),
title: doc.title.clone(),
url: doc.url.clone(),
description: doc.description.clone(),
category: doc.category.clone(),
source: doc.source.clone(),
media_type: doc.media_type.clone(),
thumbnail_url: doc.thumbnail_url.clone(),
intent_score,
relevance_score: doc.relevance_score,
commercial_score: doc.commercial_score,
spam_score: doc.spam_score,
});
local_urls.insert(doc.url.clone());
}
}
// Sort local results: intent-first, then relevance
local_results.sort_by(|a, b| {
let a_priority = a.intent_score * 0.6 + a.relevance_score * 0.4;
let b_priority = b.intent_score * 0.6 + b.relevance_score * 0.4;
b_priority
.partial_cmp(&a_priority)
.unwrap_or(std::cmp::Ordering::Equal)
});
let local_elapsed = start.elapsed().as_millis() as u64;
// Check if we already have 15+ high-quality, intent-matching results
let target_count = 15;
let quality_threshold = 0.35;
let high_quality_local: Vec<&SearchResult> = local_results
.iter()
.filter(|r| {
r.relevance_score >= quality_threshold && r.intent_score >= 0.35 && r.spam_score < 0.3
})
.collect();
let needs_improvement = local_results.len() < target_count
|| high_quality_local.len() < target_count
|| primary_intent_score < 0.3;
tracing::info!(
"Search quality: local={}, high_quality={}, intent={:.2}, needs_improve={}",
local_results.len(),
high_quality_local.len(),
primary_intent_score,
needs_improvement
);
// PHASE 2: Lightweight synchronous meta-search when local results are insufficient
let mut meta_count = 0usize;
if needs_improvement && local_elapsed < 1500 {
let meta_timeout = std::time::Duration::from_millis(2000);
if let Ok(meta_resp) = tokio::time::timeout(
meta_timeout,
state
.app
.aggregator
.search_with_intent(¶ms.q, Some(&primary)),
)
.await
{
for r in &meta_resp.results {
if local_urls.contains(&r.url) {
continue;
}
if params.media_type.is_none() && r.media_type != "text" {
continue;
}
let combined = format!(
"{} {}",
r.title.to_lowercase(),
r.description.to_lowercase()
);
let alignment = state
.app
.intent_classifier
.calculate_alignment_boost(&primary, &combined);
if alignment < 0.2 {
continue;
}
if has_significant_terms {
let meta_sig_hits =
count_phrase_aware_hits(&combined, &phrase_terms, &significant_terms);
if meta_sig_hits < 1 {
continue;
}
}
let alignment_norm = (alignment / 1.2).min(1.0);
let rrf_contribution = (r.score * 10.0).min(0.3);
let intent_score = (alignment_norm * 0.5 + rrf_contribution + 0.2).clamp(0.0, 1.0);
let doc_text = format!("{} {}", r.title, r.description);
let cat_intent = state.app.intent_classifier.get_intent_for_text(&doc_text);
local_results.push(SearchResult {
id: hash_string(&r.url),
title: r.title.clone(),
url: r.url.clone(),
description: Some(r.description.clone()),
category: format!("{:?}", cat_intent),
source: r.source.clone(),
media_type: r.media_type.clone(),
thumbnail_url: r.thumbnail_url.clone(),
intent_score,
relevance_score: intent_score,
commercial_score: 0.0,
spam_score: 0.0,
});
local_urls.insert(r.url.clone());
meta_count += 1;
}
}
if meta_count > 0 {
local_results.sort_by(|a, b| {
let a_priority = a.intent_score * 0.6 + a.relevance_score * 0.4;
let b_priority = b.intent_score * 0.6 + b.relevance_score * 0.4;
b_priority
.partial_cmp(&a_priority)
.unwrap_or(std::cmp::Ordering::Equal)
});
}
}
let self_improving_flag = needs_improvement && meta_count < 5;
// Apply pagination to merged results
let local_count = local_results.len();
let paginated_results: Vec<SearchResult> = local_results
.into_iter()
.skip(params.offset)
.take(params.limit)
.collect();
let quality_count = paginated_results
.iter()
.filter(|r| r.intent_score >= 0.35 && r.relevance_score >= 0.35 && r.spam_score < 0.3)
.count();
let is_quality_response = quality_count >= 5 && paginated_results.len() >= target_count;
let message = if meta_count > 0 {
Some(format!(
"Local {} + meta {} in {}ms ({} quality)",
local_count - meta_count,
meta_count,
start.elapsed().as_millis(),
quality_count
))
} else if self_improving_flag {
Some(format!(
"Found {} results ({}ms), {} quality. Improving in background — retry in ~30-60s for better results.",
paginated_results.len(), local_elapsed, quality_count
))
} else {
Some(format!(
"Local index: {} results in {}ms ({} quality)",
local_count, local_elapsed, quality_count
))
};
let query_owned = params.q.clone();
let response = SearchResponse {
query: params.q,
total: paginated_results.len(),
results: paginated_results,
latency_ms: start.elapsed().as_millis() as u64,
message,
intent_scores,
self_improving: self_improving_flag,
};
// Cache quality responses
if is_quality_response {
let _ = state.app.redis.set_json(&cache_key, &response, 300).await;
tracing::info!(
"Cached quality response for '{}' ({} quality, {} total)",
query_owned,
quality_count,
response.results.len()
);
}
// Spawn background self-improvement when quality is insufficient (3-min budget)
if self_improving_flag {
let lock_key = format!("self_imp:active:{}", query_owned.to_lowercase().trim());
// Acquire distributed lock via SETNX to prevent duplicate tasks
let lock_acquired = if let Ok(mut conn) = state.app.redis.get_connection().await {
let acquired: bool = redis::cmd("SETNX")
.arg(&lock_key)
.arg("1")
.query_async(&mut conn)
.await
.unwrap_or(true);
if acquired {
let _: Result<(), _> = redis::cmd("EXPIRE")
.arg(&lock_key)
.arg(180i64)
.query_async(&mut conn)
.await;
}
acquired
} else {
true
};
if lock_acquired {
let imp_state = state.clone();
let imp_query = query_owned.clone();
let imp_intent = primary.clone();
let imp_sig_terms: Vec<String> =
significant_terms.iter().map(|s| s.to_string()).collect();
let imp_phrase_terms: Vec<String> = phrase_terms.clone();
let imp_min_sig = min_sig_required;
let imp_query_terms = query_terms.clone();
let imp_cache_key = cache_key.clone();
let imp_lock_key = lock_key;
let imp_expanded_query = expanded_query.clone();
tokio::spawn(async move {
let task_start = Instant::now();
let budget = std::time::Duration::from_secs(300); // 5 minutes
let target = 15usize;
let max_rounds = 10;
let mut quality_indexed = 0usize;
let mut seen_urls: HashSet<String> = HashSet::new();
// Generate query variations for multi-round search
let mut variations = imp_state
.app
.intent_classifier
.generate_variations(&imp_query, &imp_intent);
if !variations.contains(&imp_query) {
variations.insert(0, imp_query.clone());
}
variations.push(imp_query_terms.join(" "));
// Add more aggressive variations for persistent discovery
variations.push(format!("{} tutorial examples", imp_query));
variations.push(format!("{} complete guide walkthrough", imp_query));
variations.push(format!("{} best practices tips", imp_query));
variations.push(format!("{} advanced techniques", imp_query));
variations.push(format!("{} how to step by step", imp_query));
tracing::info!(
"Background self-improvement started for '{}' (target: {}, max rounds: {}, budget: 300s, variations: {})",
imp_query, target, max_rounds, variations.len()
);
// Embed query once for intent scoring
let query_embedding = match imp_state
.app
.embedding_model
.embed_batch(std::slice::from_ref(&imp_query))
{
Ok(embs) => embs.into_iter().next().unwrap_or_default(),
Err(_) => imp_state
.app
.embedding_model
.embed_fallback(std::slice::from_ref(&imp_query))
.into_iter()
.next()
.unwrap_or_default(),
};
let mut round = 0;
let mut consecutive_empty = 0;
loop {
// Hard stop conditions
if quality_indexed >= target
|| task_start.elapsed() >= budget
|| round >= max_rounds
{
break;
}
// Stop if we've had too many consecutive empty rounds (no new URLs found)
if consecutive_empty >= 5 {
tracing::info!(
"Background self-improvement stopping for '{}': {} consecutive empty rounds, quality={}/{} (partial)",
imp_query, consecutive_empty, quality_indexed, target
);
break;
}
let search_query = &variations[round % variations.len()];
let remaining = budget.saturating_sub(task_start.elapsed());
if remaining < std::time::Duration::from_secs(10) {
break;
}
tracing::info!(
"Self-improvement round {}/{} for '{}': query='{}', quality={}/{}, elapsed={}s",
round + 1, max_rounds, imp_query, search_query, quality_indexed, target,
task_start.elapsed().as_secs()
);
// Meta search with per-round timeout (intent-aware weighted RRF)
let meta_res = tokio::time::timeout(
std::time::Duration::from_secs(10),
imp_state
.app
.aggregator
.search_with_intent(search_query, Some(&imp_intent)),
)
.await;
let meta_resp = match meta_res {
Ok(resp) => resp,
Err(_) => {
tracing::warn!(
"Self-improvement: meta search timed out round {}",
round + 1
);
round += 1;
consecutive_empty += 1;
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
continue;
}
};
if meta_resp.results.is_empty() {
consecutive_empty += 1;
tracing::debug!(
"Self-improvement round {}: meta returned 0 results, consecutive_empty={}",
round + 1, consecutive_empty
);
round += 1;
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
continue;
}
// Collect ALL unseen URLs with their scores for relative ranking
let mut scored_candidates: Vec<(
&crate::meta_search::models::SearchResult,
f32,
)> = Vec::new();
for r in &meta_resp.results {
if seen_urls.contains(&r.url) {
continue;
}
seen_urls.insert(r.url.clone());
let combined = format!(
"{} {}",
r.title.to_lowercase(),
r.description.to_lowercase()
);
let alignment = imp_state
.app
.intent_classifier
.calculate_alignment_boost(&imp_intent, &combined);
if alignment < 0.2 {
continue;
} // Relaxed alignment threshold
// Score = RRF score * 0.4 + alignment * 0.3 + source weight * 0.3
let source_weight = match r.source.as_str() {
"searxng" => 1.0,
"arxiv" | "github" => 0.9,
"reddit" => 0.8,
"duckduckgo" => 0.7,
_ => 0.5,
};
let combined_score = r.score * 0.4 + alignment * 0.3 + source_weight * 0.3;
scored_candidates.push((r, combined_score));
}
if scored_candidates.is_empty() {
consecutive_empty += 1;
tracing::debug!(
"Self-improvement round {}: all {} results already seen or filtered, consecutive_empty={}",
round + 1, meta_resp.results.len(), consecutive_empty
);
round += 1;
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
continue;
}
// Reset consecutive empty counter since we found new candidates
consecutive_empty = 0;
// Sort by combined score and take top candidates (relative ranking)
scored_candidates
.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
let take_count = std::cmp::min(10, scored_candidates.len());
let top_candidates: Vec<_> = scored_candidates
.into_iter()
.take(take_count)
.map(|(r, _)| r)
.collect();
tracing::info!(
"Self-improvement round {}: selected {}/{} candidates (top by relative score, best={:.3})",
round + 1, take_count, meta_resp.results.len(),
top_candidates.first().map(|r| r.score).unwrap_or(0.0)
);
// Crawl candidates
let urls: Vec<&str> = top_candidates.iter().map(|r| r.url.as_str()).collect();
let crawl_results = match imp_state.app.crawler.fetch_batch(urls).await {
Ok(r) => r,
Err(e) => {
tracing::warn!(
"Self-improvement: crawl failed round {}: {}",
round + 1,
e
);
round += 1;
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
continue;
}
};
// Embed, score, and index each document
for (idx, crawl_result) in crawl_results.iter().enumerate() {
if quality_indexed >= target {
break;
}
let ext = top_candidates.get(idx);
let source = ext.map(|r| r.source.as_str()).unwrap_or("self_improvement");
let rrf_score = ext.map(|r| r.score).unwrap_or(0.0);
let text = format!("{} {}", crawl_result.title, crawl_result.content);
let embedding = match imp_state
.app
.embedding_model
.embed_batch(std::slice::from_ref(&text))
{
Ok(embs) => embs.into_iter().next().unwrap_or_default(),
Err(_) => imp_state
.app
.embedding_model
.embed_fallback(std::slice::from_ref(&text))
.into_iter()
.next()
.unwrap_or_default(),
};
let intent_score =
crate::utils::cosine_similarity(&query_embedding, &embedding)
.clamp(0.0, 1.0);
let quality_score = imp_state
.app
.embedding_model
.calculate_quality_score(&text, &crawl_result.url);
let relevance_score =
(intent_score * 0.5 + quality_score * 0.3 + rrf_score.min(0.2))
.clamp(0.1, 1.0);
// Relaxed intent threshold for partial improvements
if intent_score < 0.25 {
continue;
}
// Dynamic category via intent classifier
let content_snippet: String =
crawl_result.content.chars().take(500).collect();
let doc_text = format!("{} {}", crawl_result.title, content_snippet);
let dynamic_cat = format!(
"{:?}",
imp_state
.app
.intent_classifier
.get_intent_for_text(&doc_text)
);
let safe_id = hash_string(&crawl_result.url);
let _ = imp_state
.app
.indexer
.get_redis()
.store_content(&safe_id, &crawl_result.content)
.await;
let doc = crate::indexer::IntentDocument::new(
format!("ext-{}", safe_id),
crawl_result.title.clone(),
crawl_result.content.clone(),
crawl_result.url.clone(),
source.to_string(),
dynamic_cat,
intent_score,
relevance_score,
embedding,
)
.with_extra_scores(0.0, 0.0);
if let Err(e) = imp_state.app.indexer.index_document(&doc).await {
tracing::warn!(
"Self-improvement: failed to index {}: {}",
crawl_result.url,
e
);
} else {
// Relaxed quality gate for partial improvements
let is_quality = intent_score >= 0.3 && relevance_score >= 0.3;
if is_quality {
quality_indexed += 1;
}
tracing::info!(
"Self-improvement indexed: intent={:.3} rel={:.3} quality={} [{}/{}] | {}",
intent_score, relevance_score, is_quality,
quality_indexed, target, doc.title
);
}
}
round += 1;
// Add delay between rounds to avoid rate limiting
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
}
// After indexing, re-run the search to see if quality improved
if quality_indexed > 0 {
tracing::info!(
"Re-running search for '{}' after indexing {} quality docs",
imp_query,
quality_indexed
);
let re_filter = Some(
"media_type = \"text\" AND commercial_score < 0.7 AND spam_score < 0.5"
.to_string(),
);
let re_local = imp_state
.app
.indexer
.search(&imp_expanded_query, re_filter.as_deref(), Some(50))
.await
.unwrap_or_default();
let mut re_results: Vec<SearchResult> = Vec::new();
let mut re_urls = HashSet::new();
for doc in &re_local {
let title_low = doc.title.to_lowercase();
let desc_low = doc.description.as_deref().unwrap_or("").to_lowercase();
let combined = format!("{} {}", title_low, desc_low);
if title_low.contains("just a moment")
|| title_low.contains("cloudflare")
|| doc.title.trim().is_empty()
{
continue;
}
let alignment = imp_state
.app
.intent_classifier
.calculate_alignment_boost(&imp_intent, &combined);
if alignment < 0.2 {
continue;
}
let sig_hits =
count_phrase_aware_hits(&combined, &imp_phrase_terms, &imp_sig_terms);
if !imp_sig_terms.is_empty() && sig_hits < imp_min_sig {
continue;
}
let term_relevance = if imp_sig_terms.is_empty() {
0.5
} else {
sig_hits as f32 / imp_sig_terms.len() as f32
};
let alignment_norm = (alignment / 1.2).min(1.0);
let computed_intent =
(term_relevance * 0.7 + alignment_norm * 0.3).clamp(0.0, 1.0);
let intent_score = computed_intent.max(doc.intent_score * 0.7);
if !re_urls.contains(&doc.url) {
re_results.push(SearchResult {
id: doc.id.clone(),
title: doc.title.clone(),
url: doc.url.clone(),
description: doc.description.clone(),
category: doc.category.clone(),
source: doc.source.clone(),
media_type: doc.media_type.clone(),
thumbnail_url: doc.thumbnail_url.clone(),
intent_score,
relevance_score: doc.relevance_score,
commercial_score: doc.commercial_score,
spam_score: doc.spam_score,
});
re_urls.insert(doc.url.clone());
}
}
re_results.sort_by(|a, b| {
let a_p = a.intent_score * 0.6 + a.relevance_score * 0.4;
let b_p = b.intent_score * 0.6 + b.relevance_score * 0.4;
b_p.partial_cmp(&a_p).unwrap_or(std::cmp::Ordering::Equal)
});
let re_final: Vec<SearchResult> = re_results
.into_iter()
.filter(|r| r.media_type == "text")
.take(15)
.collect();
let re_total = re_final.len();
let re_quality = re_final
.iter()
.filter(|r| {
r.intent_score >= 0.35
&& r.relevance_score >= 0.35
&& r.spam_score < 0.3
})
.count();
if re_quality >= 5 && re_total >= 15 {
let cached_response = SearchResponse {
query: imp_query.clone(),
total: re_total,
results: re_final,
latency_ms: 0,
message: Some(format!(
"Self-improved: {} quality results indexed and cached",
quality_indexed
)),
intent_scores: vec![],
self_improving: false,
};
let _ = imp_state
.app
.redis
.set_json(&imp_cache_key, &cached_response, 300)
.await;
tracing::info!(
"Cached quality response for '{}' after self-improvement ({}/{} quality)",
imp_query, re_quality, re_total
);
} else {
// Not quality yet — clear any stale cache so next request re-evaluates
if let Ok(mut conn) = imp_state.app.redis.get_connection().await {
let _: Result<(), _> = redis::cmd("DEL")
.arg(&imp_cache_key)
.query_async(&mut conn)
.await;
}
tracing::info!(
"Self-improvement for '{}': re-search has {}/{} quality (not yet sufficient to cache)",
imp_query, re_quality, re_total
);
}
}
// Release lock
if let Ok(mut conn) = imp_state.app.redis.get_connection().await {
let _: Result<(), _> = redis::cmd("DEL")
.arg(&imp_lock_key)
.query_async(&mut conn)
.await;
}
tracing::info!(
"Background self-improvement completed for '{}': quality={}/{} in {}s",
imp_query,
quality_indexed,
target,
task_start.elapsed().as_secs()
);
});
}
}
(StatusCode::OK, Json(response)).into_response()
}
/// Meta-search endpoint
async fn meta_search_handler(
State(state): State<Arc<ApiState>>,
Query(params): Query<SearchParams>,
) -> impl IntoResponse {
let start = Instant::now();
let intent = state.app.intent_classifier.classify(¶ms.q);
let response = state
.app
.aggregator
.search_with_intent(¶ms.q, Some(&intent))
.await;
(
StatusCode::OK,
Json(SearchResponse {
query: params.q,
total: response.results.len(),
results: response
.results
.into_iter()
.map(|r| SearchResult {
id: hash_string(&r.url),
title: r.title,
url: r.url,
description: Some(r.description),
category: "meta".to_string(),
source: r.source,
media_type: r.media_type,
thumbnail_url: r.thumbnail_url,
intent_score: r.score,
relevance_score: r.score,
commercial_score: 0.0,
spam_score: 0.0,
})
.collect(),
latency_ms: start.elapsed().as_millis() as u64,
message: None,
intent_scores: vec![],
self_improving: false,
}),
)
}
/// Dedicated news search endpoint
async fn news_handler(
State(state): State<Arc<ApiState>>,
Query(params): Query<MediaSearchParams>,
) -> impl IntoResponse {
let start = Instant::now();
let aggregator = &state.app.aggregator;
let response = if let Some(location) = ¶ms.location {
aggregator.search_news_geo(¶ms.q, location).await
} else {
aggregator.search_news(¶ms.q).await
};
let mut seen_urls = HashSet::new();
let mut sources = HashSet::new();
let results: Vec<NewsResult> = response
.results
.into_iter()
.filter(|r| {
if seen_urls.contains(&r.url) {
return false;
}
seen_urls.insert(r.url.clone());
sources.insert(r.source.clone());
true
})
.map(|r| NewsResult {
title: r.title,
url: r.url,
description: r.description,
source: r.source,
published_at: r.published_at,
thumbnail_url: r.thumbnail_url,
})
.take(params.limit)
.collect();
(
StatusCode::OK,
Json(NewsResponse {
query: params.q,
total: results.len(),
results,
latency_ms: start.elapsed().as_millis() as u64,
sources: sources.into_iter().collect(),
}),
)
}
/// Dedicated image search endpoint
async fn images_handler(
State(state): State<Arc<ApiState>>,
Query(params): Query<MediaSearchParams>,
) -> impl IntoResponse {
let start = Instant::now();
let (expanded_query, _) = rewrite_query(¶ms.q, &state.app.query_expansion_config);
let filter = Some("media_type = \"image\"".to_string());
let (local_docs, ext_res) = tokio::join!(
state
.app
.indexer
.search(&expanded_query, filter.as_deref(), Some(30)),
state.app.image_search.search(&expanded_query, params.limit)
);
let mut results = Vec::new();
let mut seen = HashSet::new();
let mut sources = Vec::new();
if let Ok(docs) = local_docs {
for d in docs {
seen.insert(d.url.clone());
results.push(ImageResult {
id: d.id,
title: d.title,
url: d.url,
source: d.source,
category: d.category,
intent_score: d.intent_score,
relevance_score: d.relevance_score,
thumbnail_url: d.thumbnail_url,
alt_text: d.description,
photographer: None,
width: None,
height: None,
avg_color: None,
});
}
}
if let Ok(ext) = ext_res {
for i in ext {
if !sources.contains(&i.source) {
sources.push(i.source.clone());
}
if !seen.contains(&i.url) {
results.push(ImageResult {
id: i.id,
title: i.title,
url: i.url,
source: i.source,
category: "".into(),
intent_score: 0.5,
relevance_score: 0.5,
thumbnail_url: i.thumbnail_url,
alt_text: None,
photographer: i.photographer,
width: i.width,
height: i.height,
avg_color: i.avg_color,
});
}
}
}
(
StatusCode::OK,
Json(ImageResponse {
query: params.q,
total: results.len(),
results: results.into_iter().take(params.limit).collect(),
latency_ms: start.elapsed().as_millis() as u64,
sources,
}),
)
}
/// Dedicated video search endpoint
async fn videos_handler(
State(state): State<Arc<ApiState>>,
Query(params): Query<MediaSearchParams>,
) -> impl IntoResponse {
let start = Instant::now();
let mut results = Vec::new();
let mut seen = HashSet::new();
let mut sources = Vec::new();
if let Ok(docs) = state
.app
.indexer
.search(¶ms.q, Some("media_type = \"video\""), Some(20))
.await
{
for d in docs {
seen.insert(d.url.clone());
results.push(VideoResult {
id: d.id,
title: d.title,
url: d.url,
source: d.source,
description: d.description,
intent_score: d.intent_score,
relevance_score: d.relevance_score,
thumbnail_url: d.thumbnail_url,
duration_secs: None,
view_count: None,
channel: None,
published_at: None,
});
}
}
if let Ok(videos) = state.app.video_discovery.search(¶ms.q).await {
for v in videos {
if !seen.contains(&v.url) {
if !sources.contains(&v.source) {
sources.push(v.source.clone());
}
results.push(VideoResult {
id: v.id,
title: v.title,
url: v.url,
source: v.source,
description: v.description,
intent_score: v.intent_score,
relevance_score: v.relevance_score,
thumbnail_url: Some(v.thumbnail),
duration_secs: v.duration_secs,
view_count: v.view_count,
channel: v.uploader,
published_at: v.published_at.map(|dt| dt.to_rfc3339()),
});
}
}
}
(
StatusCode::OK,
Json(VideoResponse {
query: params.q,
total: results.len(),
results: results.into_iter().take(params.limit).collect(),
latency_ms: start.elapsed().as_millis() as u64,
sources,
}),
)
}
async fn crawl_single_handler(
State(state): State<Arc<ApiState>>,
Query(params): Query<CrawlParams>,
) -> impl IntoResponse {
let start = Instant::now();
match state.app.crawler.fetch(¶ms.url).await {
Ok(res) => (
StatusCode::OK,
Json(CrawlResponse {
url: res.url,
title: res.title,
content_length: res.content.len(),
success: true,
latency_ms: start.elapsed().as_millis() as u64,
error: None,
}),
),
Err(e) => (
StatusCode::OK,
Json(CrawlResponse {
url: params.url,
title: "".into(),
content_length: 0,
success: false,
latency_ms: start.elapsed().as_millis() as u64,
error: Some(e.to_string()),
}),
),
}
}
async fn crawl_batch_handler(
State(state): State<Arc<ApiState>>,
Json(req): Json<BatchCrawlRequest>,
) -> impl IntoResponse {
let start = Instant::now();
let urls: Vec<&str> = req.urls.iter().map(|s| s.as_str()).collect();
match state.app.crawler.fetch_batch(urls).await {
Ok(res) => (
StatusCode::OK,
Json(
res.into_iter()
.map(|r| CrawlResponse {
url: r.url,
title: r.title,
content_length: r.content.len(),
success: true,
latency_ms: 0,
error: None,
})
.collect::<Vec<_>>(),
),
),
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(vec![CrawlResponse {
url: "batch".into(),
title: "".into(),
content_length: 0,
success: false,
latency_ms: start.elapsed().as_millis() as u64,
error: Some(e.to_string()),
}]),
),
}
}
async fn metrics_handler(State(state): State<Arc<ApiState>>) -> impl IntoResponse {
use prometheus::Encoder;
let encoder = prometheus::TextEncoder::new();
let mut buffer = Vec::new();
let _ = encoder.encode(&state.metrics.registry.gather(), &mut buffer);
String::from_utf8_lossy(&buffer).to_string()
}
async fn discovery_status_handler(State(state): State<Arc<ApiState>>) -> impl IntoResponse {
let queue_size = state.app.discovery.queue_size().await.unwrap_or(0);
Json(
serde_json::json!({ "queue_size": queue_size, "last_cycle_secs": state.app.discovery.last_cycle_secs(), "max_queue_size": state.app.config.discovery.max_queue_size }),
)
}
async fn discovery_enqueue_handler(
State(state): State<Arc<ApiState>>,
Json(req): Json<DiscoveryEnqueueRequest>,
) -> impl IntoResponse {
let cat = req.category.as_deref().unwrap_or("manual");
match state
.app
.discovery
.enqueue_url_public(&req.url, req.priority, cat)
.await
{
Ok(enqueued) => (
StatusCode::OK,
Json(DiscoveryEnqueueResponse {
url: req.url,
enqueued,
error: None,
}),
),
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(DiscoveryEnqueueResponse {
url: req.url,
enqueued: false,
error: Some(e.to_string()),
}),
),
}
}
async fn reindex_scores_handler(State(_state): State<Arc<ApiState>>) -> impl IntoResponse {
(
StatusCode::OK,
Json(serde_json::json!({"status": "deprecated"})),
)
}
async fn get_full_content_handler(
Path(id): Path<String>,
State(state): State<Arc<ApiState>>,
) -> impl IntoResponse {
match state.app.redis.get_content(&id).await {
Ok(Some(c)) => (
StatusCode::OK,
Json(serde_json::json!({"id": id, "content": c})),
),
_ => (
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "not found"})),
),
}
}
//! HTTP API module for IntentForge v2
//!
//! Provides REST endpoints for crawling, searching, and health checks
//! using axum web framework.
use axum::{
extract::{Path, Query, Request, State},
http::{HeaderMap, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use std::time::Instant;
use crate::metrics::Metrics;
use crate::AppState;
/// Count phrase-aware significant term hits in a text.
/// Phrase matches count as 2 hits each; individual terms that are part of a matched phrase are skipped.
fn count_phrase_aware_hits<S: AsRef<str>>(
combined: &str,
phrase_terms: &[String],
significant_terms: &[S],
) -> usize {
let phrase_hits = phrase_terms
.iter()
.filter(|p| combined.contains(p.as_str()))
.count();
let individual_hits = significant_terms
.iter()
.filter(|t| {
let t_str = t.as_ref();
let in_phrase = phrase_terms.iter().any(|p| p.contains(t_str));
if in_phrase {
return false;
}
combined.contains(t_str)
})
.count();
phrase_hits * 2 + individual_hits
}
/// Helper to hash a string for ID generation
fn hash_string(s: &str) -> String {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
s.hash(&mut hasher);
format!("{:x}", hasher.finish())
}
/// Shared API state wrapping the app state with metrics
pub struct ApiState {
pub app: Arc<AppState>,
pub metrics: Metrics,
}
/// Query parameters for search endpoint
pub struct SearchParams {
pub q: String,
pub limit: usize,
pub offset: usize,
pub filter: Option<String>,
pub category: Option<String>,
pub media_type: Option<String>,
pub semantic_ratio: Option<f32>,
}
fn default_limit() -> usize {
15
}
fn default_offset() -> usize {
0
}
/// Search result item
pub struct SearchResult {
pub id: String,
pub title: String,
pub url: String,
pub description: Option<String>,
pub category: String,
pub source: String,
pub media_type: String,
pub thumbnail_url: Option<String>,
pub intent_score: f32,
pub relevance_score: f32,
pub commercial_score: f32,
pub spam_score: f32,
}
/// Search response