Enhance greeting context management in Brain classes
- Introduce greeting context handling in BaseBrain and WorkflowBrain to manage assistant greetings effectively. - Implement prepare_greeting_context method to add greeting messages to the local context while preserving playback order. - Update pipeline event handling to ensure greeting timestamps are maintained until the client is ready. - Enhance tests to verify the correct behavior of greeting context management in various scenarios.
This commit is contained in:
@@ -19,6 +19,20 @@ from pipecat.processors.aggregators.llm_context import LLMContext
|
||||
from pipecat.processors.frame_processor import FrameProcessor
|
||||
|
||||
|
||||
GREETING_CONTEXT_MARKER = "[会话事实:助手开场白已播放]"
|
||||
|
||||
|
||||
def greeting_context_message(greeting: str) -> dict[str, str] | None:
|
||||
"""Represent spoken greeting without starting model history as assistant."""
|
||||
content = greeting.strip()
|
||||
if not content:
|
||||
return None
|
||||
return {
|
||||
"role": "system",
|
||||
"content": f"{GREETING_CONTEXT_MARKER}\n{content}",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BrainSpec:
|
||||
"""Static capabilities used by validation and runtime dispatch."""
|
||||
@@ -86,6 +100,27 @@ class BaseBrain:
|
||||
async def on_connected(self) -> None:
|
||||
"""Handle a connected client after the common greeting is queued."""
|
||||
|
||||
def prepare_greeting_context(
|
||||
self,
|
||||
greeting: str,
|
||||
context: LLMContext,
|
||||
) -> dict[str, str] | None:
|
||||
"""Add a provider-safe fact describing the greeting to local context."""
|
||||
if not self.spec.owns_context:
|
||||
return None
|
||||
message = greeting_context_message(greeting)
|
||||
if message is None:
|
||||
return None
|
||||
messages = context.get_messages()
|
||||
messages[:] = [
|
||||
item
|
||||
for item in messages
|
||||
if GREETING_CONTEXT_MARKER not in str(item.get("content") or "")
|
||||
]
|
||||
insert_at = 1 if messages and messages[0].get("role") == "system" else 0
|
||||
messages.insert(insert_at, message)
|
||||
return message
|
||||
|
||||
async def on_client_ready(self) -> None:
|
||||
"""Replay client-visible state after its app message channel is ready."""
|
||||
|
||||
@@ -129,6 +164,12 @@ class Brain(Protocol):
|
||||
|
||||
async def on_connected(self) -> None: ...
|
||||
|
||||
def prepare_greeting_context(
|
||||
self,
|
||||
greeting: str,
|
||||
context: LLMContext,
|
||||
) -> dict[str, str] | None: ...
|
||||
|
||||
async def on_client_ready(self) -> None: ...
|
||||
|
||||
def record_user_message(self, content: str) -> None: ...
|
||||
|
||||
Reference in New Issue
Block a user