Compare commits

..
4 Commits
Author SHA1 Message Date
SMKRV 8cd876195a Bump to version 2.1.6 2025-05-20 01:50:06 +03:00
SMKRV 376753e001 fix: correct field naming in Gemini API requests from camelCase to snake_case and improve message handling 2025-05-20 01:42:38 +03:00
SMKRV b6e73e847d fix(api_client): correct Google Gemini API integration
- Change JSON field names from camelCase to snake_case as required by Gemini API
  (generation_config, max_output_tokens, system_instruction)
- Improve message handling to ensure proper role alternation (user/model)
- Add safety checks for empty contents and ensure first message is always from user
- Implement robust error handling and response parsing
- Handle edge cases where candidatesTokenCount might be returned as a list

Fixes #6
2025-05-20 01:16:41 +03:00
SMKRV 440c734214 Bump release version to v2.1.4 2025-05-19 23:20:27 +03:00
2 changed files with 62 additions and 19 deletions
+61 -18
View File
@@ -254,45 +254,88 @@ class APIClient:
# Extract API key from headers (Bearer token)
api_key = self.headers.get("Authorization", "").replace("Bearer ", "")
url = f"{self.endpoint}/models/{model}:generateContent?key={api_key}"
# Convert messages to Gemini format
contents = []
system_instruction = ""
# Process messages
for msg in messages:
if msg['role'] == 'system':
system_instruction += msg['content'] + "\n"
else:
# Convert role: 'user' stays 'user', anything else becomes 'model'
role = "user" if msg['role'] == 'user' else "model"
contents.append({
"role": "user" if msg['role'] == 'user' else "model",
"role": role,
"parts": [{"text": msg['content']}]
})
# Ensure contents starts with a user message if not empty
if contents and contents[0]["role"] != "user":
# Add a placeholder user message
contents.insert(0, {
"role": "user",
"parts": [{"text": "I need your assistance."}]
})
# Ensure contents is not empty
if not contents:
contents.append({
"role": "user",
"parts": [{"text": "I need your assistance."}]
})
# Create payload with snake_case keys as required by Gemini API
payload = {
"contents": contents,
"generationConfig": {
"generation_config": { # Changed from camelCase to snake_case
"temperature": temperature,
"maxOutputTokens": max_tokens
"max_output_tokens": max_tokens # Changed from camelCase to snake_case
}
}
if system_instruction:
payload["systemInstruction"] = {
"parts": [{"text": system_instruction}]
payload["system_instruction"] = { # Changed from camelCase to snake_case
"parts": [{"text": system_instruction.strip()}]
}
data = await self._make_request(url, payload)
return {
"choices": [{
"message": {
"content": data["candidates"][0]["content"]["parts"][0]["text"]
try:
data = await self._make_request(url, payload)
# Safely extract response data
candidates = data.get("candidates", [])
if not candidates:
raise HomeAssistantError("Gemini API returned no candidates")
content = candidates[0].get("content", {})
parts = content.get("parts", [])
if not parts:
raise HomeAssistantError("Gemini API response contains no content parts")
answer_text = parts[0].get("text", "")
# Safely extract usage data
usage = data.get("usageMetadata", {})
prompt_tokens = usage.get("promptTokenCount", 0)
completion_tokens = usage.get("candidatesTokenCount", 0)
total_tokens = usage.get("totalTokenCount", prompt_tokens + completion_tokens)
return {
"choices": [{
"message": {
"content": answer_text
}
}],
"usage": {
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": total_tokens
}
}],
"usage": {
"prompt_tokens": data["usageMetadata"]["promptTokenCount"],
"completion_tokens": data["usageMetadata"]["candidatesTokenCount"],
"total_tokens": data["usageMetadata"]["totalTokenCount"]
}
}
except Exception as e:
_LOGGER.error(f"Gemini API error: {str(e)}")
raise HomeAssistantError(f"Gemini API error: {str(e)}")
async def shutdown(self) -> None:
"""Shutdown API client."""
+1 -1
View File
@@ -24,6 +24,6 @@
"single_config_entry": false,
"ssdp": [],
"usb": [],
"version": "2.1.3",
"version": "2.1.6",
"zeroconf": []
}