Spaces:
Running on Zero
Running on Zero
Naufal Arhab commited on
Commit ·
165bee7
1
Parent(s): 2ee81a5
Fix AI analysis execution, CORS regex, proxy targets, and explicit error handling
Browse files- backend/main.py +17 -7
- backend/routers/ai.py +24 -11
- frontend/src/api/ai.ts +1 -1
- frontend/src/api/client.ts +4 -10
- frontend/src/components/signals/AIAnalysisPanel.tsx +55 -3
- frontend/vite.config.ts +5 -1
backend/main.py
CHANGED
|
@@ -12,6 +12,7 @@ Background loop:
|
|
| 12 |
- For each active pair: collect data → compute signal → save to DB → broadcast via WS
|
| 13 |
"""
|
| 14 |
|
|
|
|
| 15 |
import asyncio
|
| 16 |
import logging
|
| 17 |
from contextlib import asynccontextmanager
|
|
@@ -193,13 +194,22 @@ app = FastAPI(
|
|
| 193 |
)
|
| 194 |
|
| 195 |
# CORS
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
# ── Routers ──────────────────────────────────────────────────────────────────
|
| 205 |
app.include_router(signals_router.router)
|
|
|
|
| 12 |
- For each active pair: collect data → compute signal → save to DB → broadcast via WS
|
| 13 |
"""
|
| 14 |
|
| 15 |
+
import os
|
| 16 |
import asyncio
|
| 17 |
import logging
|
| 18 |
from contextlib import asynccontextmanager
|
|
|
|
| 194 |
)
|
| 195 |
|
| 196 |
# CORS
|
| 197 |
+
if CORS_ORIGINS == ["*"]:
|
| 198 |
+
app.add_middleware(
|
| 199 |
+
CORSMiddleware,
|
| 200 |
+
allow_origin_regex=r"^https?://.*$",
|
| 201 |
+
allow_credentials=True,
|
| 202 |
+
allow_methods=["*"],
|
| 203 |
+
allow_headers=["*"],
|
| 204 |
+
)
|
| 205 |
+
else:
|
| 206 |
+
app.add_middleware(
|
| 207 |
+
CORSMiddleware,
|
| 208 |
+
allow_origins=CORS_ORIGINS,
|
| 209 |
+
allow_credentials=True,
|
| 210 |
+
allow_methods=["*"],
|
| 211 |
+
allow_headers=["*"],
|
| 212 |
+
)
|
| 213 |
|
| 214 |
# ── Routers ──────────────────────────────────────────────────────────────────
|
| 215 |
app.include_router(signals_router.router)
|
backend/routers/ai.py
CHANGED
|
@@ -209,6 +209,8 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request):
|
|
| 209 |
cache_key = f"{symbol}:{req_provider}:{model_key}"
|
| 210 |
cache_entry = _AI_CACHE.get(cache_key)
|
| 211 |
|
|
|
|
|
|
|
| 212 |
if not body.question and not body.force_refresh and cache_entry:
|
| 213 |
age_seconds = now_ts - cache_entry["timestamp"]
|
| 214 |
if age_seconds < CACHE_TTL_SECONDS:
|
|
@@ -266,12 +268,12 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request):
|
|
| 266 |
"contents": [{"parts": [{"text": prompt}]}],
|
| 267 |
"generationConfig": {
|
| 268 |
"temperature": 0.15, # Deterministic & sharp
|
| 269 |
-
"maxOutputTokens":
|
| 270 |
},
|
| 271 |
}
|
| 272 |
|
| 273 |
last_err = None
|
| 274 |
-
async with httpx.AsyncClient(timeout=
|
| 275 |
for candidate in candidate_models:
|
| 276 |
gemini_url = f"https://generativelanguage.googleapis.com/v1beta/models/{candidate}:generateContent?key={clean_api_key}"
|
| 277 |
resp = await client.post(gemini_url, json=payload)
|
|
@@ -319,19 +321,25 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request):
|
|
| 319 |
default_model = "gpt-4o-mini"
|
| 320 |
|
| 321 |
if body.base_url and body.base_url.strip():
|
| 322 |
-
|
|
|
|
|
|
|
|
|
|
| 323 |
|
| 324 |
model_name = body.model.strip() if (body.model and body.model.strip()) else default_model
|
| 325 |
used_model = model_name
|
| 326 |
|
|
|
|
| 327 |
payload = {
|
| 328 |
"model": model_name,
|
| 329 |
"messages": [
|
| 330 |
-
{
|
| 331 |
-
|
|
|
|
|
|
|
| 332 |
],
|
| 333 |
-
"temperature": 0.
|
| 334 |
-
"max_tokens":
|
| 335 |
}
|
| 336 |
|
| 337 |
headers = {
|
|
@@ -342,7 +350,7 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request):
|
|
| 342 |
headers["HTTP-Referer"] = "https://perpsai.local"
|
| 343 |
headers["X-Title"] = "PerpsAI"
|
| 344 |
|
| 345 |
-
async with httpx.AsyncClient(timeout=
|
| 346 |
target_url = f"{base_url}/chat/completions"
|
| 347 |
resp = await client.post(
|
| 348 |
target_url,
|
|
@@ -356,16 +364,21 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request):
|
|
| 356 |
err_msg = err_json.get("error", {}).get("message", err_msg)
|
| 357 |
except Exception:
|
| 358 |
pass
|
|
|
|
| 359 |
raise HTTPException(
|
| 360 |
-
status_code=resp.status_code,
|
| 361 |
-
detail=f"{provider.
|
| 362 |
)
|
| 363 |
|
| 364 |
res_json = resp.json()
|
| 365 |
choices = res_json.get("choices", [])
|
| 366 |
if not choices:
|
| 367 |
raise HTTPException(status_code=500, detail="API tidak mengembalikan konten analisa.")
|
| 368 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 369 |
|
| 370 |
else:
|
| 371 |
raise HTTPException(status_code=400, detail=f"Provider '{provider}' tidak didukung. Gunakan 'vikey', 'gemini', atau 'openai'.")
|
|
|
|
| 209 |
cache_key = f"{symbol}:{req_provider}:{model_key}"
|
| 210 |
cache_entry = _AI_CACHE.get(cache_key)
|
| 211 |
|
| 212 |
+
logger.info("[%s] AI /analyze request: provider=%s, model=%s, force_refresh=%s", symbol, req_provider, model_key, body.force_refresh)
|
| 213 |
+
|
| 214 |
if not body.question and not body.force_refresh and cache_entry:
|
| 215 |
age_seconds = now_ts - cache_entry["timestamp"]
|
| 216 |
if age_seconds < CACHE_TTL_SECONDS:
|
|
|
|
| 268 |
"contents": [{"parts": [{"text": prompt}]}],
|
| 269 |
"generationConfig": {
|
| 270 |
"temperature": 0.15, # Deterministic & sharp
|
| 271 |
+
"maxOutputTokens": 1500, # Token-efficient: concise institutional report
|
| 272 |
},
|
| 273 |
}
|
| 274 |
|
| 275 |
last_err = None
|
| 276 |
+
async with httpx.AsyncClient(timeout=60.0, verify=False) as client:
|
| 277 |
for candidate in candidate_models:
|
| 278 |
gemini_url = f"https://generativelanguage.googleapis.com/v1beta/models/{candidate}:generateContent?key={clean_api_key}"
|
| 279 |
resp = await client.post(gemini_url, json=payload)
|
|
|
|
| 321 |
default_model = "gpt-4o-mini"
|
| 322 |
|
| 323 |
if body.base_url and body.base_url.strip():
|
| 324 |
+
b_url = body.base_url.strip().rstrip("/")
|
| 325 |
+
if not b_url.endswith("/v1") and not "/v1" in b_url:
|
| 326 |
+
b_url = f"{b_url}/v1"
|
| 327 |
+
base_url = b_url
|
| 328 |
|
| 329 |
model_name = body.model.strip() if (body.model and body.model.strip()) else default_model
|
| 330 |
used_model = model_name
|
| 331 |
|
| 332 |
+
# Universal format compatible with all LLM proxies (Claude, DeepSeek, GPT, Qwen, etc.)
|
| 333 |
payload = {
|
| 334 |
"model": model_name,
|
| 335 |
"messages": [
|
| 336 |
+
{
|
| 337 |
+
"role": "user",
|
| 338 |
+
"content": f"[Instruksi: Senior Institutional Crypto Derivatives Quant. Analisa empiris, objektif, padat, anti-halusinasi.]\n\n{prompt}",
|
| 339 |
+
}
|
| 340 |
],
|
| 341 |
+
"temperature": 0.2,
|
| 342 |
+
"max_tokens": 1500,
|
| 343 |
}
|
| 344 |
|
| 345 |
headers = {
|
|
|
|
| 350 |
headers["HTTP-Referer"] = "https://perpsai.local"
|
| 351 |
headers["X-Title"] = "PerpsAI"
|
| 352 |
|
| 353 |
+
async with httpx.AsyncClient(timeout=75.0, verify=False) as client:
|
| 354 |
target_url = f"{base_url}/chat/completions"
|
| 355 |
resp = await client.post(
|
| 356 |
target_url,
|
|
|
|
| 364 |
err_msg = err_json.get("error", {}).get("message", err_msg)
|
| 365 |
except Exception:
|
| 366 |
pass
|
| 367 |
+
logger.error("[%s] AI Provider returned %d: %s", symbol, resp.status_code, err_msg)
|
| 368 |
raise HTTPException(
|
| 369 |
+
status_code=resp.status_code if resp.status_code in [400, 401, 402, 403, 404, 429] else 502,
|
| 370 |
+
detail=f"{provider.upper()} API Error ({resp.status_code}): {err_msg}",
|
| 371 |
)
|
| 372 |
|
| 373 |
res_json = resp.json()
|
| 374 |
choices = res_json.get("choices", [])
|
| 375 |
if not choices:
|
| 376 |
raise HTTPException(status_code=500, detail="API tidak mengembalikan konten analisa.")
|
| 377 |
+
|
| 378 |
+
msg = choices[0].get("message") or {}
|
| 379 |
+
analysis_text = msg.get("content") or msg.get("reasoning_content") or choices[0].get("text") or ""
|
| 380 |
+
if not analysis_text:
|
| 381 |
+
raise HTTPException(status_code=500, detail="Model AI tidak memberikan teks analisa (respon kosong).")
|
| 382 |
|
| 383 |
else:
|
| 384 |
raise HTTPException(status_code=400, detail=f"Provider '{provider}' tidak didukung. Gunakan 'vikey', 'gemini', atau 'openai'.")
|
frontend/src/api/ai.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { AIAnalysisRequest, AIAnalysisResponse } from '../types';
|
|
| 4 |
export const aiApi = {
|
| 5 |
analyze: async (payload: AIAnalysisRequest): Promise<AIAnalysisResponse> => {
|
| 6 |
const { data } = await apiClient.post<AIAnalysisResponse>('/api/ai/analyze', payload, {
|
| 7 |
-
timeout:
|
| 8 |
});
|
| 9 |
return data;
|
| 10 |
},
|
|
|
|
| 4 |
export const aiApi = {
|
| 5 |
analyze: async (payload: AIAnalysisRequest): Promise<AIAnalysisResponse> => {
|
| 6 |
const { data } = await apiClient.post<AIAnalysisResponse>('/api/ai/analyze', payload, {
|
| 7 |
+
timeout: 90000, // Allow up to 90s for deep LLM reasoning
|
| 8 |
});
|
| 9 |
return data;
|
| 10 |
},
|
frontend/src/api/client.ts
CHANGED
|
@@ -1,19 +1,13 @@
|
|
| 1 |
import axios from 'axios';
|
| 2 |
|
| 3 |
-
//
|
| 4 |
// - Uses VITE_API_URL if defined (e.g. external backend on Railway/Render)
|
| 5 |
-
// -
|
| 6 |
-
|
| 7 |
-
export const BASE_URL =
|
| 8 |
-
import.meta.env.VITE_API_URL !== undefined
|
| 9 |
-
? import.meta.env.VITE_API_URL
|
| 10 |
-
: import.meta.env.DEV
|
| 11 |
-
? 'http://localhost:8000'
|
| 12 |
-
: '';
|
| 13 |
|
| 14 |
export const apiClient = axios.create({
|
| 15 |
baseURL: BASE_URL,
|
| 16 |
-
timeout:
|
| 17 |
headers: {
|
| 18 |
'Content-Type': 'application/json',
|
| 19 |
},
|
|
|
|
| 1 |
import axios from 'axios';
|
| 2 |
|
| 3 |
+
// API Base URL:
|
| 4 |
// - Uses VITE_API_URL if defined (e.g. external backend on Railway/Render)
|
| 5 |
+
// - In local dev with Vite proxy or on Vercel production, uses relative '' (same origin, eliminates CORS)
|
| 6 |
+
export const BASE_URL = import.meta.env.VITE_API_URL || '';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
export const apiClient = axios.create({
|
| 9 |
baseURL: BASE_URL,
|
| 10 |
+
timeout: 90000,
|
| 11 |
headers: {
|
| 12 |
'Content-Type': 'application/json',
|
| 13 |
},
|
frontend/src/components/signals/AIAnalysisPanel.tsx
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import { useState } from 'react';
|
| 2 |
import {
|
| 3 |
Sparkles,
|
| 4 |
Send,
|
|
@@ -29,12 +29,18 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) {
|
|
| 29 |
const [selectedModel, setSelectedModel] = useState<string>(settings.model);
|
| 30 |
const [isSettingsModalOpen, setIsSettingsModalOpen] = useState(false);
|
| 31 |
const [isLoading, setIsLoading] = useState(false);
|
|
|
|
| 32 |
const [result, setResult] = useState<AIAnalysisResponse | null>(null);
|
| 33 |
const [customQuestion, setCustomQuestion] = useState('');
|
| 34 |
const [showDataSnapshot, setShowDataSnapshot] = useState(false);
|
| 35 |
const [copied, setCopied] = useState(false);
|
| 36 |
const { toast } = useToast();
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
// Active model in this card (either locally overridden or universal default)
|
| 39 |
const activeModel = selectedModel || settings.model;
|
| 40 |
|
|
@@ -46,6 +52,7 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) {
|
|
| 46 |
}
|
| 47 |
|
| 48 |
setIsLoading(true);
|
|
|
|
| 49 |
try {
|
| 50 |
const res = await aiApi.analyze({
|
| 51 |
symbol,
|
|
@@ -57,6 +64,7 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) {
|
|
| 57 |
force_refresh: forceRefresh,
|
| 58 |
});
|
| 59 |
setResult(res);
|
|
|
|
| 60 |
if (question) {
|
| 61 |
setCustomQuestion('');
|
| 62 |
}
|
|
@@ -66,7 +74,9 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) {
|
|
| 66 |
toast(`Analisa AI (${res.model}) selesai dimuat`, 'success');
|
| 67 |
}
|
| 68 |
} catch (err: any) {
|
| 69 |
-
|
|
|
|
|
|
|
| 70 |
} finally {
|
| 71 |
setIsLoading(false);
|
| 72 |
}
|
|
@@ -316,6 +326,46 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) {
|
|
| 316 |
</div>
|
| 317 |
)}
|
| 318 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
{/* Loading Skeleton */}
|
| 320 |
{isLoading && (
|
| 321 |
<div className="py-8 flex flex-col items-center justify-center space-y-2.5 text-center animate-fade-in">
|
|
@@ -468,10 +518,12 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) {
|
|
| 468 |
variant="primary"
|
| 469 |
size="sm"
|
| 470 |
onClick={() => handleRunAnalysis()}
|
|
|
|
|
|
|
| 471 |
icon={<Zap size={12} />}
|
| 472 |
className="bg-purple-600 hover:bg-purple-500 text-white shadow-lg shadow-purple-500/20"
|
| 473 |
>
|
| 474 |
-
Mulai Analisa AI
|
| 475 |
</Button>
|
| 476 |
</div>
|
| 477 |
)}
|
|
|
|
| 1 |
+
import { useState, useEffect } from 'react';
|
| 2 |
import {
|
| 3 |
Sparkles,
|
| 4 |
Send,
|
|
|
|
| 29 |
const [selectedModel, setSelectedModel] = useState<string>(settings.model);
|
| 30 |
const [isSettingsModalOpen, setIsSettingsModalOpen] = useState(false);
|
| 31 |
const [isLoading, setIsLoading] = useState(false);
|
| 32 |
+
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
| 33 |
const [result, setResult] = useState<AIAnalysisResponse | null>(null);
|
| 34 |
const [customQuestion, setCustomQuestion] = useState('');
|
| 35 |
const [showDataSnapshot, setShowDataSnapshot] = useState(false);
|
| 36 |
const [copied, setCopied] = useState(false);
|
| 37 |
const { toast } = useToast();
|
| 38 |
|
| 39 |
+
// Sync activeModel whenever universal settings change
|
| 40 |
+
useEffect(() => {
|
| 41 |
+
setSelectedModel(settings.model);
|
| 42 |
+
}, [settings.provider, settings.model]);
|
| 43 |
+
|
| 44 |
// Active model in this card (either locally overridden or universal default)
|
| 45 |
const activeModel = selectedModel || settings.model;
|
| 46 |
|
|
|
|
| 52 |
}
|
| 53 |
|
| 54 |
setIsLoading(true);
|
| 55 |
+
setErrorMessage(null);
|
| 56 |
try {
|
| 57 |
const res = await aiApi.analyze({
|
| 58 |
symbol,
|
|
|
|
| 64 |
force_refresh: forceRefresh,
|
| 65 |
});
|
| 66 |
setResult(res);
|
| 67 |
+
setErrorMessage(null);
|
| 68 |
if (question) {
|
| 69 |
setCustomQuestion('');
|
| 70 |
}
|
|
|
|
| 74 |
toast(`Analisa AI (${res.model}) selesai dimuat`, 'success');
|
| 75 |
}
|
| 76 |
} catch (err: any) {
|
| 77 |
+
const msg = err.message || 'Gagal melakukan analisa AI';
|
| 78 |
+
setErrorMessage(msg);
|
| 79 |
+
toast(msg, 'error');
|
| 80 |
} finally {
|
| 81 |
setIsLoading(false);
|
| 82 |
}
|
|
|
|
| 326 |
</div>
|
| 327 |
)}
|
| 328 |
|
| 329 |
+
{/* Error Alert Banner with Actionable Diagnostics */}
|
| 330 |
+
{errorMessage && (
|
| 331 |
+
<div className="p-3.5 rounded-lg bg-red-500/10 border border-red-500/30 text-xs text-red-200 flex items-start gap-3 animate-fade-in">
|
| 332 |
+
<AlertCircle size={16} className="text-red-400 shrink-0 mt-0.5" />
|
| 333 |
+
<div className="flex-1 space-y-1.5">
|
| 334 |
+
<div className="flex items-center justify-between">
|
| 335 |
+
<p className="font-bold text-red-300">
|
| 336 |
+
Gagal Memuat Analisa AI ({activeModel})
|
| 337 |
+
</p>
|
| 338 |
+
<span className="text-[10px] text-red-400/80 font-mono uppercase">
|
| 339 |
+
{settings.provider}
|
| 340 |
+
</span>
|
| 341 |
+
</div>
|
| 342 |
+
<p className="text-[11px] text-red-200/90 leading-relaxed font-mono bg-red-950/40 p-2 rounded border border-red-500/20 break-words">
|
| 343 |
+
{errorMessage}
|
| 344 |
+
</p>
|
| 345 |
+
<div className="pt-1 flex flex-wrap items-center gap-2">
|
| 346 |
+
<Button
|
| 347 |
+
variant="ghost"
|
| 348 |
+
size="sm"
|
| 349 |
+
onClick={() => handleRunAnalysis(undefined, true)}
|
| 350 |
+
loading={isLoading}
|
| 351 |
+
icon={<RefreshCw size={11} />}
|
| 352 |
+
className="text-[11px] h-7 px-2.5 bg-red-500/20 hover:bg-red-500/30 text-red-100 border border-red-500/30"
|
| 353 |
+
>
|
| 354 |
+
Coba Lagi
|
| 355 |
+
</Button>
|
| 356 |
+
<button
|
| 357 |
+
type="button"
|
| 358 |
+
onClick={() => setIsSettingsModalOpen(true)}
|
| 359 |
+
className="text-[11px] text-purple-300 hover:text-purple-200 underline flex items-center gap-1 ml-1"
|
| 360 |
+
>
|
| 361 |
+
<Settings size={11} />
|
| 362 |
+
Buka Pengaturan AI (Cek API Key / Ganti Model)
|
| 363 |
+
</button>
|
| 364 |
+
</div>
|
| 365 |
+
</div>
|
| 366 |
+
</div>
|
| 367 |
+
)}
|
| 368 |
+
|
| 369 |
{/* Loading Skeleton */}
|
| 370 |
{isLoading && (
|
| 371 |
<div className="py-8 flex flex-col items-center justify-center space-y-2.5 text-center animate-fade-in">
|
|
|
|
| 518 |
variant="primary"
|
| 519 |
size="sm"
|
| 520 |
onClick={() => handleRunAnalysis()}
|
| 521 |
+
loading={isLoading}
|
| 522 |
+
disabled={isLoading}
|
| 523 |
icon={<Zap size={12} />}
|
| 524 |
className="bg-purple-600 hover:bg-purple-500 text-white shadow-lg shadow-purple-500/20"
|
| 525 |
>
|
| 526 |
+
{isLoading ? 'Sedang Menganalisa...' : 'Mulai Analisa AI'}
|
| 527 |
</Button>
|
| 528 |
</div>
|
| 529 |
)}
|
frontend/vite.config.ts
CHANGED
|
@@ -13,9 +13,13 @@ export default defineConfig({
|
|
| 13 |
port: 5173,
|
| 14 |
proxy: {
|
| 15 |
'/api': {
|
| 16 |
-
target: 'http://
|
| 17 |
changeOrigin: true,
|
| 18 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
},
|
| 20 |
},
|
| 21 |
})
|
|
|
|
| 13 |
port: 5173,
|
| 14 |
proxy: {
|
| 15 |
'/api': {
|
| 16 |
+
target: 'http://127.0.0.1:8000',
|
| 17 |
changeOrigin: true,
|
| 18 |
},
|
| 19 |
+
'/ws': {
|
| 20 |
+
target: 'ws://127.0.0.1:8000',
|
| 21 |
+
ws: true,
|
| 22 |
+
},
|
| 23 |
},
|
| 24 |
},
|
| 25 |
})
|