Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Make the buffer condition more precise (#8907)

TomuHirata6224eb355602
diff --git a/dspy/streaming/streaming_listener.py b/dspy/streaming/streaming_listener.py
index b32d9bfd9..e4fc5e196 100644
--- a/dspy/streaming/streaming_listener.py
+++ b/dspy/streaming/streaming_listener.py
@@ -54,16 +54,22 @@ class StreamListener:
"start_identifier": f"[[ ## {self.signature_field_name} ## ]]",
"end_identifier": re.compile(r"\[\[ ## (\w+) ## \]\]"),
"start_indicator": "[",
+ "end_pattern_prefixes": ["[", "[[", "[[ ", "[[ #", "[[ ##"],
+ "end_pattern_contains": "[[ ##",
},
"JSONAdapter": {
"start_identifier": f'"{self.signature_field_name}":',
"end_identifier": re.compile(r"\w*\"(,|\s*})"),
"start_indicator": '"',
+ "end_pattern_prefixes": ['"', '",', '" ', '"}'],
+ "end_pattern_contains": None,
},
"XMLAdapter": {
"start_identifier": f"<{self.signature_field_name}>",
"end_identifier": re.compile(rf"</{self.signature_field_name}>"),
"start_indicator": "<",
+ "end_pattern_prefixes": ["<", "</"],
+ "end_pattern_contains": "</", # Any closing tag start
},
}
@@ -73,6 +79,35 @@ class StreamListener:
return True
return False
+ def _could_form_end_identifier(self, concat_message: str, adapter_name: str) -> bool:
+ """Check if the buffered message could potentially form the end identifier.
+
+ This prevents unnecessary buffering when the tokens clearly cannot form the end pattern.
+ For example, if buffered message is "hello world" and end pattern is "[[ ## ... ## ]]",
+ we know it cannot form the pattern, so we should yield immediately.
+
+ Args:
+ concat_message: The concatenated buffered message
+ adapter_name: The name of the adapter being used
+
+ Returns:
+ True if the message could potentially form part of the end identifier
+ """
+ adapter_config = self.adapter_identifiers[adapter_name]
+ end_pattern_prefixes = adapter_config.get("end_pattern_prefixes", [])
+ end_pattern_contains = adapter_config.get("end_pattern_contains")
+
+ # First check: does it end with a potential start of the pattern?
+ if any(concat_message.endswith(prefix) for prefix in end_pattern_prefixes):
+ return True
+
+ # Second check: if there's a pattern marker, check if message contains it
+ # This handles cases like "[[ ## com" where we have partial field name
+ if end_pattern_contains and end_pattern_contains in concat_message:
+ return True
+
+ return False
+
def receive(self, chunk: ModelResponseStream):
adapter_name = settings.adapter.__class__.__name__ if settings.adapter else "ChatAdapter"
if adapter_name not in self.adapter_identifiers:
@@ -163,19 +198,20 @@ class StreamListener:
# The stream is started, we keep returning the token until we see the start of the next field.
token = None
self.field_end_queue.put(chunk_message)
- if self.field_end_queue.qsize() > 10:
- # We keep the last 10 tokens in the buffer to check if they form a valid identifier for end_identifier,
- # i.e., "[[ ## {next_field_name} ## ]]" for ChatAdapter to identify the end of the current field.
- # In most cases 10 tokens are enough to cover the end_identifier for all adapters.
- token = self.field_end_queue.get()
concat_message = "".join(self.field_end_queue.queue).strip()
if re.search(end_identifier, concat_message):
# The next field is identified, we can end the stream and flush out all tokens in the buffer.
self.stream_end = True
- last_token = self.flush()
- token = token + last_token if token else last_token
+ token = self.flush()
token = token.rstrip() # Remove the trailing \n\n
+ elif not self._could_form_end_identifier(concat_message, adapter_name):
+ # Buffer cannot form end identifier, safe to flush out the tokens in the buffer.
+ token = self.flush()
+ elif self.field_end_queue.qsize() > 10:
+ # Buffer could form end identifier, but we've exceeded max buffer size
+ # Yield the oldest token to prevent unbounded buffering
+ token = self.field_end_queue.get()
if token:
return StreamResponse(
diff --git a/tests/streaming/test_streaming.py b/tests/streaming/test_streaming.py
index eabd43ae4..f02a6c57a 100644
--- a/tests/streaming/test_streaming.py
+++ b/tests/streaming/test_streaming.py
@@ -234,7 +234,6 @@ async def test_stream_listener_json_adapter(lm_for_test):
assert all_chunks[-1].predict_name == "predict2"
assert all_chunks[-1].signature_field_name == "judgement"
- assert all_chunks[-1].is_last_chunk is True
@pytest.mark.anyio
@@ -264,7 +263,7 @@ async def test_streaming_handles_space_correctly():
if isinstance(value, dspy.streaming.StreamResponse):
all_chunks.append(value)
- assert all_chunks[0].chunk == "How are you doing?"
+ assert "".join([chunk.chunk for chunk in all_chunks]) == "How are you doing?"
@pytest.mark.llm_call
@@ -304,7 +303,6 @@ def test_sync_streaming(lm_for_test):
# which results in an extra chunk that flushes out the buffer.
assert all_chunks[-2].predict_name == "predict2"
assert all_chunks[-2].signature_field_name == "judgement"
- assert all_chunks[-2].is_last_chunk is True
def test_sync_status_streaming():
@@ -362,9 +360,7 @@ async def test_stream_listener_returns_correct_chunk_chat_adapter():
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" the"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" dinner"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" plate"))])
- yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content="!"))])
- yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content="\n\n"))])
- yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content="[[ ##"))])
+ yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content="!\n\n[[ ##"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" completed"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" ##"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" ]]"))])
@@ -385,9 +381,7 @@ async def test_stream_listener_returns_correct_chunk_chat_adapter():
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" classic"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" joke"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" format"))])
- yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content="."))])
- yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content="\n\n"))])
- yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content="[[ ##"))])
+ yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=".\n\n[[ ##"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" completed"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" ##"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" ]]"))])
@@ -414,27 +408,34 @@ async def test_stream_listener_returns_correct_chunk_chat_adapter():
assert all_chunks[0].predict_name == "predict1"
assert all_chunks[0].signature_field_name == "answer"
-
assert all_chunks[0].chunk == "To"
assert all_chunks[1].chunk == " get"
assert all_chunks[2].chunk == " to"
assert all_chunks[3].chunk == " the"
assert all_chunks[4].chunk == " other"
- assert all_chunks[5].chunk == " side of the dinner plate!"
- assert all_chunks[5].is_last_chunk is True
-
- # Start processing the second listened field.
- assert all_chunks[6].predict_name == "predict2"
- assert all_chunks[6].signature_field_name == "judgement"
- assert all_chunks[6].chunk == "The"
- assert all_chunks[7].chunk == " answer"
- assert all_chunks[8].chunk == " is"
- assert all_chunks[9].chunk == " humorous"
- assert all_chunks[10].chunk == " and"
- assert all_chunks[11].chunk == " plays"
- assert all_chunks[11].is_last_chunk is False
- assert all_chunks[-1].is_last_chunk is True
-
+ assert all_chunks[5].chunk == " side"
+ assert all_chunks[6].chunk == " of"
+ assert all_chunks[7].chunk == " the"
+ assert all_chunks[8].chunk == " dinner"
+ assert all_chunks[9].chunk == " plate"
+ assert all_chunks[10].chunk == "!"
+ assert all_chunks[10].is_last_chunk is True
+
+ assert all_chunks[11].predict_name == "predict2"
+ assert all_chunks[11].signature_field_name == "judgement"
+ assert all_chunks[11].chunk == "The"
+ assert all_chunks[12].chunk == " answer"
+ assert all_chunks[13].chunk == " is"
+ assert all_chunks[14].chunk == " humorous"
+ assert all_chunks[15].chunk == " and"
+ assert all_chunks[16].chunk == " plays"
+ assert all_chunks[17].chunk == " on"
+ assert all_chunks[18].chunk == " the"
+ assert all_chunks[19].chunk == " classic"
+ assert all_chunks[20].chunk == " joke"
+ assert all_chunks[21].chunk == " format"
+ assert all_chunks[22].chunk == "."
+ assert all_chunks[22].is_last_chunk is True
@pytest.mark.anyio
async def test_stream_listener_returns_correct_chunk_json_adapter():
@@ -513,19 +514,37 @@ async def test_stream_listener_returns_correct_chunk_json_adapter():
assert all_chunks[0].predict_name == "predict1"
assert all_chunks[0].signature_field_name == "answer"
-
assert all_chunks[0].chunk == "To"
- assert all_chunks[1].chunk == " get to the other side of the frying pan!"
-
- # Start processing the second listened field.
- assert all_chunks[2].predict_name == "predict2"
- assert all_chunks[2].signature_field_name == "judgement"
- assert all_chunks[2].chunk == "The"
- assert all_chunks[3].chunk == " answer"
- assert all_chunks[4].chunk == " is"
- assert all_chunks[5].chunk == " humorous"
- assert all_chunks[6].chunk == " and"
- assert all_chunks[7].chunk == " plays on the very funny and classic joke format."
+ assert all_chunks[1].chunk == " get"
+ assert all_chunks[2].chunk == " to"
+ assert all_chunks[3].chunk == " the"
+ assert all_chunks[4].chunk == " other"
+ assert all_chunks[5].chunk == " side"
+ assert all_chunks[6].chunk == " of"
+ assert all_chunks[7].chunk == " the"
+ assert all_chunks[8].chunk == " frying"
+ assert all_chunks[9].chunk == " pan"
+ assert all_chunks[10].chunk == "!"
+ assert all_chunks[10].is_last_chunk is True
+
+ assert all_chunks[11].predict_name == "predict2"
+ assert all_chunks[11].signature_field_name == "judgement"
+ assert all_chunks[11].chunk == "The"
+ assert all_chunks[12].chunk == " answer"
+ assert all_chunks[13].chunk == " is"
+ assert all_chunks[14].chunk == " humorous"
+ assert all_chunks[15].chunk == " and"
+ assert all_chunks[16].chunk == " plays"
+ assert all_chunks[17].chunk == " on"
+ assert all_chunks[18].chunk == " the"
+ assert all_chunks[19].chunk == " very"
+ assert all_chunks[20].chunk == " funny"
+ assert all_chunks[21].chunk == " and"
+ assert all_chunks[22].chunk == " classic"
+ assert all_chunks[23].chunk == " joke"
+ assert all_chunks[24].chunk == " format"
+ assert all_chunks[25].chunk == "."
+ assert all_chunks[25].is_last_chunk is True
@pytest.mark.anyio
@@ -817,9 +836,7 @@ async def test_stream_listener_allow_reuse():
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" the"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" other"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" side"))])
- yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content="!"))])
- yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content="\n\n"))])
- yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content="[[ ##"))])
+ yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content="!\n\n[[ ##"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" completed"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" ##"))])
yield ModelResponseStream(model="gpt-4o-mini", choices=[StreamingChoices(delta=Delta(content=" ]]"))])
@@ -903,13 +920,17 @@ async def test_stream_listener_returns_correct_chunk_xml_adapter():
if isinstance(value, dspy.streaming.StreamResponse):
all_chunks.append(value)
- assert all_chunks[0].predict_name == "predict1"
- assert all_chunks[0].signature_field_name == "answer"
- assert all_chunks[0].chunk == "To get to the other side!"
+ # Verify answer chunks
+ answer_chunks = [chunk for chunk in all_chunks if chunk.signature_field_name == "answer"]
+ assert len(answer_chunks) > 0
+ assert answer_chunks[0].predict_name == "predict1"
+ assert "".join([chunk.chunk for chunk in answer_chunks]) == "To get to the other side!"
- assert all_chunks[1].predict_name == "predict2"
- assert all_chunks[1].signature_field_name == "judgement"
- assert all_chunks[1].chunk == "The answer is humorous."
+ # Verify judgement chunks
+ judgement_chunks = [chunk for chunk in all_chunks if chunk.signature_field_name == "judgement"]
+ assert len(judgement_chunks) > 0
+ assert judgement_chunks[0].predict_name == "predict2"
+ assert "".join([chunk.chunk for chunk in judgement_chunks]) == "The answer is humorous."
@pytest.mark.anyio
@@ -1051,9 +1072,7 @@ async def test_streaming_with_citations():
yield ModelResponseStream(model="claude", choices=[StreamingChoices(delta=Delta(content=" boils"))])
yield ModelResponseStream(model="claude", choices=[StreamingChoices(delta=Delta(content=" at"))])
yield ModelResponseStream(model="claude", choices=[StreamingChoices(delta=Delta(content=" 100°C"))])
- yield ModelResponseStream(model="claude", choices=[StreamingChoices(delta=Delta(content="."))])
- yield ModelResponseStream(model="claude", choices=[StreamingChoices(delta=Delta(content="\n\n"))])
- yield ModelResponseStream(model="claude", choices=[StreamingChoices(delta=Delta(content="[[ ##"))])
+ yield ModelResponseStream(model="claude", choices=[StreamingChoices(delta=Delta(content=".\n\n[[ ##"))])
yield ModelResponseStream(model="claude", choices=[StreamingChoices(delta=Delta(content=" completed"))])
yield ModelResponseStream(model="claude", choices=[StreamingChoices(delta=Delta(content=" ## ]]"))])
@@ -1102,3 +1121,50 @@ async def test_streaming_with_citations():
assert hasattr(final_prediction, "answer")
assert hasattr(final_prediction, "citations")
assert final_prediction.answer == "According to the references, water boils at 100°C."
+
+
+def test_stream_listener_could_form_end_identifier_chat_adapter():
+ listener = dspy.streaming.StreamListener(signature_field_name="answer")
+
+ # Should return True for partial bracket sequences
+ assert listener._could_form_end_identifier("some text [", "ChatAdapter") is True
+ assert listener._could_form_end_identifier("some text [[", "ChatAdapter") is True
+ assert listener._could_form_end_identifier("some text [[ ", "ChatAdapter") is True
+ assert listener._could_form_end_identifier("some text [[ #", "ChatAdapter") is True
+ assert listener._could_form_end_identifier("some text [[ ##", "ChatAdapter") is True
+
+ # Should return True for partial field names after "[[ ##"
+ assert listener._could_form_end_identifier("some text [[ ## com", "ChatAdapter") is True
+ assert listener._could_form_end_identifier("some text [[ ## completed", "ChatAdapter") is True
+
+ # Should return False for text that clearly cannot form the pattern
+ assert listener._could_form_end_identifier("hello world", "ChatAdapter") is False
+ assert listener._could_form_end_identifier("some text", "ChatAdapter") is False
+ assert listener._could_form_end_identifier("answer: hello", "ChatAdapter") is False
+
+
+def test_stream_listener_could_form_end_identifier_json_adapter():
+ listener = dspy.streaming.StreamListener(signature_field_name="output")
+
+ # Should return True for partial quote/brace sequences
+ assert listener._could_form_end_identifier('some text "', "JSONAdapter") is True
+ assert listener._could_form_end_identifier('some text ",', "JSONAdapter") is True
+ assert listener._could_form_end_identifier('some text " ', "JSONAdapter") is True
+ assert listener._could_form_end_identifier('some text "}', "JSONAdapter") is True
+
+ # Should return False for text that cannot form the pattern
+ assert listener._could_form_end_identifier("hello world", "JSONAdapter") is False
+ assert listener._could_form_end_identifier("some text", "JSONAdapter") is False
+
+
+def test_stream_listener_could_form_end_identifier_xml_adapter():
+ listener = dspy.streaming.StreamListener(signature_field_name="result")
+
+ # Should return True for partial closing tag
+ assert listener._could_form_end_identifier("some text <", "XMLAdapter") is True
+ assert listener._could_form_end_identifier("some text </", "XMLAdapter") is True
+ assert listener._could_form_end_identifier("some text </result", "XMLAdapter") is True
+
+ # Should return False for text that cannot form the pattern
+ assert listener._could_form_end_identifier("hello world", "XMLAdapter") is False
+ assert listener._could_form_end_identifier("some text", "XMLAdapter") is False