Enhance conversation history and runtime variable management
- Update ConversationRecorder to include source and nodeId metadata in transcripts for better context tracking. - Introduce optional variable handling in DynamicVariableStore, allowing for unset variables to be rendered as empty without raising errors. - Refactor WorkflowBrain to apply turn configurations and manage interaction policies dynamically, improving agent responsiveness. - Implement tests to ensure proper handling of updated session variables and workflow metadata in various scenarios.
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
from loguru import logger
|
||||
@@ -49,7 +50,13 @@ class WorkflowBrain(BaseBrain):
|
||||
|
||||
def __init__(self, cfg_or_graph: AssistantConfig | dict[str, Any]):
|
||||
cfg = cfg_or_graph if isinstance(cfg_or_graph, AssistantConfig) else None
|
||||
graph = cfg.graph if cfg is not None else cfg_or_graph
|
||||
graph = deepcopy(cfg.graph if cfg is not None else cfg_or_graph)
|
||||
if cfg is not None:
|
||||
# Graph v3 owns Workflow defaults. Keep older saved graphs compatible
|
||||
# by filling the new interaction settings from the assistant row.
|
||||
settings = graph.setdefault("settings", {})
|
||||
settings.setdefault("enableInterrupt", cfg.enableInterrupt)
|
||||
settings.setdefault("turnConfig", deepcopy(cfg.turnConfig))
|
||||
self._engine = WorkflowEngine(graph or {})
|
||||
if not self._engine.has_graph() or not self._engine.start_id:
|
||||
raise ValueError("WorkflowBrain 缺少有效的 Start 节点")
|
||||
@@ -95,6 +102,10 @@ class WorkflowBrain(BaseBrain):
|
||||
|
||||
async def on_connected(self) -> None:
|
||||
await self._emit_node_active(self._engine.start_id)
|
||||
await self._emit_variables(
|
||||
reason="initialized",
|
||||
node_id=self._engine.start_id,
|
||||
)
|
||||
edge = self._engine.deterministic_edge(
|
||||
self._engine.start_id,
|
||||
self._store,
|
||||
@@ -228,6 +239,11 @@ class WorkflowBrain(BaseBrain):
|
||||
if self._runtime and self._runtime.set_input_enabled:
|
||||
self._runtime.set_input_enabled(True)
|
||||
runtime = self._require_runtime()
|
||||
if runtime.apply_turn_config:
|
||||
await runtime.apply_turn_config(
|
||||
stage.enable_interrupt,
|
||||
stage.turn_config,
|
||||
)
|
||||
if runtime.switch_services:
|
||||
await runtime.switch_services(
|
||||
stage.llm_resource_id or None,
|
||||
@@ -248,6 +264,11 @@ class WorkflowBrain(BaseBrain):
|
||||
data = self._engine.data(node_id)
|
||||
entry_mode = str(data.get("entryMode") or "wait_user")
|
||||
entry_speech = self._store.render(str(data.get("entrySpeech") or ""))
|
||||
fixed_reply_messages = (
|
||||
[{"role": "assistant", "content": entry_speech}]
|
||||
if entry_mode == "fixed_speech" and entry_speech
|
||||
else []
|
||||
)
|
||||
strategy = (
|
||||
ContextStrategy.RESET
|
||||
if data.get("contextPolicy") == "fresh"
|
||||
@@ -265,11 +286,10 @@ class WorkflowBrain(BaseBrain):
|
||||
config: NodeConfig = {
|
||||
"name": node_id,
|
||||
"role_message": self._agent_role_message(node_id),
|
||||
"task_messages": (
|
||||
[{"role": "assistant", "content": entry_speech}]
|
||||
if entry_mode == "fixed_speech"
|
||||
else []
|
||||
),
|
||||
# Flows writes task_messages into the Pipecat LLM context. The
|
||||
# pre-action below is responsible only for display, persistence,
|
||||
# dynamic conversation history, and TTS playback.
|
||||
"task_messages": fixed_reply_messages,
|
||||
"functions": functions,
|
||||
"context_strategy": ContextStrategyConfig(strategy=strategy),
|
||||
"respond_immediately": entry_mode == "generate",
|
||||
@@ -279,6 +299,7 @@ class WorkflowBrain(BaseBrain):
|
||||
{
|
||||
"type": "workflow_fixed_speech",
|
||||
"text": entry_speech,
|
||||
"node_id": node_id,
|
||||
"handler": self._play_fixed_speech,
|
||||
}
|
||||
]
|
||||
@@ -286,9 +307,19 @@ class WorkflowBrain(BaseBrain):
|
||||
|
||||
async def _play_fixed_speech(self, action: dict, _flow_manager: FlowManager) -> None:
|
||||
"""Play and persist Agent entry speech without creating an LLM turn."""
|
||||
await self._queue_visible_speech(str(action.get("text") or ""))
|
||||
await self._queue_visible_speech(
|
||||
str(action.get("text") or ""),
|
||||
source="workflow-fixed-reply",
|
||||
node_id=str(action.get("node_id") or "") or None,
|
||||
)
|
||||
|
||||
async def _queue_visible_speech(self, text: str) -> None:
|
||||
async def _queue_visible_speech(
|
||||
self,
|
||||
text: str,
|
||||
*,
|
||||
source: str = "workflow-speech",
|
||||
node_id: str | None = None,
|
||||
) -> None:
|
||||
"""Show and persist fixed workflow speech before sending it to TTS."""
|
||||
content = text.strip()
|
||||
if not content:
|
||||
@@ -302,6 +333,8 @@ class WorkflowBrain(BaseBrain):
|
||||
"role": "assistant",
|
||||
"content": content,
|
||||
"timestamp": time_now_iso8601(),
|
||||
"source": source,
|
||||
**({"nodeId": node_id} if node_id else {}),
|
||||
}
|
||||
)
|
||||
)
|
||||
@@ -327,7 +360,13 @@ class WorkflowBrain(BaseBrain):
|
||||
result = await self._tools.execute(tool, dict(args or {}))
|
||||
except ToolExecutionError as exc:
|
||||
return {"status": "error", "message": str(exc)}
|
||||
if result.get("updated_variables"):
|
||||
updated_variables = list(result.get("updated_variables") or [])
|
||||
if updated_variables:
|
||||
await self._emit_variables(
|
||||
reason="tool",
|
||||
node_id=node_id,
|
||||
changed=updated_variables,
|
||||
)
|
||||
await self._refresh_agent_prompt(node_id)
|
||||
edge = self._engine.deterministic_edge(
|
||||
node_id,
|
||||
@@ -436,11 +475,18 @@ class WorkflowBrain(BaseBrain):
|
||||
return
|
||||
try:
|
||||
arguments = self._store.render_data(data.get("arguments") or {})
|
||||
await self._tools.execute(
|
||||
result = await self._tools.execute(
|
||||
tool,
|
||||
arguments,
|
||||
result_assignments=data.get("resultAssignments") or {},
|
||||
)
|
||||
updated_variables = list(result.get("updated_variables") or [])
|
||||
if updated_variables:
|
||||
await self._emit_variables(
|
||||
reason="action",
|
||||
node_id=node_id,
|
||||
changed=updated_variables,
|
||||
)
|
||||
self._store.values["system__last_action_status"] = "ok"
|
||||
self._store.values["system__last_action_error"] = ""
|
||||
except (ToolExecutionError, ValueError) as exc:
|
||||
@@ -501,6 +547,40 @@ class WorkflowBrain(BaseBrain):
|
||||
)
|
||||
)
|
||||
|
||||
def _public_variables(self) -> dict[str, str | int | float | bool]:
|
||||
"""Return the browser-safe part of this session's variable state."""
|
||||
return {
|
||||
name: value
|
||||
for name, value in self._store.values.items()
|
||||
if not name.startswith(("system__", "secret__"))
|
||||
and isinstance(value, (str, int, float, bool))
|
||||
}
|
||||
|
||||
async def _emit_variables(
|
||||
self,
|
||||
*,
|
||||
reason: str,
|
||||
node_id: str | None,
|
||||
changed: list[str] | None = None,
|
||||
) -> None:
|
||||
"""Publish a safe snapshot so Workflow debug mirrors runtime state."""
|
||||
message: dict[str, Any] = {
|
||||
"type": "workflow-variables",
|
||||
"reason": reason,
|
||||
"variables": self._public_variables(),
|
||||
}
|
||||
if node_id:
|
||||
message["nodeId"] = node_id
|
||||
if changed:
|
||||
message["changed"] = [
|
||||
name
|
||||
for name in changed
|
||||
if not name.startswith(("system__", "secret__"))
|
||||
]
|
||||
await self._require_runtime().queue_frame(
|
||||
OutputTransportMessageUrgentFrame(message=message)
|
||||
)
|
||||
|
||||
def _require_runtime(self) -> BrainRuntime:
|
||||
if self._runtime is None:
|
||||
raise RuntimeError("WorkflowBrain 尚未绑定 pipeline runtime")
|
||||
|
||||
Reference in New Issue
Block a user