Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/openai/_utils/_streams.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,32 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

import json
from typing import Any, Dict, Generator, List, Union, AsyncGenerator

def safe_json_parse(chunk: str) -> Dict[str, Any]:
"""Parses JSON safely by stripping leading whitespace/newlines."""
return json.loads(chunk.lstrip())

def parse_stream(chunks: List[str]) -> Generator[Dict[str, Any], None, None]:
"""Parses a list of JSON string chunks into Python dicts."""
for chunk in chunks:
if not chunk:
continue
try:
yield safe_json_parse(chunk)
except json.JSONDecodeError:
continue

async def parse_stream_async(chunks: AsyncGenerator[str, None]) -> AsyncGenerator[Dict[str, Any], None]:
"""Async version for parsing streamed JSON chunks into Python dicts."""
async for chunk in chunks:
if not chunk:
continue
try:
yield safe_json_parse(chunk)
except json.JSONDecodeError:
continue

from typing import Any
from typing_extensions import Iterator, AsyncIterator

Expand Down