47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
"""AI 玩家代理:优先 LLM,失败自动降级到启发式。"""
|
|
from __future__ import annotations
|
|
|
|
from .fallback import HeuristicAgent
|
|
|
|
|
|
class LLMAgent:
|
|
def __init__(self, player) -> None:
|
|
self.player = player
|
|
self.fallback = HeuristicAgent(player)
|
|
from .llm_client import get_llm_client
|
|
self.client = get_llm_client()
|
|
|
|
async def decide(self, kind: str, ctx: dict):
|
|
try:
|
|
from .prompts import decision_messages
|
|
system, user = decision_messages(kind, ctx)
|
|
data = await self.client.chat_json(system, user)
|
|
target = data.get("target")
|
|
if target is None:
|
|
return None
|
|
target = int(target)
|
|
if ctx["options"] and target not in ctx["options"]:
|
|
return await self.fallback.decide(kind, ctx)
|
|
return target
|
|
except Exception:
|
|
return await self.fallback.decide(kind, ctx)
|
|
|
|
async def speak(self, ctx: dict) -> str:
|
|
try:
|
|
from .prompts import speech_messages
|
|
system, user = speech_messages(ctx)
|
|
text = await self.client.chat_text(system, user, timeout=40.0)
|
|
text = text.strip().strip('"').strip()
|
|
if not text:
|
|
return await self.fallback.speak(ctx)
|
|
return text[:300]
|
|
except Exception:
|
|
return await self.fallback.speak(ctx)
|
|
|
|
|
|
def make_agent(player):
|
|
from ...config import CONFIG
|
|
if CONFIG.llm.configured:
|
|
return LLMAgent(player)
|
|
return HeuristicAgent(player)
|