diff --git a/custom_components/ha_text_ai/__init__.py b/custom_components/ha_text_ai/__init__.py index 194bde2..8872ac2 100644 --- a/custom_components/ha_text_ai/__init__.py +++ b/custom_components/ha_text_ai/__init__.py @@ -86,6 +86,9 @@ SERVICE_SCHEMA_GET_HISTORY = vol.Schema({ vol.Required("instance"): cv.string, vol.Optional("limit"): cv.positive_int, vol.Optional("filter_model"): cv.string, + vol.Optional("start_date"): cv.string, + vol.Optional("include_metadata"): cv.boolean, + vol.Optional("sort_order"): vol.In(["newest", "oldest"]), }) def get_coordinator_by_instance(hass: HomeAssistant, instance: str) -> HATextAICoordinator: @@ -168,7 +171,10 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: coordinator = get_coordinator_by_instance(hass, call.data["instance"]) return await coordinator.async_get_history( limit=call.data.get("limit"), - filter_model=call.data.get("filter_model") + filter_model=call.data.get("filter_model"), + start_date=call.data.get("start_date"), + include_metadata=call.data.get("include_metadata", False), + sort_order=call.data.get("sort_order", "newest") ) except Exception as err: _LOGGER.error("Error getting history: %s", str(err)) diff --git a/custom_components/ha_text_ai/coordinator.py b/custom_components/ha_text_ai/coordinator.py index 14397e7..92e93b0 100644 --- a/custom_components/ha_text_ai/coordinator.py +++ b/custom_components/ha_text_ai/coordinator.py @@ -1085,9 +1085,60 @@ class HATextAICoordinator(DataUpdateCoordinator): _LOGGER.error(f"Error clearing history: {e}") _LOGGER.debug(traceback.format_exc()) - async def async_get_history(self) -> List[Dict[str, str]]: - """Get conversation history.""" - return self._conversation_history + async def async_get_history( + self, + limit: Optional[int] = None, + filter_model: Optional[str] = None, + start_date: Optional[str] = None, + include_metadata: bool = False, + sort_order: str = "newest" + ) -> List[Dict[str, Any]]: + """Get conversation history with optional filtering and sorting.""" + try: + history = self._conversation_history.copy() + + # Filter by model if specified + if filter_model: + history = [entry for entry in history if entry.get("model") == filter_model] + + # Filter by start date if specified + if start_date: + try: + from datetime import datetime + start_dt = datetime.fromisoformat(start_date.replace('Z', '+00:00')) + history = [ + entry for entry in history + if datetime.fromisoformat(entry["timestamp"].replace('Z', '+00:00')) >= start_dt + ] + except (ValueError, KeyError) as e: + _LOGGER.warning(f"Invalid start_date format: {start_date}. Error: {e}") + + # Sort history + if sort_order == "oldest": + history.sort(key=lambda x: x.get("timestamp", "")) + else: # newest (default) + history.sort(key=lambda x: x.get("timestamp", ""), reverse=True) + + # Apply limit + if limit and limit > 0: + history = history[:limit] + + # Add metadata if requested + if include_metadata: + for entry in history: + entry["metadata"] = { + "entry_size": len(str(entry)), + "question_length": len(entry.get("question", "")), + "response_length": len(entry.get("response", "")), + "model_used": entry.get("model", self.model), + "instance": self.instance_name + } + + return history + + except Exception as e: + _LOGGER.error(f"Error getting history: {e}") + return [] async def async_set_system_prompt(self, prompt: str) -> None: """Set system prompt.""" diff --git a/custom_components/ha_text_ai/manifest.json b/custom_components/ha_text_ai/manifest.json index a2a9413..5fd69b2 100644 --- a/custom_components/ha_text_ai/manifest.json +++ b/custom_components/ha_text_ai/manifest.json @@ -24,6 +24,6 @@ "single_config_entry": false, "ssdp": [], "usb": [], - "version": "2.1.8", + "version": "2.1.9", "zeroconf": [] } diff --git a/ha-text-ai.code-workspace b/ha-text-ai.code-workspace new file mode 100644 index 0000000..876a149 --- /dev/null +++ b/ha-text-ai.code-workspace @@ -0,0 +1,8 @@ +{ + "folders": [ + { + "path": "." + } + ], + "settings": {} +} \ No newline at end of file