跳转至

Utils

get_sentence_based_splitter

get_sentence_based_splitter(
    min_sentence_length: int = 20,
) -> Callable[[str], tuple[str, str]]

Returns a function that splits text into chunks based on sentence boundaries.

Parameters:

Name Type Description Default
min_sentence_length int

The minimum length of a sentence to be included in a chunk.

20

Returns:

Type Description
Callable[[str], tuple[str, str]]

A function that splits text into chunks based on sentence boundaries.

Source code in .tmp/v0/src/agents/voice/utils.py
def get_sentence_based_splitter(
    min_sentence_length: int = 20,
) -> Callable[[str], tuple[str, str]]:
    """Returns a function that splits text into chunks based on sentence boundaries.

    Args:
        min_sentence_length: The minimum length of a sentence to be included in a chunk.

    Returns:
        A function that splits text into chunks based on sentence boundaries.
    """

    def sentence_based_text_splitter(text_buffer: str) -> tuple[str, str]:
        """
        A function to split the text into chunks. This is useful if you want to split the text into
        chunks before sending it to the TTS model rather than waiting for the whole text to be
        processed.

        Args:
            text_buffer: The text to split.

        Returns:
            A tuple of the text to process and the remaining text buffer.
        """
        text = text_buffer.strip()
        parts: list[str] = []
        start = 0
        for boundary in _SENTENCE_BOUNDARY.finditer(text):
            # Wait for the next sentence. A closing mark may arrive in the next delta.
            if boundary.end() == len(text):
                break
            parts.append(text[start : boundary.end("ending")])
            if boundary["space"]:
                parts.append(" ")
            start = boundary.end()

        combined_sentences = "".join(parts).rstrip()
        if len(combined_sentences) >= min_sentence_length:
            # Keep the whitespace separating the held text from the next streamed delta.
            trailing_whitespace = text_buffer[len(text_buffer.rstrip()) :]
            return combined_sentences, text[start:] + trailing_whitespace
        return "", text_buffer

    return sentence_based_text_splitter