Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

1.6 KB
Raw Blame
from collections.abc import Callable, Generator, Iterable, Mapping

from core.app.apps.streaming_utils import stream_topic_events
from core.app.entities.task_entities import StreamEvent
from extensions.ext_redis import get_pubsub_broadcast_channel
from libs.broadcast_channel.channel import SupportsPreparedSubscription, Topic
from models.model import AppMode


class MessageGenerator:
    @staticmethod
    def _make_channel_key(app_mode: AppMode, workflow_run_id: str):
        return f"channel:{app_mode}:{str(workflow_run_id)}"

    @classmethod
    def get_response_topic(cls, app_mode: AppMode, workflow_run_id: str) -> Topic:
        key = cls._make_channel_key(app_mode, workflow_run_id)
        channel = get_pubsub_broadcast_channel()
        topic = channel.topic(key)
        return topic

    @classmethod
    def retrieve_events(
        cls,
        app_mode: AppMode,
        workflow_run_id: str,
        idle_timeout=300,
        ping_interval: float = 10.0,
        on_subscribe: Callable[[], None] | None = None,
        terminal_events: Iterable[str | StreamEvent] | None = None,
    ) -> Generator[Mapping | str]:
        topic = cls.get_response_topic(app_mode, workflow_run_id)
        subscriber = topic.as_subscriber()
        subscription = (
            subscriber.prepare_subscription()
            if isinstance(subscriber, SupportsPreparedSubscription)
            else subscriber.subscribe()
        )
        return stream_topic_events(
            subscription=subscription,
            idle_timeout=idle_timeout,
            ping_interval=ping_interval,
            on_subscribe=on_subscribe,
            terminal_events=terminal_events,
        )