Update api.py
Browse files
api.py
CHANGED
|
@@ -1,35 +1,10 @@
|
|
| 1 |
import os
|
| 2 |
import traceback
|
| 3 |
-
import subprocess
|
| 4 |
-
import importlib
|
| 5 |
from flask import Flask, request, jsonify
|
| 6 |
from flask_cors import CORS
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
from langdetect import detect
|
| 9 |
from deep_translator import GoogleTranslator
|
| 10 |
-
|
| 11 |
-
# ---------- Ensure OpenAI version ----------
|
| 12 |
-
try:
|
| 13 |
-
subprocess.run(
|
| 14 |
-
["pip", "install", "--no-cache-dir", "--upgrade", "openai==1.12.0"],
|
| 15 |
-
check=True,
|
| 16 |
-
)
|
| 17 |
-
import openai
|
| 18 |
-
importlib.reload(openai)
|
| 19 |
-
print(f"✅ Using OpenAI SDK version {openai.__version__}")
|
| 20 |
-
except Exception as e:
|
| 21 |
-
print("⚠️ Could not ensure correct OpenAI version:", e)
|
| 22 |
-
import openai
|
| 23 |
-
|
| 24 |
-
# ---------- Patch huggingface_hub dynamically ----------
|
| 25 |
-
try:
|
| 26 |
-
import huggingface_hub
|
| 27 |
-
if not hasattr(huggingface_hub, "cached_download"):
|
| 28 |
-
print("⚙️ Adding compatibility patch for huggingface_hub.cached_download()")
|
| 29 |
-
huggingface_hub.cached_download = huggingface_hub.hf_hub_download
|
| 30 |
-
except Exception as e:
|
| 31 |
-
print("⚠️ Could not patch huggingface_hub:", e)
|
| 32 |
-
|
| 33 |
from sentence_transformers import SentenceTransformer
|
| 34 |
from pinecone import Pinecone
|
| 35 |
|
|
@@ -47,22 +22,24 @@ CORS(app, resources={r"/ask": {"origins": "*"}})
|
|
| 47 |
|
| 48 |
# ---------- OpenAI Client ----------
|
| 49 |
from openai import OpenAI
|
|
|
|
| 50 |
|
| 51 |
client = None
|
| 52 |
try:
|
| 53 |
if not OPENAI_API_KEY or OPENAI_API_KEY.strip() == "":
|
| 54 |
raise ValueError("Missing OPENAI_API_KEY in environment variables")
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
| 58 |
|
|
|
|
|
|
|
| 59 |
except Exception as e:
|
| 60 |
client = None
|
| 61 |
print(f"❌ Failed to initialize OpenAI client: {e}")
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
# ---------- Retriever ----------
|
| 67 |
retriever = None
|
| 68 |
try:
|
|
@@ -207,8 +184,11 @@ def ask():
|
|
| 207 |
else:
|
| 208 |
sys_prompt = system_prompt_fallback()
|
| 209 |
user_content = question
|
| 210 |
-
|
| 211 |
# ---------- OpenAI Query ----------
|
|
|
|
|
|
|
|
|
|
| 212 |
try:
|
| 213 |
response = client.chat.completions.create(
|
| 214 |
model="gpt-4o-mini",
|
|
@@ -219,11 +199,9 @@ def ask():
|
|
| 219 |
max_tokens=700,
|
| 220 |
)
|
| 221 |
answer = response.choices[0].message.content.strip()
|
| 222 |
-
|
| 223 |
except Exception as e:
|
| 224 |
traceback.print_exc()
|
| 225 |
-
return jsonify(format_answers(question, f"⚠️ OpenAI call failed: {e}",
|
| 226 |
-
|
| 227 |
|
| 228 |
return jsonify(format_answers(question, answer, results))
|
| 229 |
|
|
|
|
| 1 |
import os
|
| 2 |
import traceback
|
|
|
|
|
|
|
| 3 |
from flask import Flask, request, jsonify
|
| 4 |
from flask_cors import CORS
|
| 5 |
from dotenv import load_dotenv
|
| 6 |
from langdetect import detect
|
| 7 |
from deep_translator import GoogleTranslator
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
from sentence_transformers import SentenceTransformer
|
| 9 |
from pinecone import Pinecone
|
| 10 |
|
|
|
|
| 22 |
|
| 23 |
# ---------- OpenAI Client ----------
|
| 24 |
from openai import OpenAI
|
| 25 |
+
import inspect
|
| 26 |
|
| 27 |
client = None
|
| 28 |
try:
|
| 29 |
if not OPENAI_API_KEY or OPENAI_API_KEY.strip() == "":
|
| 30 |
raise ValueError("Missing OPENAI_API_KEY in environment variables")
|
| 31 |
|
| 32 |
+
# Handle Hugging Face’s automatic proxy injection safely
|
| 33 |
+
init_params = {"api_key": OPENAI_API_KEY}
|
| 34 |
+
if "proxies" in inspect.signature(OpenAI.__init__).parameters:
|
| 35 |
+
init_params["proxies"] = None
|
| 36 |
|
| 37 |
+
client = OpenAI(**init_params)
|
| 38 |
+
print(f"✅ Using OpenAI SDK version {client.__module__.split('.')[0]} (modern client)")
|
| 39 |
except Exception as e:
|
| 40 |
client = None
|
| 41 |
print(f"❌ Failed to initialize OpenAI client: {e}")
|
| 42 |
|
|
|
|
|
|
|
|
|
|
| 43 |
# ---------- Retriever ----------
|
| 44 |
retriever = None
|
| 45 |
try:
|
|
|
|
| 184 |
else:
|
| 185 |
sys_prompt = system_prompt_fallback()
|
| 186 |
user_content = question
|
| 187 |
+
|
| 188 |
# ---------- OpenAI Query ----------
|
| 189 |
+
if client is None:
|
| 190 |
+
return jsonify(format_answers(question, "⚠️ OpenAI client not initialized.", results)), 200
|
| 191 |
+
|
| 192 |
try:
|
| 193 |
response = client.chat.completions.create(
|
| 194 |
model="gpt-4o-mini",
|
|
|
|
| 199 |
max_tokens=700,
|
| 200 |
)
|
| 201 |
answer = response.choices[0].message.content.strip()
|
|
|
|
| 202 |
except Exception as e:
|
| 203 |
traceback.print_exc()
|
| 204 |
+
return jsonify(format_answers(question, f"⚠️ OpenAI call failed: {e}", results)), 200
|
|
|
|
| 205 |
|
| 206 |
return jsonify(format_answers(question, answer, results))
|
| 207 |
|