智慧體課程文件
構建你自己的寶可夢對戰智慧體
並獲得增強的文件體驗
開始使用
構建你自己的寶可夢對戰智慧體
既然你已經探索了代理AI在遊戲中的潛力和侷限性,現在是時候動手實踐了。在本節中,你將運用本課程所學的一切,構建你自己的AI智慧體,以進行寶可夢式的回合制戰鬥。
我們將系統分解為四個關鍵構建塊:
Poke-env: 一個旨在訓練基於規則或強化學習寶可夢機器人的Python庫。
Pokémon Showdown: 一個線上對戰模擬器,你的智慧體將在其中進行戰鬥。
LLMAgentBase: 我們構建的一個自定義Python類,用於將你的LLM連線到Poke-env對戰環境。
TemplateAgent: 一個你將完成的起始模板,用於建立你自己獨特的對戰智慧體。
讓我們更詳細地探討這些元件。
🧠 Poke-env
Poke-env 是一個Python介面,最初由 Haris Sahovic 構建,用於訓練強化學習機器人,但我們將其重新用於代理AI。
它允許你的智慧體透過簡單的API與Pokémon Showdown互動。
它提供了一個`Player`類,你的智慧體將繼承自該類,涵蓋了與圖形介面通訊所需的一切。
文件: poke-env.readthedocs.io
倉庫: github.com/hsahovic/poke-env
⚔️ Pokémon Showdown
Pokémon Showdown 是一個開源對戰模擬器,你的智慧體將在這裡進行即時寶可夢對戰。
它提供了一個完整的介面,可以即時模擬和顯示戰鬥。在我們的挑戰中,你的機器人將像人類玩家一樣,逐回合選擇行動。
我們已經部署了一個伺服器,所有參與者都將使用該伺服器進行對戰。讓我們看看誰能構建出最強大的AI對戰智慧體!
倉庫: github.com/smogon/Pokemon-Showdown
網站: pokemonshowdown.com
🔌 LLMAgentBase
LLMAgentBase
是一個 Python 類,它擴充套件了 Poke-env 的 Player
類。
它充當你的 LLM 和 寶可夢對戰模擬器 之間的橋樑,負責處理輸入/輸出格式化和維護戰鬥上下文。
這個基礎智慧體提供了一套工具(在 STANDARD_TOOL_SCHEMA
中定義),用於與環境互動,包括:
choose_move
:用於在戰鬥中選擇攻擊choose_switch
:用於切換寶可夢
LLM 應該使用這些工具在比賽中做出決策。
🧠 核心邏輯
choose_move(battle: Battle)
: 這是每回合調用的主要方法。它接收一個Battle
物件,並根據 LLM 的輸出返回一個動作字串。
🔧 關鍵內部方法
_format_battle_state(battle)
: 將當前戰鬥狀態轉換為字串,使其適合傳送給 LLM。_find_move_by_name(battle, move_name)
: 根據名稱查詢招式,用於呼叫choose_move
的 LLM 響應中。_find_pokemon_by_name(battle, pokemon_name)
: 根據 LLM 的切換指令,定位要切換到的特定寶可夢。_get_llm_decision(battle_state)
: 此方法在基類中是抽象的。你需要在你自己的代理中實現它(參見下一節),在那裡你定義如何查詢 LLM 並解析其響應。
這是展示決策如何工作的一個片段:
STANDARD_TOOL_SCHEMA = {
"choose_move": {
...
},
"choose_switch": {
...
},
}
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")
完整原始碼: agents.py
🧪 TemplateAgent
現在,有趣的部分來了!以 LLMAgentBase 為基礎,是時候實現你自己的智慧體了,用你自己的策略來攀登排行榜。
你將從這個模板開始,構建你自己的邏輯。我們還提供了三個使用 OpenAI、Mistral 和 Gemini 模型的完整示例來指導你。
這是一個簡化版的模板:
class TemplateAgent(LLMAgentBase):
"""Uses Template AI API for decisions."""
def __init__(self, api_key: str = None, model: str = "model-name", *args, **kwargs):
super().__init__(*args, **kwargs)
self.model = model
self.template_client = TemplateModelProvider(api_key=...)
self.template_tools = list(self.standard_tools.values())
async def _get_llm_decision(self, battle_state: str) -> Dict[str, Any]:
"""Sends state to the LLM and gets back the function call decision."""
system_prompt = (
"You are a ..."
)
user_prompt = f"..."
try:
response = await self.template_client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
)
message = response.choices[0].message
return {"decision": {"name": function_name, "arguments": arguments}}
except Exception as e:
print(f"Unexpected error during call: {e}")
return {"error": f"Unexpected error: {e}"}
這段程式碼不能直接執行,它是你自定義邏輯的藍圖。
所有準備就緒後,輪到你來構建一個有競爭力的智慧體了。在下一節中,我們將展示如何將你的智慧體部署到我們的伺服器上,並與其他智慧體進行即時對戰。
戰鬥開始!🔥
< > 在 GitHub 上更新