Your llm_move function attempts to interact with an LLM and submit a move, but it has several issues. The extract_moves_from_message function only looks for UCI format moves with a pattern like , while the LLM response provides moves in SAN format .
User
would that capture a cxd8Q move, just wondering
Assistant
The regular expression provided in the previous message would not capture a move like cxd8Q, which represents a pawn capture on d8 with a promotion to a queen. In algebraic notation, when a pawn reaches the back rank and is promoted, it is often denoted by the target square (e.g., d8), an equals sign, and the promotion piece (e.g., Q for queen), so a full move would be represented as .
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
i have this code where i'm trying to search an LLM response for a valid move, then make that move. i made the move e4 in the game. the LLM message response was "34 +0.28 1... e5 2.Nf3 Nc6 3.Bb5....". i wanted the program to search through the message for the first useable move, then make that move on the board, but it doesn't seem to try making any of the moves in the LLM message. the move in this example that should have been made was e5.
import tkinter as tk
from PIL import Image, ImageTk
import chess
import requests
import re
import threading
def draw_board(board, selected_square=None):
global board_images
try:
data = {
"mode": "chat",
"character": "Assistant",
"instruction_template": "ChatML",
"max_tokens": 75,
"temperature": 1.5,
"top_p": 0.9,
"typical_p": 1,
"min_p": 0,
"repetition_penalty": 1.17,
"top_k": 20,
"seed": -1,
"messages": history
}
response = requests.post(api_url, headers=headers, json=data).json()
if 'choices' in response and response['choices']:
assistant_message = response['choices'][0]['message']['content']
history.append({"role": "assistant", "content": assistant_message})
chat_window.insert(tk.END, f"\nAssistant: {assistant_message}\n")
print_history()
except Exception as e:
print(f"Error in LLM request: {e}")
chat_window.insert(tk.END, "\nAssistant: Error in LLM request")
def on_enter(event):
# Check if the cursor is in the input area
if event.widget == input_area:
move_str = move_entry.get()
submit_message()
elif event.widget == move_entry:
submit_move()
def submit_move():
global move_entry
move = move_entry.get()
print(move)
process_move(move, game_board)
move_entry.delete(0, tk.END) # Clear the entry after the move
def submit_message():
global chat_window, user_color, history
message = input_area.get("1.0", tk.END).strip()
role = "user"
chat_window.insert(tk.END, f"\n{role.capitalize()}: {message}\n")
history.append({"role": role, "content": message})
interact_with_llm(message)
print("line 215")
def extract_moves_from_message(message):
# Use a regular expression to find valid SAN moves
san_moves = re.findall(r'\b[abcdefgh][1-8][abcdefgh][1-8]\b', message)
return san_moves
def llm_move():
global san_moves, history, user_color, chat_window, san_moves
code
if (game_board.turn == chess.WHITE and user_color == "black") or (game_board.turn == chess.BLACK and user_color == "white"):
chat_window.delete(1.0, tk.END)
history = []
role = "assistant"
message = f"{san_moves.rstrip()}.... 35 +0.29"
history.append({"role": role, "content": message})
message = (f"35 +0.29")
history.append({"role": role, "content": message})
try:
data = {
"mode": "chat",
"character": "ChessAI",
"max_tokens": 40,
"temperature": 0.82,
"top_p": 0.21,
"min_p": 0,
"top_k": 72,
"repetition_penalty": 1.19,
"typical_p": 1,
"seed": -1,
"messages": history
}
response = requests.post(api_url, headers=headers, json=data).json()
if 'choices' in response and response['choices']:
assistant_message = response['choices'][0]['message']['content']
history.append({"role": "assistant", "content": assistant_message})
chat_window.insert(tk.END, san_moves)
chat_window.insert(tk.END, f"\n\nAssistant: {assistant_message}\n")
print_history()
try:
assistant_message = response['choices'][0]['message']['content']
history.append({"role": "assistant", "content": assistant_message})
chat_window.insert(tk.END, f"\nAssistant: {assistant_message}\n")
print_history()
# Extract moves from the assistant's message
moves_from_message = extract_moves_from_message(assistant_message)
# Process each extracted move
for move in moves_from_message:
# Update the game board before checking if the move is legal
game_board.push_uci(move) # Update the board state
draw_board(game_board) # Update the GUI board
try:
move = game_board.parse_san(move)
process_move(move, game_board)
except ValueError as e:
result_label.config(text=f"Invalid move: {e}")
print(f"Invalid move: {e}")
except ValueError as e:
result_label.config(text=f"Invalid move: {e}")
print(f"Invalid move: {e}")
print(f"Error processing assistant_message: {e}")
except Exception as e:
print(f"Error in LLM request: {e}")
chat_window.insert(tk.END, "\nAssistant: Error in LLM request")
def print_history():
print("\n=== Updated History ===")
for entry in history:
print(f"{entry['role']}: {entry['content']}")
print("=======================")
def clear_history():
global history, chat_window, game_board, san_moves
history = []
chat_window.delete(1.0, tk.END) # Clear the chat window
game_board = chess.Board(initial_fen)
draw_board(game_board)
san_moves = ""
Global Variables
user_color = None
history = []
san_moves = "" # Initialize an empty string to store SAN moves
san_number = 1 # Initialize real number of moves
total_moves = 1
api_url = 'http://127.0.0.1:5000/v1/chat/completions'
headers = {"Content-Type": "application/json"}
initial_fen = chess.STARTING_FEN
game_board = chess.Board(initial_fen)
board = chess.Board()
valid_moves = game_board.legal_moves
board_images = {}
square_size = 60 # Size of a square in the board
selected_square = None
move = None
Create a dictionary to map piece symbols to image filenames
Here's an updated version of extract_moves_from_message that captures SAN format moves:
python
def extract_moves_from_message(message):
# Use a regular expression to find SAN moves like "e4", "Nf3", "Bb5"
san_moves = re.findall(r'\b(?:[NBRQK]?[a-h]?[1-8]?x?[a-h][1-8](?:=[NBRQ])?|[O\-]{3,5})\b', message)
return san_moves
This new regex pattern matches SAN moves, which may include castling (O-O or O-O-O), pawn promotion (e8=Q), captures (exd5), and normal moves (e4).
Make sure you replace the existing extract_moves_from_message with the new function in your program.
After capturing the SAN moves, the loop in llm_move where you attempt to process moves must be updated accordingly. There seem to be two attempts to process the move, which might lead to confusion. Here's the simplified and corrected loop for processing the move from the LLM's message:
python
# Process each extracted move
for move_str in moves_from_message:
try:
move = game_board.parse_san(move_str)
if move in game_board.legal_moves:
game_board.push(move)
draw_board(game_board)
break # Exit the loop after making the first legal move
except ValueError as e:
result_label.config(text=f"Invalid move: {e}")
print(f"Invalid move: {e}")
Replace the loop that processes the moves with this one in the llm_move function. The 'break' statement means that once a valid move is found and made, the function does not attempt to make any further moves.
This should suffice to have your program make the first legal move found in the LLM's response. However, ensure that your entire code flows appropriately and that other parts that I haven't reviewed here are working correctly to avoid any further issues.
And remember to handle or remove any debugging or placeholder code, as it looks like there are some hardcoded history messages in llm_move that you might have used for testing (message = f"{san_moves.rstrip()}.... 35 +0.29"). These could interfere with the actual runtime logic.
cxd8=Q
To capture pawn promotions along with other moves in SAN notation, we need to extend the regular expression to include the = and promotion piece.
Here's an updated regex that would also capture moves with pawn promotion:
python
def extract_moves_from_message(message):
# Use a regular expression to find SAN moves like "e4", "Nf3", "Bb5", and promotions like "cxd8=Q"
san_moves = re.findall(r'\b(?:[NBRQK]?[a-h]?[1-8]?x?[a-h][1-8](?:=[NBRQ])?|[O\-]{3,5})\b', message)
return san_moves
This regex pattern includes the following components:
NBRQK - Optional piece identifiers for knight, bishop, rook, queen, or king (for pawn moves, the piece is not specified).
[a-h]?[1-8]? - Optional file and rank to specify the starting square, mainly for disambiguation.
x? - Optional 'x' character to denote a capture.
[a-h][1-8] - Mandatory target square.
(?:=[NBRQ])? - Non-capturing group for pawn promotion, optional, with an equals sign followed by 'N', 'B', 'R', or 'Q' for the promotion piece.
[O\-]{3,5} - Castling, either short (O-O) or long (O-O-O), using hyphens in between 'O's to denote the move.
This pattern captures a wide array of valid SAN moves including standard moves, captures, promotions, checks, and castling. If you want to match checks and checkmates as well, you can append [+#]? to the end of the regex to include these too:
python
def extract_moves_from_message(message):
# Use a regular expression to find SAN moves with captures, promotions, checks, and castling
san_moves = re.findall(r'\b(?:[NBRQK]?[a-h]?[1-8]?x?[a-h][1-8](?:=[NBRQ])?|[O\-]{3,5})[+#]?\b', message)
return san_moves
Now the pattern also allows for a check (+) or checkmate (#) symbol at the end of the move. Make sure to test the regex with various chess notation examples to ensure it correctly captures the moves you need.