File size: 5,087 Bytes
225b712
 
8b4b273
 
225b712
 
 
 
8b4b273
225b712
8b4b273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225b712
 
8b4b273
 
 
 
225b712
8b4b273
225b712
 
 
8b4b273
225b712
 
 
8b4b273
 
 
 
 
 
 
 
225b712
8b4b273
 
 
225b712
8b4b273
 
 
 
 
 
 
225b712
8b4b273
225b712
8b4b273
 
225b712
8b4b273
225b712
 
8b4b273
225b712
8b4b273
 
 
 
 
 
225b712
8b4b273
225b712
8b4b273
 
 
225b712
 
 
 
8b4b273
 
225b712
 
 
8b4b273
 
225b712
8b4b273
 
 
225b712
 
 
 
8b4b273
 
225b712
 
 
8b4b273
225b712
8b4b273
 
 
225b712
 
 
 
8b4b273
 
225b712
 
8b4b273
 
 
 
225b712
 
8b4b273
 
 
 
 
225b712
8b4b273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225b712
 
8b4b273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225b712
8b4b273
 
 
225b712
 
 
 
 
 
8b4b273
225b712
 
8b4b273
225b712
 
8b4b273
225b712
 
8b4b273
 
 
225b712
8b4b273
 
 
 
 
 
 
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
import os
import re
from typing import Any, Dict, Optional
from contextlib import asynccontextmanager

from fastapi import FastAPI
from pydantic import BaseModel
from transformers import AutoProcessor, AutoModelForCausalLM
import torch

# =========================
# Configuration
# =========================
MODEL_ID = os.getenv("GEMMA_MODEL_ID", "google/functiongemma-270m-it")

processor = None
model = None

# =========================
# Function Call Parser
# =========================
ESC = "<escape>"
START = "<start_function_call>"
END = "<end_function_call>"

def _split_commas(s: str):
    parts, buf, esc = [], [], False
    i = 0
    while i < len(s):
        if s.startswith(ESC, i):
            esc = not esc
            buf.append(ESC)
            i += len(ESC)
            continue
        if s[i] == "," and not esc:
            parts.append("".join(buf).strip())
            buf = []
        else:
            buf.append(s[i])
        i += 1
    if buf:
        parts.append("".join(buf).strip())
    return parts

def _parse_value(v: str):
    v = v.strip()
    if v.startswith(ESC) and v.endswith(ESC):
        return v[len(ESC):-len(ESC)]
    if v.lower() in ("true", "false"):
        return v.lower() == "true"
    try:
        if "." in v:
            return float(v)
        return int(v)
    except ValueError:
        return v

def parse_function_call(text: str):
    if START not in text:
        return None

    m = re.search(rf"{START}(.*?){END}", text, re.DOTALL)
    if not m:
        return None

    body = m.group(1).strip()
    m2 = re.match(r"call:([a-zA-Z0-9_]+)\{(.*)\}$", body, re.DOTALL)
    if not m2:
        return None

    name = m2.group(1)
    args_raw = m2.group(2).strip()

    args = {}
    if args_raw:
        for kv in _split_commas(args_raw):
            if ":" in kv:
                k, v = kv.split(":", 1)
                args[k.strip()] = _parse_value(v)

    return {"name": name, "arguments": args}

# =========================
# Tools (Robot Actions)
# =========================
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "move",
            "description": "Move forward or backward",
            "parameters": {
                "type": "object",
                "properties": {
                    "direction": {"type": "string"},
                    "speed": {"type": "number"}
                },
                "required": ["direction", "speed"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "turn",
            "description": "Rotate left or right",
            "parameters": {
                "type": "object",
                "properties": {
                    "angle": {"type": "number"}
                },
                "required": ["angle"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "pause",
            "description": "Stop and observe",
            "parameters": {
                "type": "object",
                "properties": {}
            }
        }
    }
]

# =========================
# FastAPI Lifespan
# =========================
@asynccontextmanager
async def lifespan(app: FastAPI):
    global processor, model
    processor = AutoProcessor.from_pretrained(MODEL_ID)
    model = AutoModelForCausalLM.from_pretrained(
        MODEL_ID,
        torch_dtype=torch.float32,
        device_map="auto"
    )
    yield
    # shutdown処理(今回は不要)

app = FastAPI(
    title="FunctionGemma Robot Brain",
    lifespan=lifespan
)

# =========================
# API Schema
# =========================
class DecideRequest(BaseModel):
    observation: Dict[str, Any]
    persona: Optional[str] = "curious"

class DecideResponse(BaseModel):
    action: Optional[Dict[str, Any]]
    raw: str

# =========================
# Endpoints
# =========================
@app.get("/health")
def health():
    return {"status": "ok", "model": MODEL_ID}

@app.post("/decide", response_model=DecideResponse)
def decide(req: DecideRequest):
    system = (
        "You are a small exploration robot.\n"
        "You must choose exactly ONE action function.\n"
        "You are curious but avoid real danger.\n"
        f"Persona: {req.persona}"
    )

    user = f"""
Observation:
{req.observation}

Choose the next action.
"""

    messages = [
        {"role": "developer", "content": "You can call functions."},
        {"role": "system", "content": system},
        {"role": "user", "content": user}
    ]

    inputs = processor.apply_chat_template(
        messages,
        tools=TOOLS,
        add_generation_prompt=True,
        return_tensors="pt"
    )

    outputs = model.generate(
        **inputs.to(model.device),
        max_new_tokens=128,
        pad_token_id=processor.eos_token_id
    )

    decoded = processor.decode(
        outputs[0][inputs["input_ids"].shape[-1]:],
        skip_special_tokens=True
    )

    action = parse_function_call(decoded)

    return {
        "action": action,
        "raw": decoded
    }