-
Notifications
You must be signed in to change notification settings - Fork 216
feat(llm): switch model profile on user message #2192
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+182
−2
Merged
Changes from 6 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
fbec87a
/model command
VascoSch92 0e254ea
fix some small issue
VascoSch92 ab6a4e4
new structure
VascoSch92 eb49ea4
rename model_info to get_profiles_info_message
VascoSch92 d4beb1b
Merge branch 'main' into command-model
VascoSch92 b088ced
Merge branch 'main' into command-model
VascoSch92 e67d28f
Merge branch 'main' into command-model
VascoSch92 4132679
new way to switch models
VascoSch92 e9ce849
Update examples/01_standalone_sdk/43_model_switching_in_convo.py
VascoSch92 dfb4179
fix after all-hands-bot review
VascoSch92 c8d8105
Merge branch 'main' into command-model
VascoSch92 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| """Interactive chat with mid-conversation model switching. | ||
|
|
||
| Usage: | ||
| uv run examples/01_standalone_sdk/41_model_switching_in_convo.py | ||
| """ | ||
|
|
||
| import os | ||
|
|
||
| from openhands.sdk import LLM, Agent, LocalConversation, Tool | ||
| from openhands.sdk.llm.llm_profile_store import LLMProfileStore | ||
| from openhands.tools.terminal import TerminalTool | ||
|
|
||
|
|
||
| LLM_API_KEY = os.getenv("LLM_API_KEY") | ||
| store = LLMProfileStore() | ||
|
|
||
| profiles: dict[str, str] = { | ||
| "kimi": "openhands/kimi-k2-0711-preview", | ||
| "deepseek": "openhands/deepseek-chat", | ||
| "gpt": "openhands/gpt-5.2", | ||
| } | ||
| for profile_name, model in profiles.items(): | ||
| store.save( | ||
| profile_name, | ||
| LLM(model=model, api_key=LLM_API_KEY), | ||
| include_secrets=True, | ||
| ) | ||
|
|
||
| llm = LLM( | ||
| model=os.getenv("LLM_MODEL", "openhands/claude-sonnet-4-5-20250929"), | ||
| api_key=LLM_API_KEY, | ||
| ) | ||
|
|
||
| agent = Agent(llm=llm, tools=[Tool(name=TerminalTool.name)]) | ||
|
|
||
| conversation = LocalConversation( | ||
| agent=agent, | ||
| workspace=os.getcwd(), | ||
| allow_model_switching=True, | ||
| ) | ||
|
|
||
| print( | ||
| "Chat with the agent. Commands:\n" | ||
| " /model — show current model and available profiles\n" # noqa: E501 | ||
| " /model <model_profile_name> — switch to a different model profile\n" | ||
| " /model <model_profile_name> [prompt] — switch and send a message in one step\n" # noqa: E501 | ||
| " /exit — quit\n" | ||
| ) | ||
|
|
||
| try: | ||
| while True: | ||
| try: | ||
| user_input = input("You: ").strip() | ||
| except (EOFError, KeyboardInterrupt): | ||
| print() | ||
| break | ||
|
|
||
| if not user_input: | ||
| continue | ||
| if user_input.lower() == "/exit": | ||
| break | ||
| conversation.send_message(user_input) | ||
| conversation.run() | ||
| except Exception: | ||
| raise | ||
| finally: | ||
| # Clean up the profiles we created | ||
| for name in profiles.keys(): | ||
| store.delete(name) | ||
|
|
||
| # Inspect metrics across all LLMs (original + switched profiles) | ||
| stats = conversation.state.stats | ||
| for usage_id, metrics in stats.usage_to_metrics.items(): | ||
| print(f" [{usage_id}] cost=${metrics.accumulated_cost:.6f}") | ||
| for usage in metrics.token_usages: | ||
| print( | ||
| f" model={usage.model}" | ||
| f" prompt={usage.prompt_tokens}" | ||
| f" completion={usage.completion_tokens}" | ||
| ) | ||
|
|
||
| combined = stats.get_combined_metrics() | ||
| print(f"\nTotal cost (all models): ${combined.accumulated_cost:.6f}") | ||
| print(f"EXAMPLE_COST: {combined.accumulated_cost}") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
86 changes: 86 additions & 0 deletions
86
openhands-sdk/openhands/sdk/conversation/switch_model_handler.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| from openhands.sdk.llm.llm_profile_store import LLMProfileStore | ||
| from openhands.sdk.llm.llm_registry import LLMRegistry | ||
| from openhands.sdk.logger import get_logger | ||
|
|
||
|
|
||
| if TYPE_CHECKING: | ||
| from openhands.sdk.agent.base import AgentBase | ||
| from openhands.sdk.llm import LLM | ||
|
|
||
| logger = get_logger(__name__) | ||
|
|
||
|
|
||
| @dataclass | ||
| class SwitchModelHandler: | ||
| """Standalone handler for /model command parsing, switching, and info.""" | ||
|
|
||
| profile_store: LLMProfileStore | ||
| llm_registry: LLMRegistry | ||
|
|
||
| @staticmethod | ||
| def parse(text: str) -> tuple[str, str | None] | None: | ||
| """Parse a /model command from user text. | ||
|
|
||
| Returns: | ||
| None if the text is not a /model command. | ||
| ("", None) for bare "/model" (info request). | ||
| ("profile_name", remaining_text_or_None) otherwise. | ||
| """ | ||
| stripped = text.strip() | ||
| if stripped == "/model": | ||
| return "", None | ||
| if not stripped.startswith("/model "): | ||
| return None | ||
| rest = stripped[len("/model ") :].strip() | ||
| if not rest: | ||
| return "", None | ||
| parts = rest.split(None, 1) | ||
| profile_name = parts[0] | ||
| remaining = parts[1] if len(parts) > 1 else None | ||
| return profile_name, remaining | ||
|
|
||
| def switch(self, agent: "AgentBase", profile_name: str) -> "AgentBase": | ||
| """Load a model profile and return a new agent with the swapped LLM. | ||
|
|
||
| The caller is responsible for storing the returned agent and updating | ||
| any external state (e.g. ConversationState). | ||
|
|
||
| Args: | ||
| agent: Current agent instance. | ||
| profile_name: Name of the profile to load from LLMProfileStore. | ||
|
|
||
| Returns: | ||
| A new AgentBase instance with the switched LLM. | ||
|
|
||
| Raises: | ||
| FileNotFoundError: If the profile does not exist. | ||
| ValueError: If the profile is corrupted or invalid. | ||
| """ | ||
| if profile_name in self.llm_registry.list_usage_ids(): | ||
| new_llm = self.llm_registry.get(profile_name) | ||
| else: | ||
| new_llm = self.profile_store.load(profile_name) | ||
| new_llm = new_llm.model_copy(update={"usage_id": profile_name}) | ||
| self.llm_registry.add(new_llm) | ||
|
|
||
| return agent.model_copy(update={"llm": new_llm}) | ||
VascoSch92 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| def get_profiles_info_message(self, llm: "LLM") -> str: | ||
| """Return a string with current model and available profiles. | ||
|
|
||
| The caller is responsible for emitting the string as an event. | ||
| """ | ||
| current_model = llm.model | ||
| stored_profiles = self.profile_store.list() | ||
| registry_profiles = self.llm_registry.list_usage_ids() | ||
| profile_names = list(set(stored_profiles).union(set(registry_profiles))) | ||
| profile_list = ( | ||
| ", ".join(sorted([Path(p).stem for p in profile_names])) | ||
| if profile_names | ||
| else "[]" | ||
| ) | ||
VascoSch92 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return f"Current model: {current_model}\nAvailable profiles: {profile_list}" | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.