-
Notifications
You must be signed in to change notification settings - Fork 114
feat(stdlib): add stream_with_chunking() with per-chunk validation (#901) #942
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
Open
planetf1
wants to merge
17
commits into
generative-computing:main
Choose a base branch
from
planetf1:feat/901-stream-with-chunking
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
8128dfa
feat(core): add cancel_generation() to ModelOutputThunk
planetf1 f26cce7
feat(stdlib): add stream_with_chunking() with per-chunk validation (#…
planetf1 93e7587
test(stdlib): add StreamingMockBackend and streaming orchestration tests
planetf1 a5d358c
docs: add streaming_chunking example (#901)
planetf1 39f18a4
docs(stdlib): add Args section to StreamChunkingResult class docstring
planetf1 36173cb
docs(stdlib): add Raises section to stream_with_chunking docstring
planetf1 ea6bdb0
fix(stdlib): stream_with_chunking passes one chunk per stream_validat…
planetf1 35df77f
docs(stdlib): fix example for delta semantics and note validator latency
planetf1 61448a9
feat(stdlib): flush trailing chunk fragment at end of stream
planetf1 def10b6
fix(stdlib): address review feedback on streaming validation
planetf1 da41a06
fix(stdlib): address second-round review feedback
planetf1 74c009d
docs(stdlib): add Args and Returns sections to chunker flush overrides
planetf1 3fb501e
fix(stdlib): address third-round review feedback
planetf1 5850f92
fix(stdlib): stash orchestrator exception and narrow finally except
planetf1 4f508fd
feat(core): add cancelled flag on ModelOutputThunk
planetf1 5075a47
docs(stdlib): note ChunkingStrategy is text-only
planetf1 f0f93b3
test(stdlib): assert cancelled flag reflects cancellation state
planetf1 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,98 @@ | ||
| # pytest: ollama, e2e | ||
|
|
||
| """Streaming generation with per-chunk validation using stream_with_chunking(). | ||
|
|
||
| Demonstrates: | ||
| - Subclassing Requirement to override stream_validate() for early-exit checks | ||
| - Calling stream_with_chunking() with sentence-level chunking | ||
| - Consuming validated chunks via astream() as they arrive | ||
| - Awaiting full completion with acomplete() to access final_validations and full_text | ||
| """ | ||
|
|
||
| import asyncio | ||
|
|
||
| from mellea.core.backend import Backend | ||
| from mellea.core.base import Context | ||
| from mellea.core.requirement import ( | ||
| PartialValidationResult, | ||
| Requirement, | ||
| ValidationResult, | ||
| ) | ||
| from mellea.stdlib.components import Instruction | ||
| from mellea.stdlib.streaming import stream_with_chunking | ||
|
|
||
|
|
||
| class MaxSentencesReq(Requirement): | ||
| """Fails if the model generates more than *limit* sentences mid-stream. | ||
|
|
||
| Each ``stream_validate`` call receives one complete sentence from the | ||
| :class:`~mellea.stdlib.chunking.SentenceChunker`. The running count is | ||
| maintained on ``self`` — this is the standard pattern for requirements | ||
| that need context beyond a single chunk. | ||
| """ | ||
|
|
||
| def __init__(self, limit: int) -> None: | ||
| super().__init__() | ||
| self._limit = limit | ||
| self._count = 0 | ||
|
|
||
| def format_for_llm(self) -> str: | ||
| return f"The response must be at most {self._limit} sentences long." | ||
|
|
||
| async def stream_validate( | ||
| self, chunk: str, *, backend: Backend, ctx: Context | ||
| ) -> PartialValidationResult: | ||
| self._count += 1 | ||
| if self._count > self._limit: | ||
| return PartialValidationResult( | ||
| "fail", | ||
| reason=f"Response exceeded {self._limit} sentence limit mid-stream", | ||
| ) | ||
| return PartialValidationResult("unknown") | ||
|
|
||
| async def validate( | ||
| self, | ||
| backend: Backend, | ||
| ctx: Context, | ||
| *, | ||
| format: type | None = None, | ||
| model_options: dict | None = None, | ||
| ) -> ValidationResult: | ||
| return ValidationResult(result=True) | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| from mellea.stdlib.session import start_session | ||
|
|
||
| m = start_session() | ||
| backend = m.backend | ||
| ctx = m.ctx | ||
|
|
||
| action = Instruction( | ||
| "Write a short paragraph about the water cycle in exactly two sentences." | ||
| ) | ||
| req = MaxSentencesReq(limit=3) | ||
|
|
||
| result = await stream_with_chunking( | ||
| action, backend, ctx, quick_check_requirements=[req], chunking="sentence" | ||
| ) | ||
|
|
||
| print("Streaming chunks as they arrive:") | ||
| async for chunk in result.astream(): | ||
| print(f" CHUNK: {chunk!r}") | ||
|
|
||
| await result.acomplete() | ||
|
|
||
| print(f"\nCompleted normally: {result.completed}") | ||
| print(f"Full text: {result.full_text!r}") | ||
|
|
||
| if result.streaming_failures: | ||
| for _req, pvr in result.streaming_failures: | ||
| print(f"Streaming failure: {pvr.reason}") | ||
|
|
||
| if result.final_validations: | ||
| for vr in result.final_validations: | ||
| print(f"Final validation: {'PASS' if vr.as_bool() else 'FAIL'}") | ||
|
|
||
|
|
||
| asyncio.run(main()) | ||
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
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
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
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.