# Copyright 2022-2023 XProbe Inc.
#
# 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 json
from typing import Any, Iterator


def streaming_response_iterator(
    response_lines: Iterator[bytes],
) -> Iterator[Any]:
    """
    Create an Iterator to handle the streaming type of generation.

    Note
    ----------
    This method is for compatible with openai. Please refer to:
    https://github.com/openai/openai-python/blob/v0.28.1/openai/api_requestor.py#L99

    Parameters
    ----------
    response_lines: Iterator[bytes]
        Generated lines by the Model Generator.

    Returns
    -------
    Iterator["CompletionChunk"]
        Iterator of CompletionChunks generated by models.

    """

    for line in response_lines:
        line = line.strip()
        if line.startswith(b"data:"):
            json_str = line[len(b"data:") :].strip()
            if json_str == b"[DONE]":
                continue
            data = json.loads(json_str.decode("utf-8"))
            error = data.get("error")
            if error is not None:
                raise Exception(str(error))
            yield data
