Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

fix(integrations): read text out of LangChain content-block lists

Bruce-Yiia367e709a68b
diff --git a/laya/integrations/langchain.py b/laya/integrations/langchain.py
index 9285f04d..c7fd17cd 100644
--- a/laya/integrations/langchain.py
+++ b/laya/integrations/langchain.py
@@ -56,15 +56,52 @@ def _extract_text(input_val: Any, state_key: Optional[Union[str, Callable[[Any],
return input_val
if isinstance(input_val, list):
+ text = _content_text(input_val)
+ if text is not input_val:
+ return text
return _extract_from_messages_list(input_val)
return str(input_val)
+def _content_text(val: Any) -> Any:
+ """The text of a message `content` value, unwrapped from a content-block list.
+
+ `content` is not only a string. A `HumanMessage(content=[{"type": "text", "text": ...}])`
+ is accepted by langchain-core and keeps `.content` as a list, so `str(content)` produced a
+ Python repr -- braces, quotes, and the literal field names `type` and `text` -- and that
+ repr is what Laya scored. Nothing raised; the guardrail simply answered about a string the
+ caller never wrote.
+
+ Text-bearing blocks are concatenated in the order they appear, which is how such a list is
+ meant to be read. A list carrying no text block is returned **unchanged**, so a genuinely
+ structured state still reaches the caller as the caller shaped it instead of being
+ flattened into invented prose; callers distinguish "extracted" from "unchanged" by identity.
+ A plain string is returned untouched.
+ """
+ if not isinstance(val, list):
+ return val
+ parts = []
+ for block in val:
+ if isinstance(block, str):
+ parts.append(block)
+ elif isinstance(block, dict):
+ text = block.get("text")
+ if isinstance(text, str):
+ parts.append(text)
+ if not parts:
+ return val
+ return "".join(parts) if len(parts) == 1 else "\n".join(parts)
+
+
def _extract_from_message_or_value(val: Any) -> Any:
if hasattr(val, "content"):
- return str(val.content)
+ return _content_text(val.content)
if isinstance(val, list):
+ # a content-block list is already text; a list of messages is not
+ text = _content_text(val)
+ if text is not val:
+ return text
return _extract_from_messages_list(val)
return val
@@ -76,9 +113,9 @@ def _extract_from_messages_list(msgs: Sequence[Any]) -> str:
for m in reversed(msgs):
role = getattr(m, "type", None) or getattr(m, "role", None)
if role in ("human", "user"):
- return str(getattr(m, "content", m))
+ return _content_text(getattr(m, "content", m))
last = msgs[-1]
- return str(getattr(last, "content", last))
+ return _content_text(getattr(last, "content", last))
class _SameOriginRedirectHandler(urllib.request.HTTPRedirectHandler):
diff --git a/tests/test_langchain.py b/tests/test_langchain.py
index 45bf3e51..8999437b 100644
--- a/tests/test_langchain.py
+++ b/tests/test_langchain.py
@@ -71,6 +71,45 @@ msgs = [
check("extract/messages_list", _extract_text(msgs), "second human message")
check("extract/dict_with_messages", _extract_text({"messages": msgs}), "second human message")
+
+# A message `content` is not only a string. langchain-core accepts
+# `HumanMessage(content=[{"type": "text", "text": ...}])` and keeps `.content` as a list, so
+# `str(content)` used to hand Laya a Python repr -- braces, quotes, and the literal field
+# names -- as the state to decide on. Nothing raised, so the guardrail just answered about a
+# string the caller never wrote. `DummyMessage` is the local stand-in for that shape.
+TXT = "I was billed twice for the same plan."
+BLOCKS = [{"type": "text", "text": TXT}]
+
+check("extract/blocks_human_message", _extract_text([DummyMessage("human", BLOCKS)]), TXT)
+check("extract/blocks_ai_message_fallback", _extract_text([DummyMessage("ai", BLOCKS)]), TXT)
+check("extract/blocks_newest_human_wins",
+ _extract_text([DummyMessage("human", BLOCKS), DummyMessage("ai", BLOCKS)]), TXT)
+check("extract/blocks_dict_messages",
+ _extract_text({"messages": [DummyMessage("human", BLOCKS)]}), TXT)
+check("extract/blocks_dict_content", _extract_text({"content": BLOCKS}), TXT)
+check("extract/blocks_dict_input", _extract_text({"input": BLOCKS}), TXT)
+check("extract/blocks_bare_list", _extract_text(BLOCKS), TXT)
+
+# Several text blocks are read in order; the separator is a newline so two sentences do not
+# fuse into one token the model reads differently than the caller wrote.
+check("extract/blocks_multiple_joined",
+ _extract_text([DummyMessage("human", [{"type": "text", "text": "first part."},
+ {"type": "text", "text": "second part."}])]),
+ "first part.\nsecond part.")
+
+# A block with no text carries nothing to score. Rather than invent prose, the value is
+# passed through as the caller shaped it, so a structured state stays structured.
+check("extract/blocks_non_text_only_preserved",
+ _extract_text([DummyMessage("human", [{"type": "image_url", "image_url": {"url": "x"}}])]),
+ [{"type": "image_url", "image_url": {"url": "x"}}])
+check("extract/blocks_empty_list_preserved", _extract_text([]), "")
+
+# Mixed blocks: only the text-bearing ones are read, and their order is kept.
+check("extract/blocks_mixed_skips_non_text",
+ _extract_text([DummyMessage("human", [{"type": "image_url", "image_url": {"url": "x"}},
+ {"type": "text", "text": TXT}])]),
+ TXT)
+
# Custom callable extractor
check("extract/custom_callable", _extract_text({"custom": "special"}, lambda x: x["custom"].upper()), "SPECIAL")