Skip to content
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
9 changes: 9 additions & 0 deletions nemoguardrails/guardrails/iorails.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,15 @@ def generate(self, messages: LLMMessages, **kwargs) -> LLMMessage:
if sync_config.metrics is not None:
sync_config.metrics.enabled = False

try:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: Could you move this up to start at line 265 so we don't mutate any of the tracing config if we're going to raise an error?

asyncio.get_running_loop()
except RuntimeError:
pass
else:
raise RuntimeError(
"IORails.generate() cannot be called from a running event loop. Use generate_async() instead."
)

async def _run_sync_iorails():
"""Spin up a short-lived IORails engine for one synchronous generate call."""
# Avoid counting this sync-API bridge as a separate user-created IORails instance.
Expand Down
13 changes: 11 additions & 2 deletions tests/guardrails/test_iorails.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
"""Unit tests for iorails module."""

import asyncio
import gc
import warnings
from unittest.mock import AsyncMock, MagicMock, patch

import pytest
Expand Down Expand Up @@ -685,8 +687,15 @@ def test_generate_raises_when_called_from_async_loop(self, iorails):
async def call_generate():
iorails.generate([{"role": "user", "content": "hi"}])

with pytest.raises(RuntimeError):
asyncio.run(call_generate())
with warnings.catch_warnings(record=True) as recorded_warnings:
warnings.simplefilter("always")

with pytest.raises(RuntimeError, match="cannot be called from a running event loop"):
asyncio.run(call_generate())

gc.collect()

assert not [warning for warning in recorded_warnings if issubclass(warning.category, RuntimeWarning)]


class TestRefusalMessage:
Expand Down
Loading