GuglielmoTor commited on
Commit
a8afa39
·
verified ·
1 Parent(s): 24f43be

Update chatbot_handler.py

Browse files
Files changed (1) hide show
  1. chatbot_handler.py +26 -49
chatbot_handler.py CHANGED
@@ -19,6 +19,8 @@ generation_config_params = {
19
  "top_p": 1,
20
  "top_k": 1,
21
  "max_output_tokens": 2048,
 
 
22
  }
23
 
24
  # Safety settings list
@@ -31,7 +33,7 @@ common_safety_settings = [
31
 
32
  try:
33
  if GEMINI_API_KEY:
34
- # Initialize client using genai.Client as per user's documentation and error
35
  client = genai.Client(api_key=GEMINI_API_KEY)
36
  logging.info(f"Gemini client (genai.Client) initialized. Target model for generation: '{model_name}'")
37
  else:
@@ -54,31 +56,14 @@ def format_history_for_gemini(gradio_chat_history: list) -> list:
54
  if part_item.get("type") == "text":
55
  parts.append({"text": part_item.get("text", "")})
56
  if parts:
57
- gemini_contents.append({"role": role, "parts": parts})
58
  else:
59
  logging.warning(f"Skipping complex but empty content part in chat history: {content}")
60
  else:
61
  logging.warning(f"Skipping non-string/non-standard content in chat history: {content}")
62
- # For the older client.models.generate_content, the 'contents' is typically a list of strings or multimodal parts,
63
- # not a list of role-based dicts. The role-based dicts are for chat history with newer .start_chat().send_message().
64
- # The user's example shows: contents=["Explain how AI works"]
65
- # If the history is to be used, it needs to be formatted as a flat list of alternating user/model prompts for some older chat patterns,
66
- # or the API might only take the latest user message if not using a dedicated chat session object.
67
- # Given the `client.models.generate_content` structure, we might need to adjust how history is passed.
68
- # For now, let's assume gemini_formatted_history is what `contents` expects, or it should be just the latest user message.
69
- # The documentation for client.models.generate_content shows `contents` can be a list of parts.
70
- # Let's re-evaluate: if chat_history_for_plot is a list of {"role": ..., "parts": ...},
71
- # client.models.generate_content might expect `contents` to be just the parts of the last user message,
72
- # or a more complex structure if it supports multi-turn via this method directly.
73
- # The example `contents=[image, "Tell me about this instrument"]` suggests a list of content parts.
74
- # Let's assume for now that the `gemini_formatted_history` (which is a list of {"role": ..., "parts": ...})
75
- # is the correct format for the `contents` argument if the SDK version handles it.
76
- # If not, this function or its usage in generate_llm_response will need adjustment.
77
- # For a simple non-chat scenario, contents would be like: `[{"parts": [{"text": user_message}]}]`
78
- # For a multi-turn conversation, the `contents` parameter for `generate_content`
79
  # expects a list of `Content` objects (or dicts that can be cast to them).
80
  # Each `Content` object has 'role' and 'parts'.
81
- # So, the current `format_history_for_gemini` output *should* be correct.
82
  return gemini_contents
83
 
84
 
@@ -87,61 +72,50 @@ async def generate_llm_response(user_message: str, plot_id: str, plot_label: str
87
  logging.error("Gemini client (genai.Client) not initialized.")
88
  return "The AI model is not available. Configuration error."
89
 
90
- # gemini_formatted_history will be a list of {"role": ..., "parts": ...} dicts
91
  gemini_formatted_history = format_history_for_gemini(chat_history_for_plot)
92
 
93
- if not gemini_formatted_history: # Should not happen if chat_history_for_plot has at least one message
94
  logging.error("Formatted history for Gemini is empty.")
95
  return "There was an issue processing the conversation history (empty)."
96
 
97
- # Ensure the last message has text if it's the only one (e.g. initial prompt)
98
  if not any(part.get("text","").strip() for message in gemini_formatted_history for part in message.get("parts",[])):
99
  logging.error("Formatted history for Gemini contains no text parts.")
100
  return "There was an issue processing the conversation history for the AI model (empty text)."
101
 
102
  try:
103
  response = None
104
- # We are now certain we need to use client.models.generate_content
105
  if hasattr(client, 'models') and hasattr(client.models, 'generate_content'):
106
  logging.debug(f"Using genai.Client.models.generate_content for model '{model_name}' (synchronous via asyncio.to_thread)")
107
 
108
- # The model name for client.models.generate_content should not be prefixed with "models/"
109
- # if it's like "gemini-1.5-flash-latest" or "gemini-2.0-flash".
110
- # If your model_name is already "models/gemini-1.5-flash-latest", then it's fine.
111
- # Let's assume model_name is like "gemini-1.5-flash-latest"
112
- effective_model_name = model_name
113
- if not model_name.startswith("models/"): # Ensure it's not like "models/models/gemini..."
114
- effective_model_name = f"models/{model_name}" # Prepend "models/" if not already there
115
-
116
  # Create the GenerateContentConfig object from our parameters
 
117
  gen_config_obj = genai_types.GenerateContentConfig(**generation_config_params)
118
 
 
 
 
119
  response = await asyncio.to_thread(
120
  client.models.generate_content,
121
- model=effective_model_name, # Pass the model name string
122
- contents=gemini_formatted_history, # This should be the list of Content dicts
123
- generation_config=gen_config_obj,
124
  safety_settings=common_safety_settings
125
  )
126
  else:
127
  logging.error(f"Gemini client (genai.Client) does not have 'models.generate_content' method. Type: {type(client)}")
128
  return "AI model interaction error (SDK method not found)."
129
 
130
- # Process response (this part should be largely consistent)
131
  if hasattr(response, 'prompt_feedback') and response.prompt_feedback and response.prompt_feedback.block_reason:
132
  reason = response.prompt_feedback.block_reason
133
- reason_name = getattr(reason, 'name', str(reason)) # .name might not exist
134
  logging.warning(f"Blocked by prompt feedback: {reason_name}")
135
  return f"Blocked due to content policy: {reason_name}."
136
 
137
- # The user's documentation example uses `response.text` directly.
138
- # This implies the response object from `client.models.generate_content` might be simpler.
139
- # Let's check for `response.text` first.
140
  if hasattr(response, 'text') and response.text:
141
  logging.debug("Response has a direct .text attribute.")
142
  return response.text
143
 
144
- # Fallback to candidates structure if .text is not available or empty
145
  logging.debug("Response does not have a direct .text attribute or it's empty, checking candidates.")
146
  if response.candidates and response.candidates[0].content and response.candidates[0].content.parts:
147
  return "".join(part.text for part in response.candidates[0].content.parts if hasattr(part, 'text'))
@@ -149,16 +123,15 @@ async def generate_llm_response(user_message: str, plot_id: str, plot_label: str
149
  finish_reason = "UNKNOWN"
150
  if response.candidates and response.candidates[0].finish_reason:
151
  finish_reason_val = response.candidates[0].finish_reason
152
- finish_reason = getattr(finish_reason_val, 'name', str(finish_reason_val)) # .name might not exist
153
 
154
  if not (hasattr(response, 'text') and response.text) and \
155
  not (response.candidates and response.candidates[0].content and response.candidates[0].content.parts):
156
  logging.warning(f"No content parts in response and no direct .text. Finish reason: {finish_reason}")
157
- if finish_reason == "SAFETY": # Or other relevant finish reasons
158
- return f"Response generation stopped due to safety reasons. Finish reason: {finish_reason}."
159
  return f"The AI model returned an empty response. Finish reason: {finish_reason}."
160
 
161
- # If we reach here, it means .text was empty and candidates structure was also empty/problematic
162
  return f"Unexpected response structure from AI model (checked .text and .candidates). Finish reason: {finish_reason}."
163
 
164
  except AttributeError as ae:
@@ -166,9 +139,13 @@ async def generate_llm_response(user_message: str, plot_id: str, plot_label: str
166
  return f"AI model error (Attribute): {type(ae).__name__} - {ae}."
167
  except Exception as e:
168
  logging.error(f"Error generating response for plot '{plot_label}': {e}", exc_info=True)
169
- # Check for specific API errors if possible
170
  if "API_KEY_INVALID" in str(e) or "API key not valid" in str(e):
171
- return "AI model error: API key is not valid. Please check configuration."
172
- if "400" in str(e) and "model" in str(e).lower() and "not found" in str(e).lower(): # Example for model not found
173
- return f"AI model error: Model '{model_name}' not found or not accessible with your API key."
 
 
 
 
174
  return f"An unexpected error occurred while contacting the AI model: {type(e).__name__}."
 
 
19
  "top_p": 1,
20
  "top_k": 1,
21
  "max_output_tokens": 2048,
22
+ # If you need a system instruction, add it here, e.g.:
23
+ # "system_instruction": "You are a helpful AI assistant providing insights on LinkedIn analytics."
24
  }
25
 
26
  # Safety settings list
 
33
 
34
  try:
35
  if GEMINI_API_KEY:
36
+ # Initialize client using genai.Client
37
  client = genai.Client(api_key=GEMINI_API_KEY)
38
  logging.info(f"Gemini client (genai.Client) initialized. Target model for generation: '{model_name}'")
39
  else:
 
56
  if part_item.get("type") == "text":
57
  parts.append({"text": part_item.get("text", "")})
58
  if parts:
59
+ gemini_contents.append({"role": role, "parts": parts})
60
  else:
61
  logging.warning(f"Skipping complex but empty content part in chat history: {content}")
62
  else:
63
  logging.warning(f"Skipping non-string/non-standard content in chat history: {content}")
64
+ # For `client.models.generate_content`, the `contents` parameter
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  # expects a list of `Content` objects (or dicts that can be cast to them).
66
  # Each `Content` object has 'role' and 'parts'.
 
67
  return gemini_contents
68
 
69
 
 
72
  logging.error("Gemini client (genai.Client) not initialized.")
73
  return "The AI model is not available. Configuration error."
74
 
 
75
  gemini_formatted_history = format_history_for_gemini(chat_history_for_plot)
76
 
77
+ if not gemini_formatted_history:
78
  logging.error("Formatted history for Gemini is empty.")
79
  return "There was an issue processing the conversation history (empty)."
80
 
 
81
  if not any(part.get("text","").strip() for message in gemini_formatted_history for part in message.get("parts",[])):
82
  logging.error("Formatted history for Gemini contains no text parts.")
83
  return "There was an issue processing the conversation history for the AI model (empty text)."
84
 
85
  try:
86
  response = None
 
87
  if hasattr(client, 'models') and hasattr(client.models, 'generate_content'):
88
  logging.debug(f"Using genai.Client.models.generate_content for model '{model_name}' (synchronous via asyncio.to_thread)")
89
 
 
 
 
 
 
 
 
 
90
  # Create the GenerateContentConfig object from our parameters
91
+ # This can include system_instruction if added to generation_config_params
92
  gen_config_obj = genai_types.GenerateContentConfig(**generation_config_params)
93
 
94
+ # Call client.models.generate_content
95
+ # 1. Use model_name directly (e.g., "gemini-1.5-flash-latest")
96
+ # 2. Use 'config' instead of 'generation_config' for the keyword argument
97
  response = await asyncio.to_thread(
98
  client.models.generate_content,
99
+ model=model_name, # Use model_name directly
100
+ contents=gemini_formatted_history,
101
+ config=gen_config_obj, # Corrected keyword argument
102
  safety_settings=common_safety_settings
103
  )
104
  else:
105
  logging.error(f"Gemini client (genai.Client) does not have 'models.generate_content' method. Type: {type(client)}")
106
  return "AI model interaction error (SDK method not found)."
107
 
108
+ # Process response
109
  if hasattr(response, 'prompt_feedback') and response.prompt_feedback and response.prompt_feedback.block_reason:
110
  reason = response.prompt_feedback.block_reason
111
+ reason_name = getattr(reason, 'name', str(reason))
112
  logging.warning(f"Blocked by prompt feedback: {reason_name}")
113
  return f"Blocked due to content policy: {reason_name}."
114
 
 
 
 
115
  if hasattr(response, 'text') and response.text:
116
  logging.debug("Response has a direct .text attribute.")
117
  return response.text
118
 
 
119
  logging.debug("Response does not have a direct .text attribute or it's empty, checking candidates.")
120
  if response.candidates and response.candidates[0].content and response.candidates[0].content.parts:
121
  return "".join(part.text for part in response.candidates[0].content.parts if hasattr(part, 'text'))
 
123
  finish_reason = "UNKNOWN"
124
  if response.candidates and response.candidates[0].finish_reason:
125
  finish_reason_val = response.candidates[0].finish_reason
126
+ finish_reason = getattr(finish_reason_val, 'name', str(finish_reason_val))
127
 
128
  if not (hasattr(response, 'text') and response.text) and \
129
  not (response.candidates and response.candidates[0].content and response.candidates[0].content.parts):
130
  logging.warning(f"No content parts in response and no direct .text. Finish reason: {finish_reason}")
131
+ if finish_reason == "SAFETY":
132
+ return f"Response generation stopped due to safety reasons. Finish reason: {finish_reason}."
133
  return f"The AI model returned an empty response. Finish reason: {finish_reason}."
134
 
 
135
  return f"Unexpected response structure from AI model (checked .text and .candidates). Finish reason: {finish_reason}."
136
 
137
  except AttributeError as ae:
 
139
  return f"AI model error (Attribute): {type(ae).__name__} - {ae}."
140
  except Exception as e:
141
  logging.error(f"Error generating response for plot '{plot_label}': {e}", exc_info=True)
 
142
  if "API_KEY_INVALID" in str(e) or "API key not valid" in str(e):
143
+ return "AI model error: API key is not valid. Please check configuration."
144
+ if "400" in str(e) and "model" in str(e).lower() and "not found" in str(e).lower():
145
+ return f"AI model error: Model '{model_name}' not found or not accessible with your API key."
146
+ # Check for the specific TypeError related to generate_content arguments
147
+ if isinstance(e, TypeError) and "got an unexpected keyword argument" in str(e):
148
+ logging.error(f"TypeError in generate_content call: {e}. This might indicate an issue with SDK version or method signature.")
149
+ return f"AI model error (Internal SDK call issue): {e}"
150
  return f"An unexpected error occurred while contacting the AI model: {type(e).__name__}."
151
+