Code Parser

class codestral_ros2_gen.utils.code_parser.ROS2CodeParser[source]

Bases: object

Generic parser for ROS2 Python code generated by AI models.

This class provides a method to parse and format Python code extracted from code blocks marked as python code in a model’s response. It ensures the code is properly formatted and includes the necessary shebang line for ROS2 compatibility.

None
parse(response

str) -> Optional[str]: Parse model response: extract and format code only from code blocks that marked as python code.

static parse(response)[source]

Parse model response: extract and format code only from code blocks with python code markers.

This method extracts Python code from a response string that is marked with python code marker at the start. It then formats the extracted code using the Black code formatter and ensures it includes the necessary shebang line for ROS2 compatibility.

Parameters:

response (str) – Raw model response containing code blocks.

Returns:

Formatted Python code or None if parsing or formatting fails.

Return type:

Optional[str]

Raises:

None

Examples

>>> parser = ROS2CodeParser()
>>> response = """Here is some text with a code block:
... ```python
... def example_function():
...     print('Hello, world!')
... ```
... """
>>> parser.parse(response)
'#!/usr/bin/env python3
def example_function():
    print("Hello, world!")'