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 8.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 logging
  7. from dataclasses import dataclass
  8. from typing import Annotated, Literal
  9. from agents import ChatCompletionAgent
  10. from autogen_core import (
  11. AgentId,
  12. AgentInstantiationContext,
  13. AgentRuntime,
  14. DefaultSubscription,
  15. DefaultTopicId,
  16. SingleThreadedAgentRuntime,
  17. )
  18. from autogen_core.model_context import BufferedChatCompletionContext
  19. from autogen_core.models import SystemMessage
  20. from autogen_core.tools import FunctionTool
  21. from chess import BLACK, SQUARE_NAMES, WHITE, Board, Move
  22. from chess import piece_name as get_piece_name
  23. from patterns import GroupChatManager
  24. from pydantic import BaseModel
  25. from utils import get_chat_completion_client_from_envs
  26. @dataclass
  27. class TextMessage(BaseModel):
  28. source: str
  29. content: str
  30. def validate_turn(board: Board, player: Literal["white", "black"]) -> None:
  31. """Validate that it is the player's turn to move."""
  32. last_move = board.peek() if board.move_stack else None
  33. if last_move is not None:
  34. if player == "white" and board.color_at(last_move.to_square) == WHITE:
  35. raise ValueError("It is not your turn to move. Wait for black to move.")
  36. if player == "black" and board.color_at(last_move.to_square) == BLACK:
  37. raise ValueError("It is not your turn to move. Wait for white to move.")
  38. elif last_move is None and player != "white":
  39. raise ValueError("It is not your turn to move. Wait for white to move first.")
  40. def get_legal_moves(
  41. board: Board, player: Literal["white", "black"]
  42. ) -> Annotated[str, "A list of legal moves in UCI format."]:
  43. """Get legal moves for the given player."""
  44. validate_turn(board, player)
  45. legal_moves = list(board.legal_moves)
  46. if player == "black":
  47. legal_moves = [move for move in legal_moves if board.color_at(move.from_square) == BLACK]
  48. elif player == "white":
  49. legal_moves = [move for move in legal_moves if board.color_at(move.from_square) == WHITE]
  50. else:
  51. raise ValueError("Invalid player, must be either 'black' or 'white'.")
  52. if not legal_moves:
  53. return "No legal moves. The game is over."
  54. return "Possible moves are: " + ", ".join([move.uci() for move in legal_moves])
  55. def get_board(board: Board) -> str:
  56. """Get the current board state."""
  57. return str(board)
  58. def make_move(
  59. board: Board,
  60. player: Literal["white", "black"],
  61. thinking: Annotated[str, "Thinking for the move."],
  62. move: Annotated[str, "A move in UCI format."],
  63. ) -> Annotated[str, "Result of the move."]:
  64. """Make a move on the board."""
  65. validate_turn(board, player)
  66. new_move = Move.from_uci(move)
  67. board.push(new_move)
  68. # Print the move.
  69. print("-" * 50)
  70. print("Player:", player)
  71. print("Move:", new_move.uci())
  72. print("Thinking:", thinking)
  73. print("Board:")
  74. print(board.unicode(borders=True))
  75. # Get the piece name.
  76. piece = board.piece_at(new_move.to_square)
  77. assert piece is not None
  78. piece_symbol = piece.unicode_symbol()
  79. piece_name = get_piece_name(piece.piece_type)
  80. if piece_symbol.isupper():
  81. piece_name = piece_name.capitalize()
  82. return f"Moved {piece_name} ({piece_symbol}) from {SQUARE_NAMES[new_move.from_square]} to {SQUARE_NAMES[new_move.to_square]}."
  83. async def chess_game(runtime: AgentRuntime) -> None: # type: ignore
  84. """Create agents for a chess game and return the group chat."""
  85. # Create the board.
  86. board = Board()
  87. # Create tools for each player.
  88. # @functools.wraps(get_legal_moves)
  89. def get_legal_moves_black() -> str:
  90. return get_legal_moves(board, "black")
  91. # @functools.wraps(get_legal_moves)
  92. def get_legal_moves_white() -> str:
  93. return get_legal_moves(board, "white")
  94. # @functools.wraps(make_move)
  95. def make_move_black(
  96. thinking: Annotated[str, "Thinking for the move"],
  97. move: Annotated[str, "A move in UCI format"],
  98. ) -> str:
  99. return make_move(board, "black", thinking, move)
  100. # @functools.wraps(make_move)
  101. def make_move_white(
  102. thinking: Annotated[str, "Thinking for the move"],
  103. move: Annotated[str, "A move in UCI format"],
  104. ) -> str:
  105. return make_move(board, "white", thinking, move)
  106. def get_board_text() -> Annotated[str, "The current board state"]:
  107. return get_board(board)
  108. black_tools = [
  109. FunctionTool(
  110. get_legal_moves_black,
  111. name="get_legal_moves",
  112. description="Get legal moves.",
  113. ),
  114. FunctionTool(
  115. make_move_black,
  116. name="make_move",
  117. description="Make a move.",
  118. ),
  119. FunctionTool(
  120. get_board_text,
  121. name="get_board",
  122. description="Get the current board state.",
  123. ),
  124. ]
  125. white_tools = [
  126. FunctionTool(
  127. get_legal_moves_white,
  128. name="get_legal_moves",
  129. description="Get legal moves.",
  130. ),
  131. FunctionTool(
  132. make_move_white,
  133. name="make_move",
  134. description="Make a move.",
  135. ),
  136. FunctionTool(
  137. get_board_text,
  138. name="get_board",
  139. description="Get the current board state.",
  140. ),
  141. ]
  142. await ChatCompletionAgent.register(
  143. runtime,
  144. "PlayerBlack",
  145. lambda: ChatCompletionAgent(
  146. description="Player playing black.",
  147. system_messages=[
  148. SystemMessage(
  149. content="You are a chess player and you play as black. "
  150. "Use get_legal_moves() to get list of legal moves. "
  151. "Use get_board() to get the current board state. "
  152. "Think about your strategy and call make_move(thinking, move) to make a move."
  153. ),
  154. ],
  155. model_context=BufferedChatCompletionContext(buffer_size=10),
  156. model_client=get_chat_completion_client_from_envs(model="gpt-4o"),
  157. tools=black_tools,
  158. ),
  159. )
  160. await runtime.add_subscription(DefaultSubscription(agent_type="PlayerBlack"))
  161. await ChatCompletionAgent.register(
  162. runtime,
  163. "PlayerWhite",
  164. lambda: ChatCompletionAgent(
  165. description="Player playing white.",
  166. system_messages=[
  167. SystemMessage(
  168. content="You are a chess player and you play as white. "
  169. "Use get_legal_moves() to get list of legal moves. "
  170. "Use get_board() to get the current board state. "
  171. "Think about your strategy and call make_move(thinking, move) to make a move."
  172. ),
  173. ],
  174. model_context=BufferedChatCompletionContext(buffer_size=10),
  175. model_client=get_chat_completion_client_from_envs(model="gpt-4o"),
  176. tools=white_tools,
  177. ),
  178. )
  179. await runtime.add_subscription(DefaultSubscription(agent_type="PlayerWhite"))
  180. # Create a group chat manager for the chess game to orchestrate a turn-based
  181. # conversation between the two agents.
  182. await GroupChatManager.register(
  183. runtime,
  184. "ChessGame",
  185. lambda: GroupChatManager(
  186. description="A chess game between two agents.",
  187. model_context=BufferedChatCompletionContext(buffer_size=10),
  188. participants=[
  189. AgentId("PlayerWhite", AgentInstantiationContext.current_agent_id().key),
  190. AgentId("PlayerBlack", AgentInstantiationContext.current_agent_id().key),
  191. ], # white goes first
  192. ),
  193. )
  194. await runtime.add_subscription(DefaultSubscription(agent_type="ChessGame"))
  195. async def main() -> None:
  196. """Main Entrypoint."""
  197. runtime = SingleThreadedAgentRuntime()
  198. await chess_game(runtime)
  199. runtime.start()
  200. # Publish an initial message to trigger the group chat manager to start
  201. # orchestration.
  202. await runtime.publish_message(
  203. TextMessage(content="Game started.", source="System"),
  204. topic_id=DefaultTopicId(),
  205. )
  206. await runtime.stop_when_idle()
  207. if __name__ == "__main__":
  208. parser = argparse.ArgumentParser(description="Run a chess game between two agents.")
  209. parser.add_argument("--verbose", action="store_true", help="Enable verbose logging.")
  210. args = parser.parse_args()
  211. if args.verbose:
  212. logging.basicConfig(level=logging.WARNING)
  213. logging.getLogger("autogen_core").setLevel(logging.DEBUG)
  214. handler = logging.FileHandler("chess_game.log")
  215. logging.getLogger("autogen_core").addHandler(handler)
  216. asyncio.run(main())