Skip to content

fix(topic_safety): handle InternalEvent objects in topic safety actions for Colang 2.0 #1335

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
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion nemoguardrails/library/topic_safety/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,17 @@ async def topic_safety_check_input(
model_name = model_name or context.get("model", None)

if events is not None:
conversation_history = to_chat_messages(events)
# convert InternalEvent objects to dictionary format for compatibility with to_chat_messages
dict_events = []
for event in events:
if hasattr(event, "name") and hasattr(event, "arguments"):
Copy link
Preview

Copilot AI Aug 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using isinstance check instead of hasattr for more robust type checking. This would be more explicit about the expected type: isinstance(event, InternalEvent)

Suggested change
if hasattr(event, "name") and hasattr(event, "arguments"):
if isinstance(event, InternalEvent):

Copilot uses AI. Check for mistakes.

dict_event = {"type": event.name}
dict_event.update(event.arguments)
dict_events.append(dict_event)
else:
dict_events.append(event)

conversation_history = to_chat_messages(dict_events)

if model_name is None:
error_msg = (
Expand Down
74 changes: 74 additions & 0 deletions tests/test_topic_safety_internalevent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Test for InternalEvent handling in topic_safety_check_input action."""

from unittest.mock import AsyncMock, patch

import pytest

from nemoguardrails.colang.v2_x.runtime.flows import InternalEvent
from nemoguardrails.library.topic_safety.actions import topic_safety_check_input


@pytest.mark.asyncio
async def test_topic_safety_check_input_with_internal_events():
"""Test that topic_safety_check_input can handle InternalEvent objects without failing.

This test would fail before the fix with:
TypeError: 'InternalEvent' object is not subscriptable
"""
internal_events = [
InternalEvent(
name="UtteranceUserActionFinished",
arguments={"final_transcript": "Hello, how are you?"},
),
InternalEvent(
name="StartUtteranceBotAction",
arguments={"script": "I'm doing well, thank you!"},
),
]

class MockTaskManager:
def render_task_prompt(self, task):
return "Check if the conversation is on topic."

def get_stop_tokens(self, task):
return []

def get_max_tokens(self, task):
return 10

llms = {"topic_control": "mock_llm"}
llm_task_manager = MockTaskManager()

with patch(
"nemoguardrails.library.topic_safety.actions.llm_call", new_callable=AsyncMock
) as mock_llm_call:
mock_llm_call.return_value = "on-topic"

# should not raise TypeError: 'InternalEvent' object is not subscriptable
result = await topic_safety_check_input(
llms=llms,
llm_task_manager=llm_task_manager,
model_name="topic_control",
context={"user_message": "Hello"},
events=internal_events,
)

assert isinstance(result, dict)
assert "on_topic" in result
assert isinstance(result["on_topic"], bool)
assert result["on_topic"] is True