Skip to content

Commit b1d0fa5

Browse files
ehz0ahktz03Pujitha Paladugu
authored
fix(langchain): preserve conversation text, roles and tool history (#6275)
* fix(langchain): retain Responses text blocks (cherry picked from commit 83702c7) Signed-off-by: Hao Zhe <[email protected]> * fix(langchain): preserve generic ChatMessage roles (cherry picked from commit cecca47) Signed-off-by: Hao Zhe <[email protected]> * fix(langchain): restore completed tool parts that carry their input Motivation: OpenVikingChatMessageHistory dropped a completed ToolPart that stores call id, name, input and output in one part. The part became a ToolMessage, and restore_openviking_messages() discarded it because no pending call had registered its id. A session holding only that part restored as [] (no exception). Approach: when a completed part has a tool_id and a nonempty tool_input, openviking_message_to_langchain() also emits the tool call on the AIMessage. restore_openviking_messages() drops calls whose id is already active from an earlier pending call, so no duplicate call is added. Result-only parts (no input) keep the existing orphan handling. A stored empty tool_input ({}) is treated as no input and is not restored. Validation (ran in a local venv with the SDK and integration installed): - pytest integrations/frameworks/langchain/tests/unit: 182 passed, 1 skipped. - The new test for a combined part fails without the src change and passes with it. - ruff check and ruff format --check pass on src and tests. Not run: a live OpenViking server or Hermes host; only the in-memory client. Report: #6242 Signed-off-by: Pujitha Paladugu <[email protected]> Assisted-by: claude-sonnet-5-5 (via Claude Code) (cherry picked from commit b468e19) Signed-off-by: Hao Zhe <[email protected]> * test(langchain): keep Responses capture coverage with the adapter Signed-off-by: Hao Zhe <[email protected]> * fix(langchain): preserve complete tool-call restoration Honor explicit empty tool inputs, deduplicate calls within a stored message, and finish existing call results before emitting another assistant turn. Require recorded call identity when reconstructing a completed part; leave result-only orphans unchanged. Extend the public sync/async history contracts for combined, split, and mixed tool records without mutating stored messages. Signed-off-by: Hao Zhe <[email protected]> * fix(messages): retain explicit empty tool inputs in serialization Signed-off-by: Hao Zhe <[email protected]> * fix(langchain): align role aliases and restored tool history Signed-off-by: Hao Zhe <[email protected]> * fix(langchain): scope restored tool-call deduplication to user turns Signed-off-by: Hao Zhe <[email protected]> * fix(session): omit tool inputs removed by the active budget Signed-off-by: Hao Zhe <[email protected]> * fix(langchain): retain late tool results across user messages Signed-off-by: Hao Zhe <[email protected]> * fix(langchain): preserve repeated tool invocations Signed-off-by: Hao Zhe <[email protected]> --------- Signed-off-by: Hao Zhe <[email protected]> Signed-off-by: Pujitha Paladugu <[email protected]> Co-authored-by: ktz03 <[email protected]> Co-authored-by: Pujitha Paladugu <[email protected]>
1 parent c6d15e9 commit b1d0fa5

10 files changed

Lines changed: 572 additions & 80 deletions

File tree

‎integrations/frameworks/langchain/src/langchain_openviking/client.py‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -814,7 +814,9 @@ def extract_message_text(content: Any) -> str:
814814
if isinstance(block, str):
815815
chunks.append(block)
816816
elif isinstance(block, dict):
817-
if block.get("type") == "text" and isinstance(block.get("text"), str):
817+
if block.get("type") in ("text", "input_text", "output_text") and isinstance(
818+
block.get("text"), str
819+
):
818820
chunks.append(block["text"])
819821
elif isinstance(block.get("content"), str):
820822
chunks.append(block["content"])
@@ -824,15 +826,32 @@ def extract_message_text(content: Any) -> str:
824826
return str(content)
825827

826828

829+
def get_message_role(message: Any) -> str:
830+
"""Normalize conversation role aliases, preserving typed-message precedence."""
831+
832+
if isinstance(message, dict):
833+
role = message.get("type") or message.get("role")
834+
else:
835+
role = getattr(message, "type", None) or getattr(message, "role", None)
836+
if role in ("chat", "ChatMessageChunk"):
837+
role = message.get("role") if isinstance(message, dict) else getattr(message, "role", None)
838+
if role in ("human", "user", "HumanMessageChunk"):
839+
return "user"
840+
if role in ("system", "developer", "SystemMessageChunk"):
841+
return "system"
842+
if role in ("ai", "assistant", "AIMessageChunk"):
843+
return "assistant"
844+
return str(role or "")
845+
846+
827847
def get_latest_user_text(messages: Iterable[Any]) -> str:
828848
for message in reversed(list(messages)):
829-
role = getattr(message, "type", None) or getattr(message, "role", None)
830-
if isinstance(message, dict):
831-
role = message.get("type") or message.get("role")
832-
content = message.get("content")
833-
else:
834-
content = getattr(message, "content", "")
835-
if role in {"human", "user"}:
849+
if get_message_role(message) == "user":
850+
content = (
851+
message.get("content")
852+
if isinstance(message, dict)
853+
else getattr(message, "content", "")
854+
)
836855
text = extract_message_text(content).strip()
837856
if text:
838857
return text

‎integrations/frameworks/langchain/src/langchain_openviking/messages.py‎

Lines changed: 90 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,15 @@
1414
BaseMessage,
1515
HumanMessage,
1616
SystemMessage,
17+
ToolCall,
1718
ToolMessage,
1819
)
1920
except ImportError as exc: # pragma: no cover - exercised by optional import path
2021
from langchain_openviking.client import missing_dependency
2122

2223
raise missing_dependency("langchain", "langchain-core") from exc
2324

24-
from langchain_openviking.client import extract_message_text
25+
from langchain_openviking.client import extract_message_text, get_message_role
2526

2627
OPENVIKING_CONTEXT_MARKER = "<openviking_context>"
2728
LANGCHAIN_SUMMARIZATION_SOURCE = "summarization"
@@ -96,13 +97,14 @@ def langchain_message_to_openviking(
9697
}
9798
]
9899

99-
if isinstance(message, SystemMessage):
100+
role = get_message_role(message)
101+
if role == "system":
100102
return []
101103

102104
text = extract_message_text(getattr(message, "content", ""))
103105
if not text:
104106
return []
105-
role = "user" if getattr(message, "type", "") == "human" else "assistant"
107+
role = "user" if role == "user" else "assistant"
106108
return [{"role": role, "parts": [{"type": "text", "text": text}]}]
107109

108110

@@ -116,15 +118,27 @@ def openviking_message_to_langchain(message: dict[str, Any]) -> list[BaseMessage
116118
return [HumanMessage(content=text)]
117119

118120
tool_calls = []
121+
tool_call_ids: set[str] = set()
119122
tool_messages = []
120123
for part in parts:
121124
if part.get("type") != "tool":
122125
continue
123126
tool_id = str(part.get("tool_id") or "")
124127
tool_name = str(part.get("tool_name") or "")
125128
status = str(part.get("tool_status") or "")
126-
has_output = part.get("tool_output") is not None
127-
is_completed_result = has_output or status in {"completed", "error"}
129+
is_completed_result = _has_tool_result(part)
130+
if not is_completed_result or (
131+
tool_id and tool_name and part.get("tool_input") is not None
132+
):
133+
if not tool_id or tool_id not in tool_call_ids:
134+
tool_calls.append(
135+
{
136+
"id": tool_id,
137+
"name": tool_name,
138+
"args": _tool_args(part.get("tool_input")),
139+
}
140+
)
141+
tool_call_ids.add(tool_id)
128142
if is_completed_result:
129143
tool_messages.append(
130144
ToolMessage(
@@ -134,14 +148,6 @@ def openviking_message_to_langchain(message: dict[str, Any]) -> list[BaseMessage
134148
status="error" if status == "error" else "success",
135149
)
136150
)
137-
else:
138-
tool_calls.append(
139-
{
140-
"id": tool_id,
141-
"name": tool_name,
142-
"args": _tool_args(part.get("tool_input")),
143-
}
144-
)
145151

146152
messages: list[BaseMessage] = []
147153
if text or tool_calls or not tool_messages:
@@ -155,28 +161,93 @@ def openviking_message_to_langchain(message: dict[str, Any]) -> list[BaseMessage
155161

156162

157163
def restore_openviking_messages(messages: Sequence[dict[str, Any]]) -> list[BaseMessage]:
158-
"""Restore a valid LangChain message sequence from OpenViking session messages."""
164+
"""Restore LangChain history, matching tool results to recorded calls."""
159165

160166
restored: list[BaseMessage] = []
161-
active_tool_call_ids: set[str] = set()
167+
active_tool_calls: dict[str, ToolCall] = {}
168+
completed_tool_calls: dict[str, tuple[ToolCall, ToolMessage]] = {}
162169
for message in messages:
163-
for langchain_message in openviking_message_to_langchain(message):
170+
converted = openviking_message_to_langchain(message)
171+
pending_call_ids = {
172+
str(part.get("tool_id") or "")
173+
for part in message.get("parts") or []
174+
if part.get("type") == "tool" and not _has_tool_result(part)
175+
}
176+
converted_calls = {
177+
str(call.get("id") or ""): call
178+
for item in converted
179+
if isinstance(item, AIMessage)
180+
for call in item.tool_calls
181+
}
182+
converted_results: dict[str, ToolMessage] = {}
183+
for item in converted:
184+
if isinstance(item, ToolMessage):
185+
converted_results.setdefault(item.tool_call_id, item)
186+
completed_here: set[str] = set()
187+
# Complete earlier calls before any new assistant text or calls.
188+
for result in converted_results.values():
189+
pending = active_tool_calls.get(result.tool_call_id)
190+
# Different arguments or names describe a new call that reused the ID.
191+
if pending is not None and converted_calls.get(result.tool_call_id, pending) == pending:
192+
restored.append(result)
193+
completed_tool_calls[result.tool_call_id] = (
194+
active_tool_calls.pop(result.tool_call_id),
195+
result,
196+
)
197+
completed_here.add(result.tool_call_id)
198+
for langchain_message in converted:
164199
if isinstance(langchain_message, AIMessage):
200+
kept: list[ToolCall] = []
201+
for call in langchain_message.tool_calls:
202+
tool_call_id = str(call.get("id") or "")
203+
if tool_call_id in completed_here:
204+
continue
205+
previous = completed_tool_calls.get(tool_call_id)
206+
call_result = converted_results.get(tool_call_id)
207+
# Only a completed pair can be a repeated stored record.
208+
if (
209+
tool_call_id not in pending_call_ids
210+
and call_result is not None
211+
and previous is not None
212+
and previous[0] == call
213+
and previous[1].content == call_result.content
214+
and previous[1].status == call_result.status
215+
):
216+
continue
217+
kept.append(call)
218+
if len(kept) != len(langchain_message.tool_calls):
219+
if not kept and not langchain_message.content:
220+
continue
221+
langchain_message = langchain_message.model_copy(update={"tool_calls": kept})
165222
restored.append(langchain_message)
166223
for tool_call in langchain_message.tool_calls or []:
167224
tool_call_id = str(tool_call.get("id") or "")
168225
if tool_call_id:
169-
active_tool_call_ids.add(tool_call_id)
226+
active_tool_calls[tool_call_id] = tool_call
227+
completed_tool_calls.pop(tool_call_id, None)
170228
elif isinstance(langchain_message, ToolMessage):
171229
tool_call_id = str(langchain_message.tool_call_id or "")
172-
if tool_call_id and tool_call_id in active_tool_call_ids:
230+
if tool_call_id and tool_call_id in active_tool_calls:
173231
restored.append(langchain_message)
174-
active_tool_call_ids.discard(tool_call_id)
232+
completed_tool_calls[tool_call_id] = (
233+
active_tool_calls.pop(tool_call_id),
234+
langchain_message,
235+
)
175236
else:
237+
if isinstance(langchain_message, HumanMessage):
238+
# Reset duplicate detection; pending calls may still finish later.
239+
completed_tool_calls.clear()
176240
restored.append(langchain_message)
177241
return restored
178242

179243

244+
def _has_tool_result(part: dict[str, Any]) -> bool:
245+
return part.get("tool_output") is not None or str(part.get("tool_status") or "") in {
246+
"completed",
247+
"error",
248+
}
249+
250+
180251
def _text_parts(content: Any) -> list[dict[str, Any]]:
181252
text = extract_message_text(content)
182253
return [{"type": "text", "text": text}] if text else []

0 commit comments

Comments
 (0)