Skip to content

protocols

The Model Protocols module defines high-level interface protocols for model interaction.

This module contains several important interface protocol definitions to provide capabilities needed in real-world application development, such as tool selection and structured output. These interfaces have clear input and output definitions and are "model-neutral", aiming to reduce the details developers need to consider when implementing features, thereby improving development efficiency.

Constraint module-attribute

The constraint type for structured LLM output.

ToolSelection

Bases: Protocol

Protocol for LLM providers that support tool selection and parameter determination.

ToolSelection defines the interface for language models that can intelligently select appropriate tools from a given tools and determine the specific parameters needed for tool execution.

Methods:

Name Description
select_tool

Synchronous method for tool selection based on conversation context.

aselect_tool

Asynchronous method for tool selection based on conversation context.

Notes
  1. Both synchronous and asynchronous methods must be implemented
  2. Tool selection should be based on conversation context and available tools
  3. Return value includes both selected tool calls and optional response text
Source code in bridgic/core/model/protocols/_tool_selection.py
class ToolSelection(Protocol):
    """
    Protocol for LLM providers that support tool selection and parameter determination.

    ToolSelection defines the interface for language models that can intelligently 
    select appropriate tools from a given tools and determine the specific parameters 
    needed for tool execution.

    Methods
    -------
    select_tool
        Synchronous method for tool selection based on conversation context.
    aselect_tool
        Asynchronous method for tool selection based on conversation context.

    Notes
    ----
    1. Both synchronous and asynchronous methods must be implemented
    2. Tool selection should be based on conversation context and available tools
    3. Return value includes both selected tool calls and optional response text
    """

    def select_tool(
        self,
        messages: List[Message],
        tools: List[Tool],
        **kwargs,
    ) -> Tuple[List[ToolCall], Optional[str]]:
        """
        Select appropriate tools and determine their parameters based on conversation context.

        Parameters
        ----------
        messages : List[Message]
            The conversation history and current context.
        tools : List[Tool]
            Available tools that can be selected for use.
        **kwargs
            Additional keyword arguments for tool selection configuration.

        Returns
        -------
        Tuple[List[ToolCall], Optional[str]]
            A tuple containing:
            - List of selected tool calls with determined parameters
            - Optional response text from the LLM
        """
        ...

    async def aselect_tool(
        self,
        messages: List[Message],
        tools: List[Tool],
        **kwargs,
    ) -> Tuple[List[ToolCall], Optional[str]]:
        """
        Asynchronously select appropriate tools and determine their parameters.

        Parameters
        ----------
        messages : List[Message]
            The conversation history and current context.
        tools : List[Tool]
            Available tools that can be selected for use.
        **kwargs
            Additional keyword arguments for tool selection configuration.

        Returns
        -------
        Tuple[List[ToolCall], Optional[str]]
            A tuple containing:
            - List of selected tool calls with determined parameters
            - Optional response text from the LLM
        """
        ...

select_tool

select_tool(
    messages: List[Message], tools: List[Tool], **kwargs
) -> Tuple[List[ToolCall], Optional[str]]

Select appropriate tools and determine their parameters based on conversation context.

Parameters:

Name Type Description Default
messages List[Message]

The conversation history and current context.

required
tools List[Tool]

Available tools that can be selected for use.

required
**kwargs

Additional keyword arguments for tool selection configuration.

{}

Returns:

Type Description
Tuple[List[ToolCall], Optional[str]]

A tuple containing: - List of selected tool calls with determined parameters - Optional response text from the LLM

Source code in bridgic/core/model/protocols/_tool_selection.py
def select_tool(
    self,
    messages: List[Message],
    tools: List[Tool],
    **kwargs,
) -> Tuple[List[ToolCall], Optional[str]]:
    """
    Select appropriate tools and determine their parameters based on conversation context.

    Parameters
    ----------
    messages : List[Message]
        The conversation history and current context.
    tools : List[Tool]
        Available tools that can be selected for use.
    **kwargs
        Additional keyword arguments for tool selection configuration.

    Returns
    -------
    Tuple[List[ToolCall], Optional[str]]
        A tuple containing:
        - List of selected tool calls with determined parameters
        - Optional response text from the LLM
    """
    ...

aselect_tool

async
aselect_tool(
    messages: List[Message], tools: List[Tool], **kwargs
) -> Tuple[List[ToolCall], Optional[str]]

Asynchronously select appropriate tools and determine their parameters.

Parameters:

Name Type Description Default
messages List[Message]

The conversation history and current context.

required
tools List[Tool]

Available tools that can be selected for use.

required
**kwargs

Additional keyword arguments for tool selection configuration.

{}

Returns:

Type Description
Tuple[List[ToolCall], Optional[str]]

A tuple containing: - List of selected tool calls with determined parameters - Optional response text from the LLM

Source code in bridgic/core/model/protocols/_tool_selection.py
async def aselect_tool(
    self,
    messages: List[Message],
    tools: List[Tool],
    **kwargs,
) -> Tuple[List[ToolCall], Optional[str]]:
    """
    Asynchronously select appropriate tools and determine their parameters.

    Parameters
    ----------
    messages : List[Message]
        The conversation history and current context.
    tools : List[Tool]
        Available tools that can be selected for use.
    **kwargs
        Additional keyword arguments for tool selection configuration.

    Returns
    -------
    Tuple[List[ToolCall], Optional[str]]
        A tuple containing:
        - List of selected tool calls with determined parameters
        - Optional response text from the LLM
    """
    ...

PydanticModel

Bases: BaseModel

A constraint defined as a Pydantic model for structured LLM output.

Source code in bridgic/core/model/protocols/_structured_output.py
class PydanticModel(BaseModel):
    """
    A constraint defined as a Pydantic model for structured LLM output.
    """
    constraint_type: Literal["pydantic_model"] = "pydantic_model"
    """The type of the constraint, in this case `pydantic_model`."""
    model: Type[BaseModel] = Field(..., description="Model type of the PydanticModel constraint.")
    """The Pydantic model type of the constraint."""

constraint_type class-attribute instance-attribute

constraint_type: Literal["pydantic_model"] = (
    "pydantic_model"
)

The type of the constraint, in this case pydantic_model.

model class-attribute instance-attribute

model: Type[BaseModel] = Field(
    ...,
    description="Model type of the PydanticModel constraint.",
)

The Pydantic model type of the constraint.

JsonSchema

Bases: BaseModel

A constraint defined as a JSON schema for structured LLM output.

Source code in bridgic/core/model/protocols/_structured_output.py
class JsonSchema(BaseModel):
    """
    A constraint defined as a JSON schema for structured LLM output.
    """
    constraint_type: Literal["json_schema"] = "json_schema"
    """The type of the constraint, in this case `json_schema`."""
    schema_dict: Dict[str, Any] = Field(..., description="Schema of the JsonSchema constraint.")
    """The JSON schema of the constraint."""

constraint_type class-attribute instance-attribute

constraint_type: Literal['json_schema'] = 'json_schema'

The type of the constraint, in this case json_schema.

schema_dict class-attribute instance-attribute

schema_dict: Dict[str, Any] = Field(
    ..., description="Schema of the JsonSchema constraint."
)

The JSON schema of the constraint.

EbnfGrammar

Bases: BaseModel

A constraint defined as an EBNF grammar for structured LLM output.

Source code in bridgic/core/model/protocols/_structured_output.py
class EbnfGrammar(BaseModel):
    """
    A constraint defined as an EBNF grammar for structured LLM output.
    """
    constraint_type: Literal["ebnf_grammar"] = "ebnf_grammar"
    """The type of the constraint, in this case `ebnf_grammar`."""
    syntax: str = Field(..., description="Syntax of the EBNF grammar constraint.")
    """The syntax of the EBNF grammar constraint."""

constraint_type class-attribute instance-attribute

constraint_type: Literal['ebnf_grammar'] = 'ebnf_grammar'

The type of the constraint, in this case ebnf_grammar.

syntax class-attribute instance-attribute

syntax: str = Field(
    ...,
    description="Syntax of the EBNF grammar constraint.",
)

The syntax of the EBNF grammar constraint.

LarkGrammar

Bases: BaseModel

A constraint defined as a Lark grammar for structured LLM output.

Source code in bridgic/core/model/protocols/_structured_output.py
class LarkGrammar(BaseModel):
    """
    A constraint defined as a Lark grammar for structured LLM output.
    """
    constraint_type: Literal["lark_grammar"] = "lark_grammar"
    """The type of the constraint, in this case `lark_grammar`."""
    syntax: str = Field(..., description="Syntax of the Lark grammar constraint.")
    """The syntax of the Lark grammar constraint."""

constraint_type class-attribute instance-attribute

constraint_type: Literal['lark_grammar'] = 'lark_grammar'

The type of the constraint, in this case lark_grammar.

syntax class-attribute instance-attribute

syntax: str = Field(
    ...,
    description="Syntax of the Lark grammar constraint.",
)

The syntax of the Lark grammar constraint.

Regex

Bases: BaseModel

A constraint defined as a regular expression for structured LLM output.

Source code in bridgic/core/model/protocols/_structured_output.py
class Regex(BaseModel):
    """
    A constraint defined as a regular expression for structured LLM output.
    """
    constraint_type: Literal["regex"] = "regex"
    """The type of the constraint, in this case `regex`."""
    pattern: str = Field(..., description="Pattern of the Regex constraint.")
    """The regular expression of the constraint."""

constraint_type class-attribute instance-attribute

constraint_type: Literal['regex'] = 'regex'

The type of the constraint, in this case regex.

pattern class-attribute instance-attribute

pattern: str = Field(
    ..., description="Pattern of the Regex constraint."
)

The regular expression of the constraint.

Choice

Bases: BaseModel

A constraint defined as a predefined set of choices for structured LLM output.

Source code in bridgic/core/model/protocols/_structured_output.py
class Choice(BaseModel):
    """
    A constraint defined as a predefined set of choices for structured LLM output.
    """
    constraint_type: Literal["choice"] = "choice"
    """The type of the constraint, in this case `choice`."""
    choices: List[str] = Field(..., description="Choices of the choice constraint.")
    """The choices of the constraint."""

constraint_type class-attribute instance-attribute

constraint_type: Literal['choice'] = 'choice'

The type of the constraint, in this case choice.

choices class-attribute instance-attribute

choices: List[str] = Field(
    ..., description="Choices of the choice constraint."
)

The choices of the constraint.

RegexPattern

Constants that define some common regular expressions for structured LLM output.

Source code in bridgic/core/model/protocols/_structured_output.py
class RegexPattern:
    """Constants that define some common regular expressions for structured LLM output."""
    INTEGER: ClassVar[Regex] = Regex(pattern=r"-?\d+")
    """A regular expression for integers."""
    FLOAT = Regex(pattern=r"-?(?:\d+\.\d+|\d+\.|\.\d+|\d+)([eE][-+]?\d+)?")
    """A regular expression for floats."""
    DATE: ClassVar[Regex] = Regex(pattern=r"\d{4}-\d{2}-\d{2}")
    """A regular expression for dates."""
    TIME: ClassVar[Regex] = Regex(pattern=r"(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?")
    """A regular expression for times."""
    DATE_TIME_ISO_8601: ClassVar[Regex] = Regex(pattern=rf"{DATE.pattern}T{TIME.pattern}(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)?")
    """A regular expression for date-time in ISO 8601 format."""
    IP_V4_ADDRESS: ClassVar[Regex] = Regex(pattern=r"(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)")
    """A regular expression for IPv4 addresses."""
    IP_V6_ADDRESS: ClassVar[Regex] = Regex(pattern=r"([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}")
    """A regular expression for IPv6 addresses."""
    EMAIL: ClassVar[Regex] = Regex(pattern=r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+")
    """A regular expression for email addresses."""

INTEGER class-attribute

INTEGER: Regex = Regex(pattern='-?\\d+')

A regular expression for integers.

FLOAT class-attribute instance-attribute

FLOAT = Regex(
    pattern="-?(?:\\d+\\.\\d+|\\d+\\.|\\.\\d+|\\d+)([eE][-+]?\\d+)?"
)

A regular expression for floats.

DATE class-attribute

DATE: Regex = Regex(pattern='\\d{4}-\\d{2}-\\d{2}')

A regular expression for dates.

TIME class-attribute

TIME: Regex = Regex(
    pattern="(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?"
)

A regular expression for times.

DATE_TIME_ISO_8601 class-attribute

DATE_TIME_ISO_8601: Regex = Regex(
    pattern=f"{pattern}T{pattern}(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)?"
)

A regular expression for date-time in ISO 8601 format.

IP_V4_ADDRESS class-attribute

IP_V4_ADDRESS: Regex = Regex(
    pattern="(?:(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)"
)

A regular expression for IPv4 addresses.

IP_V6_ADDRESS class-attribute

IP_V6_ADDRESS: Regex = Regex(
    pattern="([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}"
)

A regular expression for IPv6 addresses.

EMAIL class-attribute

EMAIL: Regex = Regex(
    pattern="[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+"
)

A regular expression for email addresses.

StructuredOutput

Bases: Protocol

Protocol for LLM providers that support structured output generation.

StructuredOutput defines the interface for language models that can generate responses in specific formats according to given constraints. This protocol enables controlled output generation for various data structures and formats.

Methods:

Name Description
structured_output

Synchronous method for generating structured output based on constraints.

astructured_output

Asynchronous method for generating structured output based on constraints.

Notes
  1. Both synchronous and asynchronous methods must be implemented
  2. Supported constraint types depend on the specific LLM provider implementation
  3. Output format is determined by the constraint type provided
  4. Common constraint types include PydanticModel, JsonSchema, Regex, Choice, etc.
Source code in bridgic/core/model/protocols/_structured_output.py
class StructuredOutput(Protocol):
    """
    Protocol for LLM providers that support structured output generation.

    StructuredOutput defines the interface for language models that can generate 
    responses in specific formats according to given constraints. This protocol 
    enables controlled output generation for various data structures and formats.

    Methods
    -------
    structured_output
        Synchronous method for generating structured output based on constraints.
    astructured_output
        Asynchronous method for generating structured output based on constraints.

    Notes
    ----
    1. Both synchronous and asynchronous methods must be implemented
    2. Supported constraint types depend on the specific LLM provider implementation
    3. Output format is determined by the constraint type provided
    4. Common constraint types include PydanticModel, JsonSchema, Regex, Choice, etc.
    """

    def structured_output(
        self,
        messages: List[Message],
        constraint: Constraint,
        **kwargs,
    ) -> Any:
        """
        Generate structured output based on conversation context and constraints.

        Parameters
        ----------
        messages : List[Message]
            The conversation history and current context.
        constraint : Constraint
            The output format constraint. Supported types:

            - PydanticModel: Output as Pydantic model instance
            - JsonSchema: Output as JSON matching the schema
            - Regex: Output matching the regex pattern
            - Choice: Output from predefined choices
            - EbnfGrammar: Output following EBNF grammar rules
            - LarkGrammar: Output following Lark grammar rules
        **kwargs
            Additional keyword arguments for output generation configuration.

        Returns
        -------
        Any
            The structured output matching the specified constraint format.
        """
        ...

    async def astructured_output(
        self,
        messages: List[Message],
        constraint: Constraint,
        **kwargs,
    ) -> Any:
        """
        Asynchronously generate structured output based on conversation context and constraints.

        Parameters
        ----------
        messages : List[Message]
            The conversation history and current context.
        constraint : Constraint
            The output format constraint. Supported types:

            - PydanticModel: Output as Pydantic model instance
            - JsonSchema: Output as JSON matching the schema
            - Regex: Output matching the regex pattern
            - Choice: Output from predefined choices
            - EbnfGrammar: Output following EBNF grammar rules
            - LarkGrammar: Output following Lark grammar rules
        **kwargs
            Additional keyword arguments for output generation configuration.

        Returns
        -------
        Any
            The structured output matching the specified constraint format.
        """
        ...

structured_output

structured_output(
    messages: List[Message],
    constraint: Constraint,
    **kwargs
) -> Any

Generate structured output based on conversation context and constraints.

Parameters:

Name Type Description Default
messages List[Message]

The conversation history and current context.

required
constraint Constraint

The output format constraint. Supported types:

  • PydanticModel: Output as Pydantic model instance
  • JsonSchema: Output as JSON matching the schema
  • Regex: Output matching the regex pattern
  • Choice: Output from predefined choices
  • EbnfGrammar: Output following EBNF grammar rules
  • LarkGrammar: Output following Lark grammar rules
required
**kwargs

Additional keyword arguments for output generation configuration.

{}

Returns:

Type Description
Any

The structured output matching the specified constraint format.

Source code in bridgic/core/model/protocols/_structured_output.py
def structured_output(
    self,
    messages: List[Message],
    constraint: Constraint,
    **kwargs,
) -> Any:
    """
    Generate structured output based on conversation context and constraints.

    Parameters
    ----------
    messages : List[Message]
        The conversation history and current context.
    constraint : Constraint
        The output format constraint. Supported types:

        - PydanticModel: Output as Pydantic model instance
        - JsonSchema: Output as JSON matching the schema
        - Regex: Output matching the regex pattern
        - Choice: Output from predefined choices
        - EbnfGrammar: Output following EBNF grammar rules
        - LarkGrammar: Output following Lark grammar rules
    **kwargs
        Additional keyword arguments for output generation configuration.

    Returns
    -------
    Any
        The structured output matching the specified constraint format.
    """
    ...

astructured_output

async
astructured_output(
    messages: List[Message],
    constraint: Constraint,
    **kwargs
) -> Any

Asynchronously generate structured output based on conversation context and constraints.

Parameters:

Name Type Description Default
messages List[Message]

The conversation history and current context.

required
constraint Constraint

The output format constraint. Supported types:

  • PydanticModel: Output as Pydantic model instance
  • JsonSchema: Output as JSON matching the schema
  • Regex: Output matching the regex pattern
  • Choice: Output from predefined choices
  • EbnfGrammar: Output following EBNF grammar rules
  • LarkGrammar: Output following Lark grammar rules
required
**kwargs

Additional keyword arguments for output generation configuration.

{}

Returns:

Type Description
Any

The structured output matching the specified constraint format.

Source code in bridgic/core/model/protocols/_structured_output.py
async def astructured_output(
    self,
    messages: List[Message],
    constraint: Constraint,
    **kwargs,
) -> Any:
    """
    Asynchronously generate structured output based on conversation context and constraints.

    Parameters
    ----------
    messages : List[Message]
        The conversation history and current context.
    constraint : Constraint
        The output format constraint. Supported types:

        - PydanticModel: Output as Pydantic model instance
        - JsonSchema: Output as JSON matching the schema
        - Regex: Output matching the regex pattern
        - Choice: Output from predefined choices
        - EbnfGrammar: Output following EBNF grammar rules
        - LarkGrammar: Output following Lark grammar rules
    **kwargs
        Additional keyword arguments for output generation configuration.

    Returns
    -------
    Any
        The structured output matching the specified constraint format.
    """
    ...