You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.py 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. """This is an example of simulating a chess game with two agents
  2. that play against each other, using tools to reason about the game state
  3. and make moves, and using a group chat manager to orchestrate the conversation."""
  4. import argparse
  5. import asyncio
  6. import json
  7. import logging
  8. from typing import Annotated, Any, Dict, List, Literal
  9. from autogen_core import (
  10. AgentId,
  11. AgentRuntime,
  12. DefaultTopicId,
  13. MessageContext,
  14. RoutedAgent,
  15. SingleThreadedAgentRuntime,
  16. default_subscription,
  17. message_handler,
  18. )
  19. from autogen_core.model_context import BufferedChatCompletionContext, ChatCompletionContext
  20. from autogen_core.models import AssistantMessage, ChatCompletionClient, LLMMessage, SystemMessage, UserMessage
  21. from autogen_core.tool_agent import ToolAgent, tool_agent_caller_loop
  22. from autogen_core.tools import FunctionTool, Tool, ToolSchema
  23. from chess import BLACK, SQUARE_NAMES, WHITE, Board, Move
  24. from chess import piece_name as get_piece_name
  25. from pydantic import BaseModel
  26. class TextMessage(BaseModel):
  27. source: str
  28. content: str
  29. @default_subscription
  30. class ToolUseAgent(RoutedAgent):
  31. def __init__(
  32. self,
  33. description: str,
  34. instructions: str,
  35. model_client: ChatCompletionClient,
  36. model_context: ChatCompletionContext,
  37. tool_schema: List[ToolSchema],
  38. tool_agent_type: str,
  39. ) -> None:
  40. super().__init__(description=description)
  41. self._system_messages: List[LLMMessage] = [SystemMessage(content=instructions)]
  42. self._model_client = model_client
  43. self._tool_schema = tool_schema
  44. self._tool_agent_id = AgentId(tool_agent_type, self.id.key)
  45. self._model_context = model_context
  46. @message_handler
  47. async def handle_message(self, message: TextMessage, ctx: MessageContext) -> None:
  48. # Add the user message to the model context.
  49. await self._model_context.add_message(UserMessage(content=message.content, source=message.source))
  50. # Run the caller loop to handle tool calls.
  51. messages = await tool_agent_caller_loop(
  52. self,
  53. tool_agent_id=self._tool_agent_id,
  54. model_client=self._model_client,
  55. input_messages=(await self._model_context.get_messages()),
  56. tool_schema=self._tool_schema,
  57. cancellation_token=ctx.cancellation_token,
  58. )
  59. assert isinstance(messages[-1].content, str)
  60. # Add the assistant message to the model context.
  61. await self._model_context.add_message(AssistantMessage(content=messages[-1].content, source=self.id.type))
  62. # Publish the final response.
  63. await self.publish_message(TextMessage(content=messages[-1].content, source=self.id.type), DefaultTopicId())
  64. def validate_turn(board: Board, player: Literal["white", "black"]) -> None:
  65. """Validate that it is the player's turn to move."""
  66. last_move = board.peek() if board.move_stack else None
  67. if last_move is not None:
  68. if player == "white" and board.color_at(last_move.to_square) == WHITE:
  69. raise ValueError("It is not your turn to move. Wait for black to move.")
  70. if player == "black" and board.color_at(last_move.to_square) == BLACK:
  71. raise ValueError("It is not your turn to move. Wait for white to move.")
  72. elif last_move is None and player != "white":
  73. raise ValueError("It is not your turn to move. Wait for white to move first.")
  74. def get_legal_moves(
  75. board: Board, player: Literal["white", "black"]
  76. ) -> Annotated[str, "A list of legal moves in UCI format."]:
  77. """Get legal moves for the given player."""
  78. validate_turn(board, player)
  79. legal_moves = list(board.legal_moves)
  80. if player == "black":
  81. legal_moves = [move for move in legal_moves if board.color_at(move.from_square) == BLACK]
  82. elif player == "white":
  83. legal_moves = [move for move in legal_moves if board.color_at(move.from_square) == WHITE]
  84. else:
  85. raise ValueError("Invalid player, must be either 'black' or 'white'.")
  86. if not legal_moves:
  87. return "No legal moves. The game is over."
  88. return "Possible moves are: " + ", ".join([move.uci() for move in legal_moves])
  89. def get_board(board: Board) -> str:
  90. """Get the current board state."""
  91. return str(board)
  92. def make_move(
  93. board: Board,
  94. player: Literal["white", "black"],
  95. thinking: Annotated[str, "Thinking for the move."],
  96. move: Annotated[str, "A move in UCI format."],
  97. ) -> Annotated[str, "Result of the move."]:
  98. """Make a move on the board."""
  99. validate_turn(board, player)
  100. new_move = Move.from_uci(move)
  101. board.push(new_move)
  102. # Print the move.
  103. print("-" * 50)
  104. print("Player:", player)
  105. print("Move:", new_move.uci())
  106. print("Thinking:", thinking)
  107. print("Board:")
  108. print(board.unicode(borders=True))
  109. # Get the piece name.
  110. piece = board.piece_at(new_move.to_square)
  111. assert piece is not None
  112. piece_symbol = piece.unicode_symbol()
  113. piece_name = get_piece_name(piece.piece_type)
  114. if piece_symbol.isupper():
  115. piece_name = piece_name.capitalize()
  116. return f"Moved {piece_name} ({piece_symbol}) from {SQUARE_NAMES[new_move.from_square]} to {SQUARE_NAMES[new_move.to_square]}."
  117. async def chess_game(runtime: AgentRuntime, model_config: Dict[str, Any]) -> None: # type: ignore
  118. """Create agents for a chess game and return the group chat."""
  119. # Create the board.
  120. board = Board()
  121. # Create tools for each player.
  122. def get_legal_moves_black() -> str:
  123. return get_legal_moves(board, "black")
  124. def get_legal_moves_white() -> str:
  125. return get_legal_moves(board, "white")
  126. def make_move_black(
  127. thinking: Annotated[str, "Thinking for the move"],
  128. move: Annotated[str, "A move in UCI format"],
  129. ) -> str:
  130. return make_move(board, "black", thinking, move)
  131. def make_move_white(
  132. thinking: Annotated[str, "Thinking for the move"],
  133. move: Annotated[str, "A move in UCI format"],
  134. ) -> str:
  135. return make_move(board, "white", thinking, move)
  136. def get_board_text() -> Annotated[str, "The current board state"]:
  137. return get_board(board)
  138. black_tools: List[Tool] = [
  139. FunctionTool(
  140. get_legal_moves_black,
  141. name="get_legal_moves",
  142. description="Get legal moves.",
  143. ),
  144. FunctionTool(
  145. make_move_black,
  146. name="make_move",
  147. description="Make a move.",
  148. ),
  149. FunctionTool(
  150. get_board_text,
  151. name="get_board",
  152. description="Get the current board state.",
  153. ),
  154. ]
  155. white_tools: List[Tool] = [
  156. FunctionTool(
  157. get_legal_moves_white,
  158. name="get_legal_moves",
  159. description="Get legal moves.",
  160. ),
  161. FunctionTool(
  162. make_move_white,
  163. name="make_move",
  164. description="Make a move.",
  165. ),
  166. FunctionTool(
  167. get_board_text,
  168. name="get_board",
  169. description="Get the current board state.",
  170. ),
  171. ]
  172. model_client = ChatCompletionClient.load_component(model_config)
  173. # Register the agents.
  174. await ToolAgent.register(
  175. runtime,
  176. "ToolAgent",
  177. lambda: ToolAgent(description="Tool agent for chess game.", tools=black_tools + white_tools),
  178. )
  179. await ToolUseAgent.register(
  180. runtime,
  181. "PlayerBlack",
  182. lambda: ToolUseAgent(
  183. description="Player playing black.",
  184. instructions="You are a chess player and you play as black. "
  185. "Use get_legal_moves() to get list of legal moves. "
  186. "Use get_board() to get the current board state. "
  187. "Think about your strategy and call make_move(thinking, move) to make a move.",
  188. model_client=model_client,
  189. model_context=BufferedChatCompletionContext(buffer_size=10),
  190. tool_schema=[tool.schema for tool in black_tools],
  191. tool_agent_type="ToolAgent",
  192. ),
  193. )
  194. await ToolUseAgent.register(
  195. runtime,
  196. "PlayerWhite",
  197. lambda: ToolUseAgent(
  198. description="Player playing white.",
  199. instructions="You are a chess player and you play as white. "
  200. "Use get_legal_moves() to get list of legal moves. "
  201. "Use get_board() to get the current board state. "
  202. "Think about your strategy and call make_move(thinking, move) to make a move.",
  203. model_client=model_client,
  204. model_context=BufferedChatCompletionContext(buffer_size=10),
  205. tool_schema=[tool.schema for tool in white_tools],
  206. tool_agent_type="ToolAgent",
  207. ),
  208. )
  209. async def main(model_config: Dict[str, Any]) -> None:
  210. """Main Entrypoint."""
  211. runtime = SingleThreadedAgentRuntime()
  212. await chess_game(runtime, model_config)
  213. runtime.start()
  214. # Publish an initial message to trigger the group chat manager to start
  215. # orchestration.
  216. # Send an initial message to player white to start the game.
  217. await runtime.send_message(
  218. TextMessage(content="Game started.", source="System"),
  219. AgentId("PlayerWhite", "default"),
  220. )
  221. await runtime.stop_when_idle()
  222. if __name__ == "__main__":
  223. parser = argparse.ArgumentParser(description="Run a chess game between two agents.")
  224. parser.add_argument("--verbose", action="store_true", help="Enable verbose logging.")
  225. parser.add_argument(
  226. "--model-config", type=str, help="Path to the model configuration file.", default="model_config.json"
  227. )
  228. args = parser.parse_args()
  229. if args.verbose:
  230. logging.basicConfig(level=logging.WARNING)
  231. logging.getLogger("autogen_core").setLevel(logging.DEBUG)
  232. handler = logging.FileHandler("chess_game.log")
  233. logging.getLogger("autogen_core").addHandler(handler)
  234. with open(args.model_config, "r") as f:
  235. model_config = json.load(f)
  236. asyncio.run(main(model_config))