Skip to content

llmling_models

Class info

Re-exported classes

Class Module Description
CodeModeToolset llmling_models.toolsets.codemode_toolset A toolset that wraps other toolsets and provides Python code execution.
DefaultInputHandler llmling_models.models.input_model.input_handlers Default input handler using standard input.
DelegationMultiModel llmling_models.models.delegation Meta-model that dynamically selects models based on a user prompt.
InputModel llmling_models.models.input_model.model Model that delegates responses to human input.
MultiModel llmling_models.models.multi Base for model configurations that combine multiple language models.
UserSelectModel llmling_models.models.userselect Model that lets users interactively select from multiple models.

🛈 DocStrings

LLMling-models: main package.

Pydantic-AI models for AgentPool.

CodeModeToolset dataclass

Bases: AbstractToolset[AgentDepsT]

A toolset that wraps other toolsets and provides Python code execution.

Source code in src/llmling_models/toolsets/codemode_toolset.py
@dataclass(kw_only=True)
class CodeModeToolset[AgentDepsT = None](AbstractToolset[AgentDepsT]):
    """A toolset that wraps other toolsets and provides Python code execution."""

    toolsets: list[AbstractToolset[Any]]
    """List of toolsets whose tools should be available in code execution"""

    toolset_id: str | None = None
    """Optional unique ID for this toolset"""

    include_docstrings: bool = True
    """Include function docstrings in tool documentation"""

    usage_notes: str = USAGE_NOTES
    """Usage notes to include in the tool description"""

    max_retries: int = 3
    """Maximum number of tool retries."""

    _tools_cache: tuple[tuple[str, int], list[dict[str, ToolsetTool[Any]]]] | None = field(
        default=None, init=False, repr=False
    )

    @property
    def id(self) -> str | None:
        """Return the toolset ID."""
        return self.toolset_id

    @property
    def label(self) -> str:
        """Return a label for error messages."""
        label = "CodeModeToolset"
        if self.id:
            label += f" {self.id!r}"
        return label

    @property
    def tool_name_conflict_hint(self) -> str:
        """Return hint for resolving name conflicts."""
        return "Rename the toolset ID or use a different CodeModeToolset instance."

    async def __aenter__(self) -> Self:
        """Enter async context."""
        for toolset in self.toolsets:
            await toolset.__aenter__()
        return self

    async def __aexit__(self, *args: object) -> None:
        """Exit async context."""
        for toolset in self.toolsets:
            await toolset.__aexit__(*args)

    async def get_tools(self, ctx: RunContext[Any]) -> dict[str, ToolsetTool[Any]]:
        """Return the single code execution tool."""
        toolset_generator = await self._get_code_generator(ctx)
        description = toolset_generator.generate_tool_description()
        tool_def = ToolDefinition(
            name=TOOL_NAME,
            description=description + "\n\n" + self.usage_notes,
            parameters_json_schema=CodeExecutionParams.model_json_schema(),
        )
        tool = ToolsetTool(
            toolset=self,
            tool_def=tool_def,
            max_retries=self.max_retries,
            args_validator=SchemaValidator(CodeExecutionParams.__pydantic_core_schema__),
        )
        return {TOOL_NAME: tool}

    async def call_tool(
        self,
        name: str,
        tool_args: dict[str, Any],
        ctx: RunContext[Any],
        tool: ToolsetTool[Any],
    ) -> Any:
        """Execute the Python code with all wrapped tools available."""
        if name != TOOL_NAME:
            msg = f"Unknown tool: {name}"
            raise ValueError(msg)
        params = CodeExecutionParams.model_validate(tool_args)
        logger.info("Executing Python code: %r", params.python_code)
        validate_code(params.python_code)
        toolset_generator = await self._get_code_generator(ctx)
        namespace = toolset_generator.generate_execution_namespace()
        try:
            exec(params.python_code, namespace)
            result = await namespace["main"]()
        except Exception as e:  # noqa: BLE001
            return f"Error executing code: {e!s}"
        else:
            return result if result is not None else "Code executed successfully"

    def apply(self, visitor: Callable[[AbstractToolset[AgentDepsT]], None]) -> None:
        """Apply visitor to all wrapped toolsets."""
        for toolset in self.toolsets:
            toolset.apply(visitor)

    def visit_and_replace(
        self,
        visitor: Callable[[AbstractToolset[AgentDepsT]], AbstractToolset[AgentDepsT]],
    ) -> AbstractToolset[AgentDepsT]:
        """Visit and replace all wrapped toolsets."""
        self.toolsets = [toolset.visit_and_replace(visitor) for toolset in self.toolsets]
        return self

    async def _get_wrapped_tools(self, ctx: RunContext[Any]) -> list[dict[str, ToolsetTool[Any]]]:
        """List the wrapped toolsets' tools, once per run step.

        Listing an MCP toolset is a round trip; the listing made for the model request
        is reused when the model's code runs in the same step.
        """
        key = (ctx.run_id, ctx.run_step) if ctx.run_id is not None else None
        if key is not None and self._tools_cache is not None and self._tools_cache[0] == key:
            return self._tools_cache[1]
        tools = list(await asyncio.gather(*(ts.get_tools(ctx) for ts in self.toolsets)))
        if key is not None:
            self._tools_cache = (key, tools)
        return tools

    async def _get_code_generator(self, ctx: RunContext[Any]) -> ToolsetCodeGenerator:
        """Build the toolset code generator, its callables bound to `ctx`."""
        callables = [
            create_tool_callable(toolset_tool, tool_name, ctx)
            for tools in await self._get_wrapped_tools(ctx)
            for tool_name, toolset_tool in tools.items()
        ]
        return ToolsetCodeGenerator.from_callables(callables, self.include_docstrings)

id property

id: str | None

Return the toolset ID.

include_docstrings class-attribute instance-attribute

include_docstrings: bool = True

Include function docstrings in tool documentation

label property

label: str

Return a label for error messages.

max_retries class-attribute instance-attribute

max_retries: int = 3

Maximum number of tool retries.

tool_name_conflict_hint property

tool_name_conflict_hint: str

Return hint for resolving name conflicts.

toolset_id class-attribute instance-attribute

toolset_id: str | None = None

Optional unique ID for this toolset

toolsets instance-attribute

toolsets: list[AbstractToolset[Any]]

List of toolsets whose tools should be available in code execution

usage_notes class-attribute instance-attribute

usage_notes: str = USAGE_NOTES

Usage notes to include in the tool description

__aenter__ async

__aenter__() -> Self

Enter async context.

Source code in src/llmling_models/toolsets/codemode_toolset.py
async def __aenter__(self) -> Self:
    """Enter async context."""
    for toolset in self.toolsets:
        await toolset.__aenter__()
    return self

__aexit__ async

__aexit__(*args: object) -> None

Exit async context.

Source code in src/llmling_models/toolsets/codemode_toolset.py
async def __aexit__(self, *args: object) -> None:
    """Exit async context."""
    for toolset in self.toolsets:
        await toolset.__aexit__(*args)

apply

apply(visitor: Callable[[AbstractToolset[AgentDepsT]], None]) -> None

Apply visitor to all wrapped toolsets.

Source code in src/llmling_models/toolsets/codemode_toolset.py
def apply(self, visitor: Callable[[AbstractToolset[AgentDepsT]], None]) -> None:
    """Apply visitor to all wrapped toolsets."""
    for toolset in self.toolsets:
        toolset.apply(visitor)

call_tool async

call_tool(
    name: str, tool_args: dict[str, Any], ctx: RunContext[Any], tool: ToolsetTool[Any]
) -> Any

Execute the Python code with all wrapped tools available.

Source code in src/llmling_models/toolsets/codemode_toolset.py
async def call_tool(
    self,
    name: str,
    tool_args: dict[str, Any],
    ctx: RunContext[Any],
    tool: ToolsetTool[Any],
) -> Any:
    """Execute the Python code with all wrapped tools available."""
    if name != TOOL_NAME:
        msg = f"Unknown tool: {name}"
        raise ValueError(msg)
    params = CodeExecutionParams.model_validate(tool_args)
    logger.info("Executing Python code: %r", params.python_code)
    validate_code(params.python_code)
    toolset_generator = await self._get_code_generator(ctx)
    namespace = toolset_generator.generate_execution_namespace()
    try:
        exec(params.python_code, namespace)
        result = await namespace["main"]()
    except Exception as e:  # noqa: BLE001
        return f"Error executing code: {e!s}"
    else:
        return result if result is not None else "Code executed successfully"

get_tools async

get_tools(ctx: RunContext[Any]) -> dict[str, ToolsetTool[Any]]

Return the single code execution tool.

Source code in src/llmling_models/toolsets/codemode_toolset.py
async def get_tools(self, ctx: RunContext[Any]) -> dict[str, ToolsetTool[Any]]:
    """Return the single code execution tool."""
    toolset_generator = await self._get_code_generator(ctx)
    description = toolset_generator.generate_tool_description()
    tool_def = ToolDefinition(
        name=TOOL_NAME,
        description=description + "\n\n" + self.usage_notes,
        parameters_json_schema=CodeExecutionParams.model_json_schema(),
    )
    tool = ToolsetTool(
        toolset=self,
        tool_def=tool_def,
        max_retries=self.max_retries,
        args_validator=SchemaValidator(CodeExecutionParams.__pydantic_core_schema__),
    )
    return {TOOL_NAME: tool}

visit_and_replace

visit_and_replace(
    visitor: Callable[[AbstractToolset[AgentDepsT]], AbstractToolset[AgentDepsT]],
) -> AbstractToolset[AgentDepsT]

Visit and replace all wrapped toolsets.

Source code in src/llmling_models/toolsets/codemode_toolset.py
def visit_and_replace(
    self,
    visitor: Callable[[AbstractToolset[AgentDepsT]], AbstractToolset[AgentDepsT]],
) -> AbstractToolset[AgentDepsT]:
    """Visit and replace all wrapped toolsets."""
    self.toolsets = [toolset.visit_and_replace(visitor) for toolset in self.toolsets]
    return self

DefaultInputHandler

Bases: InputHandler

Default input handler using standard input.

Source code in src/llmling_models/models/input_model/input_handlers.py
class DefaultInputHandler(InputHandler):
    """Default input handler using standard input."""

    def get_input(self, prompt: str) -> str:
        """Get input using basic console input."""
        return input(prompt).strip()

    async def stream_input(self, prompt: str) -> AsyncIterator[str]:
        """Simulate streaming input using standard input."""
        print(prompt, end="", flush=True)

        async def char_iterator() -> AsyncIterator[str]:
            while True:
                char = sys.stdin.read(1)
                if char == "\n":
                    break
                yield char

        return char_iterator()

    def format_messages(
        self,
        messages: list[ModelMessage],
        *,
        prompt_template: str,
        show_system: bool,
    ) -> str:
        """Format messages for display."""
        formatted: list[str] = []

        for message in messages:
            for part in message.parts:
                match part:
                    case SystemPromptPart(content=content) if show_system:
                        formatted.append(f"🔧 System: {content}")
                    case UserPromptPart(content=content):
                        formatted.append(prompt_template.format(prompt=content))
                    case TextPart(content=content):
                        formatted.append(f"Assistant: {content}")
                    case _:
                        continue

        return "\n\n".join(formatted)

format_messages

format_messages(messages: list[ModelMessage], *, prompt_template: str, show_system: bool) -> str

Format messages for display.

Source code in src/llmling_models/models/input_model/input_handlers.py
def format_messages(
    self,
    messages: list[ModelMessage],
    *,
    prompt_template: str,
    show_system: bool,
) -> str:
    """Format messages for display."""
    formatted: list[str] = []

    for message in messages:
        for part in message.parts:
            match part:
                case SystemPromptPart(content=content) if show_system:
                    formatted.append(f"🔧 System: {content}")
                case UserPromptPart(content=content):
                    formatted.append(prompt_template.format(prompt=content))
                case TextPart(content=content):
                    formatted.append(f"Assistant: {content}")
                case _:
                    continue

    return "\n\n".join(formatted)

get_input

get_input(prompt: str) -> str

Get input using basic console input.

Source code in src/llmling_models/models/input_model/input_handlers.py
def get_input(self, prompt: str) -> str:
    """Get input using basic console input."""
    return input(prompt).strip()

stream_input async

stream_input(prompt: str) -> AsyncIterator[str]

Simulate streaming input using standard input.

Source code in src/llmling_models/models/input_model/input_handlers.py
async def stream_input(self, prompt: str) -> AsyncIterator[str]:
    """Simulate streaming input using standard input."""
    print(prompt, end="", flush=True)

    async def char_iterator() -> AsyncIterator[str]:
        while True:
            char = sys.stdin.read(1)
            if char == "\n":
                break
            yield char

    return char_iterator()

DelegationMultiModel

Bases: MultiModel

Meta-model that dynamically selects models based on a user prompt.

Source code in src/llmling_models/models/delegation.py
class DelegationMultiModel(MultiModel):
    """Meta-model that dynamically selects models based on a user prompt."""

    selector_model: ModelName | str | Model
    """Model to use for delegation."""

    selection_prompt: str
    """Instructions for model selection based on task type."""

    model_descriptions: dict[str | Model, str] | None = Field(default=None, exclude=True)

    @model_validator(mode="before")
    @classmethod
    def handle_model_dict(cls, data: dict[str, Any]) -> dict[str, Any]:
        """Handle both list of models and dict[model, description]."""
        if isinstance(data.get("models"), dict):
            data["model_descriptions"] = data["models"]
            data["models"] = list(data["models"].keys())
        return data

    @property
    def model_name(self) -> str:
        """Return the model name."""
        return "delegation"

    @property
    def system(self) -> str:
        """Return the system/provider name."""
        return "delegation"

    def _models_by_id(self) -> dict[str, Model]:
        """Map the configured ids ("openai:gpt-4o-mini") to the model instances."""
        models: dict[str, Model] = {}
        for spec, model in zip(self.models, self.available_models, strict=True):
            models.setdefault(spec if isinstance(spec, str) else model.model_name, model)
        return models

    def _format_selection_text(self, base_prompt: str) -> str:
        """Format selection text using prompt and optional model descriptions."""
        if not self.model_descriptions:
            return base_prompt

        model_hints = "\n".join(
            f"Pick '{model if isinstance(model, str) else model.model_name}' for: {desc}"
            for model, desc in self.model_descriptions.items()
        )
        return f"{model_hints}\n\n{base_prompt}"

    async def _select_model(
        self, prompt: str, model_settings: ModelSettings | None
    ) -> tuple[Model, RequestUsage]:
        """Use selector model to choose appropriate model for prompt.

        Returns the chosen model and the selector's usage.
        """
        selector = (
            infer_model(self.selector_model)
            if isinstance(self.selector_model, str)
            else self.selector_model
        )
        models = self._models_by_id()
        selection_text = (
            f"{self._format_selection_text(self.selection_prompt)}\n\n"
            f"Available models: {', '.join(models)}\n\n"
            f"Task: {prompt}\n\n"
            "Return only the name of the model to use."
        )
        selection_msg = ModelRequest(parts=[UserPromptPart(content=selection_text)])
        # Plain parameters: the agent's function and output tools are not for the selector.
        response = await selector.request([selection_msg], None, ModelRequestParameters())
        text = next((p.content for p in response.parts if isinstance(p, TextPart)), "")
        selected_name = text.strip().strip("'\"`").strip()

        model = models.get(selected_name) or next(
            (m for m in models.values() if m.model_name == selected_name), None
        )
        if model is None:
            msg = f"Selector returned unknown model: {selected_name}"
            raise ValueError(msg)
        logger.debug("Selected model %s for prompt: %s", selected_name, prompt)
        return model, response.usage

    def _get_last_prompt(self, messages: list[ModelMessage]) -> str:
        """Extract the last user prompt from messages.

        After a tool call the last request holds only tool returns: the prompt is the
        one of an earlier request.
        """
        if not messages:
            msg = "No messages provided"
            raise ValueError(msg)

        for message in reversed(messages):
            if not isinstance(message, ModelRequest):
                continue
            for part in message.parts:
                if isinstance(part, UserPromptPart):
                    return str(part.content)  # TODO: could also be media content

        msg = "No user prompt found in messages"
        raise ValueError(msg)

    async def request(
        self,
        messages: list[ModelMessage],
        model_settings: ModelSettings | None,
        model_request_parameters: ModelRequestParameters,
    ) -> ModelResponse:
        """Process request using dynamically selected model."""
        # Extract the actual prompt
        prompt = self._get_last_prompt(messages)

        selected_model, selector_usage = await self._select_model(prompt, model_settings)
        response = await selected_model.request(
            messages,
            model_settings,
            model_request_parameters,
        )
        response.usage = response.usage + selector_usage
        return response

    @asynccontextmanager
    async def request_stream(
        self,
        messages: list[ModelMessage],
        model_settings: ModelSettings | None,
        model_request_parameters: ModelRequestParameters,
        run_context: RunContext[Any] | None = None,
    ) -> AsyncGenerator[StreamedResponse]:
        """Stream response using dynamically selected model."""
        # Extract the actual prompt
        prompt = self._get_last_prompt(messages)

        selected_model, _ = await self._select_model(prompt, model_settings)

        # Stream from selected model
        async with selected_model.request_stream(
            messages,
            model_settings,
            model_request_parameters,
            run_context,
        ) as stream:
            yield stream

model_name property

model_name: str

Return the model name.

selection_prompt instance-attribute

selection_prompt: str

Instructions for model selection based on task type.

selector_model instance-attribute

selector_model: ModelName | str | Model

Model to use for delegation.

system property

system: str

Return the system/provider name.

handle_model_dict classmethod

handle_model_dict(data: dict[str, Any]) -> dict[str, Any]

Handle both list of models and dict[model, description].

Source code in src/llmling_models/models/delegation.py
@model_validator(mode="before")
@classmethod
def handle_model_dict(cls, data: dict[str, Any]) -> dict[str, Any]:
    """Handle both list of models and dict[model, description]."""
    if isinstance(data.get("models"), dict):
        data["model_descriptions"] = data["models"]
        data["models"] = list(data["models"].keys())
    return data

request async

request(
    messages: list[ModelMessage],
    model_settings: ModelSettings | None,
    model_request_parameters: ModelRequestParameters,
) -> ModelResponse

Process request using dynamically selected model.

Source code in src/llmling_models/models/delegation.py
async def request(
    self,
    messages: list[ModelMessage],
    model_settings: ModelSettings | None,
    model_request_parameters: ModelRequestParameters,
) -> ModelResponse:
    """Process request using dynamically selected model."""
    # Extract the actual prompt
    prompt = self._get_last_prompt(messages)

    selected_model, selector_usage = await self._select_model(prompt, model_settings)
    response = await selected_model.request(
        messages,
        model_settings,
        model_request_parameters,
    )
    response.usage = response.usage + selector_usage
    return response

request_stream async

request_stream(
    messages: list[ModelMessage],
    model_settings: ModelSettings | None,
    model_request_parameters: ModelRequestParameters,
    run_context: RunContext[Any] | None = None,
) -> AsyncGenerator[StreamedResponse]

Stream response using dynamically selected model.

Source code in src/llmling_models/models/delegation.py
@asynccontextmanager
async def request_stream(
    self,
    messages: list[ModelMessage],
    model_settings: ModelSettings | None,
    model_request_parameters: ModelRequestParameters,
    run_context: RunContext[Any] | None = None,
) -> AsyncGenerator[StreamedResponse]:
    """Stream response using dynamically selected model."""
    # Extract the actual prompt
    prompt = self._get_last_prompt(messages)

    selected_model, _ = await self._select_model(prompt, model_settings)

    # Stream from selected model
    async with selected_model.request_stream(
        messages,
        model_settings,
        model_request_parameters,
        run_context,
    ) as stream:
        yield stream

InputModel dataclass

Bases: Model

Model that delegates responses to human input.

Source code in src/llmling_models/models/input_model/model.py
@dataclass
class InputModel(Model):
    """Model that delegates responses to human input."""

    prompt_template: str = field(default="👤 Please respond to: {prompt}")
    """Template for showing the prompt to the human."""

    show_system: bool = field(default=True)
    """Whether to show system messages to the human."""

    input_prompt: str = field(default="Your response: ")
    """Prompt to show when requesting input."""

    handler: InputHandler | type[InputHandler] = field(default=DefaultInputHandler)
    """Input handler class to use."""

    @property
    def model_name(self) -> str:
        """Return the model name."""
        return "input"

    @property
    def system(self) -> str:
        """Return the system/provider name."""
        return "input"

    async def request(
        self,
        messages: list[ModelMessage],
        model_settings: ModelSettings | None,
        model_request_parameters: ModelRequestParameters,
    ) -> ModelResponse:
        """Get response from human input."""
        # Format and display messages using handler
        handler = self.handler() if isinstance(self.handler, type) else self.handler
        display_text = handler.format_messages(
            messages,
            prompt_template=self.prompt_template,
            show_system=self.show_system,
        )
        print("\n" + "=" * 80, file=sys.stderr)
        print(display_text, file=sys.stderr)
        print("-" * 80, file=sys.stderr)

        # Get input using configured handler
        input_method = handler.get_input
        if inspect.iscoroutinefunction(input_method):
            response = await input_method(self.input_prompt)
        else:
            response_or_awaitable = input_method(self.input_prompt)
            if isinstance(response_or_awaitable, Awaitable):
                response = await response_or_awaitable
            else:
                response = response_or_awaitable

        return ModelResponse(parts=[TextPart(response)], timestamp=datetime.now(UTC))

    @asynccontextmanager
    async def request_stream(
        self,
        messages: list[ModelMessage],
        model_settings: ModelSettings | None,
        model_request_parameters: ModelRequestParameters,
        run_context: RunContext[Any] | None = None,
    ) -> AsyncGenerator[StreamedResponse]:
        """Stream responses character by character."""
        # Format and display messages using handler
        handler = self.handler() if isinstance(self.handler, type) else self.handler
        display_text = handler.format_messages(
            messages,
            prompt_template=self.prompt_template,
            show_system=self.show_system,
        )
        print("\n" + "=" * 80, file=sys.stderr)
        print(display_text, file=sys.stderr)
        print("-" * 80, file=sys.stderr)

        # Get streaming input using configured handler
        stream_method = handler.stream_input
        if inspect.iscoroutinefunction(stream_method):
            char_stream = await stream_method(self.input_prompt)
        else:
            stream_or_awaitable = stream_method(self.input_prompt)
            if isinstance(stream_or_awaitable, Awaitable):
                char_stream = await stream_or_awaitable
            else:
                char_stream = stream_or_awaitable
        reqs = ModelRequestParameters()
        yield InputStreamedResponse(model_request_parameters=reqs, stream=char_stream)

handler class-attribute instance-attribute

handler: InputHandler | type[InputHandler] = field(default=DefaultInputHandler)

Input handler class to use.

input_prompt class-attribute instance-attribute

input_prompt: str = field(default='Your response: ')

Prompt to show when requesting input.

model_name property

model_name: str

Return the model name.

prompt_template class-attribute instance-attribute

prompt_template: str = field(default='👤 Please respond to: {prompt}')

Template for showing the prompt to the human.

show_system class-attribute instance-attribute

show_system: bool = field(default=True)

Whether to show system messages to the human.

system property

system: str

Return the system/provider name.

request async

request(
    messages: list[ModelMessage],
    model_settings: ModelSettings | None,
    model_request_parameters: ModelRequestParameters,
) -> ModelResponse

Get response from human input.

Source code in src/llmling_models/models/input_model/model.py
async def request(
    self,
    messages: list[ModelMessage],
    model_settings: ModelSettings | None,
    model_request_parameters: ModelRequestParameters,
) -> ModelResponse:
    """Get response from human input."""
    # Format and display messages using handler
    handler = self.handler() if isinstance(self.handler, type) else self.handler
    display_text = handler.format_messages(
        messages,
        prompt_template=self.prompt_template,
        show_system=self.show_system,
    )
    print("\n" + "=" * 80, file=sys.stderr)
    print(display_text, file=sys.stderr)
    print("-" * 80, file=sys.stderr)

    # Get input using configured handler
    input_method = handler.get_input
    if inspect.iscoroutinefunction(input_method):
        response = await input_method(self.input_prompt)
    else:
        response_or_awaitable = input_method(self.input_prompt)
        if isinstance(response_or_awaitable, Awaitable):
            response = await response_or_awaitable
        else:
            response = response_or_awaitable

    return ModelResponse(parts=[TextPart(response)], timestamp=datetime.now(UTC))

request_stream async

request_stream(
    messages: list[ModelMessage],
    model_settings: ModelSettings | None,
    model_request_parameters: ModelRequestParameters,
    run_context: RunContext[Any] | None = None,
) -> AsyncGenerator[StreamedResponse]

Stream responses character by character.

Source code in src/llmling_models/models/input_model/model.py
@asynccontextmanager
async def request_stream(
    self,
    messages: list[ModelMessage],
    model_settings: ModelSettings | None,
    model_request_parameters: ModelRequestParameters,
    run_context: RunContext[Any] | None = None,
) -> AsyncGenerator[StreamedResponse]:
    """Stream responses character by character."""
    # Format and display messages using handler
    handler = self.handler() if isinstance(self.handler, type) else self.handler
    display_text = handler.format_messages(
        messages,
        prompt_template=self.prompt_template,
        show_system=self.show_system,
    )
    print("\n" + "=" * 80, file=sys.stderr)
    print(display_text, file=sys.stderr)
    print("-" * 80, file=sys.stderr)

    # Get streaming input using configured handler
    stream_method = handler.stream_input
    if inspect.iscoroutinefunction(stream_method):
        char_stream = await stream_method(self.input_prompt)
    else:
        stream_or_awaitable = stream_method(self.input_prompt)
        if isinstance(stream_or_awaitable, Awaitable):
            char_stream = await stream_or_awaitable
        else:
            char_stream = stream_or_awaitable
    reqs = ModelRequestParameters()
    yield InputStreamedResponse(model_request_parameters=reqs, stream=char_stream)

MultiModel

Bases: Schema, Model

Base for model configurations that combine multiple language models.

This provides the base interface for YAML-configurable multi-model setups, allowing configuration of multiple models through LLMling's config system.

Source code in src/llmling_models/models/multi.py
class MultiModel(Schema, Model):
    """Base for model configurations that combine multiple language models.

    This provides the base interface for YAML-configurable multi-model setups,
    allowing configuration of multiple models through LLMling's config system.
    """

    models: Sequence[str | Model] = Field(min_length=1)
    """List of models to use."""

    _initialized_models: list[Model] | None = None

    model_config = ConfigDict(arbitrary_types_allowed=True)

    @model_validator(mode="after")
    def initialize_models(self) -> MultiModel:
        """Convert string model names to Model instances."""
        models: list[Model] = []
        for model in self.models:
            if isinstance(model, str):
                models.append(infer_model(model))
            else:
                models.append(model)
        self._initialized_models = models
        return self

    @property
    def available_models(self) -> Sequence[Model]:
        """Get initialized model instances."""
        if self._initialized_models is None:
            msg = "Models not initialized"
            raise RuntimeError(msg)
        return self._initialized_models

available_models property

available_models: Sequence[Model]

Get initialized model instances.

models class-attribute instance-attribute

models: Sequence[str | Model] = Field(min_length=1)

List of models to use.

initialize_models

initialize_models() -> MultiModel

Convert string model names to Model instances.

Source code in src/llmling_models/models/multi.py
@model_validator(mode="after")
def initialize_models(self) -> MultiModel:
    """Convert string model names to Model instances."""
    models: list[Model] = []
    for model in self.models:
        if isinstance(model, str):
            models.append(infer_model(model))
        else:
            models.append(model)
    self._initialized_models = models
    return self

UserSelectModel

Bases: MultiModel

Model that lets users interactively select from multiple models.

Source code in src/llmling_models/models/userselect.py
class UserSelectModel(MultiModel):
    """Model that lets users interactively select from multiple models."""

    prompt_template: str = Field(default="🤖 Choose a model for: {prompt}")
    """Template for showing the prompt to the user."""

    show_system: bool = Field(default=True)
    """Whether to show system messages."""

    input_prompt: str = Field(default="Enter model number (0-{max}): ")
    """Prompt shown when requesting model selection."""

    handler: ImportString[Any] = Field(
        default="llmling_models:DefaultInputHandler", validate_default=True
    )
    """Input handler class to use."""

    @property
    def model_name(self) -> str:
        """Return the model name."""
        return "user-select"

    @property
    def system(self) -> str:
        """Return the system/provider name."""
        return "user-select"

    async def _get_user_selection(
        self,
        messages: list[ModelMessage],
        handler: InputHandler,
    ) -> Model:
        """Get model selection from user."""
        model_list = "\n".join(
            f"[{i}] {model.model_name}" for i, model in enumerate(self.available_models)
        )
        display_text = handler.format_messages(
            messages,
            prompt_template=self.prompt_template,
            show_system=self.show_system,
        )

        print("\n" + "=" * 80)
        print(display_text)
        print("\nAvailable models:\n" + model_list)
        print("-" * 80)

        while True:
            selection_prompt = self.input_prompt.format(max=len(self.available_models) - 1)
            input_method = handler.get_input
            if inspect.iscoroutinefunction(input_method):
                selection = await input_method(selection_prompt)
            else:
                response_or_awaitable = input_method(selection_prompt)
                if isinstance(response_or_awaitable, Awaitable):
                    selection = await response_or_awaitable
                else:
                    selection = response_or_awaitable
            try:
                index = int(selection)
                if 0 <= index < len(self.available_models):
                    selected_model = self.available_models[index]
                    logger.info("User selected model: %s", selected_model.model_name)
                    return selected_model

            except ValueError:
                pass

            print(
                f"Invalid selection. Please enter number between 0 and "
                f"{len(self.available_models) - 1}"
            )

    async def request(
        self,
        messages: list[ModelMessage],
        model_settings: ModelSettings | None,
        model_request_parameters: ModelRequestParameters,
    ) -> ModelResponse:
        """Process request using user-selected model."""
        handler = self.handler() if isinstance(self.handler, type) else self.handler
        selected = await self._get_user_selection(messages, handler)
        return await selected.request(messages, model_settings, model_request_parameters)

    @asynccontextmanager
    async def request_stream(
        self,
        messages: list[ModelMessage],
        model_settings: ModelSettings | None,
        model_request_parameters: ModelRequestParameters,
        run_context: RunContext[Any] | None = None,
    ) -> AsyncGenerator[StreamedResponse]:
        """Stream response using user-selected model."""
        handler = self.handler() if isinstance(self.handler, type) else self.handler
        selected_model = await self._get_user_selection(messages, handler)
        async with selected_model.request_stream(
            messages,
            model_settings,
            model_request_parameters,
            run_context,
        ) as stream:
            yield stream

handler class-attribute instance-attribute

handler: ImportString[Any] = Field(
    default="llmling_models:DefaultInputHandler", validate_default=True
)

Input handler class to use.

input_prompt class-attribute instance-attribute

input_prompt: str = Field(default='Enter model number (0-{max}): ')

Prompt shown when requesting model selection.

model_name property

model_name: str

Return the model name.

prompt_template class-attribute instance-attribute

prompt_template: str = Field(default='🤖 Choose a model for: {prompt}')

Template for showing the prompt to the user.

show_system class-attribute instance-attribute

show_system: bool = Field(default=True)

Whether to show system messages.

system property

system: str

Return the system/provider name.

request async

request(
    messages: list[ModelMessage],
    model_settings: ModelSettings | None,
    model_request_parameters: ModelRequestParameters,
) -> ModelResponse

Process request using user-selected model.

Source code in src/llmling_models/models/userselect.py
async def request(
    self,
    messages: list[ModelMessage],
    model_settings: ModelSettings | None,
    model_request_parameters: ModelRequestParameters,
) -> ModelResponse:
    """Process request using user-selected model."""
    handler = self.handler() if isinstance(self.handler, type) else self.handler
    selected = await self._get_user_selection(messages, handler)
    return await selected.request(messages, model_settings, model_request_parameters)

request_stream async

request_stream(
    messages: list[ModelMessage],
    model_settings: ModelSettings | None,
    model_request_parameters: ModelRequestParameters,
    run_context: RunContext[Any] | None = None,
) -> AsyncGenerator[StreamedResponse]

Stream response using user-selected model.

Source code in src/llmling_models/models/userselect.py
@asynccontextmanager
async def request_stream(
    self,
    messages: list[ModelMessage],
    model_settings: ModelSettings | None,
    model_request_parameters: ModelRequestParameters,
    run_context: RunContext[Any] | None = None,
) -> AsyncGenerator[StreamedResponse]:
    """Stream response using user-selected model."""
    handler = self.handler() if isinstance(self.handler, type) else self.handler
    selected_model = await self._get_user_selection(messages, handler)
    async with selected_model.request_stream(
        messages,
        model_settings,
        model_request_parameters,
        run_context,
    ) as stream:
        yield stream

function_to_model

function_to_model(callback: Callable[..., Any], streamable: bool = True) -> FunctionModel

Factory to get a text model for Callables with "simpler" signatures.

This function serves as a helper to allow creating FunctionModels which take either no arguments or a single argument in form of a prompt.

Source code in src/llmling_models/models/function_to_model.py
def function_to_model(
    callback: Callable[..., Any],
    streamable: bool = True,
) -> FunctionModel:
    """Factory to get a text model for Callables with "simpler" signatures.

    This function serves as a helper to allow creating FunctionModels which take either
    no arguments or a single argument in form of a prompt.
    """
    sig = inspect.signature(callback)
    # Count required parameters (those without defaults)
    required_params = sum(
        1 for param in sig.parameters.values() if param.default is inspect.Parameter.empty
    )
    takes_prompt = required_params > 0

    @functools.wraps(callback)
    async def callback_wrapper(
        messages: list[ModelMessage], agent_info: AgentInfo
    ) -> ModelResponse:
        try:
            if takes_prompt:
                prompt = format_part(messages[-1].parts[-1])
                if inspect.iscoroutinefunction(callback):
                    result = await callback(prompt)
                else:
                    result = callback(prompt)
            elif inspect.iscoroutinefunction(callback):
                result = await callback()
            else:
                result = callback()

            if isinstance(result, str):
                part: ModelResponsePart = TextPart(result)
            # For structured responses, check if agent expects structured output
            elif agent_info.allow_text_output:
                # Agent expects text - serialize the structured result

                serialized = (
                    anyenv.dump_json(result.model_dump())
                    if isinstance(result, BaseModel)
                    else str(result)
                )
                part = TextPart(serialized)
            else:
                # Agent expects structured output - return as ToolCallPart
                part = ToolCallPart(tool_name="final_result", args=result.model_dump())
            return ModelResponse(parts=[part])
        except Exception as e:
            logger.exception("Processor callback failed")
            name = getattr(callback, "__name__", str(callback))
            msg = f"Processor error in {name!r}: {e}"
            raise RuntimeError(msg) from e

    async def stream_function(
        messages: list[ModelMessage], agent_info: AgentInfo
    ) -> AsyncIterator[str | DeltaToolCalls | DeltaThinkingCalls | BuiltinToolCallsReturns]:
        result = await callback_wrapper(messages, agent_info)
        part = result.parts[0]
        match part:
            case TextPart():
                yield part.content
            case ToolCallPart():
                args_json = anyenv.dump_json(part.args) if part.args else "{}"
                yield {0: DeltaToolCall(name=part.tool_name, json_args=args_json)}
            case _:
                msg = f"Unexpected part type: {type(part)}"
                raise ValueError(msg)

    kwargs: dict[str, Any] = {"stream_function": stream_function} if streamable else {}
    return FunctionModel(function=callback_wrapper, **kwargs)

infer_model

infer_model(model: str | Model) -> Model

Extended infer_model from pydantic-ai with fallback support.

For fallback models, use comma-separated model names. Example: "openai:gpt-4,openai:gpt-3.5-turbo"

Source code in src/llmling_models/models/helpers.py
def infer_model(model: str | Model) -> Model:
    """Extended infer_model from pydantic-ai with fallback support.

    For fallback models, use comma-separated model names.
    Example: "openai:gpt-4,openai:gpt-3.5-turbo"
    """
    from pydantic_ai.models.fallback import FallbackModel

    # If model is already a Model instance or something else not string
    if not isinstance(model, str):
        return model

    # Check for comma-separated model list (fallback case)
    if "," in model:
        model_names = [name.strip() for name in model.split(",")]
        if len(model_names) <= 1:
            # Shouldn't happen with the comma check, but just to be safe
            return _infer_single_model(model)

        # Create fallback model chain
        default_model = _infer_single_model(model_names[0])
        fallback_models = [_infer_single_model(m) for m in model_names[1:]]
        return FallbackModel(default_model, *fallback_models)

    # Regular single model case
    return _infer_single_model(model)