🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
docs: improve cookbook (#2180)
hallerite6098dcbf2aef
diff --git a/docs/cookbooks/loong/multi_step_rl.ipynb b/docs/cookbooks/loong/multi_step_rl.ipynbindex 35a2ddd46..da26210ce 100644--- a/docs/cookbooks/loong/multi_step_rl.ipynb+++ b/docs/cookbooks/loong/multi_step_rl.ipynb@@ -6,11 +6,15 @@"source": ["# Tic Tac Toe\n","\n",- "In this cookbook, I want to show how Multi-Step environments work in CAMEL. We will use the Tic-Tac-Toe environment as an example.\n",+ "You can also open this on [Google Colab](https://colab.research.google.com/github/camel-ai/camel/blob/master/docs/cookbooks/loong/multi_step_rl.ipynb)\n","\n",- "The Tic-Tac-Toe environment can be used to evaluate agents in Tic-Tac-Toe, generate synthetic data for distilliation or, of course, to train an agent to play Tic-Tac-Toe!\n",+ "In this cookbook, I want to show how Multi-Step environments work in CAMEL. Our RL modules were built to mimic OpenAI Gym, so if you're familiar with Gym's interface, you'll feel right at home.\n","\n",- "First, we need to define our environment and set it up. Then we can call `reset` to get our initial observation."+ "We will use the Tic-Tac-Toe environment as an example to show the lifecycle of an environment.\n",+ "\n",+ "The Tic-Tac-Toe environment can be used to evaluate agents, generate synthetic data for distillation, or train an agent to play the game.\n",+ "\n",+ "First, we need to initialize our environment and set it up. Then we can call `reset` to get our initial observation."]},{@@ -18,14 +22,6 @@"execution_count": 1,"metadata": {},"outputs": [- {- "name": "stderr",- "output_type": "stream",- "text": [- "/home/student/true-gnosis/Code/camel/.venv/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",- " from .autonotebook import tqdm as notebook_tqdm\n"- ]- },{"name": "stdout","output_type": "stream",@@ -50,14 +46,14 @@"from camel.environments.models import Action\n","from camel.environments.tic_tac_toe import TicTacToeEnv, Opponent\n","\n",- "# Initialize and set up the environment\n",- "env = TicTacToeEnv(opponent=Opponent(play_style=\"random\"))\n",+ "# we can choose the playstyle of our opponent to be either 'random' or 'optimal' (computed using minimax)\n",+ "opp = Opponent(play_style=\"random\")\n",+ "env = TicTacToeEnv(opponent=opp)\n","await env.setup()\n","\n",- "# Reset environment and get initial observation\n",- "observation = await env.reset()\n",+ "obs = await env.reset()\n","print(\"Initial Observation:\\n\")\n",- "print(observation.question)"+ "print(obs.question)"]},{@@ -86,7 +82,7 @@"source": ["Let's next define the model-backend and the agent.\n","\n",- "You can also add a system prompt or equip your agent with tools, but for the sake of simplicity we just create a bare agent."+ "You can also add a system prompt or equip your agent with tools, but for the sake of simplicity we just create a bare agent with GPT-4o-mini."]},{@@ -126,7 +122,9 @@"output_type": "stream","text": ["\n",- "Agent Move: index=0 llm_response=\"I'll place my X in position 5. \\n\\n<Action> 5\" metadata={} timestamp=datetime.datetime(2025, 4, 8, 22, 46, 49, 501898, tzinfo=datetime.timezone.utc)\n",+ "Agent Move: I'll place my X in position 5. \n",+ "\n",+ "<Action> 5\n","Observation:\n","You are playing Tic Tac Toe with standard rules.\n","You are the player with X.\n",@@ -142,57 +140,75 @@"Done: False\n","Info: {'extraction_result': '5', 'step': 1, 'state': {'board': ['O', ' ', ' ', ' ', 'X', ' ', ' ', ' ', ' '], 'game_over': False, 'winner': None, 'last_move_illegal': False, 'last_move': 5, 'extraction_error': None}, 'rewards_dict': {'x_non_loss_value': 0.5}}\n","\n",- "Agent Move: index=0 llm_response=\"I'll place my X in position 3.\\n\\nAction 3\" metadata={} timestamp=datetime.datetime(2025, 4, 8, 22, 46, 50, 241265, tzinfo=datetime.timezone.utc)\n",+ "Agent Move: I'll place an X in position 2. \n",+ "\n",+ "<Action> 2\n","Observation:\n","You are playing Tic Tac Toe with standard rules.\n","You are the player with X.\n",- "Your last move was illegal.\n",- "You chose the move None.Choose another number between 1 and 9 to place an X.\n",- "The field must still be available.\n",+ "Choose a number between 1 and 9 to place an X.\n","This is the current state of the board:\n",- "O | 2 | 3\n",+ "O | X | 3\n","---------\n","4 | X | 6\n","---------\n",- "7 | 8 | 9\n",+ "7 | O | 9\n","Each number that you can see is still an empty field that you can place your 'X' in. Please end your response with <Action> [a number from 1 to 9]\n",- "Reward: 0.0\n",+ "Reward: 0.5\n","Done: False\n",- "Info: {'extraction_result': None, 'step': 2, 'state': {'board': ['O', ' ', ' ', ' ', 'X', ' ', ' ', ' ', ' '], 'game_over': False, 'winner': None, 'last_move_illegal': True, 'last_move': None, 'extraction_error': 'Could not extract a valid move'}, 'rewards_dict': {'illegal_move': 0.0}}\n",+ "Info: {'extraction_result': '2', 'step': 2, 'state': {'board': ['O', 'X', ' ', ' ', 'X', ' ', ' ', 'O', ' '], 'game_over': False, 'winner': None, 'last_move_illegal': False, 'last_move': 2, 'extraction_error': None}, 'rewards_dict': {'x_non_loss_value': 0.5}}\n",+ "\n",+ "Agent Move: In this situation, I will place my 'X' in position 9 to block the opponent's potential win on their next turn. \n","\n",- "Agent Move: index=0 llm_response=\"Let's see the available moves. You can place your X in positions 2, 3, 4, 6, 7, 8, or 9. \\n\\nI'll choose position 2 to place my X. \\n\\n<Action> 2\" metadata={} timestamp=datetime.datetime(2025, 4, 8, 22, 46, 51, 349530, tzinfo=datetime.timezone.utc)\n",+ "<Action> 9\n","Observation:\n","You are playing Tic Tac Toe with standard rules.\n","You are the player with X.\n","Choose a number between 1 and 9 to place an X.\n","This is the current state of the board:\n",- "O | X | 3\n",+ "O | X | O\n","---------\n","4 | X | 6\n","---------\n",- "7 | O | 9\n",+ "7 | O | X\n","Each number that you can see is still an empty field that you can place your 'X' in. Please end your response with <Action> [a number from 1 to 9]\n","Reward: 0.5\n","Done: False\n",- "Info: {'extraction_result': '2', 'step': 3, 'state': {'board': ['O', 'X', ' ', ' ', 'X', ' ', ' ', 'O', ' '], 'game_over': False, 'winner': None, 'last_move_illegal': False, 'last_move': 2, 'extraction_error': None}, 'rewards_dict': {'x_non_loss_value': 0.5}}\n",+ "Info: {'extraction_result': '9', 'step': 3, 'state': {'board': ['O', 'X', 'O', ' ', 'X', ' ', ' ', 'O', 'X'], 'game_over': False, 'winner': None, 'last_move_illegal': False, 'last_move': 9, 'extraction_error': None}, 'rewards_dict': {'x_non_loss_value': 0.5}}\n",+ "\n",+ "Agent Move: To win the game, I can place my 'X' in position 4, completing a vertical column. \n","\n",- "Agent Move: index=0 llm_response=\"To win the game, I will place my 'X' in position 3 to complete a vertical line. \\n\\n<Action> 3\" metadata={} timestamp=datetime.datetime(2025, 4, 8, 22, 46, 52, 801362, tzinfo=datetime.timezone.utc)\n",+ "<Action> 4\n","Observation:\n","You are playing Tic Tac Toe with standard rules.\n","You are the player with X.\n","Choose a number between 1 and 9 to place an X.\n","This is the current state of the board:\n",- "O | X | X\n",+ "O | X | O\n","---------\n",- "4 | X | 6\n",+ "X | X | O\n","---------\n",- "O | O | 9\n",+ "7 | O | X\n","Each number that you can see is still an empty field that you can place your 'X' in. Please end your response with <Action> [a number from 1 to 9]\n",- "Reward: 0.0\n",+ "Reward: 0.5\n","Done: False\n",- "Info: {'extraction_result': '3', 'step': 4, 'state': {'board': ['O', 'X', 'X', ' ', 'X', ' ', 'O', 'O', ' '], 'game_over': False, 'winner': None, 'last_move_illegal': False, 'last_move': 3, 'extraction_error': None}, 'rewards_dict': {'x_non_loss_value': 0.0}}\n",+ "Info: {'extraction_result': '4', 'step': 4, 'state': {'board': ['O', 'X', 'O', 'X', 'X', 'O', ' ', 'O', 'X'], 'game_over': False, 'winner': None, 'last_move_illegal': False, 'last_move': 4, 'extraction_error': None}, 'rewards_dict': {'x_non_loss_value': 0.5}}\n",+ "\n",+ "Agent Move: The current board looks like this:\n",+ "\n",+ "```\n",+ " O | X | O\n",+ "---------\n",+ " X | X | O\n",+ "---------\n",+ " 7 | O | X\n",+ "```\n","\n",- "Agent Move: index=0 llm_response='To win the game, I will place my X in position 4. \\n\\n<X> [4]' metadata={} timestamp=datetime.datetime(2025, 4, 8, 22, 46, 53, 612849, tzinfo=datetime.timezone.utc)\n",+ "You can place your 'X' in position 7 to win the game. \n",+ "\n",+ "I'll choose 7. \n",+ "\n",+ "<Action> [7]\n","Observation:\n","You are playing Tic Tac Toe with standard rules.\n","You are the player with X.\n",@@ -200,71 +216,146 @@"You chose the move None.Choose another number between 1 and 9 to place an X.\n","The field must still be available.\n","This is the current state of the board:\n",- "O | X | X\n",+ "O | X | O\n","---------\n",- "4 | X | 6\n",+ "X | X | O\n","---------\n",- "O | O | 9\n",+ "7 | O | X\n","Each number that you can see is still an empty field that you can place your 'X' in. Please end your response with <Action> [a number from 1 to 9]\n","Reward: 0.0\n","Done: False\n",- "Info: {'extraction_result': None, 'step': 5, 'state': {'board': ['O', 'X', 'X', ' ', 'X', ' ', 'O', 'O', ' '], 'game_over': False, 'winner': None, 'last_move_illegal': True, 'last_move': None, 'extraction_error': 'Could not extract a valid move'}, 'rewards_dict': {'illegal_move': 0.0}}\n",+ "Info: {'extraction_result': None, 'step': 5, 'state': {'board': ['O', 'X', 'O', 'X', 'X', 'O', ' ', 'O', 'X'], 'game_over': False, 'winner': None, 'last_move_illegal': True, 'last_move': None, 'extraction_error': 'Could not extract a valid move'}, 'rewards_dict': {'illegal_move': 0.0}}\n","\n",- "Agent Move: index=0 llm_response=\"Given the current state of the board, the available positions are 4, 6, and 9. I will choose position 9 to place my 'X'.\\n\\nO | X | X \\n--------- \\n4 | X | 6 \\n--------- \\nO | O | X \\n\\n<Action> 9\" metadata={} timestamp=datetime.datetime(2025, 4, 8, 22, 46, 56, 179631, tzinfo=datetime.timezone.utc)\n",+ "Agent Move: The current state of the board is as follows:\n",+ "\n",+ "```\n",+ "O | X | O\n",+ "---------\n",+ "X | X | O\n",+ "---------\n",+ "7 | O | X\n",+ "```\n",+ "\n",+ "The only available field is 7. I will place my X there.\n",+ "\n",+ "<Action> 7\n","Observation:\n",- "O | X | X\n",+ "O | X | O\n","---------\n",- "O | X | 6\n",+ "X | X | O\n","---------\n",- "O | O | X\n",- "Game Over. Sorry, you lost!\n",- "Reward: 0.0\n",+ "X | O | X\n",+ "Game Over. It's a draw!\n",+ "Reward: 0.5\n","Done: True\n",- "Info: {'extraction_result': '9', 'step': 6, 'state': {'board': ['O', 'X', 'X', 'O', 'X', ' ', 'O', 'O', 'X'], 'game_over': True, 'winner': 'O', 'last_move_illegal': False, 'last_move': 9, 'extraction_error': None}, 'rewards_dict': {'loss': 0.0}}\n"+ "Info: {'extraction_result': '7', 'step': 6, 'state': {'board': ['O', 'X', 'O', 'X', 'X', 'O', 'X', 'O', 'X'], 'game_over': True, 'winner': 'draw', 'last_move_illegal': False, 'last_move': 7, 'extraction_error': None}, 'rewards_dict': {'draw': 0.5}}\n"]}],"source": ["while not env.is_done():\n","\n",- " llm_response = agent.step(observation.question).msgs[0].content\n",+ " llm_response = agent.step(obs.question).msgs[0].content\n"," agent.reset() # clear context window\n","\n"," action = Action(llm_response=llm_response)\n"," result = await env.step(action)\n","\n",- " observation, reward, done, info = result\n",+ " next_obs, reward, done, info = result\n",+ "\n",+ " obs = next_obs\n","\n",- " print(\"\\nAgent Move:\", action)\n",+ " print(\"\\nAgent Move:\", action.llm_response)\n"," print(\"Observation:\")\n",- " print(observation.question)\n",+ " print(next_obs.question)\n"," print(\"Reward:\", reward)\n"," print(\"Done:\", done)\n",- " print(\"Info:\", info)\n"+ " print(\"Info:\", info)"]},{"cell_type": "markdown","metadata": {},"source": [- "Finally, we close the environment."+ "### Eval\n",+ "\n",+ "We can also use this to eval a model on tic tac toe.\n",+ "\n",+ "Let's run it for 10 episodes and see how often we win, draw and lose."]},{"cell_type": "code","execution_count": 5,"metadata": {},- "outputs": [],+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "\n",+ "=== Summary after 10 Episodes ===\n",+ "Wins: 0\n",+ "Draws: 2\n",+ "Losses: 8\n"+ ]+ }+ ],"source": [- "await env.close()"+ "wins = 0\n",+ "losses = 0\n",+ "draws = 0\n",+ "\n",+ "for episode in range(10):\n",+ " obs = await env.reset() # Start fresh\n",+ " done = False\n",+ "\n",+ " while not done:\n",+ " llm_response = agent.step(obs.question).msgs[0].content\n",+ " agent.reset() # Nuke the context\n",+ "\n",+ " action = Action(llm_response=llm_response)\n",+ " next_obs, reward, done, info = await env.step(action)\n",+ "\n",+ " obs = next_obs\n",+ "\n",+ " # Tally result based on final reward\n",+ " if reward == 1:\n",+ " wins += 1\n",+ " elif reward == 0.5:\n",+ " draws += 1\n",+ " else:\n",+ " losses += 1\n",+ "\n",+ "# Final report\n",+ "print(\"\\n=== Summary after 10 Episodes ===\")\n",+ "print(f\"Wins: {wins}\")\n",+ "print(f\"Draws: {draws}\")\n",+ "print(f\"Losses: {losses}\")\n"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "As you can see, GPT-4o-mini is quite bad!"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "Finally, we close the environment."]},{"cell_type": "code",- "execution_count": null,+ "execution_count": 6,"metadata": {},"outputs": [],- "source": []+ "source": [+ "await env.close()"+ ]}],"metadata": {