File size: 20,340 Bytes
22cdc3d
 
 
 
 
 
f645c4a
22cdc3d
 
 
 
 
 
6a4f566
22cdc3d
 
 
 
 
 
f645c4a
22cdc3d
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eaa8f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22cdc3d
f645c4a
22cdc3d
 
 
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
f823987
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
f645c4a
22cdc3d
 
f645c4a
22cdc3d
f645c4a
22cdc3d
 
 
 
 
 
 
 
f645c4a
22cdc3d
f645c4a
22cdc3d
 
f645c4a
22cdc3d
 
 
ba5a866
88beb6d
 
5c1a880
22cdc3d
 
 
 
 
f645c4a
6eaa8f9
 
f645c4a
6eaa8f9
 
22cdc3d
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
6eaa8f9
 
b771950
6eaa8f9
 
 
 
 
 
22cdc3d
b771950
 
 
 
 
6eaa8f9
 
b771950
 
 
f645c4a
6eaa8f9
 
f645c4a
22cdc3d
 
 
f645c4a
22cdc3d
f645c4a
 
22cdc3d
 
 
861f448
88beb6d
 
5c1a880
22cdc3d
 
 
 
 
 
 
6eaa8f9
 
22cdc3d
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f645c4a
 
22cdc3d
 
 
e3cef11
f645c4a
 
 
 
22cdc3d
f645c4a
 
 
22cdc3d
f645c4a
22cdc3d
f645c4a
22cdc3d
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
 
88beb6d
 
 
5c1a880
22cdc3d
 
 
 
 
6a4f566
22cdc3d
6eaa8f9
 
 
 
 
 
 
 
 
 
 
22cdc3d
f645c4a
22cdc3d
 
 
 
 
f645c4a
22cdc3d
 
 
 
6eaa8f9
 
 
 
 
 
 
 
22cdc3d
6eaa8f9
22cdc3d
6eaa8f9
 
22cdc3d
6eaa8f9
 
f645c4a
6eaa8f9
 
f645c4a
22cdc3d
f645c4a
6eaa8f9
f645c4a
 
 
 
 
 
 
22cdc3d
6eaa8f9
f645c4a
22cdc3d
f645c4a
22cdc3d
6eaa8f9
 
f645c4a
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import os
import json
import asyncio
import random

# --- OpenAI ---
from openai import AsyncOpenAI, APIError

# --- Google Gemini ---
from google import genai
from google.genai import types

# --- Mistral AI ---
from mistralai import Mistral

# --- Poke-Env ---
from poke_env.player import Player
from poke_env.environment.battle import Battle
from poke_env.environment.move import Move
from poke_env.environment.pokemon import Pokemon
from typing import Optional, Dict, Any, Union

# --- Helper Function & Base Class ---
def normalize_name(name: str) -> str:
    """Lowercase and remove non-alphanumeric characters."""
    return "".join(filter(str.isalnum, name)).lower()

STANDARD_TOOL_SCHEMA = {
    "choose_move": {
        "name": "choose_move",
        "description": "Selects and executes an available attacking or status move.",
        "parameters": {
            "type": "object",
            "properties": {
                "move_name": {
                    "type": "string",
                    "description": "The exact name or ID (e.g., 'thunderbolt', 'swordsdance') of the move to use. Must be one of the available moves.",
                },
            },
            "required": ["move_name"],
        },
    },
    "choose_switch": {
        "name": "choose_switch",
        "description": "Selects an available Pokémon from the bench to switch into.",
        "parameters": {
            "type": "object",
            "properties": {
                "pokemon_name": {
                    "type": "string",
                    "description": "The exact name of the Pokémon species to switch to (e.g., 'Pikachu', 'Charizard'). Must be one of the available switches.",
                },
            },
            "required": ["pokemon_name"],
        },
    },
}

# --- OpenAI Tools Schema (with 'type' field) ---
OPENAI_TOOL_SCHEMA = {
    "choose_move": {
        "type": "function",
        "function": {
            "name": "choose_move",
            "description": "Selects and executes an available attacking or status move.",
            "parameters": {
                "type": "object",
                "properties": {
                    "move_name": {
                        "type": "string",
                        "description": "The exact name or ID (e.g., 'thunderbolt', 'swordsdance') of the move to use. Must be one of the available moves.",
                    },
                },
                "required": ["move_name"],
            },
        }
    },
    "choose_switch": {
        "type": "function",
        "function": {
            "name": "choose_switch",
            "description": "Selects an available Pokémon from the bench to switch into.",
            "parameters": {
                "type": "object",
                "properties": {
                    "pokemon_name": {
                        "type": "string",
                        "description": "The exact name of the Pokémon species to switch to (e.g., 'Pikachu', 'Charizard'). Must be one of the available switches.",
                    },
                },
                "required": ["pokemon_name"],
            },
        }
    },
}


class LLMAgentBase(Player):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.standard_tools = STANDARD_TOOL_SCHEMA
        self.battle_history = []

    def _format_battle_state(self, battle: Battle) -> str:
        active_pkmn = battle.active_pokemon
        active_pkmn_info = f"Your active Pokemon: {active_pkmn.species} " \
                           f"(Type: {'/'.join(map(str, active_pkmn.types))}) " \
                           f"HP: {active_pkmn.current_hp_fraction * 100:.1f}% " \
                           f"Status: {active_pkmn.status.name if active_pkmn.status else 'None'} " \
                           f"Boosts: {active_pkmn.boosts}"

        opponent_pkmn = battle.opponent_active_pokemon
        opp_info_str = "Unknown"
        if opponent_pkmn:
            opp_info_str = f"{opponent_pkmn.species} " \
                           f"(Type: {'/'.join(map(str, opponent_pkmn.types))}) " \
                           f"HP: {opponent_pkmn.current_hp_fraction * 100:.1f}% " \
                           f"Status: {opponent_pkmn.status.name if opponent_pkmn.status else 'None'} " \
                           f"Boosts: {opponent_pkmn.boosts}"
        opponent_pkmn_info = f"Opponent's active Pokemon: {opp_info_str}"

        available_moves_info = "Available moves:\n"
        if battle.available_moves:
            available_moves_info += "\n".join(
                [f"- {move.id} (Type: {move.type}, BP: {move.base_power}, Acc: {move.accuracy}, PP: {move.current_pp}/{move.max_pp}, Cat: {move.category.name})"
                 for move in battle.available_moves]
            )
        else:
             available_moves_info += "- None (Must switch or Struggle)"

        available_switches_info = "Available switches:\n"
        if battle.available_switches:
              available_switches_info += "\n".join(
                  [f"- {pkmn.species} (HP: {pkmn.current_hp_fraction * 100:.1f}%, Status: {pkmn.status.name if pkmn.status else 'None'})"
                   for pkmn in battle.available_switches]
              )
        else:
            available_switches_info += "- None"

        state_str = f"{active_pkmn_info}\n" \
                    f"{opponent_pkmn_info}\n\n" \
                    f"{available_moves_info}\n\n" \
                    f"{available_switches_info}\n\n" \
                    f"Weather: {battle.weather}\n" \
                    f"Terrains: {battle.fields}\n" \
                    f"Your Side Conditions: {battle.side_conditions}\n" \
                    f"Opponent Side Conditions: {battle.opponent_side_conditions}"
        return state_str.strip()

    def _find_move_by_name(self, battle: Battle, move_name: str) -> Optional[Move]:
        normalized_name = normalize_name(move_name)
        # Prioritize exact ID match
        for move in battle.available_moves:
            if move.id == normalized_name:
                return move
        # Fallback: Check display name (less reliable)
        for move in battle.available_moves:
            if move.name.lower() == move_name.lower():
                print(f"Warning: Matched move by display name '{move.name}' instead of ID '{move.id}'. Input was '{move_name}'.")
                return move
        return None

    def _find_pokemon_by_name(self, battle: Battle, pokemon_name: str) -> Optional[Pokemon]:
        normalized_name = normalize_name(pokemon_name)
        for pkmn in battle.available_switches:
            # Normalize the species name for comparison
            if normalize_name(pkmn.species) == normalized_name:
                return pkmn
        return None

    async def choose_move(self, battle: Battle) -> str:
        battle_state_str = self._format_battle_state(battle)
        decision_result = await self._get_llm_decision(battle_state_str)
        print(decision_result)
        decision = decision_result.get("decision")
        error_message = decision_result.get("error")
        action_taken = False
        fallback_reason = ""

        if decision:
            function_name = decision.get("name")
            args = decision.get("arguments", {})
            if function_name == "choose_move":
                move_name = args.get("move_name")
                if move_name:
                    chosen_move = self._find_move_by_name(battle, move_name)
                    if chosen_move and chosen_move in battle.available_moves:
                        action_taken = True
                        chat_msg = f"AI Decision: Using move '{chosen_move.id}'."
                        print(chat_msg)
                        return self.create_order(chosen_move)
                    else:
                        fallback_reason = f"LLM chose unavailable/invalid move '{move_name}'."
                else:
                     fallback_reason = "LLM 'choose_move' called without 'move_name'."
            elif function_name == "choose_switch":
                pokemon_name = args.get("pokemon_name")
                if pokemon_name:
                    chosen_switch = self._find_pokemon_by_name(battle, pokemon_name)
                    if chosen_switch and chosen_switch in battle.available_switches:
                        action_taken = True
                        chat_msg = f"AI Decision: Switching to '{chosen_switch.species}'."
                        print(chat_msg)
                        return self.create_order(chosen_switch)
                    else:
                        fallback_reason = f"LLM chose unavailable/invalid switch '{pokemon_name}'."
                else:
                    fallback_reason = "LLM 'choose_switch' called without 'pokemon_name'."
            else:
                fallback_reason = f"LLM called unknown function '{function_name}'."

        if not action_taken:
            if not fallback_reason:
                 if error_message:
                     fallback_reason = f"API Error: {error_message}"
                 elif decision is None:
                      fallback_reason = "LLM did not provide a valid function call."
                 else:
                      fallback_reason = "Unknown error processing LLM decision."

            print(f"Warning: {fallback_reason} Choosing random action.")

            if battle.available_moves or battle.available_switches:
                 return self.choose_random_move(battle)
            else:
                 print("AI Fallback: No moves or switches available. Using Struggle/Default.")
                 return self.choose_default_move(battle)

    async def _get_llm_decision(self, battle_state: str) -> Dict[str, Any]:
        raise NotImplementedError("Subclasses must implement _get_llm_decision")


# --- Google Gemini Agent ---
class GeminiAgent(LLMAgentBase):
    """Uses Google Gemini API for decisions."""
    def __init__(self, api_key: str = None, model: str = "gemini-2.5-pro-preview-03-25", avatar: str = "steven", *args, **kwargs):
        # Set avatar before calling parent constructor
        kwargs['avatar'] = avatar
        kwargs['start_timer_on_battle_start'] = True
        super().__init__(*args, **kwargs)
        self.model_name = model
        used_api_key = api_key or os.environ.get("GOOGLE_API_KEY")
        if not used_api_key:
            raise ValueError("Google API key not provided or found in GOOGLE_API_KEY env var.")
        
        # Initialize Gemini client using the correct API
        self.genai_client = genai.Client(api_key=used_api_key)
        
        # Configure the tools for function calling
        self.function_declarations = list(self.standard_tools.values())

    async def _get_llm_decision(self, battle_state: str) -> Dict[str, Any]:
        """Sends state to the Gemini API and gets back the function call decision."""
        prompt = (
            "Based on the current battle state, decide the best action: either use an available move or switch to an available Pokémon. "
            "Consider type matchups, HP, status conditions, field effects, entry hazards, and potential opponent actions. "
            "Only choose actions listed as available using their exact ID (for moves) or species name (for switches). "
            "Use the provided functions to indicate your choice.\n\n"
            f"Current Battle State:\n{battle_state}\n\n"
            "Choose the best action by calling the appropriate function ('choose_move' or 'choose_switch')."
        )

        try:
            # Configure tools using the Gemini API format
            tools = genai.types.Tool(function_declarations=self.function_declarations)
            config = genai.types.GenerateContentConfig(tools=[tools],automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True))
            
            # Send request to the model
            response = self.genai_client.models.generate_content(
                model=self.model_name,
                contents=prompt,
                config=config
            )
            try:
                function_calls = response.function_calls
                if function_calls:
                    function_name = function_calls[0].name
                    arguments = function_calls[0].args
                    return {"decision": {"name": function_name, "arguments": arguments}}
                else:
                    return {"error": "Gemini did not return a function call."}
            except Exception as e:
                    return {"error": f"Model called unknown @function '{function_name}'."}
            
            # No function call found
            return {"error": "Gemini did not return a function call."}
            
        except Exception as e:
            print(f"Unexpected error during Gemini processing: {e}")
            import traceback
            traceback.print_exc()
            return {"error": f"Unexpected error: {str(e)}"}


# --- OpenAI Agent ---
class OpenAIAgent(LLMAgentBase):
    """Uses OpenAI API for decisions."""
    def __init__(self, api_key: str = None, model: str = "gpt-4.1", avatar: str = "giovanni", *args, **kwargs):
        # Set avatar before calling parent constructor
        kwargs['avatar'] = avatar
        kwargs['start_timer_on_battle_start'] = True
        super().__init__(*args, **kwargs)
        self.model = model
        used_api_key = api_key or os.environ.get("OPENAI_API_KEY")
        if not used_api_key:
            raise ValueError("OpenAI API key not provided or found in OPENAI_API_KEY env var.")
        self.openai_client = AsyncOpenAI(api_key=used_api_key)

        # Use the OpenAI-specific schema with type field
        self.openai_tools = list(OPENAI_TOOL_SCHEMA.values())

    async def _get_llm_decision(self, battle_state: str) -> Dict[str, Any]:
        system_prompt = (
            "You are a skilled Pokemon battle AI. Your goal is to win the battle. "
            "Based on the current battle state, decide the best action: either use an available move or switch to an available Pokémon. "
            "Consider type matchups, HP, status conditions, field effects, entry hazards, and potential opponent actions. "
            "Only choose actions listed as available using their exact ID (for moves) or species name (for switches). "
            "Use the provided functions to indicate your choice."
        )
        user_prompt = f"Current Battle State:\n{battle_state}\n\nChoose the best action by calling the appropriate function ('choose_move' or 'choose_switch')."

        try:
            response = await self.openai_client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt},
                ],
                tools=self.openai_tools,
                tool_choice="auto",  # Let the model choose
                temperature=0.5,
            )
            message = response.choices[0].message
            print("OPENAI RESPONSE : ",response)
            # Check for tool calls in the response
            if message.tool_calls:
                tool_call = message.tool_calls[0]  # Get the first tool call
                function_name = tool_call.function.name
                try:
                    arguments = json.loads(tool_call.function.arguments or '{}')
                    if function_name in self.standard_tools:
                        return {"decision": {"name": function_name, "arguments": arguments}}
                    else:
                        return {"error": f"Model called unknown function '{function_name}'."}
                except json.JSONDecodeError:
                    return {"error": f"Error decoding function arguments: {tool_call.function.arguments}"}
            else:
                # Model decided not to call a function
                return {"error": f"OpenAI did not return a function call. Response: {message.content}"}

        except APIError as e:
            print(f"Error during OpenAI API call: {e}")
            return {"error": f"OpenAI API Error: {e.status_code} - {e.message}"}
        except Exception as e:
            print(f"Unexpected error during OpenAI API call: {e}")
            return {"error": f"Unexpected error: {e}"}


# --- Mistral Agent ---
class MistralAgent(LLMAgentBase):
    """Uses Mistral AI API for decisions."""
    def __init__(self, api_key: str = None, model: str = "mistral-large-latest", avatar: str = "alder", *args, **kwargs):
        # Set avatar before calling parent constructor
        kwargs['avatar'] = avatar
        kwargs['start_timer_on_battle_start'] = True
        super().__init__(*args, **kwargs)
        self.model = model
        used_api_key = api_key or os.environ.get("MISTRAL_API_KEY")
        if not used_api_key:
            raise ValueError("Mistral API key not provided or found in MISTRAL_API_KEY env var.")
        self.mistral_client = Mistral(api_key=used_api_key)

        # Convert standard schema to Mistral's tool format with "function" wrapper
        self.mistral_tools = []
        for tool_name, tool_schema in self.standard_tools.items():
            self.mistral_tools.append({
                "type": "function",
                "function": {
                    "name": tool_schema["name"],
                    "description": tool_schema["description"],
                    "parameters": tool_schema["parameters"]
                }
            })

    async def _get_llm_decision(self, battle_state: str) -> Dict[str, Any]:
        system_prompt = (
            "You are a skilled Pokemon battle AI. Your goal is to win the battle. "
            "Based on the current battle state, decide the best action: either use an available move or switch to an available Pokémon. "
            "Consider type matchups, HP, status conditions, field effects, entry hazards, and potential opponent actions. "
            "Only choose actions listed as available using their exact ID (for moves) or species name (for switches). "
            "Use the provided tools to indicate your choice."
        )
        user_prompt = f"Current Battle State:\n{battle_state}\n\nChoose the best action by calling the appropriate function ('choose_move' or 'choose_switch')."

        try:
            # Create the messages array
            messages = [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt}
            ]
            
            # Call the Mistral API with tool_choice set to "any" to force tool usage
            response = self.mistral_client.chat.complete(
                model=self.model,
                messages=messages,
                tools=self.mistral_tools,
                tool_choice="any",  # Force the model to use a tool
                temperature=0.3,
            )
            print("Mistral RESPONSE : ", response)
            
            # Check for tool calls in the response
            message = response.choices[0].message
            if hasattr(message, 'tool_calls') and message.tool_calls:
                tool_call = message.tool_calls[0]  # Get the first tool call
                function_name = tool_call.function.name
                try:
                    # Parse the function arguments from JSON string
                    arguments = json.loads(tool_call.function.arguments or '{}')
                    if function_name in self.standard_tools:
                        return {"decision": {"name": function_name, "arguments": arguments}}
                    else:
                        return {"error": f"Model called unknown function '{function_name}'."}
                except json.JSONDecodeError:
                    return {"error": f"Error decoding function arguments: {tool_call.function.arguments}"}
            else:
                # Model did not return a tool call
                return {"error": f"Mistral did not return a tool call. Response: {message.content}"}

        except Exception as e:
            print(f"Error during Mistral API call: {e}")
            import traceback
            traceback.print_exc()
            return {"error": f"Unexpected error: {str(e)}"}