Skip to content

Utilities

Utility classes and functions.

IDGenerator

Deterministic ID generation with optional seeding.

IDGenerator

IDGenerator(seed: int | None = None)

Deterministic ID generator with optional seeding for reproducibility.

Supports seeded mode for deterministic IDs (useful for testing) and default mode using UUID4 for production.

Usage

Production (random IDs)

id_gen = IDGenerator() id1 = id_gen.generate("agent") # agent_a1b2c3d4

Testing (deterministic IDs)

id_gen = IDGenerator(seed=42) id1 = id_gen.generate("agent") # Same every time with seed=42

Reset for new test

id_gen.reset(seed=42)

Initialize the ID generator.

Parameters:

Name Type Description Default
seed int | None

Optional seed for deterministic ID generation. If None, uses UUID4 for true randomness.

None
Source code in src/dapr_agents_oas_adapter/utils.py
def __init__(self, seed: int | None = None) -> None:
    """Initialize the ID generator.

    Args:
        seed: Optional seed for deterministic ID generation.
              If None, uses UUID4 for true randomness.
    """
    self._seed = seed
    # S311: Random is intentionally used for non-cryptographic ID generation
    self._random: Random | None = Random(seed) if seed is not None else None  # noqa: S311
    self._counter = 0

Attributes

is_seeded property

is_seeded: bool

Check if the generator is in seeded (deterministic) mode.

seed property

seed: int | None

Get the current seed value.

Functions

generate

generate(prefix: str = '') -> str

Generate a unique identifier with optional prefix.

Parameters:

Name Type Description Default
prefix str

Optional prefix for the ID (e.g., "agent", "flow", "node")

''

Returns:

Type Description
str

Generated ID string. Format depends on mode:

str
  • Seeded: "{prefix}{8_hex_chars}" or "{counter}"
str
  • Random: "{prefix}_{8_uuid_chars}" or full UUID
Source code in src/dapr_agents_oas_adapter/utils.py
def generate(self, prefix: str = "") -> str:
    """Generate a unique identifier with optional prefix.

    Args:
        prefix: Optional prefix for the ID (e.g., "agent", "flow", "node")

    Returns:
        Generated ID string. Format depends on mode:
        - Seeded: "{prefix}_{8_hex_chars}" or "{counter}_{8_hex_chars}"
        - Random: "{prefix}_{8_uuid_chars}" or full UUID
    """
    if self._random is not None:
        # Deterministic mode: use seeded random
        hex_chars = f"{self._random.getrandbits(32):08x}"
        self._counter += 1
    else:
        # Random mode: use UUID4
        hex_chars = str(uuid4())[:8]

    if prefix:
        return f"{prefix}_{hex_chars}"
    return hex_chars if self._random is not None else str(uuid4())

reset

reset(seed: int | None = None) -> None

Reset the generator with optional new seed.

Parameters:

Name Type Description Default
seed int | None

Optional seed for deterministic ID generation.

None
Source code in src/dapr_agents_oas_adapter/utils.py
def reset(self, seed: int | None = None) -> None:
    """Reset the generator with optional new seed.

    Args:
        seed: Optional seed for deterministic ID generation.
    """
    self._seed = seed
    # S311: Random is intentionally used for non-cryptographic ID generation
    self._random = Random(seed) if seed is not None else None  # noqa: S311
    self._counter = 0

get_instance classmethod

get_instance() -> IDGenerator

Get the global IDGenerator instance (singleton pattern).

Source code in src/dapr_agents_oas_adapter/utils.py
@classmethod
def get_instance(cls) -> "IDGenerator":
    """Get the global IDGenerator instance (singleton pattern)."""
    if cls._instance is None:
        cls._instance = IDGenerator()
    return cls._instance

reset_instance classmethod

reset_instance(seed: int | None = None) -> IDGenerator

Reset the global instance with optional seed.

Source code in src/dapr_agents_oas_adapter/utils.py
@classmethod
def reset_instance(cls, seed: int | None = None) -> "IDGenerator":
    """Reset the global instance with optional seed."""
    cls._instance = IDGenerator(seed=seed)
    return cls._instance

Usage Examples

Basic ID Generation

from dapr_agents_oas_adapter import IDGenerator

gen = IDGenerator()

# Generate unique IDs
id1 = gen.generate("agent")  # "agent_a1b2c3d4"
id2 = gen.generate("agent")  # "agent_e5f6g7h8"
id3 = gen.generate("task")   # "task_i9j0k1l2"

Deterministic IDs with Seed

# With seed for reproducible IDs
gen = IDGenerator(seed=42)

id1 = gen.generate("node")
id2 = gen.generate("node")

# Reset to regenerate same sequence
gen.reset(seed=42)
assert gen.generate("node") == id1
assert gen.generate("node") == id2

Singleton Pattern

from dapr_agents_oas_adapter import IDGenerator

# Get global generator (singleton)
gen = IDGenerator.get_instance()
id1 = gen.generate("flow")

# Reset for testing
IDGenerator.reset_instance(seed=123)

Testing with Seeds

import pytest
from dapr_agents_oas_adapter import IDGenerator

@pytest.fixture(autouse=True)
def reset_ids():
    """Reset ID generator before each test."""
    IDGenerator.reset_instance(seed=42)
    yield

Module Functions

generate_id

Convenience function using global generator.

generate_id

generate_id(prefix: str = '') -> str

Generate a unique identifier with optional prefix.

This function uses the global IDGenerator instance. For testing with deterministic IDs, use IDGenerator.reset_instance(seed=42) first.

Parameters:

Name Type Description Default
prefix str

Optional prefix for the ID

''

Returns:

Type Description
str

Generated ID string

Source code in src/dapr_agents_oas_adapter/utils.py
def generate_id(prefix: str = "") -> str:
    """Generate a unique identifier with optional prefix.

    This function uses the global IDGenerator instance. For testing with
    deterministic IDs, use IDGenerator.reset_instance(seed=42) first.

    Args:
        prefix: Optional prefix for the ID

    Returns:
        Generated ID string
    """
    return IDGenerator.get_instance().generate(prefix)

Template Utilities

extract_template_variables

Extract placeholder variables from templates.

extract_template_variables

extract_template_variables(template: str) -> list[str]

Extract variable names from a Jinja2-style template string.

Parameters:

Name Type Description Default
template str

Template string with {{ variable }} placeholders

required

Returns:

Type Description
list[str]

List of variable names found in the template

Source code in src/dapr_agents_oas_adapter/utils.py
def extract_template_variables(template: str) -> list[str]:
    """Extract variable names from a Jinja2-style template string.

    Args:
        template: Template string with {{ variable }} placeholders

    Returns:
        List of variable names found in the template
    """
    pattern = r"\{\{\s*(\w+)\s*\}\}"
    return re.findall(pattern, template)

render_template

Render a template with values.

render_template

render_template(
    template: str, variables: dict[str, Any]
) -> str

Render a simple Jinja2-style template with provided variables.

Parameters:

Name Type Description Default
template str

Template string with {{ variable }} placeholders

required
variables dict[str, Any]

Dictionary of variable name to value mappings

required

Returns:

Type Description
str

Rendered template string

Source code in src/dapr_agents_oas_adapter/utils.py
def render_template(template: str, variables: dict[str, Any]) -> str:
    """Render a simple Jinja2-style template with provided variables.

    Args:
        template: Template string with {{ variable }} placeholders
        variables: Dictionary of variable name to value mappings

    Returns:
        Rendered template string
    """
    result = template
    for key, value in variables.items():
        pattern = r"\{\{\s*" + re.escape(key) + r"\s*\}\}"
        result = re.sub(pattern, str(value), result)
    return result