Naufal Arhab commited on
Commit
d46d99c
·
1 Parent(s): a01894f

fix(journal): unify LLM executor with Vikey reasoning models support, token boosting, and parameter compatibility

Browse files
backend/routers/ai.py CHANGED
@@ -662,6 +662,277 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
662
  return prompt, data_summary
663
 
664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
665
  @router.post("/analyze")
666
  async def analyze_pair(body: AIAnalyzeRequest, request: Request):
667
  """
@@ -788,262 +1059,21 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request):
788
 
789
  prompt, data_summary = _build_ai_prompt(symbol, signal, snapshots, body.question, global_regime, active_memory, journal_info)
790
 
791
- provider = req_provider
792
- analysis_text = ""
793
- used_model = body.model
794
-
795
  try:
796
- if provider == "gemini":
797
- # Multi-tier fallback: gemini-2.5-flash -> gemini-1.5-flash -> gemini-2.0-flash
798
- candidate_models = [body.model] if body.model else ["gemini-2.5-flash", "gemini-1.5-flash", "gemini-2.0-flash"]
799
- candidate_models = [m for m in candidate_models if m]
800
-
801
- gemini_max_tokens = body.max_tokens if (body.max_tokens and body.max_tokens > 0) else 8192
802
- payload = {
803
- "contents": [{"parts": [{"text": prompt}]}],
804
- "generationConfig": {
805
- "temperature": 0.15, # Deterministic & sharp
806
- "maxOutputTokens": gemini_max_tokens, # Token-efficient with thinking token headroom
807
- },
808
- }
809
-
810
- last_err = None
811
- client = get_ai_http_client()
812
- if True:
813
- for candidate in candidate_models:
814
- gemini_url = f"https://generativelanguage.googleapis.com/v1beta/models/{candidate}:generateContent"
815
- headers = {
816
- "x-goog-api-key": clean_api_key,
817
- "Content-Type": "application/json",
818
- }
819
- resp = await client.post(gemini_url, headers=headers, json=payload)
820
-
821
- if resp.status_code == 200:
822
- res_json = resp.json()
823
- candidates = res_json.get("candidates", [])
824
- if candidates:
825
- parts = candidates[0].get("content", {}).get("parts", [])
826
- text_chunks = [
827
- p.get("text", "")
828
- for p in parts
829
- if isinstance(p, dict) and p.get("text")
830
- ]
831
- if text_chunks:
832
- analysis_text = "".join(text_chunks)
833
- used_model = candidate
834
- break
835
- elif resp.status_code == 429:
836
- raise HTTPException(
837
- status_code=429,
838
- detail="Batas kuota gratis (Rate Limit) API Key Gemini Anda terlampaui. Tunggu 30 detik atau gunakan API Key lain.",
839
- )
840
- elif resp.status_code in [400, 403]:
841
- err_text = _sanitize_error_message(resp.text, clean_api_key)
842
- if "API_KEY_INVALID" in err_text or "API key not valid" in err_text:
843
- raise HTTPException(status_code=400, detail="API Key Gemini tidak valid. Harap periksa kembali key Anda.")
844
- last_err = err_text
845
- else:
846
- last_err = _sanitize_error_message(resp.text, clean_api_key)
847
-
848
- if not analysis_text:
849
- err_msg = last_err or "Model Gemini tidak tersedia."
850
- raise HTTPException(status_code=502, detail=f"Gagal memanggil Gemini: {_sanitize_error_message(err_msg, clean_api_key)}")
851
-
852
- elif provider in ["vikey", "openai", "groq", "openrouter", "custom"]:
853
- # Route to OpenAI-compatible endpoint
854
- if provider == "vikey":
855
- base_url = "https://api.vikey.ai/v1"
856
- default_model = "anthropic/claude-fable-5"
857
- elif provider == "groq":
858
- base_url = "https://api.groq.com/openai/v1"
859
- default_model = "llama-3.3-70b-versatile"
860
- elif provider == "openrouter":
861
- base_url = "https://openrouter.ai/api/v1"
862
- default_model = "anthropic/claude-3.5-sonnet"
863
- elif provider == "custom":
864
- base_url = (body.base_url or "https://api.vikey.ai/v1").rstrip("/")
865
- default_model = "anthropic/claude-fable-5"
866
- else: # openai
867
- base_url = "https://api.openai.com/v1"
868
- default_model = "gpt-4o-mini"
869
-
870
- if body.base_url and body.base_url.strip():
871
- b_url = body.base_url.strip().rstrip("/")
872
- if not b_url.endswith("/v1") and not "/v1" in b_url:
873
- b_url = f"{b_url}/v1"
874
- base_url = b_url
875
-
876
- model_name = body.model.strip().strip('"\'') if (body.model and body.model.strip()) else default_model
877
- used_model = model_name
878
-
879
- # Calculate safe max_tokens: reasoning models (Fable, Sonnet, DeepSeek R1/V4, OpenAI o-series)
880
- # spend tokens on internal thinking (Chain-of-Thought) before writing the answer.
881
- # 8192 - 10240 tokens gives generous budget for both reasoning and the final response.
882
- is_heavy_reasoner = any(k in model_name.lower() for k in ["r1", "reasoning", "fable", "opus", "sonnet", "deepseek-v4", "o1", "o3"])
883
- default_token_budget = 10240 if is_heavy_reasoner else 8192
884
- target_max_tokens = body.max_tokens if (body.max_tokens and body.max_tokens > 0) else default_token_budget
885
-
886
- is_o_series = any(prefix in model_name.lower() for prefix in ["o1", "o3", "o-1", "o-3"])
887
-
888
- # Universal format compatible with all LLM proxies (Claude, DeepSeek, GPT, Qwen, etc.)
889
- # Keep payload clean and strictly conforming to standard OpenAI chat/completions spec
890
- payload: dict[str, Any] = {
891
- "model": model_name,
892
- "messages": [
893
- {
894
- "role": "user",
895
- "content": (
896
- "[Instruksi: Damian — Senior Institutional Crypto Derivatives Quant Strategist. Analisa empiris, objektif, padat, anti-halusinasi. "
897
- "Fokus langsung pada intisari data pasar. Jika model memiliki internal reasoning/thinking, lakukan reasoning secara padat dan efisien lalu sajikan analisa lengkap.]\n\n"
898
- f"{prompt}"
899
- ),
900
- }
901
- ],
902
- }
903
-
904
- if is_o_series:
905
- # OpenAI o-series does not accept temperature and uses max_completion_tokens
906
- payload["max_completion_tokens"] = target_max_tokens
907
- else:
908
- payload["temperature"] = 0.2
909
- payload["max_tokens"] = target_max_tokens
910
-
911
- headers = {
912
- "Authorization": f"Bearer {clean_api_key}",
913
- "Content-Type": "application/json",
914
- }
915
- if "openrouter" in base_url or provider == "openrouter":
916
- headers["HTTP-Referer"] = "https://perpsai.local"
917
- headers["X-Title"] = "PerpsAI"
918
-
919
- client = get_ai_http_client()
920
- if True:
921
- target_url = f"{base_url}/chat/completions"
922
- resp = await client.post(
923
- target_url,
924
- headers=headers,
925
- json=payload,
926
- )
927
-
928
- # Defensive Multi-tier Fallback if gateway returned 400 Bad Request
929
- if resp.status_code == 400:
930
- logger.warning(
931
- "[%s] %s returned 400 for model '%s' (body: %s). Initiating smart fallback...",
932
- symbol,
933
- provider,
934
- model_name,
935
- resp.text[:150],
936
- )
937
-
938
- # Fallback Attempt 1: If model has a slash prefix (e.g. 'anthropic/claude-fable-5'), try stripped model name
939
- if "/" in model_name:
940
- stripped_model = model_name.split("/", 1)[1]
941
- payload_var = dict(payload)
942
- payload_var["model"] = stripped_model
943
- resp_var = await client.post(target_url, headers=headers, json=payload_var)
944
- if resp_var.status_code == 200:
945
- resp = resp_var
946
- used_model = stripped_model
947
-
948
- # Fallback Attempt 2: If model doesn't have prefix and provider is vikey, try with 'anthropic/' prefix
949
- elif provider == "vikey" and not "/" in model_name:
950
- prefixed_model = f"anthropic/{model_name}"
951
- payload_var = dict(payload)
952
- payload_var["model"] = prefixed_model
953
- resp_var = await client.post(target_url, headers=headers, json=payload_var)
954
- if resp_var.status_code == 200:
955
- resp = resp_var
956
- used_model = prefixed_model
957
-
958
- # Fallback Attempt 3: Parameter compatibility (e.g. o-series / reasoning models rejecting temperature or max_tokens)
959
- if resp.status_code == 400:
960
- payload_compat = dict(payload)
961
- payload_compat.pop("temperature", None)
962
- payload_compat.pop("max_tokens", None)
963
- payload_compat["max_completion_tokens"] = target_max_tokens
964
- resp_compat = await client.post(target_url, headers=headers, json=payload_compat)
965
- if resp_compat.status_code == 200:
966
- resp = resp_compat
967
-
968
- # Defensive Automatic Retry for Reasoning Token Exhaustion (502 from Vikey/OpenRouter/Anthropic gateway)
969
- if resp.status_code == 502:
970
- resp_lower = resp.text.lower()
971
- if any(phrase in resp_lower for phrase in ["max_tokens budget on reasoning", "entire max_tokens budget", "reasoning tokens count against", "increase max_tokens"]):
972
- boosted_tokens = max(target_max_tokens * 2, 16384)
973
- logger.warning(
974
- "[%s] %s returned 502 (reasoning tokens exhausted at %d). Auto-retrying with boosted max_tokens=%d...",
975
- symbol,
976
- provider,
977
- target_max_tokens,
978
- boosted_tokens,
979
- )
980
- payload_retry = dict(payload)
981
- if "max_completion_tokens" in payload_retry:
982
- payload_retry["max_completion_tokens"] = boosted_tokens
983
- else:
984
- payload_retry["max_tokens"] = boosted_tokens
985
-
986
- resp_retry = await client.post(target_url, headers=headers, json=payload_retry)
987
- if resp_retry.status_code == 200:
988
- resp = resp_retry
989
-
990
- if resp.status_code != 200:
991
- err_msg = resp.text
992
- try:
993
- err_json = resp.json()
994
- err_msg = err_json.get("error", {}).get("message", err_msg)
995
- except Exception:
996
- pass
997
- sanitized_err = _sanitize_error_message(err_msg, clean_api_key)
998
- logger.error("[%s] AI Provider returned %d: %s", symbol, resp.status_code, sanitized_err)
999
-
1000
- user_hint = ""
1001
- if resp.status_code == 400:
1002
- user_hint = f" — Periksa model '{model_name}' atau saldo di akun {provider.upper()} Anda."
1003
- elif resp.status_code in [401, 403]:
1004
- user_hint = f" — API Key {provider.upper()} tidak valid atau kedaluwarsa."
1005
- elif resp.status_code == 402:
1006
- user_hint = f" — Saldo atau kuota token {provider.upper()} Anda habis."
1007
- elif resp.status_code == 429:
1008
- user_hint = f" — Rate limit {provider.upper()} tercapai, harap coba sesaat lagi."
1009
- elif resp.status_code == 502 and "reasoning" in sanitized_err.lower():
1010
- user_hint = " — Model AI menghabiskan budget token pada proses thinking internal. Sistem telah mencoba auto-retry dengan token lebih besar."
1011
-
1012
- raise HTTPException(
1013
- status_code=resp.status_code if resp.status_code in [400, 401, 402, 403, 404, 429] else 502,
1014
- detail=f"{provider.upper()} API Error ({resp.status_code}): {sanitized_err}{user_hint}",
1015
- )
1016
-
1017
- res_json = resp.json()
1018
- choices = res_json.get("choices", [])
1019
- if not choices:
1020
- raise HTTPException(status_code=500, detail="API tidak mengembalikan konten analisa.")
1021
-
1022
- msg = choices[0].get("message") or {}
1023
- raw_content = msg.get("content") or msg.get("reasoning_content") or choices[0].get("text") or ""
1024
-
1025
- # Anthropic / Claude or certain proxy models may return content as a list of typed blocks
1026
- if isinstance(raw_content, list):
1027
- chunks = []
1028
- for part in raw_content:
1029
- if isinstance(part, dict):
1030
- chunks.append(part.get("text", "") or part.get("content", ""))
1031
- elif isinstance(part, str):
1032
- chunks.append(part)
1033
- else:
1034
- chunks.append(str(part))
1035
- analysis_text = "".join(chunks).strip()
1036
- elif isinstance(raw_content, dict):
1037
- analysis_text = str(raw_content.get("text", "") or raw_content.get("content", "")).strip()
1038
- else:
1039
- analysis_text = str(raw_content).strip() if raw_content is not None else ""
1040
-
1041
- if not analysis_text:
1042
- raise HTTPException(status_code=500, detail="Model AI tidak memberikan teks analisa (respon kosong).")
1043
-
1044
- else:
1045
- raise HTTPException(status_code=400, detail=f"Provider '{provider}' tidak didukung. Gunakan 'vikey', 'gemini', atau 'openai'.")
1046
-
1047
  except HTTPException:
1048
  raise
1049
  except Exception as exc:
@@ -1056,7 +1086,7 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request):
1056
 
1057
  response_payload = {
1058
  "symbol": symbol,
1059
- "provider": provider,
1060
  "model": used_model,
1061
  "bias": bias,
1062
  "analysis": analysis_text,
 
662
  return prompt, data_summary
663
 
664
 
665
+ async def execute_llm_completion(
666
+ provider: str,
667
+ clean_api_key: str,
668
+ model_name: str | None,
669
+ prompt: str,
670
+ base_url: str | None = None,
671
+ max_tokens: int | None = None,
672
+ system_instruction: str | None = None,
673
+ context_label: str = "AI",
674
+ ) -> tuple[str, str]:
675
+ """
676
+ Unified, robust LLM completion executor supporting:
677
+ - Native Google Gemini API with multi-tier fallback (gemini-2.5-flash -> 1.5-flash -> 2.0-flash)
678
+ - OpenAI-compatible proxies (Vikey, OpenAI, Groq, OpenRouter, Custom)
679
+ - Automatic reasoning token budgeting & auto-retry on 502 exhaustion
680
+ - Compatibility stripping of temperature/max_tokens for o-series, luna, astra, sol, etc.
681
+ - Fallback model prefix handling (e.g. anthropic/claude-fable-5 <-> claude-fable-5)
682
+ - Friendly localized user error hints (400, 401, 402, 403, 429, 502)
683
+ Returns (completed_text, model_used).
684
+ """
685
+ clean_key = clean_api_key.strip().strip('"\'')
686
+ prov = provider.lower().strip()
687
+ client = get_ai_http_client()
688
+
689
+ if prov == "gemini":
690
+ candidate_models = []
691
+ if model_name and "gemini" in model_name.lower():
692
+ candidate_models.append(model_name.strip())
693
+ candidate_models.extend(["gemini-2.5-flash", "gemini-1.5-flash", "gemini-2.0-flash"])
694
+ candidate_models = list(dict.fromkeys(candidate_models))
695
+
696
+ gemini_max_tokens = max_tokens if (max_tokens and max_tokens > 0) else 8192
697
+ full_gemini_prompt = f"[{system_instruction}]\n\n{prompt}" if system_instruction else prompt
698
+ payload = {
699
+ "contents": [{"parts": [{"text": full_gemini_prompt}]}],
700
+ "generationConfig": {
701
+ "temperature": 0.15,
702
+ "maxOutputTokens": gemini_max_tokens,
703
+ },
704
+ }
705
+
706
+ last_err = None
707
+ for candidate in candidate_models:
708
+ gemini_url = f"https://generativelanguage.googleapis.com/v1beta/models/{candidate}:generateContent"
709
+ headers = {
710
+ "x-goog-api-key": clean_key,
711
+ "Content-Type": "application/json",
712
+ }
713
+ resp = await client.post(gemini_url, headers=headers, json=payload, timeout=60.0)
714
+
715
+ if resp.status_code == 200:
716
+ res_json = resp.json()
717
+ candidates = res_json.get("candidates", [])
718
+ if candidates:
719
+ parts = candidates[0].get("content", {}).get("parts", [])
720
+ text_chunks = [
721
+ p.get("text", "")
722
+ for p in parts
723
+ if isinstance(p, dict) and p.get("text")
724
+ ]
725
+ if text_chunks:
726
+ return "".join(text_chunks).strip(), candidate
727
+ elif resp.status_code == 429:
728
+ raise HTTPException(
729
+ status_code=429,
730
+ detail="Batas kuota gratis (Rate Limit) API Key Gemini Anda terlampaui. Tunggu 30 detik atau gunakan API Key lain.",
731
+ )
732
+ elif resp.status_code in [400, 403]:
733
+ err_text = _sanitize_error_message(resp.text, clean_key)
734
+ if "API_KEY_INVALID" in err_text or "API key not valid" in err_text:
735
+ raise HTTPException(status_code=400, detail="API Key Gemini tidak valid. Harap periksa kembali key Anda.")
736
+ last_err = err_text
737
+ else:
738
+ last_err = _sanitize_error_message(resp.text, clean_key)
739
+
740
+ err_msg = last_err or "Model Gemini tidak tersedia."
741
+ raise HTTPException(status_code=502, detail=f"Gagal memanggil Gemini: {_sanitize_error_message(err_msg, clean_key)}")
742
+
743
+ elif prov in ["vikey", "openai", "groq", "openrouter", "custom"]:
744
+ if prov == "vikey":
745
+ resolved_base_url = "https://api.vikey.ai/v1"
746
+ default_model = "anthropic/claude-fable-5"
747
+ elif prov == "groq":
748
+ resolved_base_url = "https://api.groq.com/openai/v1"
749
+ default_model = "llama-3.3-70b-versatile"
750
+ elif prov == "openrouter":
751
+ resolved_base_url = "https://openrouter.ai/api/v1"
752
+ default_model = "anthropic/claude-3.5-sonnet"
753
+ elif prov == "custom":
754
+ resolved_base_url = (base_url or "https://api.vikey.ai/v1").rstrip("/")
755
+ default_model = "anthropic/claude-fable-5"
756
+ else: # openai
757
+ resolved_base_url = "https://api.openai.com/v1"
758
+ default_model = "gpt-4o-mini"
759
+
760
+ if base_url and base_url.strip():
761
+ b_url = base_url.strip().rstrip("/")
762
+ if not b_url.endswith("/v1") and not "/v1" in b_url:
763
+ b_url = f"{b_url}/v1"
764
+ resolved_base_url = b_url
765
+
766
+ resolved_model = model_name.strip().strip('"\'') if (model_name and model_name.strip()) else default_model
767
+ used_model = resolved_model
768
+
769
+ # Calculate safe max_tokens: reasoning models (Fable, Sonnet, DeepSeek R1/V4, Luna, Astra, Sol, OpenAI o-series)
770
+ is_heavy_reasoner = any(k in resolved_model.lower() for k in [
771
+ "r1", "reasoning", "fable", "opus", "sonnet", "deepseek-v4",
772
+ "o1", "o3", "o-1", "o-3", "luna", "astra", "sol"
773
+ ])
774
+ default_token_budget = 10240 if is_heavy_reasoner else 8192
775
+ target_max_tokens = max_tokens if (max_tokens and max_tokens > 0) else default_token_budget
776
+
777
+ # Reasoning models that disallow the standard 'temperature' and 'max_tokens' parameters
778
+ is_reasoning_model = any(prefix in resolved_model.lower() for prefix in [
779
+ "o1", "o3", "o-1", "o-3", "luna", "astra", "sol"
780
+ ])
781
+
782
+ user_content = f"[{system_instruction}]\n\n{prompt}" if system_instruction else prompt
783
+ payload: dict[str, Any] = {
784
+ "model": resolved_model,
785
+ "messages": [
786
+ {
787
+ "role": "user",
788
+ "content": user_content,
789
+ }
790
+ ],
791
+ }
792
+
793
+ if is_reasoning_model:
794
+ payload["max_completion_tokens"] = target_max_tokens
795
+ else:
796
+ payload["temperature"] = 0.2
797
+ payload["max_tokens"] = target_max_tokens
798
+
799
+ headers = {
800
+ "Authorization": f"Bearer {clean_key}",
801
+ "Content-Type": "application/json",
802
+ }
803
+ if "openrouter" in resolved_base_url or prov in ["openrouter", "vikey"]:
804
+ headers["HTTP-Referer"] = "https://perpsai.local"
805
+ headers["X-Title"] = "PerpsAI"
806
+
807
+ target_url = f"{resolved_base_url}/chat/completions"
808
+ resp = await client.post(
809
+ target_url,
810
+ headers=headers,
811
+ json=payload,
812
+ timeout=90.0,
813
+ )
814
+
815
+ # Defensive Multi-tier Fallback if gateway returned 400 Bad Request
816
+ if resp.status_code == 400:
817
+ logger.warning(
818
+ "[%s] %s returned 400 for model '%s' (body: %s). Initiating smart fallback...",
819
+ context_label,
820
+ prov,
821
+ resolved_model,
822
+ resp.text[:150],
823
+ )
824
+
825
+ # Fallback Attempt 1: If model has a slash prefix, try stripped model name
826
+ if "/" in resolved_model:
827
+ stripped_model = resolved_model.split("/", 1)[1]
828
+ payload_var = dict(payload)
829
+ payload_var["model"] = stripped_model
830
+ resp_var = await client.post(target_url, headers=headers, json=payload_var, timeout=90.0)
831
+ if resp_var.status_code == 200:
832
+ resp = resp_var
833
+ used_model = stripped_model
834
+
835
+ # Fallback Attempt 2: If model doesn't have prefix and provider is vikey, try with 'anthropic/' prefix
836
+ elif prov == "vikey" and not "/" in resolved_model:
837
+ prefixed_model = f"anthropic/{resolved_model}"
838
+ payload_var = dict(payload)
839
+ payload_var["model"] = prefixed_model
840
+ resp_var = await client.post(target_url, headers=headers, json=payload_var, timeout=90.0)
841
+ if resp_var.status_code == 200:
842
+ resp = resp_var
843
+ used_model = prefixed_model
844
+
845
+ # Fallback Attempt 3: Parameter compatibility (e.g. o-series / reasoning models rejecting temperature or max_tokens)
846
+ if resp.status_code == 400:
847
+ payload_compat = dict(payload)
848
+ payload_compat.pop("temperature", None)
849
+ payload_compat.pop("max_tokens", None)
850
+ payload_compat["max_completion_tokens"] = target_max_tokens
851
+ resp_compat = await client.post(target_url, headers=headers, json=payload_compat, timeout=90.0)
852
+ if resp_compat.status_code == 200:
853
+ resp = resp_compat
854
+
855
+ # Defensive Automatic Retry for Reasoning Token Exhaustion (502 from Vikey/OpenRouter/Anthropic gateway)
856
+ if resp.status_code == 502:
857
+ resp_lower = resp.text.lower()
858
+ if any(phrase in resp_lower for phrase in ["max_tokens budget on reasoning", "entire max_tokens budget", "reasoning tokens count against", "increase max_tokens"]):
859
+ boosted_tokens = max(target_max_tokens * 2, 16384)
860
+ logger.warning(
861
+ "[%s] %s returned 502 (reasoning tokens exhausted at %d). Auto-retrying with boosted max_tokens=%d...",
862
+ context_label,
863
+ prov,
864
+ target_max_tokens,
865
+ boosted_tokens,
866
+ )
867
+ payload_retry = dict(payload)
868
+ if "max_completion_tokens" in payload_retry:
869
+ payload_retry["max_completion_tokens"] = boosted_tokens
870
+ else:
871
+ payload_retry["max_tokens"] = boosted_tokens
872
+
873
+ resp_retry = await client.post(target_url, headers=headers, json=payload_retry, timeout=90.0)
874
+ if resp_retry.status_code == 200:
875
+ resp = resp_retry
876
+
877
+ if resp.status_code != 200:
878
+ err_msg = resp.text
879
+ try:
880
+ err_json = resp.json()
881
+ err_msg = err_json.get("error", {}).get("message", err_msg)
882
+ except Exception:
883
+ pass
884
+ sanitized_err = _sanitize_error_message(err_msg, clean_key)
885
+ logger.error("[%s] AI Provider returned %d: %s", context_label, resp.status_code, sanitized_err)
886
+
887
+ user_hint = ""
888
+ if resp.status_code == 400:
889
+ user_hint = f" — Periksa model '{resolved_model}' atau saldo di akun {prov.upper()} Anda."
890
+ elif resp.status_code in [401, 403]:
891
+ user_hint = f" — API Key {prov.upper()} tidak valid atau kedaluwarsa."
892
+ elif resp.status_code == 402:
893
+ user_hint = f" — Saldo atau kuota token {prov.upper()} Anda habis."
894
+ elif resp.status_code == 429:
895
+ user_hint = f" — Rate limit {prov.upper()} tercapai, harap coba sesaat lagi."
896
+ elif resp.status_code == 502 and "reasoning" in sanitized_err.lower():
897
+ user_hint = " — Model AI menghabiskan budget token pada proses thinking internal. Sistem telah mencoba auto-retry dengan token lebih besar."
898
+
899
+ raise HTTPException(
900
+ status_code=resp.status_code if resp.status_code in [400, 401, 402, 403, 404, 429] else 502,
901
+ detail=f"{prov.upper()} API Error ({resp.status_code}): {sanitized_err}{user_hint}",
902
+ )
903
+
904
+ res_json = resp.json()
905
+ choices = res_json.get("choices", [])
906
+ if not choices:
907
+ raise HTTPException(status_code=500, detail="API tidak mengembalikan konten jawaban.")
908
+
909
+ msg = choices[0].get("message") or {}
910
+ raw_content = msg.get("content") or msg.get("reasoning_content") or choices[0].get("text") or ""
911
+
912
+ if isinstance(raw_content, list):
913
+ chunks = []
914
+ for part in raw_content:
915
+ if isinstance(part, dict):
916
+ chunks.append(part.get("text", "") or part.get("content", ""))
917
+ elif isinstance(part, str):
918
+ chunks.append(part)
919
+ else:
920
+ chunks.append(str(part))
921
+ text_result = "".join(chunks).strip()
922
+ elif isinstance(raw_content, dict):
923
+ text_result = str(raw_content.get("text", "") or raw_content.get("content", "")).strip()
924
+ else:
925
+ text_result = str(raw_content).strip() if raw_content is not None else ""
926
+
927
+ if not text_result:
928
+ raise HTTPException(status_code=500, detail="Model AI tidak memberikan teks jawaban (respon kosong).")
929
+
930
+ return text_result, used_model
931
+
932
+ else:
933
+ raise HTTPException(status_code=400, detail=f"Provider '{prov}' tidak didukung. Gunakan 'vikey', 'gemini', 'openai', atau 'groq'.")
934
+
935
+
936
  @router.post("/analyze")
937
  async def analyze_pair(body: AIAnalyzeRequest, request: Request):
938
  """
 
1059
 
1060
  prompt, data_summary = _build_ai_prompt(symbol, signal, snapshots, body.question, global_regime, active_memory, journal_info)
1061
 
 
 
 
 
1062
  try:
1063
+ analysis_text, used_model = await execute_llm_completion(
1064
+ provider=req_provider,
1065
+ clean_api_key=clean_api_key,
1066
+ model_name=body.model,
1067
+ prompt=prompt,
1068
+ base_url=body.base_url,
1069
+ max_tokens=body.max_tokens,
1070
+ system_instruction=(
1071
+ "Instruksi: Damian — Senior Institutional Crypto Derivatives Quant Strategist. "
1072
+ "Analisa empiris, objektif, padat, anti-halusinasi. Fokus langsung pada intisari data pasar. "
1073
+ "Jika model memiliki internal reasoning/thinking, lakukan reasoning secara padat dan efisien lalu sajikan analisa lengkap."
1074
+ ),
1075
+ context_label=symbol,
1076
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1077
  except HTTPException:
1078
  raise
1079
  except Exception as exc:
 
1086
 
1087
  response_payload = {
1088
  "symbol": symbol,
1089
+ "provider": req_provider,
1090
  "model": used_model,
1091
  "bias": bias,
1092
  "analysis": analysis_text,
backend/routers/journal.py CHANGED
@@ -365,145 +365,20 @@ Format Output Wajib:
365
  used_model = body.model or ""
366
 
367
  try:
368
- from routers.ai import get_ai_http_client, _sanitize_error_message
369
- client = get_ai_http_client()
370
-
371
- if provider == "gemini":
372
- # Multi-tier fallback for Gemini: requested model -> gemini-2.5-flash -> gemini-1.5-flash -> gemini-2.0-flash
373
- candidate_models = []
374
- if body.model and "gemini" in body.model.lower():
375
- candidate_models.append(body.model.strip())
376
- candidate_models.extend(["gemini-2.5-flash", "gemini-1.5-flash", "gemini-2.0-flash"])
377
- # Remove duplicates preserving order
378
- candidate_models = list(dict.fromkeys(candidate_models))
379
-
380
- payload = {
381
- "contents": [{"parts": [{"text": audit_prompt}]}],
382
- "generationConfig": {
383
- "temperature": 0.2,
384
- "maxOutputTokens": 4096,
385
- },
386
- }
387
-
388
- last_err = None
389
- for candidate in candidate_models:
390
- gemini_url = f"https://generativelanguage.googleapis.com/v1beta/models/{candidate}:generateContent"
391
- headers = {
392
- "x-goog-api-key": clean_api_key,
393
- "Content-Type": "application/json",
394
- }
395
- resp = await client.post(gemini_url, headers=headers, json=payload, timeout=60.0)
396
- if resp.status_code == 200:
397
- res_json = resp.json()
398
- candidates = res_json.get("candidates", [])
399
- if candidates:
400
- parts = candidates[0].get("content", {}).get("parts", [])
401
- chunks = [
402
- p.get("text", "")
403
- for p in parts
404
- if isinstance(p, dict) and p.get("text")
405
- ]
406
- if chunks:
407
- audit_summary = "".join(chunks).strip()
408
- used_model = candidate
409
- break
410
- elif resp.status_code == 429:
411
- raise HTTPException(
412
- status_code=429,
413
- detail="Batas kuota gratis (Rate Limit) API Key Gemini Anda terlampaui. Tunggu sejenak atau gunakan API Key lain.",
414
- )
415
- elif resp.status_code in [400, 403]:
416
- err_text = _sanitize_error_message(resp.text, clean_api_key)
417
- if "API_KEY_INVALID" in err_text or "API key not valid" in err_text:
418
- raise HTTPException(status_code=400, detail="API Key Gemini tidak valid. Harap periksa kembali key Anda.")
419
- last_err = err_text
420
- else:
421
- last_err = _sanitize_error_message(resp.text, clean_api_key)
422
-
423
- if not audit_summary:
424
- err_msg = last_err or "Model Gemini tidak tersedia untuk audit."
425
- raise HTTPException(status_code=502, detail=f"Gagal memanggil Gemini: {_sanitize_error_message(err_msg, clean_api_key)}")
426
-
427
- else:
428
- # Route to OpenAI-compatible endpoint (Vikey, OpenAI, Groq, OpenRouter, Custom)
429
- if provider == "vikey":
430
- base_url = "https://api.vikey.ai/v1"
431
- default_model = "anthropic/claude-fable-5"
432
- elif provider == "groq":
433
- base_url = "https://api.groq.com/openai/v1"
434
- default_model = "llama-3.3-70b-versatile"
435
- elif provider == "openrouter":
436
- base_url = "https://openrouter.ai/api/v1"
437
- default_model = "anthropic/claude-3.5-sonnet"
438
- elif provider == "custom":
439
- base_url = (body.base_url or "https://api.vikey.ai/v1").rstrip("/")
440
- default_model = "anthropic/claude-fable-5"
441
- else: # openai
442
- base_url = "https://api.openai.com/v1"
443
- default_model = "gpt-4o-mini"
444
-
445
- if body.base_url and body.base_url.strip():
446
- b_url = body.base_url.strip().rstrip("/")
447
- if not b_url.endswith("/v1") and not "/v1" in b_url:
448
- b_url = f"{b_url}/v1"
449
- base_url = b_url
450
-
451
- # Sanitize model name against provider mismatch
452
- model_name = body.model.strip().strip('"\'') if (body.model and body.model.strip()) else default_model
453
- if provider == "groq" and not any(k in model_name.lower() for k in ["llama", "mixtral", "gemma", "deepseek"]):
454
- model_name = default_model
455
- elif provider == "openai" and not any(k in model_name.lower() for k in ["gpt", "o1", "o3", "o-1", "o-3"]):
456
- model_name = default_model
457
- elif provider == "vikey" and not ("/" in model_name or "claude" in model_name.lower() or "deepseek" in model_name.lower()):
458
- model_name = default_model
459
-
460
- used_model = model_name
461
-
462
- payload = {
463
- "model": model_name,
464
- "messages": [
465
- {
466
- "role": "user",
467
- "content": audit_prompt,
468
- }
469
- ],
470
- "temperature": 0.2,
471
- "max_tokens": 4096,
472
- }
473
-
474
- headers = {
475
- "Authorization": f"Bearer {clean_api_key}",
476
- "Content-Type": "application/json",
477
- }
478
-
479
- resp = await client.post(f"{base_url}/chat/completions", headers=headers, json=payload, timeout=60.0)
480
- if resp.status_code == 200:
481
- res_json = resp.json()
482
- choices = res_json.get("choices", [])
483
- if choices:
484
- msg = choices[0].get("message") or {}
485
- raw_content = msg.get("content") or msg.get("reasoning_content") or choices[0].get("text") or ""
486
- if isinstance(raw_content, list):
487
- chunks = []
488
- for part in raw_content:
489
- if isinstance(part, dict):
490
- chunks.append(part.get("text", "") or part.get("content", ""))
491
- elif isinstance(part, str):
492
- chunks.append(part)
493
- else:
494
- chunks.append(str(part))
495
- audit_summary = "".join(chunks).strip()
496
- elif isinstance(raw_content, dict):
497
- audit_summary = str(raw_content.get("text", "") or raw_content.get("content", "")).strip()
498
- else:
499
- audit_summary = str(raw_content).strip() if raw_content is not None else ""
500
- else:
501
- logger.error("Audit LLM request failed: %d - %s", resp.status_code, resp.text[:200])
502
- clean_err = _sanitize_error_message(resp.text[:150], clean_api_key)
503
- raise HTTPException(
504
- status_code=502,
505
- detail=f"Gagal memanggil model AI untuk audit ({resp.status_code}): {clean_err}",
506
- )
507
  except HTTPException:
508
  raise
509
  except Exception as exc:
 
365
  used_model = body.model or ""
366
 
367
  try:
368
+ from routers.ai import execute_llm_completion
369
+ audit_summary, used_model = await execute_llm_completion(
370
+ provider=provider,
371
+ clean_api_key=clean_api_key,
372
+ model_name=body.model,
373
+ prompt=audit_prompt,
374
+ base_url=body.base_url,
375
+ max_tokens=10240,
376
+ system_instruction=(
377
+ "Peran: Chief Risk Officer & Quantitative Trading Audit Committee. "
378
+ "Lakukan Root Cause Analysis empiris terhadap trade gagal dan rumuskan 3-4 Aturan Pengaman Emas."
379
+ ),
380
+ context_label="JOURNAL_AUDIT",
381
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382
  except HTTPException:
383
  raise
384
  except Exception as exc:
tests/test_journal.py CHANGED
@@ -213,3 +213,42 @@ async def test_synthesize_damian_memory_gemini_provider():
213
  mock_save.assert_called_once()
214
  mock_mark.assert_called_once_with([10])
215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  mock_save.assert_called_once()
214
  mock_mark.assert_called_once_with([10])
215
 
216
+
217
+ @pytest.mark.anyio
218
+ async def test_synthesize_damian_memory_vikey_provider():
219
+ """Verify synthesize_damian_memory works with Vikey provider and reasoning models."""
220
+ from unittest.mock import MagicMock, AsyncMock, patch
221
+ from routers.journal import synthesize_damian_memory, SynthesizeAuditRequest
222
+
223
+ req = SynthesizeAuditRequest(provider="vikey", api_key="vk_test_12345", model="openai/gpt-5.6-luna", force=True)
224
+ mock_request = MagicMock()
225
+ mock_request.headers.get.return_value = None
226
+
227
+ mock_resp = MagicMock()
228
+ mock_resp.status_code = 200
229
+ mock_resp.json.return_value = {
230
+ "choices": [
231
+ {
232
+ "message": {
233
+ "role": "assistant",
234
+ "content": "### 🛡️ ATURAN PENGAMAN EMAS DAMIAN\n1. **Anti-Trap Luna**: Periksa CVD sebelum entry.",
235
+ }
236
+ }
237
+ ]
238
+ }
239
+
240
+ with patch("routers.journal.async_save_damian_memory", new_callable=AsyncMock) as mock_save, \
241
+ patch("routers.journal.async_mark_trades_as_audited", new_callable=AsyncMock) as mock_mark, \
242
+ patch("routers.journal.async_get_unaudited_failed_trades", new_callable=AsyncMock) as mock_trades, \
243
+ patch("httpx.AsyncClient.post", new_callable=AsyncMock, return_value=mock_resp):
244
+
245
+ mock_trades.return_value = [{"id": 11, "symbol": "NILUSDT", "bias": "SHORT", "failure_tag": "WICK_HUNT"}]
246
+ mock_save.return_value = {"id": 2, "batch_index": 2, "audit_summary": "Aturan Pengaman Vikey"}
247
+
248
+ res = await synthesize_damian_memory(req, mock_request)
249
+ assert res["success"] is True
250
+ assert "Audit 1 trade gagal" in res["message"]
251
+ mock_save.assert_called_once()
252
+ mock_mark.assert_called_once_with([11])
253
+
254
+