Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(rl): support RL training by adding a `tune` module in agentscope (#816)
Xuchen Pan9f018b6db8e3
diff --git a/README.md b/README.mdindex 9a696b8f5..602f29d1b 100644--- a/README.md+++ b/README.md@@ -393,7 +393,8 @@ as_studio- [Multi-agent Concurrent](https://github.com/agentscope-ai/agentscope/tree/main/examples/workflows/multiagent_concurrent)- Evaluation- [ACEBench](https://github.com/agentscope-ai/agentscope/tree/main/examples/evaluation/ace_bench)-+ - Training+ - [Reinforcement learning (RL) with Trinity-RFT](https://github.com/agentscope-ai/agentscope/tree/main/examples/training/react_agent)## ⚖️ Licensediff --git a/README_zh.md b/README_zh.mdindex cf86a575c..84653a794 100644--- a/README_zh.md+++ b/README_zh.md@@ -395,6 +395,8 @@ as_studio- [多智能体并发](https://github.com/agentscope-ai/agentscope/tree/main/examples/workflows/multiagent_concurrent)- 评测- [ACEBench](https://github.com/agentscope-ai/agentscope/tree/main/examples/evaluation/ace_bench)+ - 训练+ - [使用 Trinity-RFT 进行强化学习训练](https://github.com/agentscope-ai/agentscope/tree/main/examples/training/react_agent)## ⚖️ 许可diff --git a/examples/training/react_agent/README.md b/examples/training/react_agent/README.mdnew file mode 100644index 000000000..57db3257b--- /dev/null+++ b/examples/training/react_agent/README.md@@ -0,0 +1,240 @@+# Training agent workflows with RL using Trinity-RFT++AgentScope exposes a `tune` interface to train agent workflows using reinforcement learning (RL).+The `tune` interface leverages [Trinity-RFT](https://github.com/modelscope/Trinity-RFT), which supports training agents with minimal code changes.++---++## How to implement++Here we use a math problem solving scenario as an example to illustrate how to convert an existing agent workflow into a trainable workflow function.++Suppose you have an agent workflow that solves math problems using the `ReActAgent`++```python+from agentscope.agent import ReActAgent++async def run_react_agent():+ # model = ... # Initialize your ChatModel here++ query = "What is the sum of the first 10 prime numbers?"+ agent = ReActAgent(+ name="react_agent",+ sys_prompt="You are a helpful math problem solving agent.",+ model=model,+ enable_meta_tool=True,+ formatter=OpenAIChatFormatter(),+ )++ response = await agent.reply(+ msg=Msg("user", query, role="user"),+ )++ print(response)+```++### Step 1: Define a workflow function++To train an agent workflow using RL, you need to implement a workflow function with the following signature.++```python+def workflow_function(+ task: Dict,+ model: TrinityChatModel,+) -> float:+ """Run the agent workflow on a single task and return a scalar reward."""+```++Inputs:++- `task`: A dictionary representing a single training task, converted from a sample in the training dataset. For example, in a math problem solving task, `task` may contain `question` and `answer` fields.++- `model`: A `TrinityChatModel` instance, which has the same interface as `OpenAIChatModel`, but it supports automatically converting invoke history into trainable data that can be used by Trinity-RFT.++Outputs:++- A scalar reward (float) indicating the quality of the agent's response on the given task.++### Step 2: Initialize and run the agent using the provided task and model++Since the `model` has the same interface as `OpenAIChatModel`, you can directly use it to initialize the agent.++However, the `task` dictionary is a sample from the training dataset and can vary. You need to extract the relevant fields from `task` to run the agent.++Suppose your training dataset is a `.jsonl` file with samples like:++```json+{"question": "What is 2 + 2?", "answer": "4"}+{"question": "What is 4 + 4?", "answer": "8"}+```++In this case, you can extract the `question` field from `task` to run the agent:++```python+def workflow_function(+ task: Dict,+ model: TrinityChatModel,+) -> float:+ agent = ReActAgent(+ name="react_agent",+ sys_prompt="You are a helpful math problem solving agent.",+ model=model,+ enable_meta_tool=True,+ formatter=OpenAIChatFormatter(),+ )++ response = await agent.reply(+ msg=Msg("user", task["question"], role="user"),+ )++ # further steps to calculate reward... (See Step 3)+```++### Step 3: Implement a reward calculation mechanism++To train the agent using RL, you need to define a reward calculation mechanism that computes a reward based on the agent's response.++Continuing from the previous code snippet, suppose you want to give a reward of `1.0` if the agent's answer matches the ground truth answer in `task["answer"]`, and `0.0` otherwise.++```python+def calculate_reward(answer: str, truth: str) -> float:+ """Simple reward: 1.0 for exact match, else 0.0."""+ return 1.0 if answer.strip() == truth.strip() else 0.0+```++To facilitate reward calculation, you can define a structured response model that allows easy parsing of the agent's output.++```python+from pydantic import BaseModel, Field++class ResponseStructure(BaseModel):+ """Response structure for math tasks (simplified).+ This structure let the agent output be easily parsed,+ allowing for easy reward calculation.+ """++ result: str = Field(description="Final answer to the math problem.")++# ... inside workflow_function ...+# response = await agent.reply(+# msg=Msg("user", task["question"], role="user"),+# structured_model=ResponseStructure, # <-- specify structured model here+# )+# return calculate_reward(response.metadata["result"], task["answer"])+```++### Step 4: Use `tune` to train the workflow function++Finally, you can use the `tune` interface to train the defined workflow function with a configuration file.++```python+from agentscope.tune import tune++# your workflow function here...++if __name__ == "__main__":+ tune(+ workflow_func=workflow_function,+ config_path="/path/to/your/config.yaml",+ )+```++The trained model, training dataset, RL algorithm, training cluster and other configurations are all located in the configuration file, which should follow the Trinity-RFT configuration format.++See [config.yaml](./config.yaml) for an example configuration. For full configuration details, see [Trinity-RFT Configuration Guide](https://modelscope.github.io/Trinity-RFT/en/main/tutorial/trinity_configs.html).++---++### Complete example++```python+from typing import Dict++from pydantic import BaseModel, Field++from agentscope.tune import tune+from agentscope.model import TrinityChatModel+from agentscope.agent import ReActAgent+from agentscope.formatter import OpenAIChatFormatter+from agentscope.message import Msg+++def calculate_reward(answer: str, truth: str) -> float:+ """Simple reward: 1.0 for exact match, else 0.0.++ This is a toy reward function; replace it with a more robust metric if needed.+ """++ return 1.0 if answer.strip() == truth.strip() else 0.0+++class ResponseStructure(BaseModel):+ """Response structure for math tasks (simplified).+ This structure makes the agent's output easy to parse,+ allowing for easy reward calculation.+ """++ result: str = Field(description="Final answer to the math problem.")+++async def react_workflow_function(task: Dict, model: TrinityChatModel) -> float:+ """Workflow function for ReAct agent training."""++ agent = ReActAgent(+ name="react_agent",+ sys_prompt="You are a helpful math problem solving agent.",+ model=model,+ enable_meta_tool=True,+ formatter=OpenAIChatFormatter(),+ )++ response = await agent.reply(+ msg=Msg("user", task["question"], role="user"),+ structured_model=ResponseStructure,+ )++ reward = calculate_reward(response.metadata["result"], task["answer"])+ return reward+++if __name__ == "__main__":+ tune(+ workflow_func=react_workflow_function,+ config_path="/path/to/your/config.yaml",+ )+```++> Above code is a simplified example for illustration purposes only.+> For a complete implementation, please refer to [main.py](./main.py).++---++## How to run++After implementing the workflow function, follow these steps to run the training:++1. Prerequisites++ - At least 2 NVIDIA GPUs with CUDA 12.8 or newer.+ - Adjust the configuration file ([config.yaml](./config.yaml)) based on your hardware.+ - Follow the Trinity-RFT [installation guide](https://modelscope.github.io/Trinity-RFT/en/main/tutorial/trinity_installation.html) to install the latest version from source code.+ - Download the GSM8K dataset and Qwen/Qwen3-8B model checkpoints (example):++ ```bash+ huggingface-cli download openai/gsm8k --repo-type dataset+ huggingface-cli download Qwen/Qwen3-8B+ ```++2. Set up a [Ray](https://github.com/ray-project/ray) cluster++ ```bash+ ray start --head+ # for multi-node setup, run the following command on worker nodes+ # ray start --address=<master_address>+ ```++3. Run the training script++ ```bash+ python main.py+ ```diff --git a/examples/training/react_agent/config.yaml b/examples/training/react_agent/config.yamlnew file mode 100644index 000000000..9248415f4--- /dev/null+++ b/examples/training/react_agent/config.yaml@@ -0,0 +1,65 @@+project: AgentScope-ReAct+name: GSM8K-Qwen3-8B+# directory to save checkpoints, default to ./checkpoints if TRINITY_CHECKPOINT_ROOT_DIR not set+checkpoint_root_dir: ${oc.env:TRINITY_CHECKPOINT_ROOT_DIR,./checkpoints}+algorithm:+ algorithm_type: multi_step_grpo # a GRPO-based algorithm for multi-step reasoning+ repeat_times: 8 # repeat each training sample 8 times+model:+ # path to the pre-trained model, default to Qwen/Qwen3-8B if TRINITY_MODEL_PATH not set+ # Note: The model should have ReAct capabilities, e.g., Qwen3 8B or above+ # smaller models may not perform well on complex reasoning tasks+ model_path: ${oc.env:TRINITY_MODEL_PATH,Qwen/Qwen3-8B}+ # maximum tokens generated in response+ max_response_tokens: 16384+ # maximum token length for both input and output+ # if you face OOM, try to reduce max_model_len and max_response_tokens+ max_model_len: 24576+cluster:+ node_num: 1 # cluster with 1 node+ gpu_per_node: 8 # each node has 8 GPUs+buffer:+ total_epochs: 1 # run taskset for 1 epoch+ batch_size: 32 # each step contains 32 samples from taskset+ train_batch_size: 256 # trainer batch size is 256 (multi-step reasoning generate more training samples)+ explorer_input:+ taskset: # define the taskset for rollout+ name: gsm8k+ storage_type: file+ path: 'openai/gsm8k'+ subset_name: 'main'+ split: 'train'+ format:+ prompt_key: 'question'+ response_key: 'answer'+ rollout_args:+ temperature: 1.0+explorer:+ runner_per_model: 16 # each model has 16 runners for parallel rollout+ max_timeout: 600 # max timeout for each rollout is 600 seconds+ rollout_model:+ engine_num: 4 # setup 4 vllm inference model instances+ tensor_parallel_size: 1 # each model instance uses tensor parallel size of 1+ enable_prefix_caching: false+ enforce_eager: true+ enable_openai_api: true # some parameters to provide openai-style API, don't change them+ enable_history: true+ enable_auto_tool_choice: true+ # Qwen3 series tool_call_parser and reasoning_parser, if you use other models, please adjust accordingly+ tool_call_parser: hermes+ reasoning_parser: deepseek_r1+ enable_thinking: true+ dtype: bfloat16+ seed: 42+synchronizer:+ sync_style: dynamic_by_explorer+ sync_method: 'nccl'+ sync_interval: 2+ sync_timeout: 1800 # wait for 30 minutes+trainer:+ save_interval: 100 # save checkpoint every 100 steps+ use_dynamic_bsz: true+ max_token_len_per_gpu: 24576 # if you face OOM, try to reduce this value+ ulysses_sequence_parallel_size: 2 # use sequence parallelism to reduce memory usage+monitor:+ monitor_type: tensorboard # here we use tensorboard, you can also use wandb or mlflow\ No newline at end of filediff --git a/examples/training/react_agent/main.py b/examples/training/react_agent/main.pynew file mode 100644index 000000000..4fc7308b6--- /dev/null+++ b/examples/training/react_agent/main.py@@ -0,0 +1,98 @@+# -*- coding: utf-8 -*-+"""Example of training a ReAct agent using RL with Trinity-RFT."""+import os+from typing import Dict+++from pydantic import BaseModel, Field+from trinity.common.rewards import MathBoxedRewardFn++from agentscope.tune import tune+from agentscope.model import TrinityChatModel+from agentscope.agent import ReActAgent+from agentscope.formatter import OpenAIChatFormatter+from agentscope.message import Msg+++class GSM8KResponseStructure(BaseModel):+ """Response structure for GSM8K tasks."""++ result: str = Field(+ description=(+ "Your solution of the given math problem. "+ "Put your final answer in boxed format, e.g., \\boxed{42}"+ ),+ )+++class GSM8KRewardFn(MathBoxedRewardFn):+ """Reward function for GSM8K tasks."""++ def __call__(+ self,+ response: Dict,+ truth: str,+ format_score_coef: float = 0.1,+ **kwargs: Dict,+ ) -> dict[str, float]:+ """Calculate the reward based on the response and truth."""+ # parse GSM8K truth+ if isinstance(truth, str) and "####" in truth:+ truth = truth.split("####")[1].strip()+ else:+ truth = str(truth)+ return super().__call__(+ response=response["result"],+ truth=truth,+ with_think=False,+ format_score_coef=format_score_coef,+ **kwargs,+ )+++async def run_react_agent(task: Dict, model: TrinityChatModel) -> float:+ """A simple workflow function using the ReAct agent to solve tasks.++ Args:+ task (Dict): The task to be solved.+ model (TrinityChatModel): The language model to use.++ Returns:+ float: The reward obtained by solving the task.+ """+ sys_prompt = (+ "You are an agent specialized in solving math problems with tools. "+ "Please solve the math problem given to you. You can write and "+ "execute Python code to perform calculation or verify your answer. "+ "You should return your final answer within \\boxed{{}}."+ )++ response_structure = GSM8KResponseStructure+ reward_fn = GSM8KRewardFn()+ agent = ReActAgent(+ name="react_agent",+ sys_prompt=sys_prompt,+ model=model,+ enable_meta_tool=True,+ formatter=OpenAIChatFormatter(),+ )+ response = await agent.reply(+ msg=Msg("user", task["question"], role="user"),+ structured_model=response_structure,+ )+ reward = reward_fn(+ response=response.metadata,+ truth=task["answer"],+ )+ return sum(reward.values())+++if __name__ == "__main__":+ config_path = os.path.join(+ os.path.dirname(__file__),+ "config.yaml",+ )+ tune(+ workflow_func=run_react_agent,+ config_path=config_path,+ )diff --git a/src/agentscope/model/__init__.py b/src/agentscope/model/__init__.pyindex 6f3a729fc..7cd0b7a8f 100644--- a/src/agentscope/model/__init__.py+++ b/src/agentscope/model/__init__.py@@ -8,6 +8,7 @@ from ._openai_model import OpenAIChatModelfrom ._anthropic_model import AnthropicChatModelfrom ._ollama_model import OllamaChatModelfrom ._gemini_model import GeminiChatModel+from ._trinity_model import TrinityChatModel__all__ = ["ChatModelBase",@@ -17,4 +18,5 @@ __all__ = ["AnthropicChatModel","OllamaChatModel","GeminiChatModel",+ "TrinityChatModel",]diff --git a/src/agentscope/model/_trinity_model.py b/src/agentscope/model/_trinity_model.pynew file mode 100644index 000000000..5f8b357d0--- /dev/null+++ b/src/agentscope/model/_trinity_model.py@@ -0,0 +1,63 @@+# -*- coding: utf-8 -*-+"""A model class for RL Training with Trinity-RFT."""+from typing import (+ Optional,+ TYPE_CHECKING,+)+from ._openai_model import OpenAIChatModel+from ..types import JSONSerializableObject+++if TYPE_CHECKING:+ from openai import AsyncOpenAI+else:+ AsyncOpenAI = "openai.AsyncOpenAI"+++class TrinityChatModel(OpenAIChatModel):+ """A model class for RL Training with Trinity-RFT."""++ def __init__(+ self,+ openai_async_client: AsyncOpenAI,+ generate_kwargs: dict[str, JSONSerializableObject] | None = None,+ enable_thinking: Optional[bool] = None,+ ) -> None:+ """Initialize the Trinity model class.++ Args:+ openai_async_client (`AsyncOpenAI`):+ The OpenAI async client instance provided by Trinity-RFT.+ generate_kwargs (`dict[str, JSONSerializableObject] | None`, \+ optional):+ Additional keyword arguments to pass to the model's generate+ method. Defaults to None.+ enable_thinking (`bool`, optional):+ Whether to enable the model's thinking capability. Only+ applicable for Qwen3 series models. Defaults to None.+ """+ model_name = getattr(openai_async_client, "model_path", None)+ if model_name is None:+ raise ValueError(+ "The provided openai_async_client does not have a "+ "`model_path` attribute. Please ensure you are using "+ "the instance provided by Trinity-RFT.",+ )+ super().__init__(+ model_name=model_name,+ api_key="EMPTY",+ generate_kwargs=generate_kwargs,+ stream=False, # RL training does not support streaming+ )+ if enable_thinking is not None:+ if "chat_template_kwargs" not in self.generate_kwargs:+ self.generate_kwargs["chat_template_kwargs"] = {}+ assert isinstance(+ self.generate_kwargs["chat_template_kwargs"],+ dict,+ ), "chat_template_kwargs must be a dictionary."+ self.generate_kwargs["chat_template_kwargs"][+ "enable_thinking"+ ] = enable_thinking+ # change the client instance to the provided one+ self.client = openai_async_clientdiff --git a/src/agentscope/tune/__init__.py b/src/agentscope/tune/__init__.pynew file mode 100644index 000000000..facf19b15--- /dev/null+++ b/src/agentscope/tune/__init__.py@@ -0,0 +1,10 @@+# -*- coding: utf-8 -*-+"""The learning module of AgentScope, including RL and SFT."""++from ._tune import tune+from ._workflow import WorkflowType++__all__ = [+ "tune",+ "WorkflowType",+]diff --git a/src/agentscope/tune/_tune.py b/src/agentscope/tune/_tune.pynew file mode 100644index 000000000..0a268e209--- /dev/null+++ b/src/agentscope/tune/_tune.py@@ -0,0 +1,72 @@+# -*- coding: utf-8 -*-+"""The main entry point for agent learning."""+from dataclasses import dataclass+from ._workflow import (+ WorkflowType,+ _validate_function_signature,+)+++def tune(workflow_func: WorkflowType, config_path: str) -> None:+ """Train the agent workflow with the specific configuration.++ Args:+ workflow_func (WorkflowType): The learning workflow function+ to execute.+ config_path (str): The configuration for the learning process.+ """+ try:+ from trinity.cli.launcher import run_stage+ from trinity.common.config import Config+ from omegaconf import OmegaConf+ except ImportError as e:+ raise ImportError(+ "Trinity-RFT is not installed. Please install it with "+ "`pip install trinity-rft`.",+ ) from e++ if not _validate_function_signature(workflow_func):+ raise ValueError(+ "Invalid workflow function signature, please "+ "check the types of your workflow input/output.",+ )++ @dataclass+ class TuneConfig(Config):+ """Configuration for learning process."""++ def to_trinity_config(self, workflow_func: WorkflowType) -> Config:+ """Convert to Trinity-RFT compatible configuration."""+ workflow_name = "agentscope_workflow_adapter"+ self.buffer.explorer_input.taskset.default_workflow_type = (+ workflow_name+ )+ self.buffer.explorer_input.default_workflow_type = workflow_name+ self.buffer.explorer_input.taskset.workflow_args[+ "workflow_func"+ ] = workflow_func+ return self.check_and_update()++ @classmethod+ def load_config(cls, config_path: str) -> "TuneConfig":+ """Load the learning configuration from a YAML file.++ Args:+ config_path (str): The path to the configuration file.++ Returns:+ TuneConfig: The loaded learning configuration.+ """+ schema = OmegaConf.structured(cls)+ yaml_config = OmegaConf.load(config_path)+ try:+ config = OmegaConf.merge(schema, yaml_config)+ return OmegaConf.to_object(config)+ except Exception as e:+ raise ValueError(f"Invalid configuration: {e}") from e++ return run_stage(+ config=TuneConfig.load_config(config_path).to_trinity_config(+ workflow_func,+ ),+ )diff --git a/src/agentscope/tune/_workflow.py b/src/agentscope/tune/_workflow.pynew file mode 100644index 000000000..623e53b6b--- /dev/null+++ b/src/agentscope/tune/_workflow.py@@ -0,0 +1,77 @@+# -*- coding: utf-8 -*-+"""Workflow for agent learning."""++from typing import (+ Dict,+ Callable,+ Awaitable,+ get_type_hints,+)++import inspect++from .._logging import logger+from ..model import TrinityChatModel+++WorkflowType = Callable[[Dict, TrinityChatModel], Awaitable[float]]+++def _validate_function_signature(func: Callable) -> bool:+ """Validate if a function matches the workflow type signature.++ Args:+ func (Callable): The function to validate.+ """+ # check if the function is asynchronous+ if not inspect.iscoroutinefunction(func):+ logger.warning("The function is not asynchronous.")+ return False+ # Define expected parameter types and return type manually+ expected_params = [+ ("task", Dict),+ ("model", TrinityChatModel),+ ]+ expected_return = float++ func_signature = inspect.signature(func)+ func_hints = get_type_hints(func)++ # Check if the number of parameters matches+ if len(func_signature.parameters) != len(expected_params):+ logger.warning(+ "Expected %d parameters, but got %d",+ len(expected_params),+ len(func_signature.parameters),+ )+ return False++ # Validate each parameter's name and type+ for (param_name, _), (expected_name, expected_type) in zip(+ func_signature.parameters.items(),+ expected_params,+ ):+ if (+ param_name != expected_name+ or func_hints.get(param_name) != expected_type+ ):+ logger.warning(+ "Expected parameter %s of type %s, but got %s of type %s",+ expected_name,+ expected_type,+ param_name,+ func_hints.get(param_name),+ )+ return False++ # Validate the return type+ return_annotation = func_hints.get("return", None)+ if return_annotation != expected_return:+ logger.warning(+ "Expected return type %s, but got %s",+ expected_return,+ return_annotation,+ )+ return False++ return Truediff --git a/tests/model_trinity_test.py b/tests/model_trinity_test.pynew file mode 100644index 000000000..ea32c9f37--- /dev/null+++ b/tests/model_trinity_test.py@@ -0,0 +1,95 @@+# -*- coding: utf-8 -*-+# pylint: disable=too-many-statements+"""Unit tests for Trinity-RFT model class."""+from unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import Mock, AsyncMock++from agentscope.model import TrinityChatModel, ChatResponse+from agentscope.message import TextBlock+++class TestTrinityModel(IsolatedAsyncioTestCase):+ """Test cases for TrinityModel."""++ async def test_init_with_trinity_client(self) -> None:+ """Test initialization with a valid OpenAI async client."""+ MODEL_NAME = "Qwen/Qwen3-8B"+ mock_client = Mock()+ mock_client.model_path = MODEL_NAME++ # test init+ model_1 = TrinityChatModel(+ openai_async_client=mock_client,+ enable_thinking=False,+ generate_kwargs={+ "temperature": 1.0,+ "top_k": 2,+ },+ )+ model_2 = TrinityChatModel(+ openai_async_client=mock_client,+ enable_thinking=True,+ generate_kwargs={+ "max_tokens": 500,+ "top_p": 0.9,+ },+ )+ self.assertEqual(model_1.model_name, MODEL_NAME)+ self.assertFalse(model_1.stream)+ self.assertIs(model_1.client, mock_client)+ self.assertEqual(model_2.model_name, MODEL_NAME)+ self.assertFalse(model_2.stream)+ self.assertIs(model_2.client, mock_client)++ # create mock response+ messages = [{"role": "user", "content": "Hello"}]+ mock_message = Mock()+ mock_message.content = "Hi there!"+ mock_message.reasoning_content = None+ mock_message.tool_calls = []+ mock_message.audio = None+ mock_message.parsed = None+ mock_choice = Mock()+ mock_choice.message = mock_message+ mock_response = Mock()+ mock_response.choices = [mock_choice]+ mock_usage = Mock()+ mock_usage.prompt_tokens = 10+ mock_usage.completion_tokens = 20+ mock_response.usage = mock_usage++ mock_client.chat.completions.create = AsyncMock(+ return_value=mock_response,+ )++ result = await model_1(messages)+ call_args = mock_client.chat.completions.create.call_args[1]+ self.assertEqual(call_args["model"], MODEL_NAME)+ self.assertEqual(call_args["messages"], messages)+ self.assertFalse(call_args["stream"])+ self.assertFalse(call_args["chat_template_kwargs"]["enable_thinking"])+ self.assertEqual(call_args["temperature"], 1.0)+ self.assertEqual(call_args["top_k"], 2)+ self.assertFalse("max_tokens" in call_args)+ self.assertFalse("top_p" in call_args)+ self.assertIsInstance(result, ChatResponse)+ expected_content = [+ TextBlock(type="text", text="Hi there!"),+ ]+ self.assertEqual(result.content, expected_content)++ result = await model_2(messages)+ call_args = mock_client.chat.completions.create.call_args[1]+ self.assertEqual(call_args["model"], MODEL_NAME)+ self.assertEqual(call_args["messages"], messages)+ self.assertFalse(call_args["stream"])+ self.assertTrue(call_args["chat_template_kwargs"]["enable_thinking"])+ self.assertEqual(call_args["max_tokens"], 500)+ self.assertEqual(call_args["top_p"], 0.9)+ self.assertFalse("temperature" in call_args)+ self.assertFalse("top_k" in call_args)+ self.assertIsInstance(result, ChatResponse)+ expected_content = [+ TextBlock(type="text", text="Hi there!"),+ ]+ self.assertEqual(result.content, expected_content)diff --git a/tests/tune_test.py b/tests/tune_test.pynew file mode 100644index 000000000..4e690acca--- /dev/null+++ b/tests/tune_test.py@@ -0,0 +1,67 @@+# -*- coding: utf-8 -*-+# pylint: disable=unused-argument+"""Learn related tests in agentscope."""+from typing import Any, Dict, List+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.model import TrinityChatModel, OpenAIChatModel+from agentscope.tune._workflow import _validate_function_signature+++async def correct_interface(task: Dict, model: TrinityChatModel) -> float:+ """Correct interface matching the workflow type."""+ return task["reward"]+++async def wrong_interface_1(+ task: Dict,+ model: TrinityChatModel,+ extra: Any,+) -> float:+ """Wrong interface with extra argument."""+ return 0.0+++async def wrong_interface_2(task: Dict) -> float:+ """Wrong interface with missing argument."""+ return 0.0+++async def wrong_interface_3(task: List, model: TrinityChatModel) -> float:+ """Wrong interface with wrong task type."""+ return 0.0+++async def wrong_interface_4(task: Dict, model: OpenAIChatModel) -> float:+ """Wrong interface with wrong model type."""+ return 0.0+++async def wrong_interface_5(task: Dict, model: TrinityChatModel) -> str:+ """Wrong interface with wrong return type."""+ return "0.0"+++class AgentLearnTest(IsolatedAsyncioTestCase):+ """Test the learning functionality of agents."""++ async def test_workflow_interface_validate(self) -> None:+ """Test the interface of workflow function."""+ self.assertTrue(+ _validate_function_signature(correct_interface),+ )+ self.assertFalse(+ _validate_function_signature(wrong_interface_1),+ )+ self.assertFalse(+ _validate_function_signature(wrong_interface_2),+ )+ self.assertFalse(+ _validate_function_signature(wrong_interface_3),+ )+ self.assertFalse(+ _validate_function_signature(wrong_interface_4),+ )+ self.assertFalse(+ _validate_function_signature(wrong_interface_5),+ )