Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions apps/application/tests/test_workflow_history_message.py
Original file line number Diff line number Diff line change
@@ -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), [])
77 changes: 77 additions & 0 deletions apps/application/workflow/history_message.py
Original file line number Diff line number Diff line change
@@ -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")
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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 [])
]
Expand Down Expand Up @@ -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 = [
Expand Down
Loading
Loading