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.
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
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 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 | |
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
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 | |
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
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 | |
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
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.