Skip to content

The agent engineering platform.

core[patch]: improve comma separated list output parser to handle non-space separated list (#20434)

Anish Chakraborty898362de81cf
diff --git a/libs/core/langchain_core/output_parsers/list.py b/libs/core/langchain_core/output_parsers/list.py
index 36b9f7e9b7..7fd96c94d8 100644
--- a/libs/core/langchain_core/output_parsers/list.py
+++ b/libs/core/langchain_core/output_parsers/list.py
@@ -115,12 +115,12 @@ class CommaSeparatedListOutputParser(ListOutputParser):
def get_format_instructions(self) -> str:
return (
"Your response should be a list of comma separated values, "
- "eg: `foo, bar, baz`"
+ "eg: `foo, bar, baz` or `foo,bar,baz`"
)
def parse(self, text: str) -> List[str]:
"""Parse the output of an LLM call."""
- return text.strip().split(", ")
+ return [part.strip() for part in text.split(",")]
@property
def _type(self) -> str:
diff --git a/libs/core/tests/unit_tests/output_parsers/test_list_parser.py b/libs/core/tests/unit_tests/output_parsers/test_list_parser.py
index 710f9e52ce..ef3a00bc5f 100644
--- a/libs/core/tests/unit_tests/output_parsers/test_list_parser.py
+++ b/libs/core/tests/unit_tests/output_parsers/test_list_parser.py
@@ -26,10 +26,29 @@ def test_single_item() -> None:
assert list(parser.transform(iter([text]))) == [[a] for a in expected]
+def test_multiple_items_with_spaces() -> None:
+ """Test that a string with multiple comma-separated items
+ with spaces is parsed to a list."""
+ parser = CommaSeparatedListOutputParser()
+ text = "foo, bar, baz"
+ expected = ["foo", "bar", "baz"]
+
+ assert parser.parse(text) == expected
+ assert add(parser.transform(t for t in text)) == expected
+ assert list(parser.transform(t for t in text)) == [[a] for a in expected]
+ assert list(parser.transform(t for t in text.splitlines(keepends=True))) == [
+ [a] for a in expected
+ ]
+ assert list(
+ parser.transform(" " + t if i > 0 else t for i, t in enumerate(text.split(" ")))
+ ) == [[a] for a in expected]
+ assert list(parser.transform(iter([text]))) == [[a] for a in expected]
+
+
def test_multiple_items() -> None:
"""Test that a string with multiple comma-separated items is parsed to a list."""
parser = CommaSeparatedListOutputParser()
- text = "foo, bar, baz"
+ text = "foo,bar,baz"
expected = ["foo", "bar", "baz"]
assert parser.parse(text) == expected