Fixed all ruff issues

This commit is contained in:
2025-12-07 05:59:53 +01:00
parent a21121d025
commit 0c48640412
13 changed files with 29 additions and 30 deletions
+1 -1
View File
@@ -51,7 +51,7 @@ class DeepSeekClient:
logger.info(f"DeepSeek client initialized with model: {self.model}") logger.info(f"DeepSeek client initialized with model: {self.model}")
def complete( def complete( # noqa: PLR0912
self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None = None self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None = None
) -> dict[str, Any]: ) -> dict[str, Any]:
""" """
+1 -1
View File
@@ -66,7 +66,7 @@ class OllamaClient:
logger.info(f"Ollama client initialized with model: {self.model}") logger.info(f"Ollama client initialized with model: {self.model}")
def complete( def complete( # noqa: PLR0912
self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None = None self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None = None
) -> dict[str, Any]: ) -> dict[str, Any]:
""" """
+7 -10
View File
@@ -39,9 +39,8 @@ class PromptBuilder:
for tool in self.tools.values() for tool in self.tools.values()
) )
def _format_episodic_context(self) -> str: def _format_episodic_context(self, memory) -> str:
"""Format episodic memory context for the prompt.""" """Format episodic memory context for the prompt."""
memory = get_memory()
lines = [] lines = []
if memory.episodic.last_search_results: if memory.episodic.last_search_results:
@@ -85,9 +84,8 @@ class PromptBuilder:
return "\n".join(lines) return "\n".join(lines)
def _format_stm_context(self) -> str: def _format_stm_context(self, memory) -> str:
"""Format short-term memory context for the prompt.""" """Format short-term memory context for the prompt."""
memory = get_memory()
lines = [] lines = []
if memory.stm.current_workflow: if memory.stm.current_workflow:
@@ -111,10 +109,8 @@ class PromptBuilder:
return "\n".join(lines) return "\n".join(lines)
def _format_config_context(self) -> str: def _format_config_context(self, memory) -> str:
"""Format configuration context.""" """Format configuration context."""
memory = get_memory()
lines = ["CURRENT CONFIGURATION:"] lines = ["CURRENT CONFIGURATION:"]
if memory.ltm.config: if memory.ltm.config:
for key, value in memory.ltm.config.items(): for key, value in memory.ltm.config.items():
@@ -125,6 +121,7 @@ class PromptBuilder:
def build_system_prompt(self) -> str: def build_system_prompt(self) -> str:
"""Build the complete system prompt.""" """Build the complete system prompt."""
# Get memory once for all context formatting
memory = get_memory() memory = get_memory()
# Base instruction # Base instruction
@@ -142,17 +139,17 @@ class PromptBuilder:
tools_section = f"\nAVAILABLE TOOLS:\n{tools_desc}" if tools_desc else "" tools_section = f"\nAVAILABLE TOOLS:\n{tools_desc}" if tools_desc else ""
# Configuration # Configuration
config_section = self._format_config_context() config_section = self._format_config_context(memory)
if config_section: if config_section:
config_section = f"\n{config_section}" config_section = f"\n{config_section}"
# STM context # STM context
stm_context = self._format_stm_context() stm_context = self._format_stm_context(memory)
if stm_context: if stm_context:
stm_context = f"\n{stm_context}" stm_context = f"\n{stm_context}"
# Episodic context # Episodic context
episodic_context = self._format_episodic_context() episodic_context = self._format_episodic_context(memory)
# Important rules # Important rules
rules = """ rules = """
+2 -2
View File
@@ -178,10 +178,10 @@ async def chat_completions(chat_request: ChatCompletionRequest):
answer = agent.step(user_input) answer = agent.step(user_input)
except LLMAPIError as e: except LLMAPIError as e:
logger.error(f"LLM API error: {e}") logger.error(f"LLM API error: {e}")
raise HTTPException(status_code=502, detail=f"LLM API error: {e}") raise HTTPException(status_code=502, detail=f"LLM API error: {e}") from e
except Exception as e: except Exception as e:
logger.error(f"Agent error: {e}", exc_info=True) logger.error(f"Agent error: {e}", exc_info=True)
raise HTTPException(status_code=500, detail="Internal agent error") raise HTTPException(status_code=500, detail="Internal agent error") from e
return JSONResponse( return JSONResponse(
{ {
+1 -1
View File
@@ -282,7 +282,7 @@ class QBittorrentClient:
} }
try: try:
response = self._make_request("POST", "/api/v2/torrents/delete", data=data) self._make_request("POST", "/api/v2/torrents/delete", data=data)
logger.info(f"Deleted torrent {torrent_hash}") logger.info(f"Deleted torrent {torrent_hash}")
return True return True
-1
View File
@@ -194,7 +194,6 @@ class TMDBClient:
if "id" not in top_result or "media_type" not in top_result: if "id" not in top_result or "media_type" not in top_result:
raise TMDBAPIError("Invalid TMDB response structure") raise TMDBAPIError("Invalid TMDB response structure")
tmdb_id = top_result["id"]
media_type = top_result["media_type"] media_type = top_result["media_type"]
# Skip if not movie or TV show # Skip if not movie or TV show
+6 -2
View File
@@ -84,7 +84,9 @@ class FileManager:
logger.error(f"Unexpected error setting path: {e}", exc_info=True) logger.error(f"Unexpected error setting path: {e}", exc_info=True)
return {"error": "internal_error", "message": "Failed to set path"} return {"error": "internal_error", "message": "Failed to set path"}
def list_folder(self, folder_type: str, path: str = ".") -> dict[str, Any]: def list_folder( # noqa: PLR0911
self, folder_type: str, path: str = "."
) -> dict[str, Any]:
""" """
List contents of a configured folder. List contents of a configured folder.
@@ -165,7 +167,9 @@ class FileManager:
logger.error(f"Unexpected error listing folder: {e}", exc_info=True) logger.error(f"Unexpected error listing folder: {e}", exc_info=True)
return {"error": "internal_error", "message": "Failed to list folder"} return {"error": "internal_error", "message": "Failed to list folder"}
def move_file(self, source: str, destination: str) -> dict[str, Any]: def move_file( # noqa: PLR0911
self, source: str, destination: str
) -> dict[str, Any]:
""" """
Move a file from one location to another. Move a file from one location to another.
+3 -3
View File
@@ -100,7 +100,7 @@ exclude = [
".qodo", ".qodo",
".vscode", ".vscode",
] ]
select = [ lint.select = [
"E", "W", "E", "W",
"F", "F",
"I", "I",
@@ -110,8 +110,8 @@ select = [
"PL", "PL",
"UP", "UP",
] ]
ignore = ["PLR0913", "PLR2004", "TID252", "E501"] lint.ignore = ["PLR0913", "PLR2004", "TID252", "E501"]
[tool.ruff.per-file-ignores] [tool.ruff.lint.per-file-ignores]
"tests/**/*.py" = ["PLC0415"] "tests/**/*.py" = ["PLC0415"]
"conftest.py" = ["PLC0415"] "conftest.py" = ["PLC0415"]
+1 -1
View File
@@ -85,7 +85,7 @@ class TestImdbIdEdgeCases:
id2 = ImdbId("tt1234567") id2 = ImdbId("tt1234567")
# Should be usable in set # Should be usable in set
s = {id1, id2} _s = {id1, id2} # Test hashability
# Depending on implementation, might be 1 or 2 items # Depending on implementation, might be 1 or 2 items
+4 -5
View File
@@ -390,9 +390,8 @@ class TestMemoryEdgeCases:
"""Should create directory if not exists.""" """Should create directory if not exists."""
new_dir = temp_dir / "new" / "nested" / "dir" new_dir = temp_dir / "new" / "nested" / "dir"
# Create parent directories first # Don't create the directory - let Memory do it
new_dir.mkdir(parents=True, exist_ok=True) Memory(storage_dir=str(new_dir))
memory = Memory(storage_dir=str(new_dir))
assert new_dir.exists() assert new_dir.exists()
@@ -405,7 +404,7 @@ class TestMemoryEdgeCases:
try: try:
os.chmod(readonly_dir, 0o444) os.chmod(readonly_dir, 0o444)
# This might raise or might work depending on OS # This might raise or might work depending on OS
memory = Memory(storage_dir=str(readonly_dir)) Memory(storage_dir=str(readonly_dir))
except (PermissionError, OSError): except (PermissionError, OSError):
pass # Expected on some systems pass # Expected on some systems
finally: finally:
@@ -512,7 +511,7 @@ class TestMemoryContextEdgeCases:
"""Should handle multiple init calls.""" """Should handle multiple init calls."""
_memory_ctx.set(None) _memory_ctx.set(None)
mem1 = init_memory(str(temp_dir)) init_memory(str(temp_dir))
mem2 = init_memory(str(temp_dir)) mem2 = init_memory(str(temp_dir))
# Second call should replace first # Second call should replace first
+1 -1
View File
@@ -178,7 +178,7 @@ class TestPromptBuilderStructure:
description = builder._format_tools_description() description = builder._format_tools_description()
# Should have tool names and descriptions # Should have tool names and descriptions
for tool_name, tool in tools.items(): for tool_name, _tool in tools.items():
assert tool_name in description assert tool_name in description
# Should have parameters info # Should have parameters info
assert "Parameters" in description or "parameters" in description assert "Parameters" in description or "parameters" in description
+1 -1
View File
@@ -71,7 +71,7 @@ class TestToolSpecFormat:
# Verify function has valid signature # Verify function has valid signature
try: try:
sig = inspect.signature(tool.func) inspect.signature(tool.func)
# If we get here, signature is valid # If we get here, signature is valid
except Exception as e: except Exception as e:
pytest.fail(f"Tool {name} has invalid signature: {e}") pytest.fail(f"Tool {name} has invalid signature: {e}")
+1 -1
View File
@@ -245,7 +245,7 @@ class TestMakeToolsEdgeCases:
for tool in tools.values(): for tool in tools.values():
if "properties" in tool.parameters: if "properties" in tool.parameters:
for prop_name, prop_schema in tool.parameters["properties"].items(): for _prop_name, prop_schema in tool.parameters["properties"].items():
if "enum" in prop_schema: if "enum" in prop_schema:
assert isinstance(prop_schema["enum"], list) assert isinstance(prop_schema["enum"], list)
assert len(prop_schema["enum"]) > 0 assert len(prop_schema["enum"]) > 0