datarobot_genai.dragent.plugins.datarobot_moderation_middleware
datarobot_moderation_middleware
NAT (NeMo Agent Toolkit) middleware: DataRobot LLM guardrails for DRAgent workflows.
Registered under the nat.plugins distribution entry datarobot_moderation_middleware so NAT
loads @register_middleware without a custom recipe mapping (_type: datarobot_moderation).
Expected workflow contracts:
- Input:
RunAgentInput(orDRAgentRunAgentInput) for DRAgent workflows, orChatRequest/ChatRequestOrMessagefor native NAT chat agents. - Output: always
DRAgentEventResponse(both single and streaming). Native NAT agents emitstr/ChatResponseChunk; the innermostdatarobot_dragent_normalizationmiddleware converts that intoDRAgentEventResponsebefore this middleware runs, so moderation only ever handles the canonical type.
Guard configuration (_type: datarobot_moderation):
- Inline (preferred) — nest guards under
middleware.<name>.moderationinworkflow.yaml. When present, this block is used even ifmoderation_config.yamlalso exists. - DRUM-style file (fallback) — when
moderationis omitted, loadmoderation_config.yamlfrommodel_dir(defaults to the directory containingworkflow.yaml, resolved fromDRAGENT_CONFIG_FILEwhen set, otherwise the process working directory). - If neither source is present or both are empty, the middleware is a no-op.
- Per-agent targeting — a
moderationblock may declare multipletargets(e.g.workflow_overall,devex-agent). Settargeton this middleware's config to apply only that entry's guards; declare one middleware instance pertargetand attach each to a differentfunctions:/workflow:entry so individual agents get their own guard set from one shared config. Omittingtargetmerges every target's guards (whole-workflow behavior).
ModerationPipeline.stream_response_async only accepts OpenAI ChatCompletionChunk; DRAgent
streaming uses convert_dragent_event_response_to_openai_chat_completion_chunk at that
boundary, then reverses to AG-UI on the way out.
DataRobotModerationConfig
Bases: FunctionMiddlewareBaseConfig
NAT middleware: DataRobot prescore / postscore guards.
The middleware is a no-op (enabled is False) when no guards are configured in the
inline moderation block or in moderation_config.yaml.
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
DataRobotModerationMiddleware
Bases: FunctionMiddleware
Guardrails middleware for DRAgent NAT workflows and native NAT chat agents.
Prescore/postscore run on AG-UI text of DRAgentEventResponse; streaming moderation uses
dragent_event_response_to_dome_chunk at the dome boundary. Native NAT agents
(ChatRequest / ChatRequestOrMessage in, str / ChatResponseChunk out) are first
converted to DRAgentEventResponse by the innermost datarobot_dragent_normalization
middleware, so this middleware only ever sees the canonical output type.
When no guards are configured (missing inline block and YAML file, or empty guard list),
load_llm_moderation_pipeline returns None and this middleware is a no-op
(enabled is False) without requiring DataRobot credentials.
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 | |
function_middleware_invoke
async
function_middleware_invoke(*args: Any, call_next: CallNext, context: FunctionMiddlewareContext, **kwargs: Any) -> Any
Run prescore guards; skip the agent when prescore blocks the prompt.
The default NAT FunctionMiddleware.function_middleware_invoke always awaits
call_next after pre_invoke. When prescore blocks, pre_invoke sets
ctx.output to the guard response; we return it immediately so call_next
(and thus the LLM) is never invoked.
On a moderation failure, pre_invoke/post_invoke set ctx.output to a terminal
RUN_ERROR; converters adapt it per route (non-streaming raises, NAT returns 422;
streaming frames it). Mid-stream: _moderated_dragent_stream.
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
pre_invoke
async
Pre-invocation hook called before the function is invoked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
InvocationContext
|
Invocation context containing function metadata and args |
required |
Returns
InvocationContext if modified (including when the prompt is blocked and
``context.output`` holds the guard message), or None to pass through unchanged.
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
post_invoke
async
Post-invocation hook called after the function returns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
InvocationContext
|
Invocation context containing function metadata, args, and output |
required |
Returns
InvocationContext if modified, or None to pass through unchanged (for example when
the response has no assistant text to moderate, or prescore did not run). When guards
are configured, agent output must already be ``DRAgentEventResponse`` (see
``datarobot_dragent_normalization``); unexpected types raise ``TypeError``.
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 | |
function_middleware_stream
async
function_middleware_stream(*args: Any, call_next: CallNextStream, context: FunctionMiddlewareContext, **kwargs: Any) -> AsyncIterator[DRAgentEventResponse]
Execute middleware hooks around DRAgent streaming (DRAgentEventResponse chunks).
Pre-invoke runs once before streaming starts. Moderation is applied per-chunk as they stream through.
Note: Framework checks enabled before calling this method.
You do NOT need to check enabled yourself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
Any
|
Positional arguments for the function (first arg is typically the input value). |
()
|
call_next
|
CallNextStream
|
Callable to invoke next middleware or target stream. |
required |
context
|
FunctionMiddlewareContext
|
Static function metadata. |
required |
kwargs
|
Any
|
Keyword arguments for the function. |
{}
|
Yields
Stream chunks with per-delta postscore via ``ModerationPipeline.stream_response_async``.
When prescore blocks the prompt, pre_invoke sets ctx.output; we yield that
response once and return without calling call_next, so the LLM stream is never
started (NAT's default stream middleware always iterates call_next after
pre_invoke).
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 | |
moderation_config_has_guards
Return whether moderation defines at least one guard across all targets.
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
select_moderation_target
Restrict moderation to the single TargetBlock named target.
Returns moderation unchanged when target is None (today's whole-workflow
behavior: every target's guards apply). When target is set but no TargetBlock
matches, the result has no targets, so the middleware becomes a no-op rather than
silently falling back to every guard.
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
resolve_moderation_model_dir
Resolve the base directory for guard assets and moderation_config.yaml.
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
moderation_config_file_path
Return the DRUM-style moderation_config.yaml path under model_dir (or workflow dir).
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
load_moderation_config_from_file
Load and validate moderation_config.yaml from a model directory (DRUM layout).
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
load_llm_moderation_pipeline
Build an LLM moderation pipeline from inline moderation or moderation_config.yaml.
Returns None when moderation is disabled, no configuration source is available, or the
resolved source has no guards, so the middleware is a no-op and can be listed unconditionally
in workflow.yaml. The inline moderation block takes priority over the YAML file.
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
dragent_event_response_to_dome_chunk
Convert one DRAgent stream chunk to an OpenAI chunk for ModerationPipeline streaming.
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
dome_chunk_to_dragent_event_response
dome_chunk_to_dragent_event_response(completion: ChatCompletionChunk, *, response_eval: EvaluationResult | None = None, source_ag_ui_events: list[Any] | None = None, stream_tool_index_map: dict[int, str] | None = None) -> DRAgentEventResponse
Convert a moderated OpenAI streaming chunk back to DRAgentEventResponse.
When response_eval is set (non-streaming postscore path), datarobot_moderations is
taken from response_eval.metrics; otherwise it is read from the completion's moderation
sidecar attribute (streaming chunks from ModerationIterator).
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
moderation_prompt_from_workflow_input
Extract the prescore prompt string from AG-UI or NAT chat input.
Delegates to get_chat_prompt on completion-params built from workflow_input.
ChatRequestOrMessage with only input_message (no messages) is handled directly
because get_chat_prompt requires a non-empty messages list.
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
nat_chat_request_like_to_completion_dict
nat_chat_request_like_to_completion_dict(request: ChatRequest | ChatRequestOrMessage) -> dict[str, Any]
Build completion-style params from NAT chat request models (LLM Gateway path).
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
workflow_input_to_completion_dict
Build OpenAI-style completion params for prescore from AG-UI or NAT chat inputs.
Source code in datarobot_genai/dragent/plugins/datarobot_moderation_middleware.py
datarobot_moderation_middleware
async
datarobot_moderation_middleware(config: DataRobotModerationConfig, builder: Builder) -> AsyncIterator[DataRobotModerationMiddleware]
Register DataRobot LLM guard middleware for NAT/DRAgent workflows.