Skip to content

Creating a Custom Model Provider

When Strands Agents doesn’t ship a provider for the model you want to run, implement the Model interface yourself. A custom model provider connects any LLM service to the agent loop while keeping the integration private to your codebase.

To connect your model service to the agent loop, extend the abstract Model class. Your provider converts conversation messages, the system prompt, and tool specifications into requests for your model API. It converts the API’s responses into Strands Agents streaming events.

The agent loop consumes those events to assemble the response and run requested tools.

The interface is the same in both SDKs:

Extend the Model class from strands.models and implement its abstract methods:

  • stream(): Handle model invocation and yield streaming events. Implement it as an async generator that yields StreamEvent objects.
  • update_config(): Update the model configuration.
  • get_config(): Return the current model configuration.
  • structured_output(): Produce a schema-validated response, yielding model events with the last event holding the structured output.

The base class also provides optional methods you can override:

  • count_tokens(): Estimate input token count (defaults to a character-based heuristic).
  • estimate_utilization(): Compute the ratio of input tokens to context_window_limit (defaults to 200,000 when not configured). See Utilization Estimation.

Create a new module in your codebase that extends the Strands Agents Model class.

Define a ModelConfig TypedDict to hold the settings for invoking your model.

your_org/models/custom_model.py
import logging
import os
from typing import Any, AsyncIterable, Optional, TypedDict
from typing_extensions import Unpack, override
from custom.model import CustomModelClient
from strands.models import Model
from strands.types.content import Messages
from strands.types.streaming import StreamEvent
from strands.types.tools import ToolSpec
logger = logging.getLogger(__name__)
class CustomModel(Model):
"""Your custom model provider implementation."""
class ModelConfig(TypedDict):
"""
Configuration your model.
Attributes:
model_id: ID of Custom model.
params: Model parameters (e.g., max_tokens).
"""
model_id: str
params: Optional[dict[str, Any]]
# Add any additional configuration parameters specific to your model
def __init__(
self,
api_key: str,
*,
**model_config: Unpack[ModelConfig]
) -> None:
"""Initialize provider instance.
Args:
api_key: The API key for connecting to your Custom model.
**model_config: Configuration options for Custom model.
"""
self.config = CustomModel.ModelConfig(**model_config)
logger.debug("config=<%s> | initializing", self.config)
self.client = CustomModelClient(api_key)
@override
def update_config(self, **model_config: Unpack[ModelConfig]) -> None:
"""Update the Custom model configuration with the provided arguments.
Can be invoked by tools to dynamically alter the model state for subsequent invocations by the agent.
Args:
**model_config: Configuration overrides.
"""
self.config.update(model_config)
@override
def get_config(self) -> ModelConfig:
"""Get the Custom model configuration.
Returns:
The Custom model configuration.
"""
return self.config

stream() is the single entry point for every model interaction: it formats the request, invokes the model, and yields the response as it streams back.

The stream method accepts three parameters:

  • Messages: A list of Strands Agents messages, containing a Role and a list of ContentBlocks.
  • list[ToolSpec]: List of tool specifications that the model can decide to use.
  • SystemPrompt: A system prompt string given to the Model to prompt it how to answer the user.
@override
async def stream(
self,
messages: Messages,
tool_specs: Optional[list[ToolSpec]] = None,
system_prompt: Optional[str] = None,
**kwargs: Any
) -> AsyncIterable[StreamEvent]:
"""Stream responses from the Custom model.
Args:
messages: List of conversation messages
tool_specs: Optional list of available tools
system_prompt: Optional system prompt
**kwargs: Additional keyword arguments for future extensibility
Returns:
Iterator of StreamEvent objects
"""
logger.debug("messages=<%s> tool_specs=<%s> system_prompt=<%s> | formatting request",
messages, tool_specs, system_prompt)
# Format the request for your model API
request = {
"messages": messages,
"tools": tool_specs,
"system_prompt": system_prompt,
**self.config, # Include model configuration
}
logger.debug("request=<%s> | invoking model", request)
# Invoke your model
try:
response = await self.client(**request)
except OverflowException as e:
raise ContextWindowOverflowException() from e
logger.debug("response received | processing stream")
# Process and yield streaming events
# If your model doesn't return a MessageStart event, create one
yield {
"messageStart": {
"role": "assistant"
}
}
# Process each chunk from your model's response
async for chunk in response["stream"]:
# Convert your model's event format to Strands Agents StreamEvent
if chunk.get("type") == "text_delta":
yield {
"contentBlockDelta": {
"delta": {
"text": chunk.get("text", "")
}
}
}
elif chunk.get("type") == "message_stop":
yield {
"messageStop": {
"stopReason": "end_turn"
}
}
logger.debug("stream processing complete")

For more complex implementations, you may want to create helper methods to organize your code:

def _format_request(
self,
messages: Messages,
tool_specs: Optional[list[ToolSpec]] = None,
system_prompt: Optional[str] = None
) -> dict[str, Any]:
"""Optional helper method to format requests for your model API."""
return {
"messages": messages,
"tools": tool_specs,
"system_prompt": system_prompt,
**self.config,
}
def _format_chunk(self, event: Any) -> Optional[StreamEvent]:
"""Optional helper method to format your model's response events."""
if event.get("type") == "text_delta":
return {
"contentBlockDelta": {
"delta": {
"text": event.get("text", "")
}
}
}
elif event.get("type") == "message_stop":
return {
"messageStop": {
"stopReason": "end_turn"
}
}
return None

Note: stream must be implemented async. If your client does not support async invocation, you may consider wrapping the relevant calls in a thread so as not to block the async event loop. For an example on how to achieve this, you can check out the BedrockModel provider implementation.

Your custom model provider needs to convert your model’s response events to Strands Agents streaming event format.

Events use the dictionary-based StreamEvent format:

  • messageStart: Event signaling the start of a message in a streaming response. This should have the role: assistant
{
"messageStart": {
"role": "assistant"
}
}
{
"contentBlockStart": {
"start": {
"name": "someToolName", # Only include name and toolUseId if this is the start of a ToolUseContentBlock
"toolUseId": "uniqueToolUseId"
}
}
}
  • contentBlockDelta: Event continuing a content block. This event can be sent several times, and each piece of content will be appended to the previously sent content.
{
"contentBlockDelta": {
"delta": { # Only include one of the following keys in each event
"text": "Some text", # String response from a model
"reasoningContent": { # Dictionary representing the reasoning of a model.
"redactedContent": b"Some encrypted bytes",
"signature": "verification token",
"text": "Some reasoning text"
},
"toolUse": { # Dictionary representing a toolUse request. This is a partial json string.
"input": "Partial json serialized response"
}
}
}
}
{
"contentBlockStop": {}
}
  • messageStop: Event marking the end of a streamed response, and the StopReason. No more content block events are expected after this event is returned.
{
"messageStop": {
"stopReason": "end_turn"
}
}
  • metadata: Event representing the metadata of the response. This contains the input, output, and total token count, along with the latency of the request.
{
"metrics": {
"latencyMs": 123 # Latency of the model request in milliseconds.
},
"usage": {
"inputTokens": 234, # Number of tokens sent in the request to the model.
"outputTokens": 234, # Number of tokens that the model generated for the request.
"totalTokens": 468 # Total number of tokens (input + output).
}
}
  • redactContent: Event that is used to redact the users input message, or the generated response of a model. This is useful for redacting content if a guardrail gets triggered.
{
"redactContent": {
"redactUserContentMessage": "User input Redacted",
"redactAssistantContentMessage": "Assistant output Redacted"
}
}

Once implemented, you can use your custom model provider in your applications for regular agent invocation:

from strands import Agent
from your_org.models.custom_model import CustomModel
# Initialize your custom model provider
custom_model = CustomModel(
api_key="your-api-key",
model_id="your-model-id",
params={
"max_tokens": 2000,
"temperature": 0.7,
},
)
# Create a Strands agent using your model
agent = Agent(model=custom_model)
# Use the agent as usual
response = agent("Hello, how are you today?")

Strands Agents uses a structured message format with role and content fields; your model API likely expects a different shape. Convert Strands Agents’ Messages, ToolSpec, and SystemPrompt types to your API’s format on the way in, and convert the API’s streaming response back into StreamEvents on the way out. Both conversions belong in stream().

If your model API supports tool calling, format the tool specifications in stream(), emit the tool-use stream events during response processing, and format tool calls and results in your message conversion.

Map your API’s failures onto the SDK’s exceptions so the agent loop can react. Handle context window overflows (raise ContextWindowOverflowException), connection errors, authentication failures, rate limits, and malformed responses.