Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions examples/19_llm_routing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import os

from pydantic import SecretStr

from openhands.sdk import (
LLM,
Agent,
Conversation,
EventBase,
ImageContent,
LLMConvertibleEvent,
Message,
TextContent,
get_logger,
)
from openhands.sdk.llm.router import MultimodalRouter
from openhands.sdk.preset.default import get_default_tools


logger = get_logger(__name__)

# Configure LLM
api_key = os.getenv("LITELLM_API_KEY")
assert api_key is not None, "LITELLM_API_KEY environment variable is not set."

primary_llm = LLM(
model="litellm_proxy/anthropic/claude-sonnet-4-20250514",
base_url="https://llm-proxy.eval.all-hands.dev",
api_key=SecretStr(api_key),
)
secondary_llm = LLM(
model="litellm_proxy/mistral/devstral-small-2507",
base_url="https://llm-proxy.eval.all-hands.dev",
api_key=SecretStr(api_key),
)
multimodal_router = MultimodalRouter(
llms_for_routing={"primary": primary_llm, "secondary": secondary_llm},
)

# Tools
cwd = os.getcwd()
tools = get_default_tools(working_dir=cwd) # Use our default openhands experience

# Agent
agent = Agent(llm=multimodal_router, tools=tools)

llm_messages = [] # collect raw LLM messages


def conversation_callback(event: EventBase):
if isinstance(event, LLMConvertibleEvent):
llm_messages.append(event.to_llm_message())


conversation = Conversation(agent=agent, callbacks=[conversation_callback])

conversation.send_message(
message=Message(
role="user",
content=[TextContent(text=("Hi there, who trained you?"))],
)
)
conversation.run()

conversation.send_message(
message=Message(
role="user",
content=[
ImageContent(
image_urls=["http://images.cocodataset.org/val2017/000000039769.jpg"]
),
TextContent(text=("What do you see in the image above?")),
],
)
)
conversation.run()

conversation.send_message(
message=Message(
role="user",
content=[TextContent(text=("Who trained you as an LLM?"))],
)
)
conversation.run()


print("=" * 100)
print("Conversation finished. Got the following LLM messages:")
for i, message in enumerate(llm_messages):
print(f"Message {i}: {str(message)[:200]}")
2 changes: 2 additions & 0 deletions openhands/sdk/llm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from openhands.sdk.llm.llm_registry import LLMRegistry, RegistryEvent
from openhands.sdk.llm.message import ImageContent, Message, TextContent, content_to_str
from openhands.sdk.llm.metadata import get_llm_metadata
from openhands.sdk.llm.router import RouterLLM
from openhands.sdk.llm.utils.metrics import Metrics, MetricsSnapshot
from openhands.sdk.llm.utils.unverified_models import (
UNVERIFIED_MODELS_EXCLUDING_BEDROCK,
Expand All @@ -13,6 +14,7 @@
__all__ = [
"LLM",
"LLMRegistry",
"RouterLLM",
"RegistryEvent",
"Message",
"TextContent",
Expand Down
10 changes: 10 additions & 0 deletions openhands/sdk/llm/router/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from openhands.sdk.llm.router.base import RouterLLM
from openhands.sdk.llm.router.impl.multimodal import MultimodalRouter
from openhands.sdk.llm.router.impl.random import RandomRouter


__all__ = [
"RouterLLM",
"RandomRouter",
"MultimodalRouter",
]
107 changes: 107 additions & 0 deletions openhands/sdk/llm/router/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
from abc import abstractmethod
from typing import Sequence

from litellm.types.utils import (
ModelResponse,
)
from pydantic import (
Field,
field_validator,
model_validator,
)

from openhands.sdk.llm.llm import LLM
from openhands.sdk.llm.message import Message
from openhands.sdk.logger import get_logger
from openhands.sdk.tool.tool import ToolBase


logger = get_logger(__name__)


class RouterLLM(LLM):
"""
Base class for multiple LLM acting as a unified LLM.
This class provides a foundation for implementing model routing by
inheriting from LLM, allowing routers to work with multiple underlying
LLM models while presenting a unified LLM interface to consumers.
Key features:
- Works with multiple LLMs configured via llms_for_routing
- Delegates all other operations/properties to the selected LLM
- Provides routing interface through select_llm() method
"""

router_name: str = Field(default="base_router", description="Name of the router")
llms_for_routing: dict[str, LLM] = Field(
default_factory=dict
) # Mapping of LLM name to LLM instance for routing
active_llm: LLM | None = Field(
default=None, description="Currently selected LLM instance"
)

@field_validator("llms_for_routing")
@classmethod
def validate_llms_not_empty(cls, v):
if not v:
raise ValueError(
"llms_for_routing cannot be empty - at least one LLM must be provided"
)
return v

def completion(
self,
messages: list[Message],
tools: Sequence[ToolBase] | None = None,
return_metrics: bool = False,
add_security_risk_prediction: bool = False,
**kwargs,
) -> ModelResponse:
"""
This method intercepts completion calls and routes them to the appropriate
underlying LLM based on the routing logic implemented in select_llm().
"""
# Select appropriate LLM
selected_model = self.select_llm(messages)
self.active_llm = self.llms_for_routing[selected_model]

logger.info(f"RouterLLM routing to {selected_model}...")

# Delegate to selected LLM
return self.active_llm.completion(
messages=messages,
tools=tools,
return_metrics=return_metrics,
add_security_risk_prediction=add_security_risk_prediction,
**kwargs,
)

@abstractmethod
def select_llm(self, messages: list[Message]) -> str:
"""
Select which LLM to use based on messages and events.
"""
pass

def __getattr__(self, name):
"""Delegate other attributes/methods to the active LLM."""
fallback_llm = next(iter(self.llms_for_routing.values()))
logger.info(f"RouterLLM: No active LLM, using first LLM for attribute '{name}'")
return getattr(fallback_llm, name)

def __str__(self) -> str:
"""String representation of the router."""
return f"{self.__class__.__name__}(llms={list(self.llms_for_routing.keys())})"

@model_validator(mode="before")
@classmethod
def set_placeholder_model(cls, data):
"""Guarantee `model` exists before LLM base validation runs."""
if not isinstance(data, dict):
return data
d = dict(data)

# In router, we don't need a model name to be specified
if "model" not in d or not d["model"]:
d["model"] = d.get("router_name", "router")

return d
76 changes: 76 additions & 0 deletions openhands/sdk/llm/router/impl/multimodal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
from typing import ClassVar

from pydantic import model_validator

from openhands.sdk.llm.message import Message
from openhands.sdk.llm.router.base import RouterLLM
from openhands.sdk.logger import get_logger


logger = get_logger(__name__)


class MultimodalRouter(RouterLLM):
"""
A RouterLLM implementation that routes requests based on multimodal content
(e.g., images) and token limits. If any message contains multimodal content
or if the token limit of the secondary model is exceeded, it routes to the
primary model. Otherwise, it routes to the secondary model.

Note: The primary model is expected to support multimodal content, while
the secondary model is typically a text-only model with a lower context window.
"""

router_name: str = "multimodal_router"

PRIMARY_MODEL_KEY: ClassVar[str] = "primary"
SECONDARY_MODEL_KEY: ClassVar[str] = "secondary"

def select_llm(self, messages: list[Message]) -> str:
"""Select LLM based on multimodal content and token limits."""
route_to_primary = False

# Check for multimodal content in messages
for message in messages:
if message.contains_image:
logger.info(
"Multimodal content detected in messages. "
"Routing to the primary model."
)
route_to_primary = True

# Check if `messages` exceeds context window of the secondary model
# Assuming the secondary model has a lower context window limit
# compared to the primary model
secondary_llm = self.llms_for_routing.get(self.SECONDARY_MODEL_KEY)
if secondary_llm and (
secondary_llm.max_input_tokens
and secondary_llm.get_token_count(messages) > secondary_llm.max_input_tokens
):
logger.warning(
f"Messages having {secondary_llm.get_token_count(messages)} tokens, exceeded secondary model's max input tokens ({secondary_llm.max_input_tokens} tokens). " # noqa: E501
"Routing to the primary model."
)
route_to_primary = True

if route_to_primary:
logger.info("Routing to the primary model...")
return self.PRIMARY_MODEL_KEY
else:
logger.info("Routing to the secondary model...")
return self.SECONDARY_MODEL_KEY

@model_validator(mode="after")
def _validate_llms_for_routing(self) -> "MultimodalRouter":
"""Ensure required models are present in llms_for_routing."""
if self.PRIMARY_MODEL_KEY not in self.llms_for_routing:
raise ValueError(
f"Primary LLM key '{self.PRIMARY_MODEL_KEY}' not found"
" in llms_for_routing."
)
if self.SECONDARY_MODEL_KEY not in self.llms_for_routing:
raise ValueError(
f"Secondary LLM key '{self.SECONDARY_MODEL_KEY}' not found"
" in llms_for_routing."
)
return self
22 changes: 22 additions & 0 deletions openhands/sdk/llm/router/impl/random.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import random

from openhands.sdk.llm.message import Message
from openhands.sdk.llm.router.base import RouterLLM
from openhands.sdk.logger import get_logger


logger = get_logger(__name__)


class RandomRouter(RouterLLM):
"""
A simple implementation of RouterLLM that randomly selects an LLM from
llms_for_routing for each completion request.
"""

router_name: str = "random_router"

def select_llm(self, messages: list[Message]) -> str:
selected_llm_name = random.choice(list(self.llms_for_routing.keys()))
logger.info(f"Randomly selected LLM: {selected_llm_name}")
return selected_llm_name