-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbase_streaming_generator.py
More file actions
53 lines (45 loc) · 1.42 KB
/
base_streaming_generator.py
File metadata and controls
53 lines (45 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from abc import ABC, abstractmethod
from typing import Any, AsyncGenerator, Callable, Dict, Generic, Optional, TypeVar
from enum import Enum
import asyncio
T = TypeVar('T')
class StreamEventType(Enum):
START = "start"
CONTENT = "content"
ERROR = "error"
DONE = "done"
class StreamEvent(Generic[T]):
"""Represents an event in a streaming response."""
def __init__(self, event_type: StreamEventType, data: Optional[T] = None, error: Optional[Exception] = None):
self.event_type = event_type
self.data = data
self.error = error
def __str__(self) -> str:
return f"StreamEvent(type={self.event_type}, data={self.data}, error={self.error})"
class BaseStreamingGenerator(ABC):
"""Abstract base class for streaming generators."""
@abstractmethod
async def stream_text(
self,
prompt: str,
**kwargs
) -> AsyncGenerator[StreamEvent[str], None]:
"""Stream text generation."""
yield
@abstractmethod
async def stream_audio(
self,
text: str,
voice: Optional[str] = None,
**kwargs
) -> AsyncGenerator[StreamEvent[bytes], None]:
"""Stream audio generation."""
yield
@abstractmethod
async def stream_image(
self,
prompt: str,
**kwargs
) -> AsyncGenerator[StreamEvent[bytes], None]:
"""Stream image generation."""
yield