Skip to content

Commit e91c370

Browse files
committed
Fix: Resolve get_history service parameter handling issue
- Fixed async_get_history method to accept limit parameter and other filtering options - Updated service schema to support all parameters from services.yaml - Added support for start_date, include_metadata, and sort_order parameters - Version bump to 2.1.9
1 parent 7f62101 commit e91c370

File tree

4 files changed

+70
-5
lines changed

4 files changed

+70
-5
lines changed

custom_components/ha_text_ai/__init__.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,9 @@
8686
vol.Required("instance"): cv.string,
8787
vol.Optional("limit"): cv.positive_int,
8888
vol.Optional("filter_model"): cv.string,
89+
vol.Optional("start_date"): cv.string,
90+
vol.Optional("include_metadata"): cv.boolean,
91+
vol.Optional("sort_order"): vol.In(["newest", "oldest"]),
8992
})
9093

9194
def get_coordinator_by_instance(hass: HomeAssistant, instance: str) -> HATextAICoordinator:
@@ -168,7 +171,10 @@ async def async_get_history(call: ServiceCall) -> list:
168171
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
169172
return await coordinator.async_get_history(
170173
limit=call.data.get("limit"),
171-
filter_model=call.data.get("filter_model")
174+
filter_model=call.data.get("filter_model"),
175+
start_date=call.data.get("start_date"),
176+
include_metadata=call.data.get("include_metadata", False),
177+
sort_order=call.data.get("sort_order", "newest")
172178
)
173179
except Exception as err:
174180
_LOGGER.error("Error getting history: %s", str(err))

custom_components/ha_text_ai/coordinator.py

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1085,9 +1085,60 @@ async def async_clear_history(self) -> None:
10851085
_LOGGER.error(f"Error clearing history: {e}")
10861086
_LOGGER.debug(traceback.format_exc())
10871087

1088-
async def async_get_history(self) -> List[Dict[str, str]]:
1089-
"""Get conversation history."""
1090-
return self._conversation_history
1088+
async def async_get_history(
1089+
self,
1090+
limit: Optional[int] = None,
1091+
filter_model: Optional[str] = None,
1092+
start_date: Optional[str] = None,
1093+
include_metadata: bool = False,
1094+
sort_order: str = "newest"
1095+
) -> List[Dict[str, Any]]:
1096+
"""Get conversation history with optional filtering and sorting."""
1097+
try:
1098+
history = self._conversation_history.copy()
1099+
1100+
# Filter by model if specified
1101+
if filter_model:
1102+
history = [entry for entry in history if entry.get("model") == filter_model]
1103+
1104+
# Filter by start date if specified
1105+
if start_date:
1106+
try:
1107+
from datetime import datetime
1108+
start_dt = datetime.fromisoformat(start_date.replace('Z', '+00:00'))
1109+
history = [
1110+
entry for entry in history
1111+
if datetime.fromisoformat(entry["timestamp"].replace('Z', '+00:00')) >= start_dt
1112+
]
1113+
except (ValueError, KeyError) as e:
1114+
_LOGGER.warning(f"Invalid start_date format: {start_date}. Error: {e}")
1115+
1116+
# Sort history
1117+
if sort_order == "oldest":
1118+
history.sort(key=lambda x: x.get("timestamp", ""))
1119+
else: # newest (default)
1120+
history.sort(key=lambda x: x.get("timestamp", ""), reverse=True)
1121+
1122+
# Apply limit
1123+
if limit and limit > 0:
1124+
history = history[:limit]
1125+
1126+
# Add metadata if requested
1127+
if include_metadata:
1128+
for entry in history:
1129+
entry["metadata"] = {
1130+
"entry_size": len(str(entry)),
1131+
"question_length": len(entry.get("question", "")),
1132+
"response_length": len(entry.get("response", "")),
1133+
"model_used": entry.get("model", self.model),
1134+
"instance": self.instance_name
1135+
}
1136+
1137+
return history
1138+
1139+
except Exception as e:
1140+
_LOGGER.error(f"Error getting history: {e}")
1141+
return []
10911142

10921143
async def async_set_system_prompt(self, prompt: str) -> None:
10931144
"""Set system prompt."""

custom_components/ha_text_ai/manifest.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,6 @@
2424
"single_config_entry": false,
2525
"ssdp": [],
2626
"usb": [],
27-
"version": "2.1.8",
27+
"version": "2.1.9",
2828
"zeroconf": []
2929
}

ha-text-ai.code-workspace

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"folders": [
3+
{
4+
"path": "."
5+
}
6+
],
7+
"settings": {}
8+
}

0 commit comments

Comments
 (0)