Skip to content

datarobot_genai.drmcp.core.dynamic_prompts.register

register

register_prompts_from_datarobot_prompt_management async

register_prompts_from_datarobot_prompt_management() -> None

Register prompts from DataRobot Prompt Management.

Source code in datarobot_genai/drmcp/core/dynamic_prompts/register.py
async def register_prompts_from_datarobot_prompt_management() -> None:
    """Register prompts from DataRobot Prompt Management."""
    prompts = get_datarobot_prompt_templates()
    logger.info(f"Found {len(prompts)} prompts in Prompts Management.")
    all_prompts_versions = get_datarobot_prompt_template_versions(
        prompt_template_ids=list({prompt.id for prompt in prompts})
    )

    # Try to register each prompt, continue on failure
    for prompt in prompts:
        prompt_versions = all_prompts_versions.get(prompt.id)
        if not prompt_versions:
            logger.warning(f"Prompt template id {prompt.id} has no versions.")
            continue

        latest_version = max(prompt_versions, key=lambda v: v.version)

        try:
            await register_prompt_from_datarobot_prompt_management(prompt, latest_version)
        except DynamicPromptRegistrationError:
            pass

register_prompt_from_datarobot_prompt_management async

register_prompt_from_datarobot_prompt_management(prompt_template: PromptTemplate, prompt_template_version: PromptTemplateVersion | None = None) -> Prompt

Register a single prompt.

Parameters:

Name Type Description Default
prompt_template PromptTemplate

The prompt within DataRobot Prompt Management.

required
prompt_template_version PromptTemplateVersion | None

Optional prompt version within DataRobot Prompt Management. If not provided -- latest version will be used

None
Raises
DynamicPromptRegistrationError: If registration fails at any step.
Returns
The registered Prompt instance.
Source code in datarobot_genai/drmcp/core/dynamic_prompts/register.py
async def register_prompt_from_datarobot_prompt_management(
    prompt_template: dr.genai.PromptTemplate,
    prompt_template_version: dr.genai.PromptTemplateVersion | None = None,
) -> Prompt:
    """Register a single prompt.

    Args:
        prompt_template: The prompt within DataRobot Prompt Management.
        prompt_template_version: Optional prompt version within DataRobot Prompt Management.
            If not provided -- latest version will be used

    Raises
    ------
        DynamicPromptRegistrationError: If registration fails at any step.

    Returns
    -------
        The registered Prompt instance.
    """
    if not prompt_template_version:
        prompt_template_version_to_register = prompt_template.get_latest_version()

        if prompt_template_version_to_register is None:
            logger.info(
                f"No latest version in Prompts Management for prompt id: {prompt_template.id}"
            )
            raise DynamicPromptRegistrationError

    else:
        prompt_template_version_to_register = prompt_template_version

    logger.info(
        f"Found prompt: id: {prompt_template.id}, "
        f"name: {prompt_template.name}, "
        f"prompt version id: {prompt_template_version_to_register.id}, "
        f"version: {prompt_template_version_to_register.version}."
    )

    try:
        valid_fn_name = to_valid_mcp_prompt_name(prompt_template.name)
    except ValueError as e:
        raise DynamicPromptRegistrationError from e

    prompt_fn = make_prompt_function(
        name=valid_fn_name,
        description=prompt_template.description,
        prompt_text=prompt_template_version_to_register.prompt_text,
        variables=prompt_template_version_to_register.variables,
    )

    try:
        # Register using generic external tool registration with the config
        return await register_prompt(
            fn=prompt_fn,
            name=prompt_template.name,
            description=prompt_template.description,
            meta={
                "prompt_template_id": prompt_template.id,
                "prompt_template_version_id": prompt_template_version_to_register.id,
            },
            prompt_template=(prompt_template.id, prompt_template_version_to_register.id),
        )

    except Exception as exc:
        logger.error(f"Skipping prompt {prompt_template.id}. Registration failed: {exc}")
        raise DynamicPromptRegistrationError(
            "Registration failed. Could not create prompt."
        ) from exc

to_valid_mcp_prompt_name

to_valid_mcp_prompt_name(s: str) -> str

Convert an arbitrary string into a valid MCP prompt name.

Source code in datarobot_genai/drmcp/core/dynamic_prompts/register.py
def to_valid_mcp_prompt_name(s: str) -> str:
    """Convert an arbitrary string into a valid MCP prompt name."""
    # If its ONLY numbers return "prompt_[number]"
    if s.isdigit():
        return f"prompt_{s}"

    # First, ASCII-transliterate using hex escape for non-ASCII
    if not s.isascii():
        # whole string non-ascii? -> escape and prefix with prompt_
        encoded = _escape_non_ascii(s)
        return f"prompt_{encoded}"

    # Replace any sequence of invalid characters with '_'
    s = re.sub(r"[^0-9a-zA-Z_]+", "_", s)

    # Remove leading characters that are not letters or underscores (can't start with a digit or _)
    s = re.sub(r"^[^a-zA-Z]+", "", s)

    # Remove following _
    s = re.sub(r"_+$", "", s)

    # If string is empty after cleaning, raise error
    if not s:
        raise ValueError(f"Cannot convert {s} to valid MCP prompt name.")

    # Make sure it's a valid identifier and not a reserved keyword
    if keyword.iskeyword(s) or not s.isidentifier():
        s = f"{s}_prompt"

    return s