making api not visible
Browse files- app/llm.py +181 -184
app/llm.py
CHANGED
|
@@ -1,184 +1,181 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import yaml
|
| 3 |
-
import requests
|
| 4 |
-
from decouple import config as decouple_config
|
| 5 |
-
from datetime import datetime
|
| 6 |
-
|
| 7 |
-
# For local LLM using transformers
|
| 8 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 9 |
-
import torch
|
| 10 |
-
|
| 11 |
-
from google import genai
|
| 12 |
-
from google.genai import types
|
| 13 |
-
# Import the Groq client
|
| 14 |
-
from groq import Groq
|
| 15 |
-
|
| 16 |
-
class LLMProcessor:
|
| 17 |
-
def __init__(self):
|
| 18 |
-
"""
|
| 19 |
-
Initialize the LLMProcessor by loading configuration and initializing all LLM clients.
|
| 20 |
-
"""
|
| 21 |
-
# Compute the absolute path to the config file (located at <project_root>/config/config.yml)
|
| 22 |
-
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
| 23 |
-
config_path = os.path.join(base_dir, "config", "config.yml")
|
| 24 |
-
with open(config_path, "r") as file:
|
| 25 |
-
self.config_data = yaml.safe_load(file)
|
| 26 |
-
|
| 27 |
-
# ---
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
#
|
| 41 |
-
#
|
| 42 |
-
|
| 43 |
-
#
|
| 44 |
-
#
|
| 45 |
-
|
| 46 |
-
#
|
| 47 |
-
#
|
| 48 |
-
#
|
| 49 |
-
#
|
| 50 |
-
#
|
| 51 |
-
# self.
|
| 52 |
-
#
|
| 53 |
-
#
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
""
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
#
|
| 156 |
-
#
|
| 157 |
-
|
| 158 |
-
#
|
| 159 |
-
#
|
| 160 |
-
#
|
| 161 |
-
|
| 162 |
-
#
|
| 163 |
-
#
|
| 164 |
-
|
| 165 |
-
#
|
| 166 |
-
#
|
| 167 |
-
#
|
| 168 |
-
|
| 169 |
-
#
|
| 170 |
-
#
|
| 171 |
-
|
| 172 |
-
#
|
| 173 |
-
#
|
| 174 |
-
#
|
| 175 |
-
|
| 176 |
-
#
|
| 177 |
-
#
|
| 178 |
-
|
| 179 |
-
#
|
| 180 |
-
#
|
| 181 |
-
#
|
| 182 |
-
# print("Local LLM response:", local_response)
|
| 183 |
-
# except Exception as e:
|
| 184 |
-
# print("Local LLM error:", e)
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import yaml
|
| 3 |
+
import requests
|
| 4 |
+
from decouple import config as decouple_config
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
|
| 7 |
+
# For local LLM using transformers
|
| 8 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from google import genai
|
| 12 |
+
from google.genai import types
|
| 13 |
+
# Import the Groq client
|
| 14 |
+
from groq import Groq
|
| 15 |
+
|
| 16 |
+
class LLMProcessor:
|
| 17 |
+
def __init__(self):
|
| 18 |
+
"""
|
| 19 |
+
Initialize the LLMProcessor by loading configuration and initializing all LLM clients.
|
| 20 |
+
"""
|
| 21 |
+
# Compute the absolute path to the config file (located at <project_root>/config/config.yml)
|
| 22 |
+
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
| 23 |
+
config_path = os.path.join(base_dir, "config", "config.yml")
|
| 24 |
+
with open(config_path, "r") as file:
|
| 25 |
+
self.config_data = yaml.safe_load(file)
|
| 26 |
+
|
| 27 |
+
# --- Gemini Initialization ---
|
| 28 |
+
gemini_config = llm_config.get("gemini", {})
|
| 29 |
+
self.gemini_api_key = os.getenv("GEMINI_API_KEY") # From Hugging Face secrets
|
| 30 |
+
self.gemini_endpoint = gemini_config.get("endpoint")
|
| 31 |
+
|
| 32 |
+
if not self.gemini_api_key:
|
| 33 |
+
print("Error: Gemini API key not found in environment variables")
|
| 34 |
+
if not self.gemini_endpoint:
|
| 35 |
+
print("Warning: Gemini endpoint not configured")
|
| 36 |
+
|
| 37 |
+
# # --- Huggingface Initialization ---
|
| 38 |
+
# hf_config = llm_config.get("huggingface", {})
|
| 39 |
+
# self.hf_api_token = hf_config.get("api_token")
|
| 40 |
+
# if not self.hf_api_token:
|
| 41 |
+
# print("Warning: Huggingface API token is missing in configuration.")
|
| 42 |
+
|
| 43 |
+
# # --- Local LLM Initialization ---
|
| 44 |
+
# local_config = llm_config.get("local", {})
|
| 45 |
+
# self.local_model_name = local_config.get("default_model")
|
| 46 |
+
# if self.local_model_name:
|
| 47 |
+
# print(f"Loading local model: {self.local_model_name}...")
|
| 48 |
+
# self.local_tokenizer = AutoTokenizer.from_pretrained(self.local_model_name)
|
| 49 |
+
# self.local_model = AutoModelForCausalLM.from_pretrained(self.local_model_name)
|
| 50 |
+
# # Optional: set the model to evaluation mode
|
| 51 |
+
# self.local_model.eval()
|
| 52 |
+
# else:
|
| 53 |
+
# print("Warning: No default local model specified in configuration.")
|
| 54 |
+
|
| 55 |
+
def call_groq_llm(self, model, message, token_limit=512, temperature=0.7):
|
| 56 |
+
"""
|
| 57 |
+
Call the Groq LLM API with a token limit and temperature.
|
| 58 |
+
|
| 59 |
+
Parameters:
|
| 60 |
+
model (str): The model name to use.
|
| 61 |
+
message (str): The input message.
|
| 62 |
+
token_limit (int): Maximum number of tokens to generate. (default: 1024)
|
| 63 |
+
temperature (float): Temperature parameter for generation. (default: 0.7)
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
The API response.
|
| 67 |
+
"""
|
| 68 |
+
response = self.groq_client.llm.generate(model=model, message=message,max_tokens=token_limit, temperature=temperature)
|
| 69 |
+
return response
|
| 70 |
+
|
| 71 |
+
def call_gemini_llm(self, model, message, token_limit=400, temperature=0.6):
|
| 72 |
+
"""
|
| 73 |
+
Call the Google Gemini LLM API with a token limit and temperature.
|
| 74 |
+
|
| 75 |
+
Parameters:
|
| 76 |
+
model (str): The Gemini model to use.
|
| 77 |
+
message (str): The input message.
|
| 78 |
+
token_limit (int): Maximum number of tokens to generate (default: 512).
|
| 79 |
+
temperature (float): Temperature for generation (default: 0.7).
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
The API response as JSON/dict.
|
| 83 |
+
"""
|
| 84 |
+
sys_instruct = """You are a Cancer doctor who is an expert in the field of oncology. You are very knowledgeable and can answer any question related to cancer. You are also a great teacher and can explain complex concepts in simple terms. You are very patient and understanding, and you always take the time to listen to your patients' concerns. You are also very compassionate and empathetic, and you always put your patients' needs first. and make it short and straight to the point and take the data from the context"""
|
| 85 |
+
if not (self.gemini_api_key and self.gemini_endpoint):
|
| 86 |
+
raise Exception("Gemini API configuration is missing.")
|
| 87 |
+
client = genai.Client(api_key=self.gemini_api_key)
|
| 88 |
+
try:
|
| 89 |
+
response = client.models.generate_content(
|
| 90 |
+
model=model,
|
| 91 |
+
config=types.GenerateContentConfig(
|
| 92 |
+
system_instruction=sys_instruct,
|
| 93 |
+
max_output_tokens=token_limit,
|
| 94 |
+
temperature=temperature
|
| 95 |
+
),
|
| 96 |
+
contents=[message]
|
| 97 |
+
)
|
| 98 |
+
return response.text
|
| 99 |
+
except Exception as e:
|
| 100 |
+
raise Exception(f"Gemini API error: {response.status_code} {response.text}")
|
| 101 |
+
|
| 102 |
+
def call_huggingface_llm(self, model_path, message):
|
| 103 |
+
"""
|
| 104 |
+
Call the Huggingface Inference API.
|
| 105 |
+
|
| 106 |
+
Parameters:
|
| 107 |
+
model_path (str): The Huggingface model identifier or path.
|
| 108 |
+
message (str): The input message.
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
The API response as JSON.
|
| 112 |
+
"""
|
| 113 |
+
if not self.hf_api_token:
|
| 114 |
+
raise Exception("Huggingface API token is missing in configuration.")
|
| 115 |
+
hf_endpoint = f"https://api-inference.huggingface.co/models/{model_path}"
|
| 116 |
+
headers = {"Authorization": f"Bearer {self.hf_api_token}"}
|
| 117 |
+
payload = {"inputs": message}
|
| 118 |
+
response = requests.post(hf_endpoint, json=payload, headers=headers)
|
| 119 |
+
if response.status_code == 200:
|
| 120 |
+
return response.json()
|
| 121 |
+
else:
|
| 122 |
+
raise Exception(f"Huggingface API error: {response.status_code} {response.text}")
|
| 123 |
+
|
| 124 |
+
def call_local_llm(self, model_name, message):
|
| 125 |
+
"""
|
| 126 |
+
Call a local LLM using the Transformers library.
|
| 127 |
+
|
| 128 |
+
Parameters:
|
| 129 |
+
model_name (str): The local model name or path (if different from the default).
|
| 130 |
+
message (str): The input message.
|
| 131 |
+
|
| 132 |
+
Returns:
|
| 133 |
+
The generated text.
|
| 134 |
+
"""
|
| 135 |
+
# Use the preloaded local model if the model_name matches the default.
|
| 136 |
+
if model_name == self.local_model_name:
|
| 137 |
+
tokenizer = self.local_tokenizer
|
| 138 |
+
model = self.local_model
|
| 139 |
+
else:
|
| 140 |
+
# Load a new model if different from the default.
|
| 141 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 142 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 143 |
+
model.eval()
|
| 144 |
+
|
| 145 |
+
inputs = tokenizer(message, return_tensors="pt")
|
| 146 |
+
# Optionally, use model.generate with parameters (e.g., max_length, temperature)
|
| 147 |
+
outputs = model.generate(**inputs)
|
| 148 |
+
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 149 |
+
return generated_text
|
| 150 |
+
|
| 151 |
+
# # Example usage:
|
| 152 |
+
# if __name__ == "__main__":
|
| 153 |
+
# llm_processor = LLMProcessor()
|
| 154 |
+
|
| 155 |
+
# # Groq API call example.
|
| 156 |
+
# try:
|
| 157 |
+
# groq_response = llm_processor.call_groq_llm("whisper-large-v3-turbo", "Hello, how are you?")
|
| 158 |
+
# print("Groq response:", groq_response)
|
| 159 |
+
# except Exception as e:
|
| 160 |
+
# print("Groq error:", e)
|
| 161 |
+
|
| 162 |
+
# # Gemini API call example.
|
| 163 |
+
# try:
|
| 164 |
+
# gemini_response = llm_processor.call_gemini_llm("gemini-model", "Hello, how are you?")
|
| 165 |
+
# print("Gemini response:", gemini_response)
|
| 166 |
+
# except Exception as e:
|
| 167 |
+
# print("Gemini error:", e)
|
| 168 |
+
|
| 169 |
+
# # Huggingface API call example.
|
| 170 |
+
# try:
|
| 171 |
+
# hf_response = llm_processor.call_huggingface_llm("gpt2", "Hello, how are you?")
|
| 172 |
+
# print("Huggingface response:", hf_response)
|
| 173 |
+
# except Exception as e:
|
| 174 |
+
# print("Huggingface error:", e)
|
| 175 |
+
|
| 176 |
+
# # Local LLM call example.
|
| 177 |
+
# try:
|
| 178 |
+
# local_response = llm_processor.call_local_llm(llm_processor.local_model_name, "Hello, how are you?")
|
| 179 |
+
# print("Local LLM response:", local_response)
|
| 180 |
+
# except Exception as e:
|
| 181 |
+
# print("Local LLM error:", e)
|
|
|
|
|
|
|
|
|