-
Notifications
You must be signed in to change notification settings - Fork 116
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
25
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
25 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 18bfe02
fix(stdlib): address psschwei review comments on streaming
planetf1 7fc40a4
fix(stdlib): clone requirements before backend start; cancel peer val…
planetf1 d8018dd
fix(core,hf): cooperative cancel via StoppingCriteria backed by threa…
planetf1 bf9a62b
fix(stdlib,core,hf): three pre-merge correctness fixes
planetf1 9a715d6
fix: address second-review feedback on bf9a62bc
planetf1 f3e3501
docs(core): add Raises section to cancel_generation() docstring
planetf1 2f2e352
docs(agents): add docstring quality gate to self-review checklist
planetf1 66260fe
fix: address review feedback from psschwei + jakelorocco
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
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,110 @@ | ||
| # 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 | ||
| import re | ||
|
|
||
| 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 | ||
|
|
||
| # Crude sentence-terminator detector. A run of ``.``/``!``/``?`` counts once | ||
| # (so "..." and "!!!" are a single terminator). Good enough for an example; | ||
| # production code might use spaCy/NLTK for proper sentence segmentation. | ||
| _SENTENCE_END = re.compile(r"[.!?]+") | ||
|
|
||
|
|
||
| class MaxSentencesReq(Requirement): | ||
| """Fails if the model generates more than *limit* sentences mid-stream. | ||
|
|
||
| Counts sentence terminators in the chunk *text* rather than counting | ||
| ``stream_validate`` calls. This makes the requirement **chunker-agnostic**: | ||
| the same instance behaves correctly with sentence, word, or paragraph | ||
| chunking, because the semantics depend on content, not on the chunker's | ||
| structural decisions. | ||
|
|
||
| When writing your own streaming requirements, prefer this content-driven | ||
| pattern over coupling the requirement to a specific chunker. Reach for | ||
| chunker-coupled logic only when the requirement is genuinely a property | ||
| of chunk boundaries (e.g. "no chunk longer than N tokens"). | ||
| """ | ||
|
|
||
| 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 += len(_SENTENCE_END.findall(chunk)) | ||
| if self._count > self._limit: | ||
| return PartialValidationResult( | ||
| "fail", | ||
| reason=f"Response exceeded {self._limit} sentence limit mid-stream", | ||
| ) | ||
| return PartialValidationResult("unknown") | ||
|
jakelorocco marked this conversation as resolved.
|
||
|
|
||
| async def validate( | ||
| self, | ||
| backend: Backend, | ||
| ctx: Context, | ||
| *, | ||
| format: type | None = None, | ||
| model_options: dict | None = None, | ||
| ) -> ValidationResult: | ||
| return ValidationResult(result=True) | ||
|
Comment on lines
+65
to
+73
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think validate and stream_validate should return equivalent results for most requirements. |
||
|
|
||
|
|
||
| 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
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.