# -*- coding: utf-8 -*- """ timeless_agent.py This script contains the full implementation for the Timeless_Agent, a Pokémon battle agent that uses a Large Language Model (LLM) for strategic decision-making. Agent Details: - Agent Name: Timeless_Agent - LLM Provider: OpenRouter - LLM Model: deepseek/deepseek-chat-v3-0324:free This single file is designed to be uploaded to a Hugging Face Space for deployment. It includes all necessary classes and logic. """ import asyncio import json import logging import os from typing import Dict, List, Optional, Union from openai import AsyncOpenAI from poke_env.environment.battle import Battle from poke_env.environment.move import Move from poke_env.environment.pokemon import Pokemon from poke_env.player import Player # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # --- Helper Functions & Data Structures --- def normalize_name(name: str) -> str: """ Normalizes a Pokémon or move name by converting it to lowercase and removing non-alphanumeric characters. This is crucial for matching names from LLM output with the game's internal IDs. Args: name (str): The name to normalize. Returns: str: The normalized name. """ return "".join(filter(str.isalnum, name)).lower() # Defines the schema for the tools (functions) the LLM can call. # This structure is compatible with most standard function-calling APIs. STANDARD_TOOL_SCHEMA = [ { "type": "function", "function": { "name": "choose_move", "description": "Selects a move to use for the current turn.", "parameters": { "type": "object", "properties": { "move_name": { "type": "string", "description": "The name of the move to use.", } }, "required": ["move_name"], }, }, }, { "type": "function", "function": { "name": "choose_switch", "description": "Switches the active Pokémon with one from the bench.", "parameters": { "type": "object", "properties": { "pokemon_name": { "type": "string", "description": "The name of the Pokémon to switch to.", } }, "required": ["pokemon_name"], }, }, }, ] # The tool schema specifically formatted for OpenAI's API. OPENAI_TOOL_SCHEMA = {"tools": STANDARD_TOOL_SCHEMA, "tool_choice": "auto"} # --- Base Agent Class --- class LLMAgentBase(Player): """ An abstract base class for a Pokémon battle agent that uses an LLM for decision-making. It handles the main battle loop, state formatting, action validation, and fallback logic. Subclasses must implement the `_get_llm_decision` method to provide the logic for communicating with a specific LLM API. """ def _format_battle_state(self, battle: Battle) -> str: """ Formats the complex Battle object into a concise, text-based string for the LLM. Args: battle (Battle): The current battle state from poke-env. Returns: str: A formatted string representing the current battle state. """ # Your active Pokémon active_pokemon_info = f"- Species: {battle.active_pokemon.species}\\n" active_pokemon_info += f"- Type: {' / '.join(map(str, battle.active_pokemon.types))}\\n" active_pokemon_info += f"- HP: {battle.active_pokemon.current_hp_fraction * 100:.1f}%\\n" active_pokemon_info += f"- Status: {battle.active_pokemon.status.name if battle.active_pokemon.status else 'None'}\\n" active_pokemon_info += f"- Stats: {battle.active_pokemon.stats}\\n" active_pokemon_info += f"- Boosts: {battle.active_pokemon.boosts}" # Opponent's active Pokémon opponent_info = "Opponent's Active Pokemon:\\n" if battle.opponent_active_pokemon: opponent_info += f"- Species: {battle.opponent_active_pokemon.species}\\n" opponent_info += f"- Type: {' / '.join(map(str, battle.opponent_active_pokemon.types))}\\n" opponent_info += f"- HP: {battle.opponent_active_pokemon.current_hp_fraction * 100:.1f}%\\n" opponent_info += f"- Status: {battle.opponent_active_pokemon.status.name if battle.opponent_active_pokemon.status else 'None'}\\n" opponent_info += f"- Boosts: {battle.opponent_active_pokemon.boosts}" else: opponent_info += "Unknown" # Available moves moves_info = "Available Moves:\\n" for move in battle.available_moves: moves_info += f"- {move.id}: Type={move.type.name}, Power={move.base_power}, Acc={move.accuracy}, PP={move.current_pp}/{move.max_pp}\\n" if not battle.available_moves: moves_info += "No moves available." # Available switches (bench Pokémon) switches_info = "Available Switches:\\n" for pokemon in battle.available_switches: switches_info += f"- {pokemon.species}: HP={pokemon.current_hp_fraction * 100:.1f}%, Status={pokemon.status.name if pokemon.status else 'None'}\\n" if not battle.available_switches: switches_info += "No switches available." # Field conditions field_info = "Field Conditions:\\n" field_info += f"- Weather: {battle.weather.name if battle.weather else 'None'}\\n" field_info += f"- Terrains: {[t.name for t in battle.fields]}\\n" field_info += f"- Your Side: {[c.name for c in battle.side_conditions]}\\n" field_info += f"- Opponent Side: {[c.name for c in battle.opponent_side_conditions]}" return f""" Your Active Pokemon: {active_pokemon_info} {opponent_info} {moves_info} {switches_info} {field_info} """ def _find_move_by_name(self, move_name: str, available_moves: List[Move]) -> Optional[Move]: """Finds a move in the list of available moves by its name.""" normalized_move_name = normalize_name(move_name) for move in available_moves: if normalize_name(move.id) == normalized_move_name: return move return None def _find_pokemon_by_name(self, pokemon_name: str, available_switches: List[Pokemon]) -> Optional[Pokemon]: """Finds a Pokémon in the list of available switches by its species.""" normalized_pokemon_name = normalize_name(pokemon_name) for pokemon in available_switches: if normalize_name(pokemon.species) == normalized_pokemon_name: return pokemon return None async def choose_move(self, battle: Battle) -> Union[Move, Pokemon]: """ The main decision-making loop called by poke-env each turn. """ battle_state_str = self._format_battle_state(battle) # Get LLM decision try: decision_data = await self._get_llm_decision(battle_state_str) decision = decision_data.get("decision", {}) if decision.get("name") == "choose_move": move_name = decision.get("arguments", {}).get("move_name") move = self._find_move_by_name(move_name, battle.available_moves) if move: logger.info(f"LLM chose move: {move.id}") return self.create_order(move) elif decision.get("name") == "choose_switch": pokemon_name = decision.get("arguments", {}).get("pokemon_name") pokemon = self._find_pokemon_by_name(pokemon_name, battle.available_switches) if pokemon: logger.info(f"LLM chose to switch to: {pokemon.species}") return self.create_order(pokemon) logger.warning("LLM failed to provide a valid action. Falling back to random.") except Exception as e: logger.error(f"Error during LLM decision making: {e}") # Fallback to a random valid action return self.choose_random_move(battle) async def _get_llm_decision(self, battle_state: str) -> Dict: """ Abstract method for getting a decision from an LLM. This must be implemented by subclasses. """ raise NotImplementedError("This method should be implemented by a subclass.") # --- Specific Agent Implementation --- class Timeless_Agent(LLMAgentBase): """ A Pokémon battle agent that uses the OpenRouter API to make decisions. It is configured to use a specific free, high-performance model. """ def __init__(self, api_key: str, **kwargs): """ Initializes the Timeless_Agent. Args: api_key (str): The API key for the OpenRouter service. **kwargs: Additional arguments for the parent Player class. """ kwargs.pop('start_challenging', None) super().__init__(**kwargs) if not api_key: raise ValueError("OpenRouter API key is required.") # This is the Hugging Face Hub token required for repository authentication # when deploying the agent. It is not used in the battle logic itself. self.hf_token = "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" # Configure the client to use the OpenRouter API self.llm_client = AsyncOpenAI( base_url="https://openrouter.ai/api/v1", api_key=api_key, ) self.model = "deepseek/deepseek-chat-v3-0324:free" self.system_prompt = ( "You are a world-class Pokémon battle strategist. Your goal is to win " "the battle by making the most logical move each turn. Analyze the provided " "battle state, considering type advantages/disadvantages, Pokémon HP, " "status effects, and active field conditions. Your only available actions " "are to use an available move or switch to an available Pokémon. You must use " "the provided `choose_move` or `choose_switch` functions to state your decision." ) async def _get_llm_decision(self, battle_state: str) -> Dict: """ Gets a decision by calling the OpenRouter API. Args: battle_state (str): The formatted string of the current battle state. Returns: Dict: A dictionary containing the LLM's decision. """ try: response = await self.llm_client.chat.completions.create( model=self.model, messages=[ {"role": "system", "content": self.system_prompt}, { "role": "user", "content": f"Current Battle State:\\n{battle_state}\\n\\nChoose the best action by calling the appropriate function.", }, ], **OPENAI_TOOL_SCHEMA, ) tool_call = response.choices[0].message.tool_calls[0] function_data = tool_call.function logger.info(f"LLM Response: {function_data.name}({function_data.arguments})") return { "decision": { "name": function_data.name, "arguments": json.loads(function_data.arguments), } } except Exception as e: logger.error(f"Failed to get decision from OpenRouter: {e}") return {"error": str(e)} # --- Local Execution Block --- async def main(): """ Main function to run the agent locally for testing purposes. """ print("Starting Timeless_Agent for a local battle...") # IMPORTANT: Set your OpenRouter API key as an environment variable # before running this script locally. # On Linux/macOS: export OPENROUTER_API_KEY="your-key-here" # On Windows: set OPENROUTER_API_KEY="your-key-here" api_key = os.getenv("OPENROUTER_API_KEY") if not api_key: print("\\nERROR: OPENROUTER_API_KEY environment variable not found.") print("Please set it before running the agent.") return # Create the agent instance agent = Timeless_Agent( api_key=api_key, battle_format="gen8randombattle", # The username 'Timeless_Agent' is primarily used when deploying on a server. # For local testing, a default or random username might be used by poke-env. start_challenging=True, ) # You can challenge a specific user: # await agent.challenge('some_username', from_user=None, packed_team=None) # Or start battling against random players on the ladder: print("Timeless_Agent is now challenging random players on the ladder.") print("Press Ctrl+C to stop.") await agent.ladder(1) if __name__ == "__main__": # This block allows you to run the agent locally. # It will not be executed when the agent is run on the Hugging Face Space. try: asyncio.get_event_loop().run_until_complete(main()) except KeyboardInterrupt: print("\\nAgent stopped by user.")