File size: 2,091 Bytes
86cbfce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a5daef
86cbfce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a5daef
 
86cbfce
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from smolagents import Tool
from stockfish import Stockfish
import traceback


#AUTHORIZED_TYPES = [
#    "string",
#    "boolean",
#    "integer",
#    "number",
#    "image",
#    "audio",
#    "array",
#    "object",
#    "any",
#    "null",
#]

# https://pypi.org/project/stockfish/


class ChessAnalysisTool(Tool):
    name = "_my_tool_chess_analysis"
    description = """
        Analyze chess position provided as FEN notation and answer with best move for player color
        To invoke the tool use code as below
        <code>
        best_answer = _my_tool_chess_analysis(fen=loaded_fen, player_color="dummy")
        </code>
    """

    inputs = {
        "fen": {
            "type": "string",
            "description": "board position in FEN notation",
        },
        "player_color": {
            "type": "string",
            "description": "black or white to make next move",
            "nullable": True
        }
    }

    output_type = "string"

    is_initialized = True

    def __init__(self):
        print(f"***KS*** Chess analysis tool initializing ...")
        self.engine = Stockfish()
        print(f"***KS*** Chess analysis tool initialized with engine: {self.engine}")

    def initialize(self):
        print(f"***KS*** Chess analysis tool initialized (2) with engine: {self.engine}")

    def forward(self, fen: str, player_color = "") -> str:
        # TODO use player_color correctly and set it on FEN in proper position
        print(f"***KS*** Chess analysis tool getting best move for player: {player_color} with position: {fen}")
        best_move = ""
        try:
            self.engine.set_fen_position(fen)
            board = self.engine.get_board_visual()
            print(f"{board}")
            top_3_moves = self.engine.get_top_moves(3)
            print(f"Top 3 moves:\n{top_3_moves}")
            best_move = self.engine.get_best_move()
        except Exception as ex:
            print(traceback.format_exc())
            print(f"***KS*** Exception invoking ChessAnalysisTool: {ex}")

        return f"FINAL ANSWER: {best_move}"