File size: 18,790 Bytes
22cdc3d
 
 
 
 
 
f645c4a
22cdc3d
 
 
 
 
 
6a4f566
22cdc3d
 
 
 
 
 
f645c4a
22cdc3d
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f645c4a
22cdc3d
 
 
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
f645c4a
22cdc3d
 
f645c4a
22cdc3d
f645c4a
22cdc3d
 
 
 
 
 
 
 
f645c4a
22cdc3d
f645c4a
22cdc3d
 
f645c4a
22cdc3d
 
 
f645c4a
22cdc3d
 
 
 
 
f645c4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22cdc3d
 
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
f645c4a
 
 
 
22cdc3d
f645c4a
22cdc3d
f645c4a
 
 
 
 
 
22cdc3d
 
 
 
f645c4a
 
 
 
22cdc3d
 
f645c4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22cdc3d
 
 
f645c4a
22cdc3d
f645c4a
 
22cdc3d
 
 
f645c4a
22cdc3d
 
 
 
 
 
 
 
f645c4a
22cdc3d
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f645c4a
 
22cdc3d
 
 
f645c4a
 
 
 
 
22cdc3d
f645c4a
 
 
22cdc3d
f645c4a
22cdc3d
f645c4a
22cdc3d
f645c4a
22cdc3d
 
 
 
 
 
 
 
 
 
 
 
 
f645c4a
22cdc3d
 
 
 
 
6a4f566
22cdc3d
f645c4a
 
22cdc3d
f645c4a
22cdc3d
 
 
 
 
f645c4a
22cdc3d
 
 
 
693f765
22cdc3d
 
f645c4a
 
22cdc3d
 
f645c4a
22cdc3d
 
 
 
f645c4a
22cdc3d
f645c4a
22cdc3d
f645c4a
 
 
 
 
 
 
 
22cdc3d
f645c4a
 
22cdc3d
f645c4a
22cdc3d
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
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"],
        },
    },
}


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)
        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-1.5-flash", *args, **kwargs):
        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
        genai.configure(api_key=used_api_key)
        
        # Configure the model with tools
        self.gemini_tool_config = [
            {
                "function_declarations": list(self.standard_tools.values())
            }
        ]
        
        # Initialize the model
        self.model = genai.GenerativeModel(
            model_name=self.model_name,
            tools=self.gemini_tool_config
        )

    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 = (
            "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.\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:
            # Use the async API for Gemini
            response = await self.model.generate_content_async(
                prompt,
                generation_config={"temperature": 0.5}
            )
            
            if not response.candidates:
                finish_reason_str = "No candidates found"
                try: 
                    finish_reason_str = response.prompt_feedback.block_reason.name
                except AttributeError: 
                    pass
                return {"error": f"Gemini response issue. Reason: {finish_reason_str}"}

            candidate = response.candidates[0]
            if not candidate.content or not candidate.content.parts:
                finish_reason_str = "Unknown"
                try: 
                    finish_reason_str = candidate.finish_reason.name
                except AttributeError: 
                    pass
                return {"error": f"Gemini response issue. Finish Reason: {finish_reason_str}"}

            for part in candidate.content.parts:
                if hasattr(part, 'function_call') and part.function_call:
                    fc = part.function_call
                    function_name = fc.name
                    # Convert arguments to dict
                    arguments = {}
                    if fc.args:
                        arguments = {k: v for k, v in fc.args.items()}
                    
                    if function_name in self.standard_tools:
                        return {"decision": {"name": function_name, "arguments": arguments}}
                    else:
                        return {"error": f"Model called unknown function '{function_name}'. Args: {arguments}"}
            
            # If we got here, no function call was found in any part
            text_content = " ".join([
                part.text if hasattr(part, 'text') else str(part) 
                for part in candidate.content.parts
            ])
            return {"error": f"Gemini did not return a function call. Response: {text_content[:100]}..."}
            
        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-4o", *args, **kwargs):
        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)

        # Convert standard schema to OpenAI's format
        self.openai_tools = list(self.standard_tools.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
            
            # 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", *args, **kwargs):
        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
        self.mistral_tools = list(self.standard_tools.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 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:
            response = await self.mistral_client.chat.complete(
                model=self.model,
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt}
                ],
                tools=self.mistral_tools,
                tool_choice="auto",  # Let the model choose
                temperature=0.5,
            )
            
            message = response.choices[0].message
            # 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 tool
                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}")
            return {"error": f"Unexpected error: {str(e)}"}