diff --git a/apps/application/tests/test_workflow_history_message.py b/apps/application/tests/test_workflow_history_message.py new file mode 100644 index 00000000000..e80e27346cc --- /dev/null +++ b/apps/application/tests/test_workflow_history_message.py @@ -0,0 +1,107 @@ +from django.test import SimpleTestCase + +from application.models import ChatRecord +from application.workflow.history_message import get_history_message, media_detail_url + +NODE_ID = "media-node-1" +IMAGE_MEDIA = {"media_key": "image_list", "media_type": "image_url", "to_media_url": media_detail_url} +VIDEO_MEDIA = {"media_key": "video_list", "media_type": "video_url", "to_media_url": media_detail_url} + + +def _record(problem, answer, node_details): + return ChatRecord( + problem_text=problem, + answer_text=answer, + question={"content": problem}, + messages=[{"type": "TEXT", "content": answer}], + details=[{"node_id": "start-node", "type": "start-node"}, {"node_id": NODE_ID, **node_details}], + ) + + +def _contents(messages): + return [(m.type, m.content) for m in messages] + + +class WorkflowHistoryMessageTests(SimpleTestCase): + def setUp(self): + self.records = [ + _record( + "q1", + "final answer 1", + {"question": "prompt 1", "answer": "described 1", "image_list": [{"file_id": "f1"}]}, + ), + _record( + "q2", + "final answer 2", + {"question": "prompt 2", "answer": "described 2", "image_list": [{"url": "http://img/2.png"}]}, + ), + ] + + def test_node_type_uses_own_question_images_and_answer(self): + messages = get_history_message(self.records, 2, "NODE", NODE_ID, **IMAGE_MEDIA) + self.assertEqual( + _contents(messages), + [ + ( + "human", + [ + {"type": "text", "text": "prompt 1"}, + {"type": "image_url", "image_url": {"url": "./oss/file/f1"}}, + ], + ), + ("ai", "described 1"), + ( + "human", + [ + {"type": "text", "text": "prompt 2"}, + {"type": "image_url", "image_url": {"url": "http://img/2.png"}}, + ], + ), + ("ai", "described 2"), + ], + ) + + def test_node_type_with_video_media(self): + self.records[1].details[1]["video_list"] = [{"file_id": "v2"}] + messages = get_history_message(self.records, 1, "NODE", NODE_ID, **VIDEO_MEDIA) + self.assertEqual( + _contents(messages), + [ + ( + "human", + [ + {"type": "text", "text": "prompt 2"}, + {"type": "video_url", "video_url": {"url": "./oss/file/v2"}}, + ], + ), + ("ai", "described 2"), + ], + ) + + def test_node_type_without_media_uses_plain_question(self): + """生成类节点不传媒体参数;理解类节点该轮没有图片时同样退化为纯文本""" + self.assertEqual( + _contents(get_history_message(self.records, 1, "NODE", NODE_ID)), + [("human", "prompt 2"), ("ai", "described 2")], + ) + self.records[1].details[1]["image_list"] = [] + self.assertEqual( + _contents(get_history_message(self.records, 1, "NODE", NODE_ID, **IMAGE_MEDIA)), + [("human", "prompt 2"), ("ai", "described 2")], + ) + + def test_workflow_type_uses_chat_record_messages(self): + messages = get_history_message(self.records, 2, "WORKFLOW", NODE_ID, **IMAGE_MEDIA) + self.assertEqual( + _contents(messages), + [("human", "q1"), ("ai", "final answer 1"), ("human", "q2"), ("ai", "final answer 2")], + ) + + def test_node_type_skips_rounds_where_node_did_not_run(self): + self.records[0].details = [{"node_id": "start-node", "type": "start-node"}] + messages = get_history_message(self.records, 2, "NODE", NODE_ID) + self.assertEqual(_contents(messages), [("human", "prompt 2"), ("ai", "described 2")]) + + def test_zero_dialogue_number_returns_empty(self): + self.assertEqual(get_history_message(self.records, 0, "NODE", NODE_ID), []) + self.assertEqual(get_history_message(self.records, 0, "WORKFLOW", NODE_ID), []) diff --git a/apps/application/workflow/history_message.py b/apps/application/workflow/history_message.py new file mode 100644 index 00000000000..0f77c435d76 --- /dev/null +++ b/apps/application/workflow/history_message.py @@ -0,0 +1,77 @@ +""" +节点历史上下文:根据 dialogue_type 从历史对话记录中组装 LangChain 消息 + +- WORKFLOW: 取整个工作流的问答(对话记录的 question / messages) +- NODE: 取本节点在每轮对话中的问答(节点详情里的 question / answer,可附带图片、视频) +""" + +from functools import reduce +from typing import Callable, Optional + +from langchain_core.messages import AIMessage, HumanMessage + + +def get_workflow_message(chat_record): + return [*chat_record.get_human_message(), *chat_record.get_ai_message()] + + +def get_node_message( + chat_record, + runtime_node_id, + media_key: Optional[str] = None, + media_type: str = "image_url", + to_media_url: Optional[Callable[[dict], Optional[str]]] = None, +): + """ + 本节点在该轮对话中的问答,本节点该轮未运行时返回空列表。 + @param media_key: 节点详情中存储媒体的字段(如 image_list / video_list),为空表示纯文本 + @param media_type: 消息内容块类型 image_url / video_url + @param to_media_url: 把存储的媒体({file_id} / {url})转换为消息中的 url,返回 None 表示忽略 + """ + node_details = chat_record.get_node_details_runtime_node_id(runtime_node_id) + if node_details is None: + return [] + question = node_details.get("question") or "" + media_url_list = [] + if media_key and to_media_url: + media_url_list = [url for url in map(to_media_url, node_details.get(media_key) or []) if url] + if media_url_list: + human_message = HumanMessage( + content=[ + {"type": "text", "text": question}, + *[{"type": media_type, media_type: {"url": url}} for url in media_url_list], + ] + ) + else: + human_message = HumanMessage(content=question) + message_list = [human_message] + answer = node_details.get("answer") + if answer: + message_list.append(AIMessage(content=answer)) + return message_list + + +def get_history_message(history_chat_record, dialogue_number, dialogue_type, runtime_node_id, **media_kwargs): + """media_kwargs 透传给 get_node_message,仅 NODE 模式使用""" + start_index = len(history_chat_record) - (dialogue_number or 0) + return reduce( + lambda x, y: [*x, *y], + [ + ( + get_workflow_message(chat_record) + if dialogue_type == "WORKFLOW" + else get_node_message(chat_record, runtime_node_id, **media_kwargs) + ) + for chat_record in history_chat_record[max(start_index, 0) :] + ], + [], + ) + + +def media_detail_url(media) -> Optional[str]: + """详情展示用:file_id 转为 oss 地址,不读取文件内容""" + if not isinstance(media, dict): + return None + if media.get("file_id"): + return f"./oss/file/{media.get('file_id')}" + return media.get("url") diff --git a/apps/application/workflow/nodes/ai_chat_node/ai_chat_node.py b/apps/application/workflow/nodes/ai_chat_node/ai_chat_node.py index 98ecb182b3d..0d81336f1e8 100644 --- a/apps/application/workflow/nodes/ai_chat_node/ai_chat_node.py +++ b/apps/application/workflow/nodes/ai_chat_node/ai_chat_node.py @@ -186,7 +186,6 @@ def _get_node_message(chat_record, runtime_node_id): if node_details is None: return [] return [*to_human_message_list(node_details.get("question")), *to_ai_message_list(node_details.get("messages"))] - return [HumanMessage(node_details.get("question")), AIMessage(node_details.get("messages"))] def _get_workflow_message(chat_record): diff --git a/apps/application/workflow/nodes/image_generate_node/image_generate_node.py b/apps/application/workflow/nodes/image_generate_node/image_generate_node.py index ded316b987f..ed6fe669349 100644 --- a/apps/application/workflow/nodes/image_generate_node/image_generate_node.py +++ b/apps/application/workflow/nodes/image_generate_node/image_generate_node.py @@ -9,17 +9,16 @@ import asyncio import base64 -from functools import reduce import uuid_utils.compat as uuid from django.db.models import QuerySet from django.utils.translation import gettext_lazy as _ -from langchain_core.messages import HumanMessage, AIMessage from rest_framework import serializers from application.workflow.common import AsyncRunner, WorkflowType from application.workflow.content_type import ContentType from application.workflow.file_access import save_generated_file +from application.workflow.history_message import get_history_message from application.workflow.i_node import INode from application.workflow.media_download import MAX_GENERATED_IMAGE_BYTES, download_http_bytes from application.workflow.message.struct.content import Content, NodeInfo, Position @@ -87,7 +86,7 @@ def execute(self): prompt = node_params.get("prompt", "") negative_prompt = node_params.get("negative_prompt", "") dialogue_number = node_params.get("dialogue_number", 0) - dialogue_type = node_params.get("dialogue_type", "NODE") + dialogue_type = node_params.get("dialogue_type") or "NODE" model_params_setting = node_params.get("model_params_setting") workflow_type = self.get_workflow_type() @@ -117,7 +116,7 @@ def execute(self): workspace_id = workflow_params.get("workspace_id") tti_model = get_model_instance_by_model_workspace_id(model_id, workspace_id, **(model_params_setting or {})) - history_message = self._get_history_message(history_chat_record, dialogue_number) + history_message = get_history_message(history_chat_record, dialogue_number, dialogue_type, self.get_node_id()) self.data["history_message"] = [{"content": m.content, "role": m.type} for m in (history_message or [])] question = self.workflow_manage.generate_prompt(prompt) @@ -156,42 +155,6 @@ def execute(self): async def _await_generate(self, tti_model, question, negative_prompt): return await asyncio.to_thread(tti_model.generate_image, question, negative_prompt) - def _get_history_message(self, history_chat_record, dialogue_number): - start_index = len(history_chat_record) - dialogue_number - return reduce( - lambda x, y: [*x, *y], - [ - [ - self._generate_history_human_message(history_chat_record[index]), - *self._generate_history_ai_message(history_chat_record[index]), - ] - for index in range(max(start_index, 0), len(history_chat_record)) - ], - [], - ) - - def _generate_history_human_message(self, chat_record): - for data in chat_record.details.values(): - if self.node.id == data.get("node_id") and "image_list" in data: - image_list = data["image_list"] - if len(image_list) == 0 or data.get("dialogue_type") == "WORKFLOW": - return HumanMessage(content=chat_record.problem_text) - return HumanMessage(content=data.get("question", chat_record.problem_text)) - return HumanMessage(content=chat_record.problem_text) - - def _generate_history_ai_message(self, chat_record): - for val in chat_record.details.values(): - if self.node.id == val.get("node_id") and "image_list" in val: - if val.get("dialogue_type") == "WORKFLOW": - return chat_record.get_ai_message() - image_list = val["image_list"] - return [ - AIMessage( - content=[{"type": "image_url", "image_url": {"url": f"{file_url}"}} for file_url in image_list] - ) - ] - return chat_record.get_ai_message() - def _upload_file(self, file, workflow_params, workflow_type): return save_generated_file(file, workflow_params) diff --git a/apps/application/workflow/nodes/image_to_video_node/image_to_video_node.py b/apps/application/workflow/nodes/image_to_video_node/image_to_video_node.py index 48af1334a42..9840d0abe62 100644 --- a/apps/application/workflow/nodes/image_to_video_node/image_to_video_node.py +++ b/apps/application/workflow/nodes/image_to_video_node/image_to_video_node.py @@ -2,17 +2,17 @@ import asyncio import base64 import uuid_utils.compat as uuid -from functools import reduce from typing import List from django.db.models import QuerySet from django.utils.translation import gettext_lazy as _, gettext -from langchain_core.messages import BaseMessage, HumanMessage, AIMessage +from langchain_core.messages import BaseMessage, HumanMessage from rest_framework import serializers from application.workflow.common import AsyncRunner, WorkflowType from application.workflow.content_type import ContentType from application.workflow.file_access import get_authorized_file, save_generated_file +from application.workflow.history_message import get_history_message from application.workflow.i_node import INode from application.workflow.media_download import MAX_GENERATED_VIDEO_BYTES, download_http_bytes from application.workflow.message.struct.content import Content, NodeInfo, Position @@ -85,7 +85,7 @@ def execute(self): prompt = node_params.get("prompt", "") negative_prompt = node_params.get("negative_prompt", "") dialogue_number = node_params.get("dialogue_number", 0) - dialogue_type = node_params.get("dialogue_type", "NODE") + dialogue_type = node_params.get("dialogue_type") or "NODE" model_params_setting = node_params.get("model_params_setting") first_frame_url_ref = node_params.get("first_frame_url") last_frame_url_ref = node_params.get("last_frame_url") @@ -127,7 +127,7 @@ def execute(self): ttv_model = get_model_instance_by_model_workspace_id(model_id, workspace_id, **(model_params_setting or {})) - history_message = self._get_history_message(history_chat_record, dialogue_number) + history_message = get_history_message(history_chat_record, dialogue_number, dialogue_type, self.get_node_id()) self.data["history_message"] = [ {"content": message.content, "role": message.type} for message in (history_message or []) ] @@ -194,45 +194,6 @@ def _get_file_base64(self, image_url): def _upload_file(self, file, workflow_type, workflow_params): return save_generated_file(file, workflow_params) - def _generate_history_ai_message(self, chat_record): - for val in chat_record.details.values(): - if self.node.id == val["node_id"] and "image_list" in val: - if val["dialogue_type"] == "WORKFLOW": - return chat_record.get_ai_message() - image_list = val["image_list"] - return [ - AIMessage( - content=[ - *[{"type": "image_url", "image_url": {"url": f"{file_url}"}} for file_url in image_list] - ] - ) - ] - return chat_record.get_ai_message() - - def _get_history_message(self, history_chat_record, dialogue_number): - start_index = len(history_chat_record) - dialogue_number - history_message = reduce( - lambda x, y: [*x, *y], - [ - [ - self._generate_history_human_message(history_chat_record[index]), - *self._generate_history_ai_message(history_chat_record[index]), - ] - for index in range(start_index if start_index > 0 else 0, len(history_chat_record)) - ], - [], - ) - return history_message - - def _generate_history_human_message(self, chat_record): - for data in chat_record.details.values(): - if self.node.id == data["node_id"] and "image_list" in data: - image_list = data["image_list"] - if len(image_list) == 0 or data["dialogue_type"] == "WORKFLOW": - return HumanMessage(content=chat_record.problem_text) - return HumanMessage(content=data["question"]) - return HumanMessage(content=chat_record.problem_text) - @staticmethod def reset_message_list(message_list: List[BaseMessage], answer_text): result = [ diff --git a/apps/application/workflow/nodes/image_understand_node/image_understand_node.py b/apps/application/workflow/nodes/image_understand_node/image_understand_node.py index 974606926d9..85e9b744b67 100644 --- a/apps/application/workflow/nodes/image_understand_node/image_understand_node.py +++ b/apps/application/workflow/nodes/image_understand_node/image_understand_node.py @@ -3,16 +3,16 @@ import base64 import contextlib import uuid_utils.compat as uuid -from functools import reduce from django.db.models import QuerySet from django.utils.translation import gettext_lazy as _ -from langchain_core.messages import HumanMessage, SystemMessage, AIMessage +from langchain_core.messages import HumanMessage, SystemMessage from rest_framework import serializers from application.workflow.common import AsyncRunner, WorkflowType from application.workflow.content_type import ContentType from application.workflow.file_access import get_authorized_file +from application.workflow.history_message import get_history_message, media_detail_url from application.workflow.i_node import INode from application.workflow.message.struct.content import Content, NodeInfo, Position from application.workflow.message.struct.reasoning_content import ReasoningContent @@ -85,7 +85,8 @@ def execute(self): system = node_params.get("system", "") prompt = node_params.get("prompt", "") dialogue_number = node_params.get("dialogue_number", 0) - dialogue_type = node_params.get("dialogue_type", "WORKFLOW") + # 新建节点由前端显式写入(默认 NODE);缺省只出现在旧数据中,沿用工作流历史 + dialogue_type = node_params.get("dialogue_type") or "WORKFLOW" image_list_ref = node_params.get("image_list") model_params_setting = node_params.get("model_params_setting") model_setting = node_params.get("model_setting") @@ -132,7 +133,14 @@ def execute(self): chat_model = get_model_instance_by_model_workspace_id(model_id, workspace_id, **(model_params_setting or {})) - history_message_for_details = self._get_history_message_for_details(history_chat_record, dialogue_number) + runtime_node_id = self.get_node_id() + history_message_for_details = get_history_message( + history_chat_record, + dialogue_number, + dialogue_type, + runtime_node_id, + **self._history_media(media_detail_url), + ) self.data["history_message"] = [ {"content": message.content, "role": message.type} for message in (history_message_for_details or []) ] @@ -143,8 +151,14 @@ def execute(self): system = self.workflow_manage.generate_prompt(system) self.data["system"] = system - history_message = self._get_history_message(history_chat_record, dialogue_number) - message_list = self._generate_message_list(chat_model, system, prompt, history_message, image) + history_message = get_history_message( + history_chat_record, + dialogue_number, + dialogue_type, + runtime_node_id, + **self._history_media(self._image_to_model_url), + ) + message_list = self._generate_message_list(system, question, history_message, image) self.data["message_list"] = [{"content": m.content, "role": m.type} for m in message_list] @@ -287,103 +301,23 @@ def _generate_context_image(self, image): elif image is not None and len(image) > 0: self.data["image_list"] = image - def _get_history_message_for_details(self, history_chat_record, dialogue_number): - start_index = len(history_chat_record) - dialogue_number - history_message = reduce( - lambda x, y: [*x, *y], - [ - [ - self._generate_history_human_message_for_details(history_chat_record[index]), - *self._generate_history_ai_message(history_chat_record[index]), - ] - for index in range(start_index if start_index > 0 else 0, len(history_chat_record)) - ], - [], - ) - return history_message - - def _generate_history_ai_message(self, chat_record): - for val in chat_record.details.values(): - if self.node.id == val["node_id"] and "image_list" in val: - if val["dialogue_type"] == "WORKFLOW": - return chat_record.get_ai_message() - return [AIMessage(content=val["answer"])] - return chat_record.get_ai_message() - - def _generate_history_human_message_for_details(self, chat_record): - for data in chat_record.details.values(): - if self.node.id == data["node_id"] and "image_list" in data: - image_list = data["image_list"] or [] - if len(image_list) == 0 or data["dialogue_type"] == "WORKFLOW": - return HumanMessage(content=chat_record.problem_text) - file_id_list = [] - url_list = [] - for image in image_list: - if "file_id" in image: - file_id_list.append(image.get("file_id")) - elif "url" in image: - url_list.append(image.get("url")) - return HumanMessage( - content=[ - {"type": "text", "text": data["question"]}, - *[ - {"type": "image_url", "image_url": {"url": f"./oss/file/{file_id}"}} - for file_id in file_id_list - ], - *[{"type": "image_url", "image_url": {"url": url}} for url in url_list], - ] - ) - return HumanMessage(content=chat_record.problem_text) - - def _get_history_message(self, history_chat_record, dialogue_number): - start_index = len(history_chat_record) - dialogue_number - history_message = reduce( - lambda x, y: [*x, *y], - [ - [ - self._generate_history_human_message(history_chat_record[index]), - *self._generate_history_ai_message(history_chat_record[index]), - ] - for index in range(start_index if start_index > 0 else 0, len(history_chat_record)) - ], - [], - ) - return history_message - - def _generate_history_human_message(self, chat_record): - for data in chat_record.details.values(): - if self.node.id == data["node_id"] and "image_list" in data: - image_list = data["image_list"] or [] - if len(image_list) == 0 or data["dialogue_type"] == "WORKFLOW": - return HumanMessage(content=chat_record.problem_text) - file_id_list = [] - url_list = [] - for image in image_list: - if "file_id" in image: - file_id_list.append(image.get("file_id")) - elif "url" in image: - url_list.append(image.get("url")) - image_base64_list = [self._file_id_to_base64(file_id) for file_id in file_id_list] - return HumanMessage( - content=[ - {"type": "text", "text": data["question"]}, - *[ - { - "type": "image_url", - "image_url": {"url": f"data:image/{base64_image[1]};base64,{base64_image[0]}"}, - } - for base64_image in image_base64_list - ], - *[{"type": "image_url", "image_url": {"url": url}} for url in url_list], - ] - ) - return HumanMessage(content=chat_record.problem_text) - - def _file_id_to_base64(self, file_id: str): - file = get_authorized_file(file_id, self.get_workflow_parameters()) - file_bytes = file.get_bytes() - base64_image = base64.b64encode(file_bytes).decode("utf-8") - return [base64_image, guess_image_format(file_bytes, file.file_name)] + @staticmethod + def _history_media(to_media_url): + return {"media_key": "image_list", "media_type": "image_url", "to_media_url": to_media_url} + + def _image_to_model_url(self, image): + """发给模型用:file_id 经鉴权后转为 base64,http 地址原样保留""" + if not isinstance(image, dict): + return None + if image.get("file_id"): + file = get_authorized_file(image.get("file_id"), self.get_workflow_parameters()) + file_bytes = file.get_bytes() + base64_image = base64.b64encode(file_bytes).decode("utf-8") + return f"data:image/{guess_image_format(file_bytes, file.file_name)};base64,{base64_image}" + url = image.get("url") + if isinstance(url, str) and url.startswith("http"): + return url + return None def _process_images(self, image): images = [] @@ -404,8 +338,7 @@ def _process_images(self, image): images.append({"type": "image_url", "image_url": {"url": img["url"]}}) return images - def _generate_message_list(self, image_model, system: str, prompt: str, history_message, image): - prompt_text = self.workflow_manage.generate_prompt(prompt) + def _generate_message_list(self, system: str, prompt_text: str, history_message, image): images = self._process_images(image) if images: diff --git a/apps/application/workflow/nodes/text_to_video_node/text_to_video_node.py b/apps/application/workflow/nodes/text_to_video_node/text_to_video_node.py index 11a57d01b25..9e85f66fea3 100644 --- a/apps/application/workflow/nodes/text_to_video_node/text_to_video_node.py +++ b/apps/application/workflow/nodes/text_to_video_node/text_to_video_node.py @@ -1,17 +1,17 @@ # coding=utf-8 import asyncio import uuid_utils.compat as uuid -from functools import reduce from typing import List from django.db.models import QuerySet from django.utils.translation import gettext_lazy as _, gettext -from langchain_core.messages import BaseMessage, HumanMessage, AIMessage +from langchain_core.messages import BaseMessage, HumanMessage from rest_framework import serializers from application.workflow.common import AsyncRunner, WorkflowType from application.workflow.content_type import ContentType from application.workflow.file_access import save_generated_file +from application.workflow.history_message import get_history_message from application.workflow.i_node import INode from application.workflow.media_download import MAX_GENERATED_VIDEO_BYTES, download_http_bytes from application.workflow.message.struct.content import Content, NodeInfo, Position @@ -81,7 +81,7 @@ def execute(self): prompt = node_params.get("prompt", "") negative_prompt = node_params.get("negative_prompt", "") dialogue_number = node_params.get("dialogue_number", 0) - dialogue_type = node_params.get("dialogue_type", "NODE") + dialogue_type = node_params.get("dialogue_type") or "NODE" model_params_setting = node_params.get("model_params_setting") workflow_type = self.get_workflow_type() @@ -112,7 +112,7 @@ def execute(self): ttv_model = get_model_instance_by_model_workspace_id(model_id, workspace_id, **(model_params_setting or {})) - history_message = self._get_history_message(history_chat_record, dialogue_number) + history_message = get_history_message(history_chat_record, dialogue_number, dialogue_type, self.get_node_id()) self.data["history_message"] = [ {"content": message.content, "role": message.type} for message in (history_message or []) ] @@ -157,45 +157,6 @@ async def _await_generate(self, ttv_model, question, negative_prompt): def _upload_file(self, file, workflow_type, workflow_params): return save_generated_file(file, workflow_params) - def _generate_history_ai_message(self, chat_record): - for val in chat_record.details.values(): - if self.node.id == val["node_id"] and "image_list" in val: - if val["dialogue_type"] == "WORKFLOW": - return chat_record.get_ai_message() - image_list = val["image_list"] - return [ - AIMessage( - content=[ - *[{"type": "image_url", "image_url": {"url": f"{file_url}"}} for file_url in image_list] - ] - ) - ] - return chat_record.get_ai_message() - - def _get_history_message(self, history_chat_record, dialogue_number): - start_index = len(history_chat_record) - dialogue_number - history_message = reduce( - lambda x, y: [*x, *y], - [ - [ - self._generate_history_human_message(history_chat_record[index]), - *self._generate_history_ai_message(history_chat_record[index]), - ] - for index in range(start_index if start_index > 0 else 0, len(history_chat_record)) - ], - [], - ) - return history_message - - def _generate_history_human_message(self, chat_record): - for data in chat_record.details.values(): - if self.node.id == data["node_id"] and "image_list" in data: - image_list = data["image_list"] - if len(image_list) == 0 or data["dialogue_type"] == "WORKFLOW": - return HumanMessage(content=chat_record.problem_text) - return HumanMessage(content=data["question"]) - return HumanMessage(content=chat_record.problem_text) - @staticmethod def reset_message_list(message_list: List[BaseMessage], answer_text): result = [ diff --git a/apps/application/workflow/nodes/video_understand_node/video_understand_node.py b/apps/application/workflow/nodes/video_understand_node/video_understand_node.py index 019451a4a34..733ec869672 100644 --- a/apps/application/workflow/nodes/video_understand_node/video_understand_node.py +++ b/apps/application/workflow/nodes/video_understand_node/video_understand_node.py @@ -2,16 +2,16 @@ import asyncio import contextlib import uuid_utils.compat as uuid -from functools import reduce from django.db.models import QuerySet from django.utils.translation import gettext_lazy as _ -from langchain_core.messages import HumanMessage, SystemMessage, AIMessage +from langchain_core.messages import HumanMessage, SystemMessage from rest_framework import serializers from application.workflow.common import AsyncRunner, WorkflowType from application.workflow.content_type import ContentType from application.workflow.file_access import get_authorized_file +from application.workflow.history_message import get_history_message, media_detail_url from application.workflow.i_node import INode from application.workflow.message.struct.content import Content, NodeInfo, Position from application.workflow.message.struct.reasoning_content import ReasoningContent @@ -83,7 +83,8 @@ def execute(self): system = node_params.get("system", "") prompt = node_params.get("prompt", "") dialogue_number = node_params.get("dialogue_number", 0) - dialogue_type = node_params.get("dialogue_type", "WORKFLOW") + # 缺省只出现在旧数据中,沿用工作流历史 + dialogue_type = node_params.get("dialogue_type") or "WORKFLOW" video_list_ref = node_params.get("video_list") model_params_setting = node_params.get("model_params_setting") model_setting = node_params.get("model_setting") @@ -130,7 +131,14 @@ def execute(self): chat_model = get_model_instance_by_model_workspace_id(model_id, workspace_id, **(model_params_setting or {})) - history_message_for_details = self._get_history_message_for_details(history_chat_record, dialogue_number) + runtime_node_id = self.get_node_id() + history_message_for_details = get_history_message( + history_chat_record, + dialogue_number, + dialogue_type, + runtime_node_id, + **self._history_media(media_detail_url), + ) self.data["history_message"] = [ {"content": message.content, "role": message.type} for message in (history_message_for_details or []) ] @@ -141,8 +149,14 @@ def execute(self): system = self.workflow_manage.generate_prompt(system) self.data["system"] = system - history_message = self._get_history_message(history_chat_record, dialogue_number, chat_model) - message_list = self._generate_message_list(chat_model, system, prompt, history_message, video) + history_message = get_history_message( + history_chat_record, + dialogue_number, + dialogue_type, + runtime_node_id, + **self._history_media(lambda v: self._video_to_model_url(v, chat_model)), + ) + message_list = self._generate_message_list(chat_model, system, question, history_message, video) self.data["message_list"] = [{"content": m.content, "role": m.type} for m in message_list] self._generate_context_video(video) @@ -285,99 +299,21 @@ def _generate_context_video(self, video): elif video is not None and len(video) > 0: self.data["video_list"] = video - def _get_history_message_for_details(self, history_chat_record, dialogue_number): - start_index = len(history_chat_record) - dialogue_number - history_message = reduce( - lambda x, y: [*x, *y], - [ - [ - self._generate_history_human_message_for_details(history_chat_record[index]), - *self._generate_history_ai_message(history_chat_record[index]), - ] - for index in range(start_index if start_index > 0 else 0, len(history_chat_record)) - ], - [], - ) - return history_message - - def _generate_history_ai_message(self, chat_record): - for val in chat_record.details.values(): - if self.node.id == val["node_id"] and "video_list" in val: - if val["dialogue_type"] == "WORKFLOW": - return chat_record.get_ai_message() - return [AIMessage(content=val["answer"])] - return chat_record.get_ai_message() - - def _generate_history_human_message_for_details(self, chat_record): - for data in chat_record.details.values(): - if self.node.id == data["node_id"] and "video_list" in data: - video_list = data["video_list"] or [] - if len(video_list) == 0 or data["dialogue_type"] == "WORKFLOW": - return HumanMessage(content=chat_record.problem_text) - file_id_list = [] - url_list = [] - for video in video_list: - if "file_id" in video: - file_id_list.append(video.get("file_id")) - elif "url" in video: - url_list.append(video.get("url")) - return HumanMessage( - content=[ - {"type": "text", "text": data["question"]}, - *[ - {"type": "video_url", "video_url": {"url": f"./oss/file/{file_id}"}} - for file_id in file_id_list - ], - *[{"type": "video_url", "video_url": {"url": url}} for url in url_list], - ] - ) - return HumanMessage(content=chat_record.problem_text) - - def _get_history_message(self, history_chat_record, dialogue_number, video_model): - start_index = len(history_chat_record) - dialogue_number - history_message = reduce( - lambda x, y: [*x, *y], - [ - [ - self._generate_history_human_message(history_chat_record[index], video_model), - *self._generate_history_ai_message(history_chat_record[index]), - ] - for index in range(start_index if start_index > 0 else 0, len(history_chat_record)) - ], - [], - ) - return history_message - - def _generate_history_human_message(self, chat_record, video_model): - for data in chat_record.details.values(): - if self.node.id == data["node_id"] and "video_list" in data: - video_list = data["video_list"] or [] - if len(video_list) == 0 or data["dialogue_type"] == "WORKFLOW": - return HumanMessage(content=chat_record.problem_text) - file_id_list = [] - url_list = [] - for video in video_list: - if "file_id" in video: - file_id_list.append(video.get("file_id")) - elif "url" in video: - url_list.append(video.get("url")) - video_base64_list = [self._file_id_to_base64(file_id, video_model) for file_id in file_id_list] - return HumanMessage( - content=[ - {"type": "text", "text": data["question"]}, - *[ - {"type": "video_url", "video_url": {"url": base64_video}} - for base64_video in video_base64_list - ], - *[{"type": "video_url", "video_url": {"url": url}} for url in url_list], - ] - ) - return HumanMessage(content=chat_record.problem_text) - - def _file_id_to_base64(self, file_id: str, video_model): - file = get_authorized_file(file_id, self.get_workflow_parameters()) - file_bytes = file.get_bytes() - return video_model.upload_file_and_get_url(file_bytes, file.file_name) + @staticmethod + def _history_media(to_media_url): + return {"media_key": "video_list", "media_type": "video_url", "to_media_url": to_media_url} + + def _video_to_model_url(self, video, video_model): + """发给模型用:file_id 经鉴权后上传到模型侧换取 url,http 地址原样保留""" + if not isinstance(video, dict): + return None + if video.get("file_id"): + file = get_authorized_file(video.get("file_id"), self.get_workflow_parameters()) + return video_model.upload_file_and_get_url(file.get_bytes(), file.file_name) + url = video.get("url") + if isinstance(url, str) and url.startswith("http"): + return url + return None def _process_videos(self, video, video_model): videos = [] @@ -394,8 +330,7 @@ def _process_videos(self, video, video_model): videos.append({"type": "video_url", "video_url": {"url": v["url"]}}) return videos - def _generate_message_list(self, video_model, system: str, prompt: str, history_message, video): - prompt_text = self.workflow_manage.generate_prompt(prompt) + def _generate_message_list(self, video_model, system: str, prompt_text: str, history_message, video): videos = self._process_videos(video, video_model) if videos: