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
def choose_white():
global user_color, white_button, black_button
user_color = "white"
history.append({"role": "user", "content": "White"})
print_history()
white_button.destroy() # Remove the "Choose White" button
black_button.destroy() # Remove the "Choose Black" button
def choose_black():
global user_color, white_button, black_button
user_color = "black"
history.append({"role": "user", "content": "Black"})
print_history()
white_button.destroy() # Remove the "Choose White" button
black_button.destroy() # Remove the "Choose Black" button
def process_move(move_str, game_board):
global san_moves, san_number, total_moves
Assistant
It seems you might have an issue with your regex pattern in the extract_moves_from_message function. The pattern is intended to match Standard Algebraic Notation (SAN) moves such as "", "", "", etc. However, it currently has a few errors. Instead of the correct symbol for "to", which is "-", your regex pattern uses "1-8", which is an unintended range.
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 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?|[O-]{3,5})\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_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}")
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
So your modified extract_moves_from_message function should look like this:
python
def extract_moves_from_message(message):
# Use a regular expression to find SAN moves like “e4”, “Nf3”, “Bb5”, promotions like “c8=Q”, and castling “O-O” or “O-O-O”
san_moves = re.findall(r'\b(?:[NBRQK]?[a-h][1-8]?x?[a-h][1-8]=?[NBRQK]?|[O-O]{3})\b', message)
return san_moves
Additionally, when calling llm_move, you should first ensure that the assistant's response contains a valid move before attempting to push it onto the board.
Here is the section of llm_move where you can adjust the logic:
python
# ...
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()
# Extract moves from the assistant's message
moves_from_message = extract_moves_from_message(assistant_message)
# Process each extracted move
if moves_from_message: # Check if there are moves extracted
move_str = moves_from_message[0] # Use the first move
# Now attempt to process the move
process_move(move_str, game_board)
else:
result_label.config(text="No valid moves found")
# ...
Make sure that you review the above section of llm_move and integrate it properly within your existing function. The given snippet is not the entire function and should replace the relevant part of your code.
Lastly, ensure that your entries in the history list are formatted correctly. Note that LLM's response can follow different formats, so you need to adapt the extraction pattern if the format changes.