RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
feat(channels): WeCom can bind agent (#18598)
brucehu6754722b00d6
diff --git a/api/channels/bootstrap.py b/api/channels/bootstrap.pyindex d799afa2ed..fadba7e911 100644--- a/api/channels/bootstrap.py+++ b/api/channels/bootstrap.py@@ -51,6 +51,47 @@ _BUNDLED_CHANNELS = (_RECONCILE_INTERVAL_SECS = 10+def _remove_reasoning_content(txt: str) -> str:+ """Strip ``<think>...</think>`` reasoning blocks from a reply.++ Mirrors ``LLMBundle._remove_reasoning_content`` (and the shared Go+ ``StripThinkTrailing`` helper): everything through the last ``</think>``+ marker is reasoning, and only what follows is shown to the end user.+ """+ if not txt:+ return txt+ first_think_start = txt.find("<think>")+ if first_think_start == -1:+ return txt+ last_think_end = txt.rfind("</think>")+ if last_think_end == -1 or last_think_end < first_think_start:+ return txt+ return txt[last_think_end + len("</think>") :]+++async def _send_thinking_message(ch, msg) -> None:+ """Send a lightweight "thinking" placeholder before the real reply (WeCom only)."""+ if ch.channel_id != "wecom":+ return+ from api.channels.core.base import OutgoingMessage++ try:+ await ch.send(+ OutgoingMessage(+ chat_id=msg.chat_id,+ text="π€ εΌε§ζθ...",+ reply_to_message_id=msg.message_id or None,+ )+ )+ except Exception:+ LOGGER.warning(+ "[%s:%s] failed to send thinking placeholder",+ ch.channel_id,+ ch.account_id,+ exc_info=True,+ )++def _canvas_state(dsl) -> dict:"""Normalize a persisted canvas DSL into a dictionary."""value = dsl@@ -139,7 +180,7 @@ def _make_chat_handler(ch):bot, a RAG completion is run against that dialog, and the answer is sentback. The connected dialog is resolved per message, so connection changestake effect immediately without restarting the channel. Channels with no- connected dialog ignore inbound messages.+ connected target ignore inbound messages."""from api.channels.core.base import IncomingMessage, OutgoingMessagefrom api.db.services.api_service import API4ConversationService@@ -176,6 +217,7 @@ def _make_chat_handler(ch):user_id = _channel_agent_user_id(ch.account_id, msg.chat_id, msg.sender_id)session = API4ConversationService.get_latest_agent_channel_session(cc.agent_id, user_id)query, inputs = _prepare_agent_turn(msg.text, session.dsl if session else None)+ await _send_thinking_message(ch, msg)answer_text = ""try:async for raw in agent_completion(@@ -196,7 +238,12 @@ def _make_chat_handler(ch):continueevent = json.loads(payload)if event.get("event") == "message":- answer_text += event.get("data", {}).get("content", "") or ""+ data = event.get("data") or {}+ answer_text += data.get("content", "") or ""+ if data.get("start_to_think", False):+ answer_text += "<think>"+ elif data.get("end_to_think", False):+ answer_text += "</think>"except Exception:LOGGER.exception("[%s:%s] Agent completion failed", ch.channel_id, ch.account_id)answer_text = "ζ±ζοΌε½εζ ζ³ε€ηθΏζ‘ζΆζ―οΌθ―·η¨ειθ―γ"@@ -205,7 +252,7 @@ def _make_chat_handler(ch):await ch.send(OutgoingMessage(chat_id=msg.chat_id,- text=answer_text,+ text=_remove_reasoning_content(answer_text),reply_to_message_id=msg.message_id or None,))@@ -238,6 +285,8 @@ def _make_chat_handler(ch):continuehistory.append(m)+ await _send_thinking_message(ch, msg)+answer_text = ""try:chat_kwargs = {"quote": False}@@ -256,7 +305,7 @@ def _make_chat_handler(ch):await ch.send(OutgoingMessage(chat_id=msg.chat_id,- text=answer_text,+ text=_remove_reasoning_content(answer_text),reply_to_message_id=msg.message_id or None,))diff --git a/api/channels/wecom/channel.py b/api/channels/wecom/channel.pyindex b102fafa00..faf0ac9247 100644--- a/api/channels/wecom/channel.py+++ b/api/channels/wecom/channel.py@@ -102,10 +102,39 @@ class _SharedWebhookServer:LOGGER.error("[wecom:%s] parse error", account_id, exc_info=True)return web.Response(text="")+ # WeCom retries callbacks that are not acknowledged within a few+ # seconds. Answering a message runs an LLM completion that can take+ # far longer, so acknowledge the webhook immediately and process+ # the message in the background; a late retry is deduped by the+ # message id instead of being answered a second time.+ message_id = str(getattr(msg, "id", "") or "")+ dedupe_key = (account_id, message_id) if message_id else None+ if dedupe_key is not None:+ now = time.time()+ last_seen = _recent_message_ids.get(dedupe_key)+ if last_seen is not None and now - last_seen < _MESSAGE_DEDUPE_WINDOW_SECS:+ LOGGER.info(+ "[wecom:%s] skip duplicate callback message_id=%s",+ account_id,+ message_id,+ )+ return web.Response(text="")+ _recent_message_ids[dedupe_key] = now+ if len(_recent_message_ids) > _MESSAGE_DEDUPE_MAX:+ for key, ts in list(_recent_message_ids.items()):+ if now - ts > _MESSAGE_DEDUPE_WINDOW_SECS:+ del _recent_message_ids[key]+ while len(_recent_message_ids) > _MESSAGE_DEDUPE_MAX:+ del _recent_message_ids[min(_recent_message_ids, key=_recent_message_ids.get)]+try:- await channel.handle_decrypted_message(msg)+ task = asyncio.create_task(channel.handle_decrypted_message(msg))+ _pending_handler_tasks.add(task)+ task.add_done_callback(_on_handler_task_done)except Exception:- LOGGER.error("[wecom:%s] handler error", account_id, exc_info=True)+ if dedupe_key is not None:+ _recent_message_ids.pop(dedupe_key, None)+ LOGGER.error("[wecom:%s] failed to schedule handler", account_id, exc_info=True)except Exception:LOGGER.error("[wecom:%s] inbound request handling error", account_id, exc_info=True)# Empty 200 OK tells WeCom we accepted the event.@@ -115,6 +144,26 @@ class _SharedWebhookServer:_servers: Dict[Tuple[str, int], _SharedWebhookServer] = {}_active_per_server: Dict[Tuple[str, int], int] = {}+# In-process guard against WeCom callback retries: the same (account, message)+# pair seen within this window is acknowledged but not answered twice.+_recent_message_ids: Dict[Tuple[str, str], float] = {}+_MESSAGE_DEDUPE_WINDOW_SECS = 30.0+_MESSAGE_DEDUPE_MAX = 2000++# Strong references to background handler tasks: asyncio only keeps weak+# references, so an unreferenced long-running task can be garbage-collected+# before it sends the answer. Tasks are discarded when they finish.+_pending_handler_tasks: set = set()+++def _on_handler_task_done(task: asyncio.Task) -> None:+ _pending_handler_tasks.discard(task)+ if task.cancelled():+ return+ exc = task.exception()+ if exc is not None:+ LOGGER.error("background wecom handler task failed: %s", exc, exc_info=exc)+async def _acquire_server(host: str, port: int) -> _SharedWebhookServer:key = (host, port)diff --git a/docs/guides/chatchannel/channel_access_and_configuration.md b/docs/guides/chatchannel/channel_access_and_configuration.mdindex aecee076db..1e2af16d62 100644--- a/docs/guides/chatchannel/channel_access_and_configuration.md+++ b/docs/guides/chatchannel/channel_access_and_configuration.md@@ -177,7 +177,34 @@ Usage:The credentials for `Webhook` and `WebSocket` cannot be mixed. When selecting `WebSocket`, first create a smart bot in WeCom, then fill the obtained `BotID` and `Secret` into RAGFlow. When selecting `Webhook`, fill in `CorpID`, `AgentID`, `Secret`, `Token`, and `AESKey` according to the WeCom application callback configuration.-After saving the channel, connect the WeCom channel to a Chat. After the connection succeeds, users can send messages to the bot in WeCom, and the bot calls the bound Chat to return replies.+After saving the channel, connect the WeCom channel to a Chat, or bind it to a custom Agent (see below). After the connection succeeds, users can send messages to the bot in WeCom, and the bot calls the bound Chat or Agent to return replies.++### Binding a custom Agent++Besides a Chat, a WeCom channel can be bound to a custom Flow Agent, so inbound messages are answered by the workflow you designed on the **Agent** canvas instead of a regular Chat.++Prerequisites:++- Design a Flow Agent in RAGFlow (**Agent > Flow agents**) and make sure the models used by its components are configured for the tenant (for example, the LLM node must point to a valid model of the tenant that owns the channel).+- The agent must be owned by, or shared (permission `team`) with, the tenant that owns the WeCom channel.+- Complete the WeCom channel connection first (`Webhook` or `WebSocket`), as described above.++Configuration parameters:++- **Target**: The connect dialog shows a single dropdown whose entries are prefixed with their type. Entries labeled `[Chat assistant]` are the Chats of the current tenant; entries labeled `[Agent]` are the Flow Agents (canvas category `agent_canvas`) accessible to the current tenant. The stored value is the selected Chat id or Agent id, which is filled in automatically when you pick an entry, so no external credential is required. If you need the Agent id explicitly, open the Agent in **Agent > Flow agents** and copy the id from the browser URL. A channel can be bound to exactly one target at a time: picking another target replaces the previous binding, and clearing the selection disconnects the channel. If the selected agent has components without a configured model, the runtime replies with an error message.++Usage:++1. Open **User settings > Chat channels**, find the WeCom channel, and click the link icon to open the connect dialog.+2. In the connect dialog, pick the `[Agent]` entry of the Flow Agent (or a `[Chat assistant]` entry to bind a Chat) from the **Select an assistant or Agent** dropdown.+3. Click confirm; reopening the dialog shows the currently bound target.+4. Send a test message to the bot in WeCom and verify the reply.++### Thinking placeholder++To keep the end user informed while a completion is still running, the WeCom channel first sends a short `π€ εΌε§ζθ...` placeholder for every accepted, non-empty inbound message, and then sends a second message with the final answer once the Chat or Agent has produced a result. Blank messages are ignored, and if a completion produces no result, no final reply is sent. This applies to both Chat and custom Agent bindings.++The placeholder is only sent on the WeCom channel. The final reply is also cleaned up before it is sent: reasoning content (the `<think>` blocks produced by the model) is removed, so end users only see the final answer instead of the internal thinking process.Connection verification:diff --git a/web/src/hooks/use-agent-request.ts b/web/src/hooks/use-agent-request.tsindex 3d4e89f986..1b94330f71 100644--- a/web/src/hooks/use-agent-request.ts+++ b/web/src/hooks/use-agent-request.ts@@ -244,23 +244,36 @@ export const useFetchAgentListByPage = () => {};};+export const fetchAllAgents = async (): Promise<AgentListItem[]> => {+ const all: AgentListItem[] = [];+ let page = 1;+ let total = Number.POSITIVE_INFINITY;+ while (all.length < total) {+ const { data } = await agentService.listAgents(+ {+ params: buildAgentListParams({+ page,+ pageSize: 100,+ canvasCategoryIds: [AgentCategory.AgentCanvas],+ }),+ },+ true,+ );+ const canvas: AgentListItem[] = data?.data?.canvas ?? [];+ all.push(...canvas);+ total = data?.data?.total ?? all.length;+ if (canvas.length === 0) {+ break;+ }+ page += 1;+ }+ return all;+};+export function useFetchAllAgentList() {const { data, isFetching: loading } = useQuery<AgentListItem[]>({queryKey: AgentKeys.all(),- queryFn: async () => {- const { data } = await agentService.listAgents(- {- params: buildAgentListParams({- page: 1,- pageSize: 100000,- canvasCategoryIds: [AgentCategory.AgentCanvas],- }),- },- true,- );-- return data?.data?.canvas;- },+ queryFn: fetchAllAgents,});return { data, loading };diff --git a/web/src/pages/user-setting/chat-channel/component/added-channel-card.tsx b/web/src/pages/user-setting/chat-channel/component/added-channel-card.tsxindex 90329a4454..090435f6e6 100644--- a/web/src/pages/user-setting/chat-channel/component/added-channel-card.tsx+++ b/web/src/pages/user-setting/chat-channel/component/added-channel-card.tsx@@ -156,7 +156,7 @@ export const AddedChannelCard = (props: IAddedChannelCardProps) => {><Settings size={14} /></Button>- {channel.channel === ChatChannelKey.WHATSAPP && (+ {channel.id === ChatChannelKey.WHATSAPP && (<Buttonvariant={'ghost'}className="rounded-lg px-2 py-1 bg-transparent hover:bg-bg-card"diff --git a/web/src/pages/user-setting/chat-channel/component/connect-dialog-modal.tsx b/web/src/pages/user-setting/chat-channel/component/connect-dialog-modal.tsxindex db7bb9c3e1..33937a9b07 100644--- a/web/src/pages/user-setting/chat-channel/component/connect-dialog-modal.tsx+++ b/web/src/pages/user-setting/chat-channel/component/connect-dialog-modal.tsx@@ -74,8 +74,10 @@ const ConnectDialogModal = ({if (!channel) {return;}- await connect({ channelId: channel.id, targetValue });- hideModal();+ const result = await connect({ channelId: channel.id, targetValue });+ if (result.code === 0) {+ hideModal();+ }};return (