ronantakizawa/codereview-bench huggingface dataset:
Repository: emcie-co/parlant
File: tests/adapters/nlp/test_litellm_service.py (Python)

Code before:
# Copyright 2026 Emcie Co Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import os
from unittest.mock import AsyncMock, patch, Mock

import pytest
from lagom import Container

from parlant.adapters.nlp.litellm_service import (
    LiteLLMEmbedder,
    LiteLLMService,
)
from parlant.adapters.nlp.hugging_face import JinaAIEmbedder

Review comment (suggestion):
I'm not sure we need this (I presume generated?) test file.  The tests don't seem particularly meaningful, and ultimately, the maintenance and testing of specific provider adapters is IMO better done manually.

Code after:
# Copyright 2026 Emcie Co Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import os
from unittest.mock import patch, Mock

from lagom import Container

from parlant.adapters.nlp.litellm_service import (
    LiteLLMEmbedder,
    LiteLLMService,
)
from parlant.core.loggers import Logger
from parlant.core.meter import Meter
Repository: faif/python-patterns
File: behavioral/chain.py (Python)

Code before:
Allow a request to pass down a chain of receivers until it is handled.
"""

import abc


class Handler(object):
    __metaclass__ = abc.ABCMeta

    def __init__(self, successor=None):
        self.successor = successor

    def handle(self, request):
        """
        Handle request and stop.
        If can't - call next handler in chain.

        As an alternative you might even in case of success
        call the next handler.
        """
        res = self.compare(request)
        if not res and self.successor:
            self.successor.handle(request)

    @abc.abstractmethod
    def compare(self, request):
        """Compare passed value to predefined interval"""


class ConcreteHandler0(Handler):
    def compare(self, request):
        if 0 <= request < 10:
            print('request {} handled in handler 0'.format(request))
            return True


class ConcreteHandler1(Handler):
    def compare(self, request):
        if 10 <= request < 20:
            print('request {} handled in handler 1'.format(request))
            return True


class ConcreteHandler2(Handler):
    def compare(self, request):
        if 20 <= request < 30:
            print('request {} handled in handler 2'.format(request))
            return True


class DefaultHandler(Handler):

Review comment (suggestion):
I suggest to find a better name for `compare` and make it static (using @staticmethod). `compare` as a class method means compare this object/instance to another object/instance of the same class (e.g. implemented as `__cmp__(self, other)`

Code after:
Allow a request to pass down a chain of receivers until it is handled.
"""

import abc


class Handler(object):
    __metaclass__ = abc.ABCMeta

    def __init__(self, successor=None):
        self.successor = successor

    def handle(self, request):
        """
        Handle request and stop.
        If can't - call next handler in chain.

        As an alternative you might even in case of success
        call the next handler.
        """
        res = self.check_range(request)
        if not res and self.successor:
            self.successor.handle(request)

    @abc.abstractmethod
    def check_range(self, request):
        """Compare passed value to predefined interval"""


class ConcreteHandler0(Handler):
    """Each handler can be different.
    Be simple and static...
    """

    @staticmethod
    def check_range(request):
        if 0 <= request < 10:
            print("request {} handled in handler 0".format(request))
            return True


class ConcreteHandler1(Handler):
    """... With it's own internal state"""

    start, end = 10, 20

    def check_range(self, request):
        if self.start <= request < self.end:
            print("request {} handled in handler 1".format(request))
            return True
Repository: faif/python-patterns
File: patterns/structural/proxy.py (Python)

Code before:

        if user == 'admin':
            self._real_subject.do_the_job(user)
        else:
            print(f'[log] I can do the job just for `admins`.')


def client(job_doer, user):
    job_doer.do_the_job(user)

if __name__ == '__main__':
    proxy = Proxy()
    real_subject = RealSubject()

    print('# doing the job with proxy:')
    client(proxy, 'admin')
    client(proxy, 'anonymous')

    print()

    print('# doing the job with real-subject:')
    client(real_subject, 'admin')
    client(real_subject, 'anonymous')


OUTPUT = """
# doing the job with proxy:
[log] Doing the job for admin is requested.
> I am doing the job for admin
[log] Doing the job for anonymous is requested.
[log] I can do the job just for `admins`.

# doing the job with real-subject:
> I am doing the job for admin
> I am doing the job for anonymous
"""  # noqa


Review comment (suggestion):
I would like you to try this kind of outputs testing
https://github.com/faif/python-patterns/blob/8dbfbd67b8c178b23b84e74302563a0f6ec95cfa/patterns/behavioral/template.py#L49-L72

It is an ongoing task to move all OUTPUTs to be like doctests.

Code after:

        if user == 'admin':
            self._real_subject.do_the_job(user)
        else:
            print(f'[log] I can do the job just for `admins`.')


def client(job_doer, user):
    job_doer.do_the_job(user)

def main():
    """
    >>> proxy = Proxy()

    >>> real_subject = RealSubject()

    >>> client(proxy, 'admin')
    [log] Doing the job for admin is requested.
    I am doing the job for admin

    >>> client(proxy, 'anonymous')
    [log] Doing the job for anonymous is requested.
    [log] I can do the job just for `admins`.

    >>> client(real_subject, 'admin')
    I am doing the job for admin

    >>> client(real_subject, 'anonymous')
    I am doing the job for anonymous
    """


if __name__ == '__main__':
    import doctest
    doctest.testmod()
Repository: faif/python-patterns
File: patterns/behavioral/command.py (Python)

Code before:
"""
Command pattern decouples the object invoking a job from the one who knows
how to do it. As mentioned in the GoF book, a good example is in menu items.
You have a menu that has lots of items. Each item is responsible for doing a
special thing and you want your menu item just call the `execute` method when
it is pressed. To achieve this you implement a command object with the `execute`
method for each menu item and pass to it.

*TL;DR
Object oriented implementation of callback functions.

*Examples in Python ecosystem:
Django HttpRequest (without `execute` method):
https://docs.djangoproject.com/en/2.1/ref/request-response/#httprequest-objects
"""


class Command:
    """
    The interface that commands implement. This is used to abstract invoker from
    the command is going to handle the job.
    """

    def execute(self):
        raise NotImplementedError()


class MakeBoldCommand(Command):
    """
    A simple command to bold a text.
    """

    def execute(self):
        print('I am making it bold.')


class MakeItalicCommand(Command):
    """
    A simple command to italic a text.
    """

    def execute(self):
        print('I am making it italic.')


class MenuItem:
    """
    The invoker class. Here it is items in a menu.

Review comment (suggestion):
I'm also not a fan of interfaces in Python. They are not required so I recommend removing the `Command` class.

Code after:
"""
Command pattern decouples the object invoking a job from the one who knows
how to do it. As mentioned in the GoF book, a good example is in menu items.
You have a menu that has lots of items. Each item is responsible for doing a
special thing and you want your menu item just call the execute method when
it is pressed. To achieve this you implement a command object with the execute
method for each menu item and pass to it.

*About the example
We have a menu containing two items. Each item accepts a file name, one hides the file
and the other deletes it. Both items have an undo option.
Each item is a MenuItem class that accepts the corresponding command as input and executes
it's execute method when it is pressed.

*TL;DR
Object oriented implementation of callback functions.

*Examples in Python ecosystem:
Django HttpRequest (without execute method):
https://docs.djangoproject.com/en/2.1/ref/request-response/#httprequest-objects
"""


class HideFileCommand:
    """
    A command to hide a file given its name
    """

    def __init__(self):
        # an array of files hidden, to undo them as needed
        self._hidden_files = []

    def execute(self, filename):
        print(f'hiding {filename}')
        self._hidden_files.append(filename)

    def undo(self):
        filename = self._hidden_files.pop()
        print(f'un-hiding {filename}')


class DeleteFileCommand:
    """
    A command to delete a file given its name
    """

    def __init__(self):
        # an array of deleted files, to undo them as needed
Repository: faif/python-patterns
File: patterns/behavioral/command.py (Python)

Code before:

*TL;DR
Object oriented implementation of callback functions.

*Examples in Python ecosystem:
Django HttpRequest (without `execute` method):
https://docs.djangoproject.com/en/2.1/ref/request-response/#httprequest-objects
"""


class Command:
    """
    The interface that commands implement. This is used to abstract invoker from
    the command is going to handle the job.
    """

    def execute(self):
        raise NotImplementedError()


class MakeBoldCommand(Command):
    """
    A simple command to bold a text.
    """

    def execute(self):
        print('I am making it bold.')


class MakeItalicCommand(Command):
    """
    A simple command to italic a text.
    """

    def execute(self):
        print('I am making it italic.')


class MenuItem:
    """
    The invoker class. Here it is items in a menu.
    """

    def __init__(self, command):
        self._command = command

    def on_press(self):
        self._command.execute()


def main():

Review comment (suggestion):
To show the effect of the command it is good to have some definition of bold. Maybe in this case wrap the text with the HTML `<b>` or `<strong>` element. The same goes for italic.

Code after:

*About the example
We have a menu containing two items. Each item accepts a file name, one hides the file
and the other deletes it. Both items have an undo option.
Each item is a MenuItem class that accepts the corresponding command as input and executes
it's execute method when it is pressed.

*TL;DR
Object oriented implementation of callback functions.

*Examples in Python ecosystem:
Django HttpRequest (without execute method):
https://docs.djangoproject.com/en/2.1/ref/request-response/#httprequest-objects
"""


class HideFileCommand:
    """
    A command to hide a file given its name
    """

    def __init__(self):
        # an array of files hidden, to undo them as needed
        self._hidden_files = []

    def execute(self, filename):
        print(f'hiding {filename}')
        self._hidden_files.append(filename)

    def undo(self):
        filename = self._hidden_files.pop()
        print(f'un-hiding {filename}')


class DeleteFileCommand:
    """
    A command to delete a file given its name
    """

    def __init__(self):
        # an array of deleted files, to undo them as needed
        self._deleted_files = []

    def execute(self, filename):
        print(f'deleting {filename}')
        self._deleted_files.append(filename)

    def undo(self):
        filename = self._deleted_files.pop()
        print(f'restoring {filename}')
Repository: faif/python-patterns
File: patterns/behavioral/command.py (Python)

Code before:
    """
    A simple command to bold a text.
    """

    def execute(self):
        print('I am making it bold.')


class MakeItalicCommand(Command):
    """
    A simple command to italic a text.
    """

    def execute(self):
        print('I am making it italic.')


class MenuItem:
    """
    The invoker class. Here it is items in a menu.
    """

    def __init__(self, command):
        self._command = command

    def on_press(self):
        self._command.execute()


def main():
    """
    >>> item1 = MenuItem(MakeBoldCommand())

    >>> item2 = MenuItem(MakeItalicCommand())

    >>> item1.on_press()
    I am making it bold.

    >>> item2.on_press()
    I am making it italic.
    """


if __name__ == "__main__":
    import doctest
    doctest.testmod()


Review comment (suggestion):
`undo` is one of the features that characterises the command pattern, so I don't think that it's a good idea to remove it.

Code after:
    def __init__(self):
        # an array of files hidden, to undo them as needed
        self._hidden_files = []

    def execute(self, filename):
        print(f'hiding {filename}')
        self._hidden_files.append(filename)

    def undo(self):
        filename = self._hidden_files.pop()
        print(f'un-hiding {filename}')


class DeleteFileCommand:
    """
    A command to delete a file given its name
    """

    def __init__(self):
        # an array of deleted files, to undo them as needed
        self._deleted_files = []

    def execute(self, filename):
        print(f'deleting {filename}')
        self._deleted_files.append(filename)

    def undo(self):
        filename = self._deleted_files.pop()
        print(f'restoring {filename}')


class MenuItem:
    """
    The invoker class. Here it is items in a menu.
    """

    def __init__(self, command):
        self._command = command

    def on_do_press(self, filename):
        self._command.execute(filename)

    def on_undo_press(self):
        self._command.undo()


def main():
    """
    >>> item1 = MenuItem(DeleteFileCommand())

    >>> item2 = MenuItem(HideFileCommand())
Repository: faif/python-patterns
File: patterns/behavioral/command.py (Python)

Code before:

            os.rename(filename, f'.{filename}')
            self._hidden_files.append(filename)
        else:
            print(f'{filename} dose not exists to hide')

    def undo(self):
        if len(self._hidden_files) > 0:
            filename = self._hidden_files.pop()

            print(f'un-hiding {filename}')

            os.rename(f'.{filename}', filename)


class DeleteFileCommand:
    """
    A command to delete a file given its name
    """

    def __init__(self):
        # an array of deleted files, to undo them as needed
        self._deleted_files = []

        # create a directory to store deleted files
        if not os.path.exists('bin'):
            os.makedirs('bin')

    def execute(self, filename):
        if os.path.isfile(filename):
            print(f'deleting {filename}')

            os.rename(filename, f'bin/{filename}')
            self._deleted_files.append(filename)
        else:
            print(f'{filename} dose not exists to delete')

    def undo(self):
        if len(self._deleted_files) > 0:
            filename = self._deleted_files.pop()

            print(f'un-deleting {filename}')

            os.rename(f'bin/{filename}', filename)


class MenuItem:
    """
    The invoker class. Here it is items in a menu.
    """


Review comment (suggestion):
Please choose something else (maybe "trash)" since `bin` is a common name for storing executable files and might cause confusion

Code after:
        filename = self._hidden_files.pop()
        print(f'un-hiding {filename}')


class DeleteFileCommand:
    """
    A command to delete a file given its name
    """

    def __init__(self):
        # an array of deleted files, to undo them as needed
        self._deleted_files = []

    def execute(self, filename):
        print(f'deleting {filename}')
        self._deleted_files.append(filename)

    def undo(self):
        filename = self._deleted_files.pop()
        print(f'restoring {filename}')


class MenuItem:
    """
    The invoker class. Here it is items in a menu.
    """

    def __init__(self, command):
        self._command = command

    def on_do_press(self, filename):
        self._command.execute(filename)

    def on_undo_press(self):
        self._command.undo()


def main():
    """
    >>> item1 = MenuItem(DeleteFileCommand())

    >>> item2 = MenuItem(HideFileCommand())

    # create a file named `test-file` to work with
    >>> test_file_name = 'test-file'

    # deleting `test-file`
    >>> item1.on_do_press(test_file_name)
    deleting test-file

    # restoring `test-file`
Repository: faif/python-patterns
File: patterns/behavioral/command.py (Python)

Code before:

    def undo(self):
        if len(self._hidden_files) > 0:
            filename = self._hidden_files.pop()

            print(f'un-hiding {filename}')

            os.rename(f'.{filename}', filename)


class DeleteFileCommand:
    """
    A command to delete a file given its name
    """
    _deleted_files_path = 'trash'

    def __init__(self):
        # an array of deleted files, to undo them as needed
        self._deleted_files = []

        # create a directory to store deleted files
        if not os.path.exists(self._deleted_files_path):
            os.makedirs(self._deleted_files_path)

    def execute(self, filename):
        if os.path.isfile(filename):
            print(f'deleting {filename}')

            os.rename(filename, f'{self._deleted_files_path}/{filename}')
            self._deleted_files.append(filename)
        else:
            print(f'{filename} dose not exists to delete')

    def undo(self):
        if len(self._deleted_files) > 0:
            filename = self._deleted_files.pop()

            print(f'un-deleting {filename}')

            os.rename(f'{self._deleted_files_path}/{filename}', filename)


class MenuItem:
    """
    The invoker class. Here it is items in a menu.
    """

    def __init__(self, command):
        self._command = command

    def on_do_press(self, filename):

Review comment (suggestion):
I think names like `on_do_press` and `on_undo_press` are harder to read then `rename`, `delete` or whatever else

Code after:
    """
    A command to delete a file given its name
    """

    def __init__(self):
        # an array of deleted files, to undo them as needed
        self._deleted_files = []

    def execute(self, filename):
        print(f'deleting {filename}')
        self._deleted_files.append(filename)

    def undo(self):
        filename = self._deleted_files.pop()
        print(f'restoring {filename}')


class MenuItem:
    """
    The invoker class. Here it is items in a menu.
    """

    def __init__(self, command):
        self._command = command

    def on_do_press(self, filename):
        self._command.execute(filename)

    def on_undo_press(self):
        self._command.undo()


def main():
    """
    >>> item1 = MenuItem(DeleteFileCommand())

    >>> item2 = MenuItem(HideFileCommand())

    # create a file named `test-file` to work with
    >>> test_file_name = 'test-file'

    # deleting `test-file`
    >>> item1.on_do_press(test_file_name)
    deleting test-file

    # restoring `test-file`
    >>> item1.on_undo_press()
    restoring test-file

    # hiding `test-file`
    >>> item2.on_do_press(test_file_name)
Repository: faif/python-patterns
File: patterns/creational/factory.py (Python)

Code before:
http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/

*TL;DR
Creates objects without having to specify the exact class.
"""


class GreekLocalizer:
    """A simple localizer a la gettext"""

    def __init__(self) -> None:
        self.translations = {"dog": "σκύλος", "cat": "γάτα"}

    def localize(self, msg: str) -> str:
        """We'll punt if we don't have a translation"""
        return self.translations.get(msg, msg)


class EnglishLocalizer:
    """Simply echoes the message"""

    def localize(self, msg: str) -> str:
        return msg


def get_localizer(language: str = "English",) -> object:

    """Factory"""
    localizers = {
        "English": EnglishLocalizer,
        "Greek": GreekLocalizer,
    }

    return localizers[language]()


def main():
    """
    # Create our localizers
    >>> e, g = get_localizer(language="English"), get_localizer(language="Greek")

    # Localize some text
    >>> for msg in "dog parrot cat bear".split():
    ...     print(e.localize(msg), g.localize(msg))
    dog σκύλος
    parrot parrot
    cat γάτα
    bear bear
    """



Review comment (suggestion):
Is the comma required here? Also, please check with a linter like `pep8`. AFAIR spaces around arguments are not recommended.

Code after:
http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/

*TL;DR
Creates objects without having to specify the exact class.
"""


class GreekLocalizer:
    """A simple localizer a la gettext"""

    def __init__(self) -> None:
        self.translations = {"dog": "σκύλος", "cat": "γάτα"}

    def localize(self, msg: str) -> str:
        """We'll punt if we don't have a translation"""
        return self.translations.get(msg, msg)


class EnglishLocalizer:
    """Simply echoes the message"""

    def localize(self, msg: str) -> str:
        return msg


def get_localizer(language: str = "English") -> object:

    """Factory"""
    localizers = {
        "English": EnglishLocalizer,
        "Greek": GreekLocalizer,
    }

    return localizers[language]()


def main():
    """
    # Create our localizers
    >>> e, g = get_localizer(language="English"), get_localizer(language="Greek")

    # Localize some text
    >>> for msg in "dog parrot cat bear".split():
    ...     print(e.localize(msg), g.localize(msg))
    dog σκύλος
    parrot parrot
    cat γάτα
    bear bear
    """