Spaces:
Sleeping
Sleeping
from langchain_core.tools import tool | |
import requests | |
def get_best_move(fen: str) -> str: | |
""" | |
Given the description of a chess board using FEN notation, returns the next best move. | |
Args: | |
fen (str): The description of the chessboard position in FEN notation. | |
Returns: | |
str: The description of the next best move. | |
""" | |
url = "https://lichess.org/api/cloud-eval" | |
params = { | |
"fen": fen, | |
"multiPv": 1, # only top move | |
"syzygy": 5 # enable tablebase for 5-piece positions | |
} | |
response = requests.get(url, params=params) | |
if response.status_code != 200: | |
return f"API error: {response.status_code} - {response.text}" | |
data = response.json() | |
if not data.get("pvs"): | |
return "No best move found." | |
best_line = data["pvs"][0] | |
score = best_line["cp"] if "cp" in best_line else f"Mate in {best_line.get('mate')}" | |
move = best_line["moves"].split()[0] | |
# Optional: threshold to define a "guaranteed win" | |
if "mate" in best_line or best_line.get("cp", 0) > 500: | |
return move | |
return f"No clearly winning move. Best suggestion: {move} (score: {score})" | |