mgbam commited on
Commit
250b6ae
·
verified ·
1 Parent(s): 9bc4849

Update core/llm_clients.py

Browse files
Files changed (1) hide show
  1. core/llm_clients.py +137 -0
core/llm_clients.py CHANGED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # algoforge_prime/core/llm_clients.py
2
+ import os
3
+ import google.generativeai as genai
4
+ from huggingface_hub import InferenceClient
5
+
6
+ # --- Configuration ---
7
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
8
+ HF_TOKEN = os.getenv("HF_TOKEN")
9
+
10
+ GEMINI_API_CONFIGURED = False
11
+ HF_API_CONFIGURED = False
12
+
13
+ hf_inference_client = None
14
+ google_gemini_models = {} # To store initialized Gemini model instances
15
+
16
+ # --- Initialization ---
17
+ def initialize_clients():
18
+ global GEMINI_API_CONFIGURED, HF_API_CONFIGURED, hf_inference_client, google_gemini_models
19
+
20
+ # Google Gemini
21
+ if GOOGLE_API_KEY:
22
+ try:
23
+ genai.configure(api_key=GOOGLE_API_KEY)
24
+ GEMINI_API_CONFIGURED = True
25
+ print("INFO: llm_clients.py - Google Gemini API configured.")
26
+ except Exception as e:
27
+ print(f"ERROR: llm_clients.py - Failed to configure Google Gemini API: {e}")
28
+ else:
29
+ print("WARNING: llm_clients.py - GOOGLE_API_KEY not found.")
30
+
31
+ # Hugging Face
32
+ if HF_TOKEN:
33
+ try:
34
+ hf_inference_client = InferenceClient(token=HF_TOKEN)
35
+ HF_API_CONFIGURED = True
36
+ print("INFO: llm_clients.py - Hugging Face InferenceClient initialized.")
37
+ except Exception as e:
38
+ print(f"ERROR: llm_clients.py - Failed to initialize Hugging Face InferenceClient: {e}")
39
+ else:
40
+ print("WARNING: llm_clients.py - HF_TOKEN not found.")
41
+
42
+ # Call initialize_clients when the module is imported for the first time.
43
+ # However, for Gradio apps that might reload, it's often better to call this explicitly from app.py's main scope.
44
+ # For now, let's assume it's called once. If you see issues, move the call.
45
+ # initialize_clients() # Or call this from app.py
46
+
47
+ def get_gemini_model_instance(model_id, system_instruction=None):
48
+ """Gets or creates a Gemini model instance."""
49
+ if not GEMINI_API_CONFIGURED:
50
+ raise ConnectionError("Google Gemini API not configured.")
51
+
52
+ instance_key = model_id + ("_sys" if system_instruction else "") # Simple keying
53
+ if instance_key not in google_gemini_models:
54
+ try:
55
+ google_gemini_models[instance_key] = genai.GenerativeModel(
56
+ model_name=model_id,
57
+ system_instruction=system_instruction
58
+ )
59
+ print(f"INFO: Initialized Gemini Model Instance: {instance_key}")
60
+ except Exception as e:
61
+ print(f"ERROR: Failed to initialize Gemini model {model_id}: {e}")
62
+ raise # Re-raise the exception to be caught by the caller
63
+ return google_gemini_models[instance_key]
64
+
65
+
66
+ class LLMResponse:
67
+ def __init__(self, text=None, error=None, success=True, raw_response=None):
68
+ self.text = text
69
+ self.error = error
70
+ self.success = success
71
+ self.raw_response = raw_response # Store original API response if needed
72
+
73
+ def __str__(self):
74
+ if self.success:
75
+ return self.text if self.text is not None else ""
76
+ return f"ERROR: {self.error}"
77
+
78
+
79
+ def call_huggingface_api(prompt_text, model_id, temperature=0.7, max_new_tokens=350, system_prompt_text=None):
80
+ if not HF_API_CONFIGURED or not hf_inference_client:
81
+ return LLMResponse(error="Hugging Face API not configured.", success=False)
82
+
83
+ full_prompt = prompt_text
84
+ if system_prompt_text: # Simple prepend, specific formatting depends on model
85
+ full_prompt = f"<s>[INST] <<SYS>>\n{system_prompt_text}\n<</SYS>>\n\n{prompt_text} [/INST]" # Llama-style
86
+
87
+ try:
88
+ use_sample = temperature > 0.0
89
+ raw_response = hf_inference_client.text_generation(
90
+ full_prompt, model=model_id, max_new_tokens=max_new_tokens,
91
+ temperature=temperature if use_sample else None,
92
+ do_sample=use_sample, stream=False
93
+ )
94
+ return LLMResponse(text=raw_response, raw_response=raw_response)
95
+ except Exception as e:
96
+ error_msg = f"HF API Error ({model_id}): {type(e).__name__} - {e}"
97
+ print(f"ERROR: llm_clients.py - {error_msg}")
98
+ return LLMResponse(error=error_msg, success=False, raw_response=e)
99
+
100
+ def call_gemini_api(prompt_text, model_id, temperature=0.7, max_new_tokens=400, system_prompt_text=None):
101
+ if not GEMINI_API_CONFIGURED:
102
+ return LLMResponse(error="Google Gemini API not configured.", success=False)
103
+
104
+ try:
105
+ model_instance = get_gemini_model_instance(model_id, system_instruction=system_prompt_text)
106
+
107
+ generation_config = genai.types.GenerationConfig(
108
+ temperature=temperature,
109
+ max_output_tokens=max_new_tokens
110
+ )
111
+ raw_response = model_instance.generate_content(
112
+ prompt_text, # User prompt
113
+ generation_config=generation_config,
114
+ stream=False
115
+ )
116
+
117
+ if raw_response.prompt_feedback and raw_response.prompt_feedback.block_reason:
118
+ reason = raw_response.prompt_feedback.block_reason_message or raw_response.prompt_feedback.block_reason
119
+ error_msg = f"Gemini API: Prompt blocked due to safety. Reason: {reason}"
120
+ print(f"WARNING: llm_clients.py - {error_msg}")
121
+ return LLMResponse(error=error_msg, success=False, raw_response=raw_response)
122
+
123
+ if not raw_response.candidates or not raw_response.candidates[0].content.parts:
124
+ finish_reason = raw_response.candidates[0].finish_reason if raw_response.candidates else "Unknown"
125
+ if str(finish_reason).upper() == "SAFETY":
126
+ error_msg = f"Gemini API: Response generation stopped by safety filters. Finish Reason: {finish_reason}"
127
+ else:
128
+ error_msg = f"Gemini API: Empty response or no content. Finish Reason: {finish_reason}"
129
+ print(f"WARNING: llm_clients.py - {error_msg}")
130
+ return LLMResponse(error=error_msg, success=False, raw_response=raw_response)
131
+
132
+ return LLMResponse(text=raw_response.candidates[0].content.parts[0].text, raw_response=raw_response)
133
+
134
+ except Exception as e:
135
+ error_msg = f"Gemini API Error ({model_id}): {type(e).__name__} - {e}"
136
+ print(f"ERROR: llm_clients.py - {error_msg}")
137
+ return LLMResponse(error=error_msg, success=False, raw_response=e)