Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions src/utils/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,21 @@ class InvalidConfigurationError(Exception):


def get_attribute_from_file(data: dict, file_name_key: str) -> Optional[str]:
"""Retrieve value of an attribute from a file."""
"""
Return the contents of a file whose path is stored in the given mapping.

Looks up file_name_key in data; if a non-None value is found it is treated
as a filesystem path, the content of the file is read. In case the key is
missing or maps to None, returns None.

Parameters:
data (dict): Mapping containing the file path under file_name_key.
file_name_key (str): Key in `data` whose value is the path to the file.

Returns:
Optional[str]: File contents with trailing whitespace stripped, or None
if the key is not present or is None.
"""
file_path = data.get(file_name_key)
if file_path is not None:
with open(file_path, encoding="utf-8") as f:
Expand All @@ -22,7 +36,21 @@ def get_attribute_from_file(data: dict, file_name_key: str) -> Optional[str]:


def file_check(path: FilePath, desc: str) -> None:
"""Check that path is a readable regular file."""
"""
Ensure the given path is an existing regular file and is readable.

If the path is not a regular file or is not readable, raises
InvalidConfigurationError.

Parameters:
path (FilePath): Filesystem path to validate.
desc (str): Short description of the value being checked; used in error
messages.

Raises:
InvalidConfigurationError: If `path` does not point to a file or is not
readable.
"""
if not os.path.isfile(path):
raise InvalidConfigurationError(f"{desc} '{path}' is not a file")
if not os.access(path, os.R_OK):
Expand Down
22 changes: 16 additions & 6 deletions src/utils/suid.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,31 @@


def get_suid() -> str:
"""Generate a unique session ID (SUID) using UUID4.
"""
Generate a unique session ID (SUID) using UUID4.
The value is a canonical RFC 4122 UUID (hex groups separated by
hyphens) generated with uuid.uuid4().
Returns:
A unique session ID.
str: A UUID4 string suitable for use as a session identifier.
"""
return str(uuid.uuid4())


def check_suid(suid: str) -> bool:
"""Check if given string is a proper session ID.
Args:
suid: The string to check.
"""
Check if given string is a proper session ID.
Returns True if the string is a valid UUID, False otherwise.
Parameters:
suid (str | bytes): UUID value to validate — accepts a UUID string or
its byte representation.
Notes:
Validation is performed by attempting to construct uuid.UUID(suid);
invalid formats or types result in False.
Comment on lines 19 to +31
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Align docstring and signature with declared behavior.

The docstring now promises that check_suid accepts str | bytes, yet the type annotation still restricts the argument to str, which will force callers to fight type checkers. While you are touching the docstring, please update the signature (and the docstring sections) so that the runtime behavior, annotations, and Google-style docs stay consistent. Suggested fix:

-def check_suid(suid: str) -> bool:
+def check_suid(suid: str | bytes) -> bool:
@@
-    Parameters:
-        suid (str | bytes): UUID value to validate — accepts a UUID string or
-        its byte representation.
-
-    Notes:
-        Validation is performed by attempting to construct uuid.UUID(suid);
-        invalid formats or types result in False.
+    Args:
+        suid: UUID value to validate — accepts a UUID string or its byte
+            representation.
+
+    Returns:
+        bool: True if `uuid.UUID(suid)` succeeds, False otherwise.
+
+    Notes:
+        Validation is performed by attempting to construct uuid.UUID(suid);
+        invalid formats or types result in False.

As per coding guidelines.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def check_suid(suid: str) -> bool:
"""Check if given string is a proper session ID.
Args:
suid: The string to check.
"""
Check if given string is a proper session ID.
Returns True if the string is a valid UUID, False otherwise.
Parameters:
suid (str | bytes): UUID value to validateaccepts a UUID string or
its byte representation.
Notes:
Validation is performed by attempting to construct uuid.UUID(suid);
invalid formats or types result in False.
def check_suid(suid: str | bytes) -> bool:
"""
Check if given string is a proper session ID.
Args:
suid: UUID value to validateaccepts a UUID string or its byte
representation.
Returns:
bool: True if `uuid.UUID(suid)` succeeds, False otherwise.
Notes:
Validation is performed by attempting to construct uuid.UUID(suid);
invalid formats or types result in False.
"""
🤖 Prompt for AI Agents
In src/utils/suid.py around lines 19 to 31, the function signature and docstring
disagree: the docstring says the parameter accepts str | bytes but the type
annotation is only str; update the function signature to accept both types
(e.g., suid: str | bytes or Union[str, bytes]) and edit the docstring parameter
type and description to match the annotation (ensure the "Parameters" section
shows "suid (str | bytes): ..." and remove any contradictory wording), keeping
the existing runtime validation logic unchanged and ensuring imports
(typing.Union) are added if needed.

"""
try:
# accepts strings and bytes only
Expand Down
34 changes: 31 additions & 3 deletions src/utils/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ class Singleton(type):
_instances = {} # type: ignore

def __call__(cls, *args, **kwargs): # type: ignore
"""Ensure a single instance is created."""
"""
Return the single cached instance of the class, creating and caching it on first call.

Returns:
object: The singleton instance for this class.
"""
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
Expand All @@ -29,14 +34,37 @@ class GraniteToolParser(ToolParser):
"""Workaround for 'tool_calls' with granite models."""

def get_tool_calls(self, output_message: CompletionMessage) -> list[ToolCall]:
"""Use 'tool_calls' associated with the CompletionMessage, if available."""
"""
Return the `tool_calls` list from a CompletionMessage, or an empty list if none are present.

Parameters:
output_message (CompletionMessage | None): Completion
message potentially containing `tool_calls`.

Returns:
list[ToolCall]: The list of tool call entries
extracted from `output_message`, or an empty list.
"""
if output_message and output_message.tool_calls:
return output_message.tool_calls
return []

@staticmethod
def get_parser(model_id: str) -> Optional[ToolParser]:
"""Get the applicable ToolParser for the model."""
"""
Return a GraniteToolParser when the model identifier denotes a Granite model.

Returns None otherwise.

Parameters:
model_id (str): Model identifier string checked case-insensitively.
If it starts with "granite", a GraniteToolParser instance is
returned.

Returns:
Optional[ToolParser]: GraniteToolParser for Granite models, or None
if `model_id` is falsy or does not start with "granite".
"""
if model_id and model_id.lower().startswith("granite"):
return GraniteToolParser()
return None
Expand Down
Loading