-
Notifications
You must be signed in to change notification settings - Fork 59
feat: add real-time observer system for voicemail/hallucination detec… #828
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Dev-Bhumika03
wants to merge
1
commit into
juspay:release
Choose a base branch
from
Dev-Bhumika03:BZ-3716-side-llm-observers-support
base: release
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+999
−10
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| from .factory import build_observers | ||
| from .manager import ObserverManager | ||
| from .observer import RealtimeObserver | ||
|
|
||
| __all__ = ["build_observers", "ObserverManager", "RealtimeObserver"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| """Observer factory — builds RealtimeObserver instances from template config. | ||
|
|
||
| Uses existing ``get_llm_service()`` for LLM service creation and existing | ||
| ``LLMConfiguration`` for config merging (inherit with override). | ||
| """ | ||
|
|
||
| from typing import Any, Dict, List, Optional | ||
|
|
||
| from app.ai.voice.agents.breeze_buddy.llm import get_llm_service | ||
| from app.ai.voice.agents.breeze_buddy.template.types import ObserverConfig | ||
| from app.ai.voice.llm.types import LLMConfiguration | ||
| from app.core.logger import logger | ||
|
|
||
| from .observer import RealtimeObserver | ||
|
|
||
|
|
||
| def merge_llm_config( | ||
| override: Optional[LLMConfiguration], | ||
| base: LLMConfiguration, | ||
| ) -> LLMConfiguration: | ||
| """Merge observer's optional LLM overrides on top of template's config. | ||
|
|
||
| Model defaults to ``gpt-4o-mini``. Temperature defaults to 0.1. | ||
| """ | ||
| if override is None: | ||
| return LLMConfiguration( | ||
| provider=base.provider, | ||
| sdk=base.sdk, | ||
| model="gpt-4o-mini", | ||
| region=getattr(base, "region", None), | ||
| endpoint=base.endpoint, | ||
| api_key_name=base.api_key_name, | ||
| temperature=0.1, | ||
| max_tokens=100, | ||
| ) | ||
|
|
||
| return LLMConfiguration( | ||
| provider=override.provider or base.provider, | ||
| sdk=override.sdk or base.sdk, | ||
| model=override.model or "gpt-4o-mini", | ||
| region=override.region or getattr(base, "region", None), | ||
| endpoint=override.endpoint or base.endpoint, | ||
| api_key_name=override.api_key_name or base.api_key_name, | ||
| temperature=(override.temperature if override.temperature is not None else 0.1), | ||
| max_tokens=(override.max_tokens if override.max_tokens is not None else 100), | ||
| ) | ||
|
|
||
|
|
||
| async def build_observers( | ||
| configs: List[ObserverConfig], | ||
| template: Any, | ||
| agent_context: Any, | ||
| handler_map: Dict[str, Any], | ||
| ) -> List[RealtimeObserver]: | ||
| """Build observer instances from template config.""" | ||
| template_llm = template.configurations.llm_configurations | ||
| if template_llm is None: | ||
| # Template uses global env defaults — create a minimal config | ||
| # that will resolve to Azure gpt-4o-mini via get_llm_service() | ||
| logger.info( | ||
| "Template has no llm_configurations — " | ||
| "observers will use env defaults with gpt-4o-mini" | ||
| ) | ||
| template_llm = LLMConfiguration() | ||
|
|
||
| observers: List[RealtimeObserver] = [] | ||
|
|
||
| for cfg in configs: | ||
| try: | ||
| merged_config = merge_llm_config(cfg.llm, template_llm) | ||
| llm_service = await get_llm_service(merged_config, pooled=True) | ||
| observers.append( | ||
| RealtimeObserver(cfg, llm_service, agent_context, handler_map) | ||
| ) | ||
| logger.info( | ||
| f"Built observer '{cfg.name}' with model=" | ||
| f"{merged_config.model}, start_after_turn={cfg.start_after_turn}" | ||
| ) | ||
| except Exception as e: | ||
| logger.error(f"Failed to build observer '{cfg.name}': {e}") | ||
|
|
||
| return observers | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| """ObserverManager — coordinates N real-time observers. | ||
|
|
||
| Reads the conversation transcript from the pipeline's existing LLMContext, | ||
| builds a formatted transcript string, and feeds it to all eligible observers | ||
| in parallel after every LLM turn. | ||
|
|
||
| Not a pipeline processor. Completely separate async system. | ||
| """ | ||
|
|
||
| import asyncio | ||
| import json | ||
| from typing import Any, List | ||
|
|
||
| from pipecat.processors.aggregators.llm_context import LLMContext | ||
|
|
||
| from app.core.logger import logger | ||
|
|
||
| from .observer import RealtimeObserver | ||
|
|
||
|
|
||
| class ObserverManager: | ||
| """Coordinates N observers. Reads existing LLMContext. | ||
|
|
||
| Triggered on every LLM turn (via ``on_user_turn_started``) and on every | ||
| function call (via ``on_function_calls_started``). All eligible observers | ||
| run in parallel via ``asyncio.gather``. First to detect wins. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| observers: List[RealtimeObserver], | ||
| llm_context: LLMContext, | ||
| ): | ||
| self._observers = observers | ||
| self._llm_context = llm_context | ||
| self._function_calls: List[str] = [] | ||
| self._turn_count: int = 0 | ||
| self._action_taken: bool = False | ||
| self._check_lock = asyncio.Lock() | ||
| # Strong references to in-flight tasks — prevents GC from collecting | ||
| # them mid-flight when PipelineRunner runs with force_gc=True. | ||
| self._pending: set[asyncio.Task] = set() | ||
|
|
||
| # ------------------------------------------------------------------ | ||
| # Data ingestion (called by pipeline event hooks in agent/__init__.py) | ||
| # ------------------------------------------------------------------ | ||
|
|
||
| def _track_task(self, task: asyncio.Task) -> None: | ||
| """Hold a strong ref so GC cannot collect in-flight tasks.""" | ||
| self._pending.add(task) | ||
| task.add_done_callback(self._pending.discard) | ||
|
|
||
| def on_turn_completed(self): | ||
| """A turn completed — kick off observer checks in background.""" | ||
| if self._action_taken: | ||
| return | ||
| self._turn_count += 1 | ||
| self._track_task( | ||
| asyncio.create_task(self._run_checks(), name="observer:check_round") | ||
| ) | ||
|
|
||
| def on_function_call(self, function_name: str, arguments: Any): | ||
|
Dev-Bhumika03 marked this conversation as resolved.
|
||
| """Bot called a function — record it and trigger checks.""" | ||
| args_str = json.dumps(arguments) if arguments else "" | ||
| self._function_calls.append(f"{function_name}({args_str})") | ||
| if not self._action_taken: | ||
| self._track_task( | ||
| asyncio.create_task(self._run_checks(), name="observer:check_round_fn") | ||
| ) | ||
|
|
||
| # ------------------------------------------------------------------ | ||
| # Check execution | ||
| # ------------------------------------------------------------------ | ||
|
|
||
| async def _run_checks(self): | ||
| """Run all eligible observers in parallel. First to detect wins.""" | ||
| if self._action_taken: | ||
| return | ||
|
|
||
| async with self._check_lock: | ||
| if self._action_taken: | ||
| return | ||
|
|
||
| transcript = self._build_transcript() | ||
|
|
||
| eligible = [ | ||
| obs | ||
| for obs in self._observers | ||
| if not obs._detected and self._turn_count >= obs.config.start_after_turn | ||
| ] | ||
| if not eligible: | ||
| logger.debug( | ||
| f"Observer check: turn {self._turn_count}, " | ||
| f"no eligible observers" | ||
| ) | ||
| return | ||
|
|
||
| logger.debug( | ||
| f"Observer check: turn {self._turn_count}, " | ||
| f"running {len(eligible)} observer(s): " | ||
| f"{[o.name for o in eligible]}" | ||
| ) | ||
|
|
||
| # gather() over as_completed(): as_completed wraps futures in | ||
| # new coroutines so the original future→observer mapping breaks. | ||
| # gather() returns results in input order which is deterministic | ||
| # and keeps the observer→result pairing trivial via zip(). | ||
| results = await asyncio.gather( | ||
| *[obs.check(transcript) for obs in eligible], | ||
| return_exceptions=True, | ||
| ) | ||
|
|
||
| for obs, result in zip(eligible, results): | ||
| if self._action_taken: | ||
| return | ||
| if isinstance(result, Exception): | ||
| logger.warning(f"Observer '{obs.name}' check failed: {result}") | ||
| continue | ||
| if result is True: | ||
| self._action_taken = True | ||
| try: | ||
| await obs.execute_action() | ||
| except Exception as e: | ||
| logger.error( | ||
| f"Observer '{obs.name}' execute_action failed: {e}" | ||
| ) | ||
| return | ||
|
Dev-Bhumika03 marked this conversation as resolved.
|
||
|
|
||
| # ------------------------------------------------------------------ | ||
| # Transcript building | ||
| # ------------------------------------------------------------------ | ||
|
|
||
| def _build_transcript(self) -> str: | ||
| """Build transcript from LLMContext messages + recorded function calls.""" | ||
| lines: List[str] = [] | ||
|
|
||
| for msg in self._llm_context.messages: | ||
| if not isinstance(msg, dict): | ||
| continue | ||
| role = msg.get("role", "") | ||
| content = msg.get("content", "") | ||
| if not content: | ||
| continue | ||
| if role == "user": | ||
| lines.append(f"[customer] {content}") | ||
| elif role == "assistant": | ||
| lines.append(f"[bot] {content}") | ||
|
|
||
| for fc in self._function_calls: | ||
| lines.append(f"[bot_action] {fc}") | ||
|
|
||
| return "\n".join(lines) | ||
|
|
||
| # ------------------------------------------------------------------ | ||
| # Lifecycle | ||
| # ------------------------------------------------------------------ | ||
|
|
||
| async def stop(self): | ||
| """Cleanup. Called when the call ends.""" | ||
| self._action_taken = True | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.