Fix some ruff issues in code

This commit is contained in:
2025-12-07 05:33:39 +01:00
parent 7c9598f632
commit 10704896f9
12 changed files with 27 additions and 28 deletions
+7 -4
View File
@@ -2,7 +2,8 @@
import json import json
import logging import logging
from typing import Any, AsyncGenerator from collections.abc import AsyncGenerator
from typing import Any
from infrastructure.persistence import get_memory from infrastructure.persistence import get_memory
@@ -77,7 +78,7 @@ class Agent:
tools_spec = self.prompt_builder.build_tools_spec() tools_spec = self.prompt_builder.build_tools_spec()
# Tool execution loop # Tool execution loop
for iteration in range(self.max_tool_iterations): for _iteration in range(self.max_tool_iterations):
# Call LLM with tools # Call LLM with tools
llm_result = self.llm.complete(messages, tools=tools_spec) llm_result = self.llm.complete(messages, tools=tools_spec)
@@ -229,7 +230,7 @@ class Agent:
tools_spec = self.prompt_builder.build_tools_spec() tools_spec = self.prompt_builder.build_tools_spec()
# Tool execution loop # Tool execution loop
for iteration in range(self.max_tool_iterations): for _iteration in range(self.max_tool_iterations):
# Call LLM with tools # Call LLM with tools
llm_result = self.llm.complete(messages, tools=tools_spec) llm_result = self.llm.complete(messages, tools=tools_spec)
@@ -317,7 +318,9 @@ class Agent:
) )
# Stream tool result as content # Stream tool result as content
result_text = f"\n🔧 {tool_name}: {json.dumps(tool_result, ensure_ascii=False)}\n" result_text = (
f"\n🔧 {tool_name}: {json.dumps(tool_result, ensure_ascii=False)}\n"
)
yield { yield {
"id": completion_id, "id": completion_id,
"object": "chat.completion.chunk", "object": "chat.completion.chunk",
+4 -4
View File
@@ -46,13 +46,13 @@ def _create_tool_from_function(func: Callable) -> Tool:
# Map Python types to JSON schema types # Map Python types to JSON schema types
param_type = "string" # default param_type = "string" # default
if param.annotation != inspect.Parameter.empty: if param.annotation != inspect.Parameter.empty:
if param.annotation == str: if param.annotation is str:
param_type = "string" param_type = "string"
elif param.annotation == int: elif param.annotation is int:
param_type = "integer" param_type = "integer"
elif param.annotation == float: elif param.annotation is float:
param_type = "number" param_type = "number"
elif param.annotation == bool: elif param.annotation is bool:
param_type = "boolean" param_type = "boolean"
properties[param_name] = { properties[param_name] = {
+7 -2
View File
@@ -207,7 +207,9 @@ async def chat_completions(chat_request: ChatCompletionRequest):
async def event_generator(): async def event_generator():
try: try:
# Stream the agent execution # Stream the agent execution
async for chunk in agent.step_streaming(user_input, completion_id, created_ts, chat_request.model): async for chunk in agent.step_streaming(
user_input, completion_id, created_ts, chat_request.model
):
yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n" yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
yield "data: [DONE]\n\n" yield "data: [DONE]\n\n"
except LLMAPIError as e: except LLMAPIError as e:
@@ -237,7 +239,10 @@ async def chat_completions(chat_request: ChatCompletionRequest):
"choices": [ "choices": [
{ {
"index": 0, "index": 0,
"delta": {"role": "assistant", "content": "Internal agent error"}, "delta": {
"role": "assistant",
"content": "Internal agent error",
},
"finish_reason": "stop", "finish_reason": "stop",
} }
], ],
+1 -2
View File
@@ -1,5 +1,6 @@
"""Movie domain value objects.""" """Movie domain value objects."""
import re
from dataclasses import dataclass from dataclasses import dataclass
from enum import Enum from enum import Enum
@@ -66,8 +67,6 @@ class MovieTitle:
Removes special characters and replaces spaces with dots. Removes special characters and replaces spaces with dots.
""" """
import re
# Remove special characters except spaces, dots, and hyphens # Remove special characters except spaces, dots, and hyphens
cleaned = re.sub(r"[^\w\s\.\-]", "", self.value) cleaned = re.sub(r"[^\w\s\.\-]", "", self.value)
# Replace spaces with dots # Replace spaces with dots
+1 -4
View File
@@ -1,5 +1,6 @@
"""TV Show domain entities.""" """TV Show domain entities."""
import re
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import datetime from datetime import datetime
@@ -65,8 +66,6 @@ class TVShow:
Format: "Title" Format: "Title"
Example: "Breaking.Bad" Example: "Breaking.Bad"
""" """
import re
# Remove special characters and replace spaces with dots # Remove special characters and replace spaces with dots
cleaned = re.sub(r"[^\w\s\.\-]", "", self.title) cleaned = re.sub(r"[^\w\s\.\-]", "", self.title)
return cleaned.replace(" ", ".") return cleaned.replace(" ", ".")
@@ -193,8 +192,6 @@ class Episode:
episode_str = f"E{self.episode_number.value:02d}" episode_str = f"E{self.episode_number.value:02d}"
# Clean title for filename # Clean title for filename
import re
clean_title = re.sub(r"[^\w\s\-]", "", self.title) clean_title = re.sub(r"[^\w\s\-]", "", self.title)
clean_title = clean_title.replace(" ", ".") clean_title = clean_title.replace(" ", ".")
+3 -3
View File
@@ -99,7 +99,7 @@ class TestExecuteToolCall:
"arguments": '{"folder_name": 123}', # Wrong type "arguments": '{"folder_name": 123}', # Wrong type
}, },
} }
result = agent._execute_tool_call(tool_call) agent._execute_tool_call(tool_call)
mem = get_memory() mem = get_memory()
assert len(mem.episodic.recent_errors) > 0 assert len(mem.episodic.recent_errors) > 0
@@ -187,7 +187,7 @@ class TestStep:
mock_llm.complete = Mock(side_effect=mock_complete) mock_llm.complete = Mock(side_effect=mock_complete)
agent = Agent(llm=mock_llm, max_tool_iterations=3) agent = Agent(llm=mock_llm, max_tool_iterations=3)
response = agent.step("Do something") agent.step("Do something")
assert call_count[0] == 4 assert call_count[0] == 4
@@ -278,6 +278,6 @@ class TestAgentIntegration:
mock_llm.complete = Mock(side_effect=mock_complete) mock_llm.complete = Mock(side_effect=mock_complete)
agent = Agent(llm=mock_llm) agent = Agent(llm=mock_llm)
response = agent.step("List my downloads and movies") agent.step("List my downloads and movies")
assert call_count[0] == 3 assert call_count[0] == 3
+4 -4
View File
@@ -164,7 +164,7 @@ class TestStepEdgeCases:
mock_llm.complete = Mock(side_effect=mock_complete) mock_llm.complete = Mock(side_effect=mock_complete)
agent = Agent(llm=mock_llm, max_tool_iterations=3) agent = Agent(llm=mock_llm, max_tool_iterations=3)
response = agent.step("Loop test") agent.step("Loop test")
assert call_count[0] == 4 assert call_count[0] == 4
@@ -191,7 +191,7 @@ class TestStepEdgeCases:
) )
agent = Agent(llm=mock_llm) agent = Agent(llm=mock_llm)
response = agent.step("Hello") agent.step("Hello")
call_args = mock_llm.complete.call_args[0][0] call_args = mock_llm.complete.call_args[0][0]
system_prompt = call_args[0]["content"] system_prompt = call_args[0]["content"]
@@ -208,7 +208,7 @@ class TestStepEdgeCases:
) )
agent = Agent(llm=mock_llm) agent = Agent(llm=mock_llm)
response = agent.step("Hello") agent.step("Hello")
call_args = mock_llm.complete.call_args[0][0] call_args = mock_llm.complete.call_args[0][0]
system_prompt = call_args[0]["content"] system_prompt = call_args[0]["content"]
@@ -268,7 +268,7 @@ class TestAgentConcurrencyEdgeCases:
mock_llm.complete = Mock(side_effect=mock_complete) mock_llm.complete = Mock(side_effect=mock_complete)
agent = Agent(llm=mock_llm) agent = Agent(llm=mock_llm)
response = agent.step("Set movie folder") agent.step("Set movie folder")
mem = get_memory() mem = get_memory()
assert mem.ltm.get_config("movie_folder") == str(real_folder["movies"]) assert mem.ltm.get_config("movie_folder") == str(real_folder["movies"])
-1
View File
@@ -1,6 +1,5 @@
"""Critical tests for configuration validation.""" """Critical tests for configuration validation."""
import pytest import pytest
from agent.config import ConfigurationError, Settings from agent.config import ConfigurationError, Settings
-1
View File
@@ -1,6 +1,5 @@
"""Critical tests for prompt builder - Tests that would have caught bugs.""" """Critical tests for prompt builder - Tests that would have caught bugs."""
from agent.prompts import PromptBuilder from agent.prompts import PromptBuilder
from agent.registry import make_tools from agent.registry import make_tools
-1
View File
@@ -1,6 +1,5 @@
"""Edge case tests for PromptBuilder.""" """Edge case tests for PromptBuilder."""
from agent.prompts import PromptBuilder from agent.prompts import PromptBuilder
from agent.registry import make_tools from agent.registry import make_tools
-1
View File
@@ -1,6 +1,5 @@
"""Edge case tests for tool registry.""" """Edge case tests for tool registry."""
import pytest import pytest
from agent.registry import Tool, make_tools from agent.registry import Tool, make_tools
-1
View File
@@ -1,6 +1,5 @@
"""Tests for JSON repositories.""" """Tests for JSON repositories."""
from domain.movies.entities import Movie from domain.movies.entities import Movie
from domain.movies.value_objects import MovieTitle, Quality, ReleaseYear from domain.movies.value_objects import MovieTitle, Quality, ReleaseYear
from domain.shared.value_objects import FilePath, FileSize, ImdbId from domain.shared.value_objects import FilePath, FileSize, ImdbId