sync update from LAN repo (source master-yx @ cf505220)
This commit is contained in:
1 parent
e243ec3a46
commit
19d3cb96dc
114 files changed
+14787
-451
No files matched your search
+29
-8
@@ -6,7 +6,6 @@ from typing import Any
|
||||
|
||||
from langchain_core.messages import BaseMessage, SystemMessage
|
||||
|
||||
|
||||
_SYSTEM_SEPARATOR = "\n\n---\n\n"
|
||||
|
||||
|
||||
@@ -35,7 +34,11 @@ def normalize_langchain_messages(messages: list[BaseMessage]) -> list[BaseMessag
|
||||
return messages
|
||||
|
||||
first_non_system_index = next((idx for idx, message in enumerate(messages) if not isinstance(message, SystemMessage)), len(messages))
|
||||
if len(system_messages) == first_non_system_index:
|
||||
# A number of strict chat templates accept *one* system message, and only
|
||||
# at index zero. Two adjacent leading system messages are therefore not a
|
||||
# valid no-op case: LangChain's agent prompt followed by DeerFlow's
|
||||
# transient compaction summary must still be folded into one message.
|
||||
if len(system_messages) == 1 and first_non_system_index == 1:
|
||||
return messages
|
||||
|
||||
merged = system_messages[0].model_copy(
|
||||
@@ -46,20 +49,38 @@ def normalize_langchain_messages(messages: list[BaseMessage]) -> list[BaseMessag
|
||||
return [merged, *(message for message in messages if not isinstance(message, SystemMessage))]
|
||||
|
||||
|
||||
def normalize_model_request_messages(
|
||||
system_message: SystemMessage | None,
|
||||
messages: list[BaseMessage],
|
||||
) -> tuple[SystemMessage | None, list[BaseMessage]]:
|
||||
"""Normalize LangChain's split ``ModelRequest`` message representation.
|
||||
|
||||
``ModelRequest.messages`` is documented as excluding the system prompt.
|
||||
Transient middleware (notably context compaction) can nevertheless place a
|
||||
``SystemMessage`` in that list. Fold every such message into the dedicated
|
||||
system slot so adapters without a DeerFlow-specific payload patch also
|
||||
receive exactly one leading system message.
|
||||
"""
|
||||
if system_message is None and not any(isinstance(message, SystemMessage) for message in messages):
|
||||
return None, messages
|
||||
|
||||
combined = [system_message, *messages] if system_message is not None else messages
|
||||
normalized = normalize_langchain_messages(combined)
|
||||
if normalized and isinstance(normalized[0], SystemMessage):
|
||||
return normalized[0], normalized[1:]
|
||||
return None, normalized
|
||||
|
||||
|
||||
def _normalize_payload_message_list(messages: list[Any]) -> list[Any]:
|
||||
system_messages = [message for message in messages if isinstance(message, dict) and message.get("role") == "system"]
|
||||
if not system_messages:
|
||||
return messages
|
||||
|
||||
first_non_system_index = next(
|
||||
(
|
||||
idx
|
||||
for idx, message in enumerate(messages)
|
||||
if not (isinstance(message, dict) and message.get("role") == "system")
|
||||
),
|
||||
(idx for idx, message in enumerate(messages) if not (isinstance(message, dict) and message.get("role") == "system")),
|
||||
len(messages),
|
||||
)
|
||||
if len(system_messages) == first_non_system_index:
|
||||
if len(system_messages) == 1 and first_non_system_index == 1:
|
||||
return messages
|
||||
|
||||
merged_system = dict(system_messages[0])
|
||||
|
||||
+66
-1
@@ -25,6 +25,7 @@ message that originally carried it:
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
from langchain_core.language_models import LanguageModelInput
|
||||
@@ -36,6 +37,65 @@ from deerflow.models.message_ordering import normalize_chat_payload_messages
|
||||
from deerflow.models.reasoning_fields import apply_reasoning_from_payload, extract_reasoning_text, fill_ui_reasoning_content, restore_reasoning_fields
|
||||
|
||||
|
||||
class OpenAICompatibleUpstreamError(RuntimeError):
|
||||
"""An OpenAI-compatible gateway reported an error inside a HTTP 200 body.
|
||||
|
||||
Several compatible gateways do not use an HTTP error status for quota,
|
||||
concurrency, or inference failures. Instead they return ``choices=null``
|
||||
(or an empty streamed chunk) together with a vendor ``base_resp`` object.
|
||||
LangChain raises a generic ``TypeError`` for the non-streaming shape and
|
||||
treats the streaming shape as an empty successful response. Raising one
|
||||
stable exception here lets DeerFlow's model middleware retry both paths.
|
||||
"""
|
||||
|
||||
def __init__(self, *, code: Any, message: str | None = None) -> None:
|
||||
self.code = code
|
||||
detail = _bounded_error_message(message)
|
||||
suffix = f": {detail}" if detail else ""
|
||||
super().__init__(f"OpenAI-compatible upstream application error (code={code}){suffix}")
|
||||
|
||||
|
||||
def _bounded_error_message(value: Any, *, limit: int = 500) -> str:
|
||||
"""Return a log-safe, bounded one-line provider message."""
|
||||
if not isinstance(value, str):
|
||||
return ""
|
||||
normalized = " ".join(value.split())
|
||||
return normalized[:limit]
|
||||
|
||||
|
||||
def _application_error(payload: Mapping[str, Any]) -> tuple[Any, str | None] | None:
|
||||
"""Extract a non-success ``base_resp`` error from a compatible payload."""
|
||||
raw = payload.get("base_resp") or payload.get("baseResp")
|
||||
if not isinstance(raw, Mapping):
|
||||
return None
|
||||
|
||||
code = raw.get("status_code")
|
||||
if code is None:
|
||||
code = raw.get("statusCode")
|
||||
if code is None:
|
||||
code = raw.get("code")
|
||||
|
||||
# MiniMax-compatible responses use 0 for success. Be conservative for
|
||||
# gateways that put informational metadata in ``base_resp``.
|
||||
normalized_code = str(code).strip().lower() if code is not None else ""
|
||||
if normalized_code in {"", "0", "200", "ok", "success"}:
|
||||
return None
|
||||
|
||||
message = raw.get("status_msg")
|
||||
if message is None:
|
||||
message = raw.get("statusMsg")
|
||||
if message is None:
|
||||
message = raw.get("message")
|
||||
return code, message if isinstance(message, str) else None
|
||||
|
||||
|
||||
def _raise_for_application_error(payload: Mapping[str, Any]) -> None:
|
||||
error = _application_error(payload)
|
||||
if error is not None:
|
||||
code, message = error
|
||||
raise OpenAICompatibleUpstreamError(code=code, message=message)
|
||||
|
||||
|
||||
class PatchedChatOpenAI(ChatOpenAI):
|
||||
"""ChatOpenAI with ``thought_signature`` preservation for Gemini thinking via OpenAI gateway.
|
||||
|
||||
@@ -108,6 +168,10 @@ class PatchedChatOpenAI(ChatOpenAI):
|
||||
base_generation_info: dict | None,
|
||||
) -> ChatGenerationChunk | None:
|
||||
"""Preserve streamed ``reasoning_content`` in ``additional_kwargs``."""
|
||||
# Some compatible gateways return a vendor error event followed by a
|
||||
# normal-looking usage chunk, all under HTTP 200. Detect the first
|
||||
# event before LangChain converts it into an empty AIMessageChunk.
|
||||
_raise_for_application_error(chunk)
|
||||
generation_chunk = super()._convert_chunk_to_generation_chunk(
|
||||
chunk,
|
||||
default_chunk_class,
|
||||
@@ -133,8 +197,9 @@ class PatchedChatOpenAI(ChatOpenAI):
|
||||
generation_info: dict | None = None,
|
||||
) -> ChatResult:
|
||||
"""Preserve non-stream ``reasoning_content`` in ``additional_kwargs``."""
|
||||
result = super()._create_chat_result(response, generation_info)
|
||||
response_dict = response if isinstance(response, dict) else response.model_dump()
|
||||
_raise_for_application_error(response_dict)
|
||||
result = super()._create_chat_result(response, generation_info)
|
||||
choices = response_dict.get("choices", [])
|
||||
|
||||
generations: list[ChatGeneration] = []
|
||||
|
||||
Reference in new issue
Block a user