ShadowTEM commited on
Commit
db9bbfd
·
verified ·
1 Parent(s): 3528eef

making api not visible

Browse files
Files changed (1) hide show
  1. 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
- # --- Groq Initialization ---
28
- llm_config = self.config_data.get("llm", {})
29
- # groq_config = llm_config.get("groq", {})
30
- # self.groq_api_key = groq_config.get("api_key") or decouple_config("GROQ_API_KEY")
31
- # self.groq_client = Groq(api_key=self.groq_api_key)
32
-
33
- # --- Gemini Initialization ---
34
- gemini_config = llm_config.get("gemini", {})
35
- self.gemini_api_key = gemini_config.get("api_key")
36
- self.gemini_endpoint = gemini_config.get("endpoint")
37
- if not (self.gemini_api_key and self.gemini_endpoint):
38
- print("Warning: Gemini API configuration is incomplete.")
39
-
40
- # # --- Huggingface Initialization ---
41
- # hf_config = llm_config.get("huggingface", {})
42
- # self.hf_api_token = hf_config.get("api_token")
43
- # if not self.hf_api_token:
44
- # print("Warning: Huggingface API token is missing in configuration.")
45
-
46
- # # --- Local LLM Initialization ---
47
- # local_config = llm_config.get("local", {})
48
- # self.local_model_name = local_config.get("default_model")
49
- # if self.local_model_name:
50
- # print(f"Loading local model: {self.local_model_name}...")
51
- # self.local_tokenizer = AutoTokenizer.from_pretrained(self.local_model_name)
52
- # self.local_model = AutoModelForCausalLM.from_pretrained(self.local_model_name)
53
- # # Optional: set the model to evaluation mode
54
- # self.local_model.eval()
55
- # else:
56
- # print("Warning: No default local model specified in configuration.")
57
-
58
- def call_groq_llm(self, model, message, token_limit=512, temperature=0.7):
59
- """
60
- Call the Groq LLM API with a token limit and temperature.
61
-
62
- Parameters:
63
- model (str): The model name to use.
64
- message (str): The input message.
65
- token_limit (int): Maximum number of tokens to generate. (default: 1024)
66
- temperature (float): Temperature parameter for generation. (default: 0.7)
67
-
68
- Returns:
69
- The API response.
70
- """
71
- response = self.groq_client.llm.generate(model=model, message=message,max_tokens=token_limit, temperature=temperature)
72
- return response
73
-
74
- def call_gemini_llm(self, model, message, token_limit=400, temperature=0.6):
75
- """
76
- Call the Google Gemini LLM API with a token limit and temperature.
77
-
78
- Parameters:
79
- model (str): The Gemini model to use.
80
- message (str): The input message.
81
- token_limit (int): Maximum number of tokens to generate (default: 512).
82
- temperature (float): Temperature for generation (default: 0.7).
83
-
84
- Returns:
85
- The API response as JSON/dict.
86
- """
87
- 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"""
88
- if not (self.gemini_api_key and self.gemini_endpoint):
89
- raise Exception("Gemini API configuration is missing.")
90
- client = genai.Client(api_key=self.gemini_api_key)
91
- try:
92
- response = client.models.generate_content(
93
- model=model,
94
- config=types.GenerateContentConfig(
95
- system_instruction=sys_instruct,
96
- max_output_tokens=token_limit,
97
- temperature=temperature
98
- ),
99
- contents=[message]
100
- )
101
- return response.text
102
- except Exception as e:
103
- raise Exception(f"Gemini API error: {response.status_code} {response.text}")
104
-
105
- def call_huggingface_llm(self, model_path, message):
106
- """
107
- Call the Huggingface Inference API.
108
-
109
- Parameters:
110
- model_path (str): The Huggingface model identifier or path.
111
- message (str): The input message.
112
-
113
- Returns:
114
- The API response as JSON.
115
- """
116
- if not self.hf_api_token:
117
- raise Exception("Huggingface API token is missing in configuration.")
118
- hf_endpoint = f"https://api-inference.huggingface.co/models/{model_path}"
119
- headers = {"Authorization": f"Bearer {self.hf_api_token}"}
120
- payload = {"inputs": message}
121
- response = requests.post(hf_endpoint, json=payload, headers=headers)
122
- if response.status_code == 200:
123
- return response.json()
124
- else:
125
- raise Exception(f"Huggingface API error: {response.status_code} {response.text}")
126
-
127
- def call_local_llm(self, model_name, message):
128
- """
129
- Call a local LLM using the Transformers library.
130
-
131
- Parameters:
132
- model_name (str): The local model name or path (if different from the default).
133
- message (str): The input message.
134
-
135
- Returns:
136
- The generated text.
137
- """
138
- # Use the preloaded local model if the model_name matches the default.
139
- if model_name == self.local_model_name:
140
- tokenizer = self.local_tokenizer
141
- model = self.local_model
142
- else:
143
- # Load a new model if different from the default.
144
- tokenizer = AutoTokenizer.from_pretrained(model_name)
145
- model = AutoModelForCausalLM.from_pretrained(model_name)
146
- model.eval()
147
-
148
- inputs = tokenizer(message, return_tensors="pt")
149
- # Optionally, use model.generate with parameters (e.g., max_length, temperature)
150
- outputs = model.generate(**inputs)
151
- generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
152
- return generated_text
153
-
154
- # # Example usage:
155
- # if __name__ == "__main__":
156
- # llm_processor = LLMProcessor()
157
-
158
- # # Groq API call example.
159
- # try:
160
- # groq_response = llm_processor.call_groq_llm("whisper-large-v3-turbo", "Hello, how are you?")
161
- # print("Groq response:", groq_response)
162
- # except Exception as e:
163
- # print("Groq error:", e)
164
-
165
- # # Gemini API call example.
166
- # try:
167
- # gemini_response = llm_processor.call_gemini_llm("gemini-model", "Hello, how are you?")
168
- # print("Gemini response:", gemini_response)
169
- # except Exception as e:
170
- # print("Gemini error:", e)
171
-
172
- # # Huggingface API call example.
173
- # try:
174
- # hf_response = llm_processor.call_huggingface_llm("gpt2", "Hello, how are you?")
175
- # print("Huggingface response:", hf_response)
176
- # except Exception as e:
177
- # print("Huggingface error:", e)
178
-
179
- # # Local LLM call example.
180
- # try:
181
- # local_response = llm_processor.call_local_llm(llm_processor.local_model_name, "Hello, how are you?")
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)