|
|
import re |
|
|
from typing import Dict, Optional |
|
|
from fastapi import FastAPI |
|
|
from pydantic import BaseModel |
|
|
from mlx_lm import load, generate |
|
|
from mlx_lm.sample_utils import make_sampler |
|
|
|
|
|
base_model_id = "qwen2.5-0.5b-instruct-sumobot" |
|
|
lora_adapter_or_id = "qwen2.5-0.5b-instruct-sumobot" |
|
|
|
|
|
model, tokenizer = load(base_model_id, adapter_path=lora_adapter_or_id) |
|
|
|
|
|
def parse_action(output: str): |
|
|
|
|
|
action_map = { |
|
|
"SK": "Skill", |
|
|
"DS": "Dash", |
|
|
"FWD": "Accelerate", |
|
|
"TL": "TurnLeft", |
|
|
"TR": "TurnRight", |
|
|
} |
|
|
|
|
|
actions: Dict[str, Optional[float]] = {} |
|
|
|
|
|
for part in [p.strip() for p in output.split(",")]: |
|
|
name = part |
|
|
duration = None |
|
|
|
|
|
direct_match = re.match(r"^([A-Za-z]+)\s*([\d.]+)$", part) |
|
|
if direct_match: |
|
|
name = direct_match.group(1).strip() |
|
|
duration = float(direct_match.group(2)) |
|
|
|
|
|
|
|
|
for short, full in action_map.items(): |
|
|
if name.upper().startswith(short): |
|
|
name = full |
|
|
break |
|
|
|
|
|
actions[name] = duration |
|
|
|
|
|
return {"action": actions} |
|
|
|
|
|
|
|
|
def get_finetuned_action(query_state): |
|
|
|
|
|
messages = [ |
|
|
{"role": "system", "content": "You are a Sumobot assistant that decides actions based on game state."}, |
|
|
{"role": "user", "content": f"Given this game state: {query_state}"}, |
|
|
] |
|
|
|
|
|
|
|
|
chat_prompt = tokenizer.apply_chat_template( |
|
|
messages, |
|
|
tokenize=False, |
|
|
add_generation_prompt=True |
|
|
) |
|
|
|
|
|
result = "" |
|
|
for token in generate(model, tokenizer, chat_prompt, max_tokens=50): |
|
|
result += token |
|
|
|
|
|
parsedResult = parse_action(result) |
|
|
return parsedResult |
|
|
|
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
class QueryInput(BaseModel): |
|
|
state: str |
|
|
|
|
|
@app.post("/query") |
|
|
def query(input: QueryInput): |
|
|
return get_finetuned_action(input.state) |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
uvicorn.run(app, host="0.0.0.0", port=8000) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|