Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(tool_choice): print warning only once for deprecated tool_choice argument (#950)
qbc28547e7c8367
diff --git a/src/agentscope/__init__.py b/src/agentscope/__init__.pyindex 02075757e..a7d0097d7 100644--- a/src/agentscope/__init__.py+++ b/src/agentscope/__init__.py@@ -3,6 +3,7 @@# pylint: disable=wrong-import-position"""The agentscope serialization module"""import os+import warningsfrom contextvars import ContextVarfrom datetime import datetime@@ -63,6 +64,9 @@ from ._logging import (from .hooks import _equip_as_studio_hooksfrom ._version import __version__+# Raise each warning only once+warnings.filterwarnings("once", category=DeprecationWarning)+def init(project: str | None = None,diff --git a/src/agentscope/agent/_react_agent.py b/src/agentscope/agent/_react_agent.pyindex d1569c588..e52b2aec4 100644--- a/src/agentscope/agent/_react_agent.py+++ b/src/agentscope/agent/_react_agent.py@@ -189,7 +189,7 @@ class ReActAgent(ReActAgentBase):self.plan_notebook = plan_notebook# When enable_meta_tool is True, plan tools are in plan_related# group and active by agent.- # Otherwise, plan tools in bassic group and always active.+ # Otherwise, plan tools in basic group and always active.if enable_meta_tool:self.toolkit.create_tool_group("plan_related",@@ -267,7 +267,7 @@ class ReActAgent(ReActAgentBase):await self._retrieve_from_knowledge(msg)# Control if LLM generates tool calls in each reasoning step- tool_choice: Literal["auto", "none", "any", "required"] | None = None+ tool_choice: Literal["auto", "none", "required"] | None = None# -------------- Structured output management --------------self._required_structured_model = structured_model@@ -392,7 +392,7 @@ class ReActAgent(ReActAgentBase):async def _reasoning(self,- tool_choice: Literal["auto", "none", "any", "required"] | None = None,+ tool_choice: Literal["auto", "none", "required"] | None = None,) -> Msg:"""Perform the reasoning process."""if self.plan_notebook:diff --git a/src/agentscope/model/_anthropic_model.py b/src/agentscope/model/_anthropic_model.pyindex a9bc28629..31e89fd11 100644--- a/src/agentscope/model/_anthropic_model.py+++ b/src/agentscope/model/_anthropic_model.py@@ -1,7 +1,7 @@# -*- coding: utf-8 -*-# pylint: disable=too-many-branches, too-many-statements"""The Anthropic API model classes."""-+import warningsfrom datetime import datetimefrom typing import (Any,@@ -128,9 +128,7 @@ class AnthropicChatModel(ChatModelBase):self,messages: list[dict[str, Any]],tools: list[dict] | None = None,- tool_choice: Literal["auto", "none", "any", "required"]- | str- | None = None,+ tool_choice: Literal["auto", "none", "required"] | str | None = None,structured_model: Type[BaseModel] | None = None,**generate_kwargs: Any,) -> ChatResponse | AsyncGenerator[ChatResponse, None]:@@ -168,10 +166,10 @@ class AnthropicChatModel(ChatModelBase):# More schemas here]- tool_choice (`Literal["auto", "none", "any", "required"] | str \+ tool_choice (`Literal["auto", "none", "required"] | str \| None`, default `None`):Controls which (if any) tool is called by the model.- Can be "auto", "none", "any", "required", or specific tool+ Can be "auto", "none", "required", or specific toolname. For more details, please refer tohttps://docs.anthropic.com/en/docs/agents-and-tools/tool-use/implement-tool-usestructured_model (`Type[BaseModel] | None`, default `None`):@@ -210,6 +208,14 @@ class AnthropicChatModel(ChatModelBase):kwargs["tools"] = self._format_tools_json_schemas(tools)if tool_choice:+ # Handle deprecated "any" option with warning+ if tool_choice == "any":+ warnings.warn(+ '"any" is deprecated and will be removed in a future '+ "version.",+ DeprecationWarning,+ )+ tool_choice = "required"self._validate_tool_choice(tool_choice, tools)kwargs["tool_choice"] = self._format_tool_choice(tool_choice)@@ -503,15 +509,15 @@ class AnthropicChatModel(ChatModelBase):def _format_tool_choice(self,- tool_choice: Literal["auto", "none", "any", "required"] | str | None,+ tool_choice: Literal["auto", "none", "required"] | str | None,) -> dict | None:"""Format tool_choice parameter for API compatibility.Args:- tool_choice (`Literal["auto", "none", "any", "required"] | str \+ tool_choice (`Literal["auto", "none", "required"] | str \| None`, default `None`):Controls which (if any) tool is called by the model.- Can be "auto", "none", "any", "required", or specific tool+ Can be "auto", "none", "required", or specific toolname. For more details, please refer tohttps://docs.anthropic.com/en/docs/agents-and-tools/tool-use/implement-tool-useReturns:@@ -525,7 +531,6 @@ class AnthropicChatModel(ChatModelBase):type_mapping = {"auto": {"type": "auto"},"none": {"type": "none"},- "any": {"type": "any"},"required": {"type": "any"},}if tool_choice in type_mapping:diff --git a/src/agentscope/model/_dashscope_model.py b/src/agentscope/model/_dashscope_model.pyindex 8e404a9f7..c17a08e70 100644--- a/src/agentscope/model/_dashscope_model.py+++ b/src/agentscope/model/_dashscope_model.py@@ -1,6 +1,7 @@# -*- coding: utf-8 -*-"""The dashscope API model classes."""import collections+import warningsfrom datetime import datetimefrom http import HTTPStatusfrom typing import (@@ -104,9 +105,7 @@ class DashScopeChatModel(ChatModelBase):self,messages: list[dict[str, Any]],tools: list[dict] | None = None,- tool_choice: Literal["auto", "none", "any", "required"]- | str- | None = None,+ tool_choice: Literal["auto", "none", "required"] | str | None = None,structured_model: Type[BaseModel] | None = None,**kwargs: Any,) -> ChatResponse | AsyncGenerator[ChatResponse, None]:@@ -123,10 +122,12 @@ class DashScopeChatModel(ChatModelBase):required.tools (`list[dict] | None`, default `None`):The tools JSON schemas that the model can use.- tool_choice (`Literal["auto", "none", "any", "required"] | str \+ tool_choice (`Literal["auto", "none", "required"] | str \| None`, default `None`):Controls which (if any) tool is called by the model.- Can be "auto", "none", or specific tool name.+ Can be "auto", "none", "required", or specific tool name.+ Note: DashScope API only supports "auto" and "none", so+ "required" will be converted to "auto".For more details, please refer tohttps://help.aliyun.com/zh/model-studio/qwen-function-callingstructured_model (`Type[BaseModel] | None`, default `None`):@@ -176,6 +177,15 @@ class DashScopeChatModel(ChatModelBase):kwargs["tools"] = self._format_tools_json_schemas(tools)if tool_choice:+ # Handle deprecated "any" option with warning+ if tool_choice in ["any", "required"]:+ warnings.warn(+ f"'{tool_choice}' is not supported by DashScope API. "+ "It will be converted to 'auto'.",+ DeprecationWarning,+ )+ tool_choice = "auto"+self._validate_tool_choice(tool_choice, tools)kwargs["tool_choice"] = self._format_tool_choice(tool_choice)@@ -496,17 +506,17 @@ class DashScopeChatModel(ChatModelBase):def _format_tool_choice(self,- tool_choice: Literal["auto", "none", "any", "required"] | str | None,+ tool_choice: Literal["auto", "none", "required"] | str | None,) -> str | dict | None:"""Format tool_choice parameter for API compatibility.Args:- tool_choice (`Literal["auto", "none", "any", "required"] | str \+ tool_choice (`Literal["auto", "none", "required"] | str \| None`, default `None`):- Controls which (if any) tool is called by the model.- Can be "auto", "none", or specific tool name.- For more details, please refer to- https://help.aliyun.com/zh/model-studio/qwen-function-calling+ Controls which (if any) tool is called by the model. For more+ details, please refer to+ https://help.aliyun.com/zh/model-studio/qwen-function-calling+Returns:`dict | None`:The formatted tool choice configuration dict, or None if@@ -516,12 +526,6 @@ class DashScopeChatModel(ChatModelBase):return Noneif tool_choice in ["auto", "none"]:return tool_choice- if tool_choice in ["any", "required"]:- logger.warning(- "tool_choice '%s' is not supported by DashScope API. "- "Supported options are 'auto', 'none', or specific function "- "name. Automatically using 'auto' instead.",- tool_choice,- )+ if tool_choice == "required":return "auto"return {"type": "function", "function": {"name": tool_choice}}diff --git a/src/agentscope/model/_gemini_model.py b/src/agentscope/model/_gemini_model.pyindex 285fb6375..1910ddebf 100644--- a/src/agentscope/model/_gemini_model.py+++ b/src/agentscope/model/_gemini_model.py@@ -1,6 +1,7 @@# -*- coding: utf-8 -*-# mypy: disable-error-code="dict-item""""The Google Gemini model in agentscope."""+import warningsfrom datetime import datetimefrom typing import (AsyncGenerator,@@ -120,9 +121,7 @@ class GeminiChatModel(ChatModelBase):self,messages: list[dict],tools: list[dict] | None = None,- tool_choice: Literal["auto", "none", "any", "required"]- | str- | None = None,+ tool_choice: Literal["auto", "none", "required"] | str | None = None,structured_model: Type[BaseModel] | None = None,**config_kwargs: Any,) -> ChatResponse | AsyncGenerator[ChatResponse, None]:@@ -134,11 +133,11 @@ class GeminiChatModel(ChatModelBase):required.tools (`list[dict] | None`, default `None`):The tools JSON schemas that the model can use.- tool_choice (`Literal["auto", "none", "any", "required"] | str \+ tool_choice (`Literal["auto", "none", "required"] | str \| None`, default `None`):Controls which (if any) tool is called by the model.- Can be "auto", "none", "any", "required", or specific tool- name. For more details, please refer to+ Can be "auto", "none", "required", or specific tool name.+ For more details, please refer tohttps://ai.google.dev/gemini-api/docs/function-calling?hl=en&example=meeting#function_calling_modesstructured_model (`Type[BaseModel] | None`, default `None`):A Pydantic BaseModel class that defines the expected structure@@ -166,6 +165,14 @@ class GeminiChatModel(ChatModelBase):config["tools"] = self._format_tools_json_schemas(tools)if tool_choice:+ # Handle deprecated "any" option with warning+ if tool_choice == "any":+ warnings.warn(+ '"any" is deprecated and will be removed in a future '+ "version.",+ DeprecationWarning,+ )+ tool_choice = "required"self._validate_tool_choice(tool_choice, tools)config["tool_config"] = self._format_tool_choice(tool_choice)@@ -478,16 +485,15 @@ class GeminiChatModel(ChatModelBase):def _format_tool_choice(self,- tool_choice: Literal["auto", "none", "any", "required"] | str | None,+ tool_choice: Literal["auto", "none", "required"] | str | None,) -> dict | None:"""Format tool_choice parameter for API compatibility.Args:- tool_choice (`Literal["auto", "none"] | str | None`, default \- `None`):+ tool_choice (`Literal["auto", "none", "required"] | str | None`, \+ default `None`):Controls which (if any) tool is called by the model.- Can be "auto", "none", "any", "required", or specific tool- name.+ Can be "auto", "none", "required", or specific tool name.For more details, please refer tohttps://ai.google.dev/gemini-api/docs/function-calling?hl=en&example=meeting#function_calling_modesReturns:@@ -501,7 +507,6 @@ class GeminiChatModel(ChatModelBase):mode_mapping = {"auto": "AUTO","none": "NONE",- "any": "ANY","required": "ANY",}mode = mode_mapping.get(tool_choice)diff --git a/src/agentscope/model/_model_base.py b/src/agentscope/model/_model_base.pyindex d615dc3dc..ff2503cad 100644--- a/src/agentscope/model/_model_base.py+++ b/src/agentscope/model/_model_base.py@@ -6,7 +6,8 @@ from typing import AsyncGenerator, Anyfrom ._model_response import ChatResponse-TOOL_CHOICE_MODES = ["auto", "none", "any", "required"]++_TOOL_CHOICE_MODES = ["auto", "none", "required"]class ChatModelBase:@@ -63,13 +64,13 @@ class ChatModelBase:raise TypeError(f"tool_choice must be str, got {type(tool_choice)}",)- if tool_choice in TOOL_CHOICE_MODES:+ if tool_choice in _TOOL_CHOICE_MODES:returnavailable_functions = [tool["function"]["name"] for tool in tools]if tool_choice not in available_functions:- all_options = TOOL_CHOICE_MODES + available_functions+ all_options = _TOOL_CHOICE_MODES + available_functionsraise ValueError(f"Invalid tool_choice '{tool_choice}'. "f"Available options: {', '.join(sorted(all_options))}",diff --git a/src/agentscope/model/_ollama_model.py b/src/agentscope/model/_ollama_model.pyindex f82bdcf9d..fe5307309 100644--- a/src/agentscope/model/_ollama_model.py+++ b/src/agentscope/model/_ollama_model.py@@ -101,9 +101,7 @@ class OllamaChatModel(ChatModelBase):self,messages: list[dict[str, Any]],tools: list[dict] | None = None,- tool_choice: Literal["auto", "none", "any", "required"]- | str- | None = None,+ tool_choice: Literal["auto", "none", "required"] | str | None = None,structured_model: Type[BaseModel] | None = None,**kwargs: Any,) -> ChatResponse | AsyncGenerator[ChatResponse, None]:@@ -116,11 +114,9 @@ class OllamaChatModel(ChatModelBase):required, and `name` field is optional.tools (`list[dict]`, default `None`):The tools JSON schemas that the model can use.- tool_choice (`Literal["auto", "none", "any", "required"] | str \+ tool_choice (`Literal["auto", "none", "required"] | str \| None`, default `None`):- Controls which (if any) tool is called by the model.- Can be "auto", "none", "any", "required", or specific tool- name.+ Ollama doesn't support `tool_choice` argument yet.structured_model (`Type[BaseModel] | None`, default `None`):A Pydantic BaseModel class that defines the expected structurefor the model's output.diff --git a/src/agentscope/model/_openai_model.py b/src/agentscope/model/_openai_model.pyindex e7f0b4813..bd6c6bca4 100644--- a/src/agentscope/model/_openai_model.py+++ b/src/agentscope/model/_openai_model.py@@ -1,6 +1,7 @@# -*- coding: utf-8 -*-# pylint: disable=too-many-branches"""OpenAI Chat model class."""+import warningsfrom datetime import datetimefrom typing import (Any,@@ -147,9 +148,7 @@ class OpenAIChatModel(ChatModelBase):self,messages: list[dict],tools: list[dict] | None = None,- tool_choice: Literal["auto", "none", "any", "required"]- | str- | None = None,+ tool_choice: Literal["auto", "none", "required"] | str | None = None,structured_model: Type[BaseModel] | None = None,**kwargs: Any,) -> ChatResponse | AsyncGenerator[ChatResponse, None]:@@ -162,10 +161,10 @@ class OpenAIChatModel(ChatModelBase):required, and `name` field is optional.tools (`list[dict]`, default `None`):The tools JSON schemas that the model can use.- tool_choice (`Literal["auto", "none", "any", "required"] | str \+ tool_choice (`Literal["auto", "none", "required"] | str \| None`, default `None`):Controls which (if any) tool is called by the model.- Can be "auto", "none", "any", "required", or specific tool+ Can be "auto", "none", "required", or specific toolname. For more details, please refer tohttps://platform.openai.com/docs/api-reference/responses/create#responses_create-tool_choicestructured_model (`Type[BaseModel] | None`, default `None`):@@ -224,6 +223,14 @@ class OpenAIChatModel(ChatModelBase):kwargs["tools"] = self._format_tools_json_schemas(tools)if tool_choice:+ # Handle deprecated "any" option with warning+ if tool_choice == "any":+ warnings.warn(+ '"any" is deprecated and will be removed in a future '+ "version.",+ DeprecationWarning,+ )+ tool_choice = "required"self._validate_tool_choice(tool_choice, tools)kwargs["tool_choice"] = self._format_tool_choice(tool_choice)@@ -543,16 +550,16 @@ class OpenAIChatModel(ChatModelBase):def _format_tool_choice(self,- tool_choice: Literal["auto", "none", "any", "required"] | str | None,+ tool_choice: Literal["auto", "none", "required"] | str | None,) -> str | dict | None:"""Format tool_choice parameter for API compatibility.Args:- tool_choice (`Literal["auto", "none", "any", "required"] | str \+ tool_choice (`Literal["auto", "none", "required"] | str \| None`, default `None`):Controls which (if any) tool is called by the model.- Can be "auto", "none", "any", "required", or specific tool- name. For more details, please refer to+ Can be "auto", "none", "required", or specific tool name.+ For more details, please refer tohttps://platform.openai.com/docs/api-reference/responses/create#responses_create-tool_choiceReturns:`dict | None`:@@ -561,10 +568,10 @@ class OpenAIChatModel(ChatModelBase):"""if tool_choice is None:return None+mode_mapping = {"auto": "auto","none": "none",- "any": "required","required": "required",}if tool_choice in mode_mapping: