sumobot_ml / vdb /api.py
arbyazra123
support multiple instance of vect search
b615834
"""
FastAPI server for Sumobot with Milvus Vector Search
Real-time action retrieval using similarity search
"""
import re
import platform
import time
from typing import Dict, Optional, List
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
import numpy as np
from pymilvus import connections, Collection
# ==================== Configuration ====================
MILVUS_HOST = "127.0.0.1"
MILVUS_PORT = "19530"
COLLECTION_NAME = "sumobot_states"
TOP_K = 1 # Number of similar states to retrieve
NPROBE = 16 # Search parameter for IVF_FLAT index
print("="*70)
print("🤖 Sumobot Milvus Vector Search API Server")
print("="*70)
print(f"Platform: {platform.system()} {platform.machine()}")
print(f"Milvus: {MILVUS_HOST}:{MILVUS_PORT}")
print(f"Collection: {COLLECTION_NAME}")
print("="*70)
# ==================== Connect to Milvus ====================
print("\n⏳ Connecting to Milvus...")
start_time = time.time()
try:
connections.connect("default", host=MILVUS_HOST, port=MILVUS_PORT)
col = Collection(COLLECTION_NAME)
col.load()
load_time = time.time() - start_time
num_entities = col.num_entities
print(f"✅ Connected to Milvus in {load_time:.2f}s")
print(f"📊 Collection has {num_entities} entities\n")
except Exception as e:
print(f"❌ Failed to connect to Milvus: {e}")
print("\nMake sure:")
print(f" 1. Milvus is running at {MILVUS_HOST}:{MILVUS_PORT}")
print(f" 2. Collection '{COLLECTION_NAME}' exists")
print(" 3. pymilvus is installed: pip install pymilvus")
exit(1)
# ==================== State Encoding ====================
def encode_state(angle: float, angle_score: float, dist_score: float,
near_score: float, facing: float) -> np.ndarray:
"""
Encode game state into 5D vector
Args:
angle: AngleToEnemy (degrees, normalized to [-1, 1])
angle_score: AngleToEnemyScore [0, 1]
dist_score: DistanceToEnemyScore [0, 1]
near_score: NearBorderArenaScore [0, 1]
facing: FacingToArena [-1, 1]
Returns:
5D numpy array [angle_normalized, angle_score, dist_score, near_score, facing]
"""
# Normalize angle from [-180, 180] to [-1, 1]
angle_normalized = angle / 180.0
return np.array([
angle_normalized,
angle_score,
dist_score,
near_score,
facing
], dtype=np.float32)
def parse_state_string(state_str: str) -> Dict[str, float]:
"""
Parse state string into dictionary
Example input: "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"
Returns: {"AngleToEnemy": 7.77, "AngleToEnemyScore": 0.99, ...}
"""
state_dict = {}
# Remove trailing punctuation from entire string
state_str = state_str.rstrip('.,;')
for part in state_str.split(","):
part = part.strip()
if "=" in part:
key, value = part.split("=", 1) # Split only on first '='
# Clean up value: remove trailing periods, spaces, etc.
value_clean = value.strip().rstrip('.')
try:
state_dict[key.strip()] = float(value_clean)
except ValueError as e:
raise ValueError(f"Cannot parse '{key.strip()}={value}' - invalid float value: {e}")
return state_dict
# ==================== Action Parser ====================
def parse_action(output: str) -> Dict[str, Optional[float]]:
"""
Parse action string into dictionary
Expected format: "FWD 1.5, TR 0.8" or "SK, DS 2.0"
Returns: {"Accelerate": 1.5, "TurnRight": 0.8} or {"Skill": None, "Dash": 2.0}
"""
action_map = {
"SK": "Skill",
"DS": "Dash",
"FWD": "Accelerate",
"TL": "TurnLeft",
"TR": "TurnRight",
}
actions: Dict[str, Optional[float]] = {}
# Split by comma and process each action
for part in [p.strip() for p in output.split(",")]:
if not part:
continue
name = part
duration = None
# Try to extract duration (e.g., "FWD 1.5" -> name="FWD", duration=1.5)
direct_match = re.match(r"^([A-Za-z]+)\s*([\d.]+)$", part)
if direct_match:
name = direct_match.group(1).strip()
duration = float(direct_match.group(2))
# Normalize shorthand to full action name
for short, full in action_map.items():
if name.upper().startswith(short):
name = full
break
actions[name] = duration
return actions
# ==================== Vector Search Function ====================
def query_action(angle: float, angle_score: float, dist_score: float,
near_score: float, facing: float, top_k: int = TOP_K) -> dict:
"""
Query action from Milvus using vector similarity search
Args:
angle: AngleToEnemy (degrees)
angle_score: AngleToEnemyScore [0, 1]
dist_score: DistanceToEnemyScore [0, 1]
near_score: NearBorderArenaScore [0, 1]
facing: FacingToArena [-1, 1]
top_k: Number of similar states to retrieve
Returns:
{
"raw_output": "FWD 1.5, TR 0.8",
"action": {"Accelerate": 1.5, "TurnRight": 0.8},
"search_time_ms": 2.5,
"distance": 0.123,
"top_k_results": [...] # Only if top_k > 1
}
"""
# Encode state into vector
vec = encode_state(angle, angle_score, dist_score, near_score, facing)
# Perform vector search
start = time.time()
result = col.search(
data=[vec.tolist()],
anns_field="state_vec",
param={"nprobe": NPROBE},
limit=top_k,
output_fields=["action"],
)
search_time = (time.time() - start) * 1000 # Convert to ms
# Extract results
if len(result[0]) == 0:
raise ValueError("No similar states found in database")
top_hit = result[0][0]
action_str = top_hit.entity.get("action")
distance = top_hit.distance
# Parse action
parsed_actions = parse_action(action_str)
response = {
"raw_output": action_str,
"action": parsed_actions,
"search_time_ms": round(search_time, 2),
"distance": round(distance, 4)
}
# Include all results if top_k > 1
if top_k > 1:
response["top_k_results"] = [
{
"action": hit.entity.get("action"),
"distance": round(hit.distance, 4)
}
for hit in result[0]
]
return response
def query_action_from_string(state_str: str, top_k: int = TOP_K) -> dict:
"""
Query action from state string
Args:
state_str: "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"
top_k: Number of similar states to retrieve
Returns:
Same as query_action()
"""
# Parse state string
state_dict = parse_state_string(state_str)
# Extract required fields
required_fields = [
"AngleToEnemy",
"AngleToEnemyScore",
"DistanceToEnemyScore",
"NearBorderArenaScore",
"FacingToArena"
]
missing_fields = [f for f in required_fields if f not in state_dict]
if missing_fields:
raise ValueError(f"Missing required fields: {missing_fields}")
# Query action
return query_action(
angle=state_dict["AngleToEnemy"],
angle_score=state_dict["AngleToEnemyScore"],
dist_score=state_dict["DistanceToEnemyScore"],
near_score=state_dict["NearBorderArenaScore"],
facing=state_dict["FacingToArena"],
top_k=top_k
)
# ==================== FastAPI Setup ====================
app = FastAPI(
title="Sumobot Milvus Vector Search API",
description="Real-time Sumobot action retrieval using vector similarity search",
version="1.0.0"
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ==================== Request/Response Models ====================
class QueryInput(BaseModel):
state: str
top_k: Optional[int] = 1
class Config:
json_schema_extra = {
"example": {
"state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
"top_k": 1
}
}
class QueryResponse(BaseModel):
raw_output: str
action: Dict[str, Optional[float]]
search_time_ms: float
distance: float
top_k_results: Optional[List[Dict]] = None
class BatchQueryInput(BaseModel):
states: List[str]
top_k: Optional[int] = 1
class HealthResponse(BaseModel):
status: str
milvus_host: str
collection: str
num_entities: int
platform: str
# ==================== API Endpoints ====================
@app.get("/", tags=["Info"])
def root():
"""Root endpoint with API information"""
return {
"message": "Sumobot Milvus Vector Search API",
"endpoints": {
"health": "/health",
"query": "/query (POST)",
"batch": "/batch (POST)",
"benchmark": "/benchmark (GET)",
"stats": "/stats (GET)"
}
}
@app.get("/health", response_model=HealthResponse, tags=["Info"])
def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"milvus_host": f"{MILVUS_HOST}:{MILVUS_PORT}",
"collection": COLLECTION_NAME,
"num_entities": col.num_entities,
"platform": f"{platform.system()} {platform.machine()}"
}
@app.get("/stats", tags=["Info"])
def collection_stats():
"""Get collection statistics"""
return {
"collection": COLLECTION_NAME,
"num_entities": col.num_entities,
"schema": {
"fields": [
{
"name": field.name,
"type": str(field.dtype),
"params": field.params
}
for field in col.schema.fields
]
},
"indexes": [
{
"field": index.field_name,
"type": index.params.get("index_type"),
"metric": index.params.get("metric_type")
}
for index in col.indexes
]
}
@app.post("/query", response_model=QueryResponse, tags=["Search"])
def query(input: QueryInput):
"""
Get action prediction for a single game state
Example:
```json
{
"state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
"top_k": 1
}
```
"""
try:
result = query_action_from_string(input.state, input.top_k)
return result
except Exception as e:
print(input.state)
print(f"Error query:\nInput: {input.state}\nDetail: {e.with_traceback()}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/batch", tags=["Search"])
def batch_query(input: BatchQueryInput):
"""
Get action predictions for multiple game states
Example:
```json
{
"states": [
"AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
"AngleToEnemy=2.31, AngleToEnemyScore=0.45, DistanceToEnemyScore=0.92, NearBorderArenaScore=0.12, FacingToArena=0.67"
],
"top_k": 1
}
```
"""
try:
results = []
total_time = 0
for state in input.states:
result = query_action_from_string(state, input.top_k)
results.append(result)
total_time += result["search_time_ms"]
return {
"results": results,
"total_search_time_ms": round(total_time, 2),
"avg_search_time_ms": round(total_time / len(results), 2)
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/benchmark", tags=["Diagnostics"])
def benchmark():
"""
Benchmark vector search performance
Runs 100 searches and returns statistics
"""
test_state = "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"
print("\n🔥 Running benchmark...")
# Warmup
query_action_from_string(test_state)
# Benchmark
times = []
outputs = []
num_runs = 100
for i in range(num_runs):
result = query_action_from_string(test_state)
times.append(result["search_time_ms"])
outputs.append(result["raw_output"])
if (i + 1) % 20 == 0:
print(f" Run {i+1}/{num_runs}: {result['search_time_ms']:.2f}ms")
times_sorted = sorted(times)
return {
"runs": num_runs,
"test_state": test_state,
"stats": {
"avg_latency_ms": round(sum(times) / len(times), 2),
"min_latency_ms": round(min(times), 2),
"max_latency_ms": round(max(times), 2),
"p50_latency_ms": round(times_sorted[len(times) // 2], 2),
"p95_latency_ms": round(times_sorted[int(len(times) * 0.95)], 2),
"p99_latency_ms": round(times_sorted[int(len(times) * 0.99)], 2),
},
"platform": {
"system": platform.system(),
"machine": platform.machine(),
"milvus": f"{MILVUS_HOST}:{MILVUS_PORT}",
"collection_size": col.num_entities
},
"sample_outputs": list(set(outputs[:10])) # First 10 unique outputs
}
# ==================== Main ====================
if __name__ == "__main__":
import sys
port = 9999
workers = 20 # Number of worker processes
# Check if running with multiple workers
if "--workers" in sys.argv:
try:
workers_idx = sys.argv.index("--workers")
workers = int(sys.argv[workers_idx + 1])
except (IndexError, ValueError):
print("⚠️ Invalid --workers argument, using default: 20")
if "--port" in sys.argv:
try:
port_idx = sys.argv.index("--port")
port = int(sys.argv[port_idx + 1])
except (IndexError, ValueError):
print(f"⚠️ Invalid --port argument, using default: {port}")
print("\n🚀 Starting Sumobot Milvus API server...")
print(f"📡 Server will be available at: http://0.0.0.0:{port}")
print(f"👷 Workers: {workers}")
print(f"📚 API docs: http://0.0.0.0:{port}/docs")
print(f"🔍 Health check: http://0.0.0.0:{port}/health")
print(f"📊 Stats: http://0.0.0.0:{port}/stats")
print("\n" + "="*70 + "\n")
# For production with multiple workers, use uvicorn with workers parameter
# Each worker will have its own connection to Milvus
uvicorn.run(
"api:app", # Use string import path for workers to work properly
host="0.0.0.0",
port=port,
workers=workers,
log_level="info",
access_log=True
)
# ==================== Usage Instructions ====================
"""
# ==================== Running the Server ====================
# Run with 20 workers (default)
python vdb/api.py
# Run with custom number of workers
python vdb/api.py --workers 10
# Run with custom port
python vdb/api.py --port 8000 --workers 20
# Alternative: Using Gunicorn for production (install: pip install gunicorn)
gunicorn vdb.api:app \
--workers 20 \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:9999 \
--timeout 120 \
--access-logfile - \
--error-logfile -
# ==================== Testing the API ====================
# Health check
curl http://localhost:9999/health
# Collection stats
curl http://localhost:9999/stats
# Single query
curl -X POST http://localhost:9999/query \
-H "Content-Type: application/json" \
-d '{
"state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"
}'
# Query with top-k results
curl -X POST http://localhost:9999/query \
-H "Content-Type: application/json" \
-d '{
"state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
"top_k": 3
}'
# Batch query
curl -X POST http://localhost:9999/batch \
-H "Content-Type: application/json" \
-d '{
"states": [
"AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
"AngleToEnemy=2.31, AngleToEnemyScore=0.45, DistanceToEnemyScore=0.92, NearBorderArenaScore=0.12, FacingToArena=0.67"
]
}'
# Benchmark
curl http://localhost:9999/benchmark
# Interactive API docs
# Open in browser: http://localhost:9999/docs
# ==================== Performance Testing ====================
# Load test with Apache Bench (install: brew install httpd or apt-get install apache2-utils)
ab -n 10000 -c 100 -T 'application/json' \
-p query.json \
http://localhost:9999/query
# Where query.json contains:
# {"state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"}
"""