-
Notifications
You must be signed in to change notification settings - Fork 3k
JSONL stream #39478
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
JSONL stream #39478
Changes from 11 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
036c7d0
move wip jsonl stream impl to corehttp
kristapratico 1ae20e8
async fixes
kristapratico 03c0dc1
lint/black
kristapratico c289dbe
add more tests
kristapratico 4275fab
add docstrings
kristapratico 505c2ef
pylint/black
kristapratico 8ef1983
fix test: anext --> s.__anext__ for <py3.10
kristapratico fb3eb4d
callback should take pipeline_response
kristapratico 852b7ee
move protocols
kristapratico 744a0a5
fix docstring
kristapratico cfb365d
black
kristapratico 55cbb96
make decoders, events public; stream accepts HttpResponse instead of …
kristapratico 0e9f38d
johan feedback: use codecs.getincrementaldecoder()
kristapratico 43e2517
make decoder kwonly required
kristapratico b3fbc02
remove docstring repeat
kristapratico 889f1d8
create incrementaldecoder in iter_events; remove unused test
kristapratico 6d2e5bb
switch back to splitlines(); remove event() from decoders
kristapratico 7ba7b5c
johan's feedback
kristapratico 77d90a6
remove file
kristapratico e4daa81
some feedback
kristapratico 217d14b
fix typing
kristapratico 23746d9
make JSONLDecoder generic type default to JSON + remove terminal_even…
kristapratico 02ee683
decoders -> _decoders + add more tests
kristapratico File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
# -------------------------------------------------------------------------- | ||
# | ||
# Copyright (c) Microsoft Corporation. All rights reserved. | ||
# | ||
# The MIT License (MIT) | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy | ||
# of this software and associated documentation files (the ""Software""), to | ||
# deal in the Software without restriction, including without limitation the | ||
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or | ||
# sell copies of the Software, and to permit persons to whom the Software is | ||
# furnished to do so, subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in | ||
# all copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | ||
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS | ||
# IN THE SOFTWARE. | ||
# | ||
# -------------------------------------------------------------------------- | ||
|
||
from ._stream import Stream, AsyncStream | ||
|
||
|
||
__all__ = ["Stream", "AsyncStream"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,192 @@ | ||
# -------------------------------------------------------------------------- | ||
# | ||
# Copyright (c) Microsoft Corporation. All rights reserved. | ||
# | ||
# The MIT License (MIT) | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy | ||
# of this software and associated documentation files (the ""Software""), to | ||
# deal in the Software without restriction, including without limitation the | ||
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or | ||
# sell copies of the Software, and to permit persons to whom the Software is | ||
# furnished to do so, subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in | ||
# all copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | ||
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS | ||
# IN THE SOFTWARE. | ||
# | ||
# -------------------------------------------------------------------------- | ||
|
||
|
||
from typing import Iterator, AsyncIterator, Tuple, Protocol | ||
|
||
from typing_extensions import runtime_checkable | ||
|
||
from ._events import JSONLEvent, EventType | ||
|
||
|
||
@runtime_checkable | ||
class StreamDecoder(Protocol): | ||
"""Protocol for stream decoders.""" | ||
|
||
def iter_events(self, iter_bytes: Iterator[bytes]) -> Iterator[EventType]: | ||
"""Iterate over events from a byte iterator. | ||
|
||
:param iter_bytes: An iterator of byte chunks. | ||
:type iter_bytes: Iterator[bytes] | ||
:return: An iterator of events. | ||
""" | ||
... | ||
|
||
def event(self) -> EventType: | ||
"""Get the current event. | ||
|
||
:rtype: EventType | ||
:return: The current event. | ||
""" | ||
... | ||
|
||
def decode(self, line: bytes) -> None: | ||
"""Decode a line of bytes. | ||
|
||
:param bytes line: A line of bytes to decode. | ||
""" | ||
... | ||
|
||
|
||
@runtime_checkable | ||
class AsyncStreamDecoder(Protocol): | ||
"""Protocol for async stream decoders.""" | ||
|
||
# Why this isn't async def: https://mypy.readthedocs.io/en/stable/more_types.html#asynchronous-iterators | ||
def aiter_events(self, iter_bytes: AsyncIterator[bytes]) -> AsyncIterator[EventType]: | ||
"""Asynchronously iterate over events from a byte iterator. | ||
|
||
:param iter_bytes: An asynchronous iterator of byte chunks. | ||
:type iter_bytes: AsyncIterator[bytes] | ||
:return: An asynchronous iterator of events. | ||
""" | ||
... | ||
|
||
def event(self) -> EventType: | ||
"""Get the current event. | ||
|
||
:return: The current event. | ||
""" | ||
... | ||
|
||
def decode(self, line: bytes) -> None: | ||
"""Decode a line of bytes. | ||
|
||
:param bytes line: A line of bytes to decode. | ||
""" | ||
... | ||
|
||
|
||
class JSONLDecoder: | ||
"""Decoder for JSON Lines (JSONL) format. https://jsonlines.org/""" | ||
|
||
def __init__(self) -> None: | ||
self._data: str = "" | ||
self._line_separators: Tuple[bytes, ...] = (b"\n", b"\r\n") | ||
|
||
def decode(self, line: bytes) -> None: | ||
"""Decode a line of bytes into a string. | ||
|
||
:param bytes line: A line of bytes to decode. | ||
:rtype: None | ||
""" | ||
self._data = line.decode("utf-8") | ||
|
||
def iter_events(self, iter_bytes: Iterator[bytes]) -> Iterator[JSONLEvent]: | ||
"""Iterate over JSONL events from a byte iterator. | ||
|
||
:param iter_bytes: An iterator of byte chunks. | ||
:type iter_bytes: Iterator[bytes] | ||
:rtype: Iterator[JSONLEvent] | ||
:return: An iterator of JSONLEvent objects. | ||
""" | ||
data = b"" | ||
for chunk in iter_bytes: | ||
for line in chunk.splitlines(keepends=True): | ||
data += line | ||
if data.endswith(self._line_separators): | ||
self.decode(data.splitlines()[0]) | ||
event = self.event() | ||
yield event | ||
data = b"" | ||
|
||
if data: | ||
# the last line did not end with a line separator | ||
# ok per JSONL spec | ||
self.decode(data) | ||
event = self.event() | ||
yield event | ||
|
||
def event(self) -> JSONLEvent: | ||
"""Get the current event. | ||
|
||
:rtype: JSONLEvent | ||
:return: The current event. | ||
""" | ||
jsonl = JSONLEvent(data=self._data) | ||
self._data = "" | ||
return jsonl | ||
|
||
|
||
class AsyncJSONLDecoder: | ||
"""Asynchronous decoder for JSON Lines (JSONL) format. https://jsonlines.org/""" | ||
|
||
def __init__(self) -> None: | ||
self._data: str = "" | ||
self._line_separators: Tuple[bytes, ...] = (b"\n", b"\r\n") | ||
|
||
def decode(self, line: bytes) -> None: | ||
"""Decode a line of bytes into a string. | ||
|
||
:param bytes line: A line of bytes to decode. | ||
:rtype: None | ||
""" | ||
self._data = line.decode("utf-8") | ||
|
||
async def aiter_events(self, iter_bytes: AsyncIterator[bytes]) -> AsyncIterator[JSONLEvent]: | ||
"""Asynchronously iterate over JSONL events from a byte iterator. | ||
|
||
:param iter_bytes: An asynchronous iterator of byte chunks. | ||
:type iter_bytes: AsyncIterator[bytes] | ||
:rtype: AsyncIterator[JSONLEvent] | ||
:return: An asynchronous iterator of JSONLEvent objects. | ||
""" | ||
data = b"" | ||
async for chunk in iter_bytes: | ||
for line in chunk.splitlines(keepends=True): | ||
data += line | ||
if data.endswith(self._line_separators): | ||
self.decode(data.splitlines()[0]) | ||
event = self.event() | ||
yield event | ||
data = b"" | ||
|
||
if data: | ||
# the last line did not end with a line separator | ||
# ok per JSONL spec | ||
self.decode(data) | ||
event = self.event() | ||
yield event | ||
|
||
def event(self) -> JSONLEvent: | ||
"""Get the current event. | ||
|
||
:rtype: JSONLEvent | ||
:return: The current event. | ||
""" | ||
jsonl = JSONLEvent(data=self._data) | ||
self._data = "" | ||
return jsonl |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
# -------------------------------------------------------------------------- | ||
# | ||
# Copyright (c) Microsoft Corporation. All rights reserved. | ||
# | ||
# The MIT License (MIT) | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy | ||
# of this software and associated documentation files (the ""Software""), to | ||
# deal in the Software without restriction, including without limitation the | ||
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or | ||
# sell copies of the Software, and to permit persons to whom the Software is | ||
# furnished to do so, subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in | ||
# all copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | ||
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS | ||
# IN THE SOFTWARE. | ||
# | ||
# -------------------------------------------------------------------------- | ||
|
||
import json | ||
from typing import Any, Protocol | ||
|
||
from typing_extensions import runtime_checkable | ||
|
||
|
||
@runtime_checkable | ||
class EventType(Protocol): | ||
"""Protocol for event types.""" | ||
|
||
data: str | ||
"""The event data.""" | ||
|
||
def json(self) -> Any: | ||
"""Parse the event data as JSON. | ||
|
||
:return: The parsed JSON data. | ||
""" | ||
... | ||
|
||
|
||
class JSONLEvent: | ||
kristapratico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""Class representing a JSONL Event.""" | ||
|
||
data: str | ||
"""The event data.""" | ||
|
||
def __init__(self, *, data: str) -> None: | ||
"""Create a new JSONL event. | ||
|
||
:keyword str data: The event data. | ||
""" | ||
self.data = data | ||
|
||
def json(self) -> Any: | ||
"""Parse the event data as JSON. | ||
|
||
:rtype: any | ||
:return: The JSON data for the event | ||
""" | ||
return json.loads(self.data) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.