| |
| """ |
| ALFWorld 合成トラジェクトリ生成スクリプト v2 |
| ============================================= |
| v1からの改善: |
| - go toの探索パターンを大幅に多様化 |
| - 実際のALFWorld環境に近いレセプタクル構成(cabinet 1-15等) |
| - 探索失敗パターンの多様化(closed→open、空、多数のアイテム等) |
| - 探索長の現実的な分布(短い探索〜長い探索) |
| - 部屋レイアウトのバリエーション強化 |
| |
| 使い方: |
| python generate_alfworld_synthetic_v2.py --output synthetic_alfworld_v2.jsonl --count 3000 --focus-weak |
| """ |
|
|
| import json |
| import random |
| import argparse |
| from typing import List, Dict, Any, Tuple, Optional |
| from dataclasses import dataclass, field |
| from copy import deepcopy |
|
|
|
|
| |
| |
| |
| |
| |
|
|
| ROOM_TEMPLATES = { |
| "kitchen_large": { |
| "cabinet": (8, 15), |
| "countertop": (2, 4), |
| "drawer": (2, 4), |
| "fridge": (1, 1), |
| "microwave": (1, 1), |
| "sinkbasin": (1, 1), |
| "stoveburner": (2, 4), |
| "toaster": (1, 1), |
| "coffeemachine": (1, 1), |
| "garbagecan": (1, 1), |
| "shelf": (0, 3), |
| }, |
| "kitchen_medium": { |
| "cabinet": (5, 10), |
| "countertop": (1, 3), |
| "drawer": (1, 3), |
| "fridge": (1, 1), |
| "microwave": (1, 1), |
| "sinkbasin": (1, 1), |
| "stoveburner": (2, 4), |
| "toaster": (0, 1), |
| "coffeemachine": (0, 1), |
| "garbagecan": (1, 1), |
| }, |
| "kitchen_small": { |
| "cabinet": (3, 6), |
| "countertop": (1, 2), |
| "drawer": (1, 2), |
| "fridge": (1, 1), |
| "microwave": (1, 1), |
| "sinkbasin": (1, 1), |
| "stoveburner": (1, 2), |
| "garbagecan": (1, 1), |
| }, |
| "bedroom_large": { |
| "bed": (1, 1), |
| "dresser": (1, 2), |
| "drawer": (2, 6), |
| "desk": (1, 1), |
| "shelf": (1, 4), |
| "sidetable": (1, 2), |
| "garbagecan": (1, 1), |
| "laundryhamper": (0, 1), |
| "safe": (0, 1), |
| }, |
| "bedroom_small": { |
| "bed": (1, 1), |
| "dresser": (0, 1), |
| "drawer": (1, 3), |
| "desk": (0, 1), |
| "shelf": (0, 2), |
| "sidetable": (1, 2), |
| "garbagecan": (1, 1), |
| }, |
| "livingroom": { |
| "sofa": (1, 2), |
| "coffeetable": (1, 1), |
| "sidetable": (1, 3), |
| "shelf": (1, 6), |
| "drawer": (1, 4), |
| "armchair": (1, 2), |
| "ottoman": (0, 1), |
| "tvstand": (0, 1), |
| "garbagecan": (1, 1), |
| "dresser": (0, 1), |
| }, |
| "bathroom": { |
| "sinkbasin": (1, 2), |
| "bathtub": (0, 1), |
| "toilet": (1, 1), |
| "shelf": (1, 3), |
| "drawer": (0, 2), |
| "cabinet": (1, 4), |
| "towelholder": (0, 1), |
| "garbagecan": (1, 1), |
| }, |
| } |
|
|
|
|
| |
| OBJECTS = { |
| "heatable": [ |
| "apple", "bread", "cup", "egg", "mug", "plate", |
| "potato", "bowl", "tomato", |
| ], |
| "coolable": [ |
| "apple", "bowl", "bread", "cup", "egg", "lettuce", |
| "mug", "plate", "potato", "tomato", "wine", |
| ], |
| "cleanable": [ |
| "apple", "bowl", "cloth", "cup", "fork", "knife", |
| "ladle", "lettuce", "mug", "pan", "plate", "pot", |
| "soapbar", "spatula", "spoon", "tomato", |
| ], |
| "examinable": [ |
| "alarmclock", "book", "bowl", "box", "candle", "cd", |
| "cellphone", "cloth", "creditcard", "cup", "houseplant", |
| "keychain", "laptop", "lettuce", "mug", "newspaper", |
| "pen", "pencil", "pillow", "plate", "remotecontrol", |
| "statue", "vase", "watch", |
| ], |
| "pickable": [ |
| "apple", "book", "bowl", "box", "bread", "butterknife", |
| "candle", "cd", "cellphone", "cloth", "creditcard", "cup", |
| "dishsponge", "egg", "fork", "houseplant", "kettle", |
| "keychain", "knife", "ladle", "lettuce", "mug", |
| "newspaper", "pan", "pen", "pencil", "peppershaker", |
| "pillow", "plate", "plunger", "pot", "potato", |
| "remotecontrol", "saltshaker", "soapbar", "soapbottle", |
| "spatula", "spoon", "statue", "teddybear", "tissuebox", |
| "toiletpaper", "tomato", "towel", "vase", |
| "watch", "wateringcan", |
| ], |
| "lamps": ["desklamp", "floorlamp"], |
| } |
|
|
| PLACEMENT_TARGETS = [ |
| "countertop", "shelf", "cabinet", "drawer", "dresser", |
| "desk", "sidetable", "coffeetable", "sofa", "armchair", |
| "bed", "ottoman", "tvstand", "garbagecan", "fridge", |
| "bathtub", "toilet", "safe", |
| ] |
|
|
| |
| OPENABLE_RECEPTACLES = { |
| "cabinet", "drawer", "fridge", "microwave", "safe", |
| } |
|
|
| |
| |
| |
|
|
| THINK_FIND_OBJECT_INITIAL = [ |
| "Think: I need to find a {obj} first. Let me look around the room. A {obj} is more likely to appear in {recep}. I'll go there first.", |
| "Think: My task requires a {obj}. I should check {recep} - that seems like a reasonable place to look.", |
| "Think: To accomplish this task, I first need to locate a {obj}. I'll start searching from {recep}.", |
| "Think: I need to find a {obj}. {recep_type}s might have one. Let me check {recep}.", |
| "Think: First, let me find a {obj}. I'll try {recep} since it's a common place for household items.", |
| "Think: Let me start by finding a {obj}. I'll go to {recep} to look for one.", |
| "Think: I need a {obj}. Let me search {recep} first - {obj}s are often found there.", |
| "Think: The first step is to find a {obj}. I'll check {recep}.", |
| "Think: I should look for a {obj}. Let me start with {recep}.", |
| "Think: My goal requires a {obj}. I'll begin my search at {recep}.", |
| ] |
|
|
| THINK_NOT_FOUND_CONTINUE = [ |
| "Think: The {obj} is not here. Let me try another location. I'll go to {next_recep}.", |
| "Think: No {obj} in {recep}. I'll check {next_recep} next.", |
| "Think: I don't see a {obj} here. Let me look in {next_recep}.", |
| "Think: {recep} doesn't have a {obj}. Moving on to {next_recep}.", |
| "Think: Not here. I should try {next_recep} to find the {obj}.", |
| "Think: The {obj} isn't on {recep}. Let me search {next_recep}.", |
| "Think: Still looking for a {obj}. Let me check {next_recep}.", |
| "Think: I need to keep searching. I'll try {next_recep} for the {obj}.", |
| "Think: No luck with {recep}. Let me try {next_recep}.", |
| "Think: Didn't find a {obj} on {recep}. Next, I'll check {next_recep}.", |
| ] |
|
|
| THINK_FOUND_OBJECT = [ |
| "Think: I found a {obj} {id} on {recep}. I should take it.", |
| "Think: Great, there's a {obj} {id} here. Let me pick it up.", |
| "Think: I can see a {obj} {id} on {recep}. I'll take it.", |
| "Think: Found it! A {obj} {id} is on {recep}. I need to pick it up.", |
| "Think: There's a {obj} {id} on the {recep}. Let me take it.", |
| "Think: I see a {obj} {id}. Let me grab it to continue the task.", |
| "Think: Good, {recep} has a {obj} {id}. I'll pick it up now.", |
| "Think: Found a {obj} {id} here. I should take it for my task.", |
| ] |
|
|
| THINK_OPEN_CLOSED = [ |
| "Think: The {recep} is closed. I need to open it first to see what's inside.", |
| "Think: {recep} is closed. Let me open it.", |
| "Think: I can't see inside because {recep} is closed. I'll open it.", |
| "Think: It's closed. Let me open {recep} to check for items.", |
| "Think: I need to open {recep} first before I can look inside.", |
| ] |
|
|
| THINK_GO_TO_TARGET = [ |
| "Think: Now I need to put the {obj} in/on {recep}. Let me go there.", |
| "Think: I have the {obj}. I need to go to {recep} and place it there.", |
| "Think: Good, I picked up the {obj}. Time to bring it to {recep}.", |
| "Think: With the {obj} in hand, I need to head to {recep}.", |
| "Think: Now I should take this {obj} to {recep}.", |
| "Think: The next step is to go to {recep} with the {obj}.", |
| "Think: Let me bring the {obj} to {recep} to complete this step.", |
| ] |
|
|
| THINK_CLEAN = [ |
| "Think: Now I need to clean the {obj}. I should go to sinkbasin and wash it.", |
| "Think: The task requires a clean {obj}. Let me go to {recep} to wash it.", |
| "Think: I have the {obj} and need to clean it. I'll use the sinkbasin.", |
| "Think: Before placing the {obj}, I need to wash it at {recep}.", |
| "Think: To clean the {obj}, I need to go to {recep} and use it.", |
| "Think: I should clean the {obj} now. The sinkbasin is where I can do that.", |
| ] |
|
|
| THINK_HEAT = [ |
| "Think: I need to heat the {obj}. I should use the microwave.", |
| "Think: The task requires a hot {obj}. Let me heat it with {recep}.", |
| "Think: I have the {obj} and need to heat it. The microwave will do.", |
| "Think: Before placing the {obj}, I need to heat it using {recep}.", |
| "Think: To heat the {obj}, I'll go to {recep}.", |
| "Think: Now I need to heat the {obj} in the microwave.", |
| ] |
|
|
| THINK_COOL = [ |
| "Think: I need to cool the {obj}. I should use the fridge.", |
| "Think: The task requires a cool {obj}. Let me cool it with {recep}.", |
| "Think: I have the {obj} and need to cool it. The fridge is the right place.", |
| "Think: Before placing the {obj}, I need to cool it using {recep}.", |
| "Think: To cool the {obj}, I'll put it in {recep}.", |
| "Think: Now I need to cool the {obj} in the fridge.", |
| ] |
|
|
| THINK_EXAMINE = [ |
| "Think: I need to examine the {obj} under a light source. Let me find a {lamp} and use it.", |
| "Think: Now I need to look at the {obj} under a lamp. I should go to {lamp} and turn it on.", |
| "Think: To examine the {obj}, I need a light. Let me go to {lamp}.", |
| "Think: The task requires examining the {obj} under {lamp}. Let me go there.", |
| "Think: I have the {obj}. Now I need to use {lamp} to examine it.", |
| "Think: Now I should find {lamp} and use it to examine the {obj}.", |
| ] |
|
|
| THINK_PLACE = [ |
| "Think: Now I need to put the {obj} in/on {recep}.", |
| "Think: Time to place the {obj} in/on {recep}.", |
| "Think: I should put the {obj} in/on {recep} now.", |
| "Think: Almost done. Let me place the {obj} in/on {recep}.", |
| "Think: Final step - putting the {obj} in/on {recep}.", |
| "Think: Let me put the {obj} down on {recep}.", |
| "Think: I'll place the {obj} in/on {recep} to complete the task.", |
| ] |
|
|
| THINK_PICK_SECOND = [ |
| "Think: Good, I placed the first {obj}. Now I need to find another {obj} and put it in {recep} too.", |
| "Think: One {obj} done. I need to find a second one for this task.", |
| "Think: First {obj} placed successfully. Now let me look for another {obj}.", |
| "Think: I've placed one {obj}. Time to find the second one. Let me search again.", |
| ] |
|
|
|
|
| |
| |
| |
|
|
| def generate_room_v2(rng: random.Random, room_template_key: str = None, |
| ensure_objects: List[str] = None, |
| ensure_receptacles: List[str] = None): |
| """ |
| 実際のALFWorld環境に近いレセプタクル構成で部屋を生成する。 |
| cabinet 1-13 のような広い番号範囲を持つ部屋が生成される。 |
| """ |
| if room_template_key is None: |
| room_template_key = rng.choice(list(ROOM_TEMPLATES.keys())) |
|
|
| template = ROOM_TEMPLATES[room_template_key] |
|
|
| |
| recep_names = [] |
| recep_type_counts = {} |
| for recep_type, (lo, hi) in template.items(): |
| count = rng.randint(lo, hi) |
| if count > 0: |
| recep_type_counts[recep_type] = count |
| for i in range(1, count + 1): |
| recep_names.append(f"{recep_type} {i}") |
|
|
| |
| if ensure_receptacles: |
| for r in ensure_receptacles: |
| |
| r_name = f"{r} 1" if " " not in r else r |
| if r_name not in recep_names: |
| recep_names.append(r_name) |
|
|
| |
| items_on = {} |
| all_pickable = list(OBJECTS["pickable"]) |
|
|
| for recep_name in recep_names: |
| recep_type = recep_name.rsplit(" ", 1)[0] |
| |
| if recep_type in OPENABLE_RECEPTACLES: |
| num_items = rng.choices([0, 1, 2], weights=[0.4, 0.4, 0.2])[0] |
| else: |
| num_items = rng.choices([0, 1, 2, 3, 4], weights=[0.25, 0.30, 0.25, 0.15, 0.05])[0] |
|
|
| items = [] |
| for _ in range(num_items): |
| obj = rng.choice(all_pickable) |
| obj_id = rng.randint(1, 3) |
| items.append((obj, obj_id)) |
| items_on[recep_name] = items |
|
|
| |
| if ensure_objects: |
| for obj in ensure_objects: |
| |
| open_receps = [r for r in recep_names |
| if r.rsplit(" ", 1)[0] not in OPENABLE_RECEPTACLES] |
| target = rng.choice(open_receps if open_receps else recep_names) |
| obj_id = rng.randint(1, 3) |
| items_on.setdefault(target, []).append((obj, obj_id)) |
|
|
| |
| desc_receps = list(recep_names) |
| rng.shuffle(desc_receps) |
| parts = [f"a {r}" for r in desc_receps] |
| if len(parts) > 1: |
| room_items = ", ".join(parts[:-1]) + ", and " + parts[-1] |
| else: |
| room_items = parts[0] |
| room_desc = f"You are in the middle of a room. Looking quickly around you, you see {room_items}." |
|
|
| return items_on, room_desc, recep_names |
|
|
|
|
| |
| |
| |
|
|
| TOOLS_DEFINITION = [ |
| { |
| "type": "function", |
| "function": { |
| "name": "act", |
| "description": "Execute an action in the household environment.", |
| "parameters": { |
| "type": "object", |
| "properties": { |
| "action": { |
| "type": "string", |
| "description": "The action to execute" |
| } |
| }, |
| "required": ["action"] |
| } |
| } |
| } |
| ] |
|
|
| SYSTEM_PROMPT = ( |
| "Interact with a household to solve a task. Imagine you are an intelligent agent " |
| "in a household environment and your target is to perform actions to complete the " |
| "task goal. At the beginning of your interactions, you will be given the detailed " |
| "description of the current environment and your goal to accomplish. For each of " |
| "your turn, you will be given the observation of the last executed action. You are " |
| "only allowed to output an action at each turn, and you should think about what to " |
| "do before outputting an action. Your output must strictly follow this format: " |
| "\"Think: your thoughts.\\nAct: your next action\".\n" |
| "Your available actions are:\n" |
| "1. go to {recep}\n2. take {obj} from {recep}\n3. put {obj} in/on {recep}\n" |
| "4. open {recep}\n5. close {recep}\n6. toggle {obj} {recep}\n" |
| "7. clean {obj} with {recep}\n8. heat {obj} with {recep}\n" |
| "9. cool {obj} with {recep}\n10. use {recep}\n11. look" |
| ) |
|
|
|
|
| def _sys(): |
| return {"role": "system", "content": SYSTEM_PROMPT} |
|
|
| def _user(content): |
| return {"role": "user", "content": content} |
|
|
| def _assistant(think_act_text, action, call_id): |
| return { |
| "role": "assistant", |
| "content": think_act_text, |
| "tool_calls": [{ |
| "id": call_id, |
| "type": "function", |
| "function": { |
| "name": "act", |
| "arguments": json.dumps({"action": action}) |
| } |
| }] |
| } |
|
|
| def _tool(call_id, observation): |
| return {"role": "tool", "tool_call_id": call_id, "content": observation} |
|
|
| def _call_id(step, rng): |
| return f"call_{step}_{rng.randint(1000, 9999)}" |
|
|
|
|
| |
| |
| |
|
|
| def make_observation_for_recep(rng, recep_name, items_on, force_items=None): |
| """ |
| レセプタクルを訪問した際の観察テキストを生成する。 |
| 開閉可能なレセプタクルの場合は closed 状態を返すこともある。 |
| """ |
| recep_type = recep_name.rsplit(" ", 1)[0] |
| items = force_items if force_items is not None else items_on.get(recep_name, []) |
|
|
| if items: |
| items_parts = [] |
| for obj, oid in items: |
| items_parts.append(f"a {obj} {oid}") |
| items_str = ", ".join(items_parts[:-1]) + ", and " + items_parts[-1] if len(items_parts) > 1 else items_parts[0] |
| return f"On the {recep_name}, you see {items_str}." |
| else: |
| return f"On the {recep_name}, you see nothing." |
|
|
|
|
| def make_open_observation(rng, recep_name, items_on): |
| """開閉可能レセプタクルを開けた際の観察""" |
| items = items_on.get(recep_name, []) |
| if items: |
| items_parts = [f"a {obj} {oid}" for obj, oid in items] |
| items_str = ", ".join(items_parts[:-1]) + ", and " + items_parts[-1] if len(items_parts) > 1 else items_parts[0] |
| return f"You open the {recep_name}. The {recep_name} is open. In it, you see {items_str}." |
| else: |
| return f"You open the {recep_name}. The {recep_name} is open. In it, you see nothing." |
|
|
|
|
| |
| |
| |
|
|
| def generate_search_trajectory(rng, obj_name, items_on, recep_names, |
| start_step, search_strategy=None): |
| """ |
| オブジェクトを探すトラジェクトリを生成する。 |
| |
| 探索戦略(search_strategy): |
| - "sequential": 番号順に探す(cabinet 1, 2, 3...) |
| - "random": ランダム順 |
| - "type_first": 特定のレセプタクルタイプを優先 |
| - "high_number_first": 大きい番号から探す |
| - "mixed": 異なるタイプを交互に探す |
| - None: ランダムに戦略を選択 |
| """ |
| msgs = [] |
| step = start_step |
|
|
| |
| if search_strategy is None: |
| search_strategy = rng.choice([ |
| "random", "random", "random", |
| "type_first", "type_first", |
| "high_number_first", |
| "mixed", |
| "sequential", |
| ]) |
|
|
| |
| target_locations = [] |
| for recep_name, items in items_on.items(): |
| for (o, oid) in items: |
| if o == obj_name: |
| target_locations.append((recep_name, oid)) |
|
|
| if not target_locations: |
| |
| non_openable = [r for r in recep_names |
| if r.rsplit(" ", 1)[0] not in OPENABLE_RECEPTACLES] |
| place_recep = rng.choice(non_openable if non_openable else recep_names) |
| obj_id = rng.randint(1, 3) |
| items_on.setdefault(place_recep, []).append((obj_name, obj_id)) |
| target_locations = [(place_recep, obj_id)] |
|
|
| found_recep, found_id = rng.choice(target_locations) |
|
|
| |
| search_pool = [r for r in recep_names if r != found_recep] |
|
|
| if search_strategy == "sequential": |
| |
| search_pool.sort(key=lambda r: (r.rsplit(" ", 1)[0], int(r.rsplit(" ", 1)[1]))) |
| elif search_strategy == "high_number_first": |
| search_pool.sort(key=lambda r: -int(r.rsplit(" ", 1)[1])) |
| elif search_strategy == "type_first": |
| |
| preferred = rng.sample(["countertop", "shelf", "sidetable", "dresser", |
| "desk", "coffeetable", "drawer", "cabinet", |
| "stoveburner", "bed", "sofa", "armchair"], 3) |
| def priority(r): |
| rtype = r.rsplit(" ", 1)[0] |
| return (0 if rtype in preferred else 1, rng.random()) |
| search_pool.sort(key=priority) |
| elif search_strategy == "mixed": |
| |
| by_type = {} |
| for r in search_pool: |
| rtype = r.rsplit(" ", 1)[0] |
| by_type.setdefault(rtype, []).append(r) |
| for v in by_type.values(): |
| rng.shuffle(v) |
| types = list(by_type.keys()) |
| rng.shuffle(types) |
| mixed = [] |
| while any(by_type[t] for t in types if t in by_type): |
| for t in types: |
| if t in by_type and by_type[t]: |
| mixed.append(by_type[t].pop(0)) |
| search_pool = mixed |
| else: |
| rng.shuffle(search_pool) |
|
|
| |
| max_search = rng.choices( |
| [1, 2, 3, 4, 5, 6, 7, 8], |
| weights=[0.15, 0.20, 0.25, 0.15, 0.10, 0.07, 0.05, 0.03], |
| )[0] |
| max_search = min(max_search, len(search_pool)) |
|
|
| |
| for i in range(max_search): |
| recep = search_pool[i] |
| recep_type = recep.rsplit(" ", 1)[0] |
| call_id = _call_id(step, rng) |
| next_recep = search_pool[i + 1] if i + 1 < len(search_pool) else found_recep |
|
|
| |
| if i == 0: |
| think = rng.choice(THINK_FIND_OBJECT_INITIAL).format( |
| obj=obj_name, recep=recep, recep_type=recep_type |
| ) |
| else: |
| think = rng.choice(THINK_NOT_FOUND_CONTINUE).format( |
| obj=obj_name, recep=search_pool[i-1] if i > 0 else recep, |
| next_recep=recep |
| ) |
|
|
| action = f"go to {recep}" |
|
|
| |
| is_openable = recep_type in OPENABLE_RECEPTACLES |
| is_closed = is_openable and rng.random() < 0.4 |
|
|
| if is_closed: |
| obs = f"The {recep} is closed." |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| |
| call_id2 = _call_id(step, rng) |
| think2 = rng.choice(THINK_OPEN_CLOSED).format(recep=recep) |
| action2 = f"open {recep}" |
| obs2 = make_open_observation(rng, recep, items_on) |
| msgs.append(_assistant(think2 + f"\nAct: {action2}", action2, call_id2)) |
| msgs.append(_tool(call_id2, obs2)) |
| step += 1 |
| else: |
| obs = make_observation_for_recep(rng, recep, items_on) |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| |
| call_id = _call_id(step, rng) |
| if max_search == 0: |
| think = rng.choice(THINK_FIND_OBJECT_INITIAL).format( |
| obj=obj_name, recep=found_recep, |
| recep_type=found_recep.rsplit(" ", 1)[0] |
| ) |
| else: |
| think = rng.choice(THINK_NOT_FOUND_CONTINUE).format( |
| obj=obj_name, recep=search_pool[max_search - 1] if max_search > 0 else "nowhere", |
| next_recep=found_recep |
| ) |
| action = f"go to {found_recep}" |
|
|
| |
| found_type = found_recep.rsplit(" ", 1)[0] |
| found_closed = found_type in OPENABLE_RECEPTACLES and rng.random() < 0.3 |
|
|
| if found_closed: |
| obs = f"The {found_recep} is closed." |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| call_id = _call_id(step, rng) |
| think = rng.choice(THINK_OPEN_CLOSED).format(recep=found_recep) |
| action = f"open {found_recep}" |
| obs = make_open_observation(rng, found_recep, items_on) |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
| else: |
| obs = make_observation_for_recep(rng, found_recep, items_on) |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| |
| call_id = _call_id(step, rng) |
| obj_full = f"{obj_name} {found_id}" |
| think = rng.choice(THINK_FOUND_OBJECT).format( |
| obj=obj_name, recep=found_recep, id=found_id |
| ) |
| action = f"take {obj_full} from {found_recep}" |
| obs = f"You pick up the {obj_full} from the {found_recep}." |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| return msgs, found_recep, obj_full, found_id, step |
|
|
|
|
| |
| |
| |
|
|
| def _go_and_place(rng, msgs, step, obj_full, target_recep, items_on): |
| """目的地に移動して置くステップを追加""" |
| |
| call_id = _call_id(step, rng) |
| think = rng.choice(THINK_GO_TO_TARGET).format(obj=obj_full, recep=target_recep) |
| action = f"go to {target_recep}" |
| obs = make_observation_for_recep(rng, target_recep, items_on) |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| |
| call_id = _call_id(step, rng) |
| think = rng.choice(THINK_PLACE).format(obj=obj_full, recep=target_recep) |
| action = f"put {obj_full} in/on {target_recep}" |
| obs = f"You put the {obj_full} in/on the {target_recep}." |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| return msgs, step |
|
|
|
|
| def generate_pick_and_place(rng, idx): |
| obj = rng.choice(OBJECTS["pickable"]) |
| target_type = rng.choice(PLACEMENT_TARGETS) |
| room_key = rng.choice(["kitchen_large", "kitchen_medium", "kitchen_small", |
| "bedroom_large", "bedroom_small", "livingroom"]) |
| items_on, room_desc, recep_names = generate_room_v2( |
| rng, room_key, ensure_objects=[obj], ensure_receptacles=[target_type] |
| ) |
|
|
| target_recep = f"{target_type} 1" if f"{target_type} 1" in recep_names else \ |
| next((r for r in recep_names if r.startswith(target_type)), f"{target_type} 1") |
|
|
| goal = f"Your task is to: put some {obj} on {target_type}." |
| msgs = [_sys(), _user(f"{room_desc}\n{goal}")] |
|
|
| search_msgs, _, obj_full, _, step = generate_search_trajectory( |
| rng, obj, items_on, recep_names, start_step=1 |
| ) |
| msgs.extend(search_msgs) |
|
|
| msgs, step = _go_and_place(rng, msgs, step, obj_full, target_recep, items_on) |
|
|
| return {"messages": msgs, "tools": TOOLS_DEFINITION, |
| "metadata": {"task_type": "pick_and_place", "trajectory_outcome": "success", |
| "synthetic": True, "generator_version": "v2.0"}} |
|
|
|
|
| def generate_clean_and_place(rng, idx): |
| obj = rng.choice(OBJECTS["cleanable"]) |
| target_type = rng.choice(PLACEMENT_TARGETS) |
| items_on, room_desc, recep_names = generate_room_v2( |
| rng, rng.choice(["kitchen_large", "kitchen_medium", "kitchen_small"]), |
| ensure_objects=[obj], ensure_receptacles=[target_type, "sinkbasin"] |
| ) |
|
|
| target_recep = f"{target_type} 1" if f"{target_type} 1" in recep_names else \ |
| next((r for r in recep_names if r.startswith(target_type)), f"{target_type} 1") |
|
|
| goal = f"Your task is to: clean some {obj} and put it in {target_type}." |
| msgs = [_sys(), _user(f"{room_desc}\n{goal}")] |
|
|
| search_msgs, _, obj_full, _, step = generate_search_trajectory( |
| rng, obj, items_on, recep_names, start_step=1 |
| ) |
| msgs.extend(search_msgs) |
|
|
| |
| call_id = _call_id(step, rng) |
| think = rng.choice(THINK_CLEAN).format(obj=obj_full.split()[0], recep="sinkbasin 1") |
| action = "go to sinkbasin 1" |
| obs = make_observation_for_recep(rng, "sinkbasin 1", items_on) |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| call_id = _call_id(step, rng) |
| think = f"Think: Now I'll clean the {obj_full} with the sinkbasin.\nAct: clean {obj_full} with sinkbasin 1" |
| action = f"clean {obj_full} with sinkbasin 1" |
| obs = f"You clean the {obj_full} using the sinkbasin 1." |
| msgs.append(_assistant(think, action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| msgs, step = _go_and_place(rng, msgs, step, obj_full, target_recep, items_on) |
|
|
| return {"messages": msgs, "tools": TOOLS_DEFINITION, |
| "metadata": {"task_type": "clean_and_place", "trajectory_outcome": "success", |
| "synthetic": True, "generator_version": "v2.0"}} |
|
|
|
|
| def generate_heat_and_place(rng, idx): |
| obj = rng.choice(OBJECTS["heatable"]) |
| target_type = rng.choice(PLACEMENT_TARGETS) |
| items_on, room_desc, recep_names = generate_room_v2( |
| rng, rng.choice(["kitchen_large", "kitchen_medium"]), |
| ensure_objects=[obj], ensure_receptacles=[target_type, "microwave"] |
| ) |
|
|
| target_recep = f"{target_type} 1" if f"{target_type} 1" in recep_names else \ |
| next((r for r in recep_names if r.startswith(target_type)), f"{target_type} 1") |
|
|
| goal = f"Your task is to: heat some {obj} and put it in {target_type}." |
| msgs = [_sys(), _user(f"{room_desc}\n{goal}")] |
|
|
| search_msgs, _, obj_full, _, step = generate_search_trajectory( |
| rng, obj, items_on, recep_names, start_step=1 |
| ) |
| msgs.extend(search_msgs) |
|
|
| |
| call_id = _call_id(step, rng) |
| think = rng.choice(THINK_HEAT).format(obj=obj_full.split()[0], recep="microwave 1") |
| action = "go to microwave 1" |
|
|
| if rng.random() < 0.4: |
| obs = "The microwave 1 is closed." |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| call_id = _call_id(step, rng) |
| think = rng.choice(THINK_OPEN_CLOSED).format(recep="microwave 1") |
| action = "open microwave 1" |
| obs = make_open_observation(rng, "microwave 1", items_on) |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
| else: |
| obs = f"The microwave 1 is open. In it, you see nothing." |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| call_id = _call_id(step, rng) |
| think = f"Think: I'll heat the {obj_full} with the microwave.\nAct: heat {obj_full} with microwave 1" |
| action = f"heat {obj_full} with microwave 1" |
| obs = f"You heat the {obj_full} using the microwave 1." |
| msgs.append(_assistant(think, action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| msgs, step = _go_and_place(rng, msgs, step, obj_full, target_recep, items_on) |
|
|
| return {"messages": msgs, "tools": TOOLS_DEFINITION, |
| "metadata": {"task_type": "heat_and_place", "trajectory_outcome": "success", |
| "synthetic": True, "generator_version": "v2.0"}} |
|
|
|
|
| def generate_cool_and_place(rng, idx): |
| obj = rng.choice(OBJECTS["coolable"]) |
| target_type = rng.choice(PLACEMENT_TARGETS) |
| items_on, room_desc, recep_names = generate_room_v2( |
| rng, rng.choice(["kitchen_large", "kitchen_medium"]), |
| ensure_objects=[obj], ensure_receptacles=[target_type, "fridge"] |
| ) |
|
|
| target_recep = f"{target_type} 1" if f"{target_type} 1" in recep_names else \ |
| next((r for r in recep_names if r.startswith(target_type)), f"{target_type} 1") |
|
|
| goal = f"Your task is to: cool some {obj} and put it in {target_type}." |
| msgs = [_sys(), _user(f"{room_desc}\n{goal}")] |
|
|
| search_msgs, _, obj_full, _, step = generate_search_trajectory( |
| rng, obj, items_on, recep_names, start_step=1 |
| ) |
| msgs.extend(search_msgs) |
|
|
| |
| call_id = _call_id(step, rng) |
| think = rng.choice(THINK_COOL).format(obj=obj_full.split()[0], recep="fridge 1") |
| action = "go to fridge 1" |
|
|
| if rng.random() < 0.4: |
| obs = "The fridge 1 is closed." |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| call_id = _call_id(step, rng) |
| think = rng.choice(THINK_OPEN_CLOSED).format(recep="fridge 1") |
| action = "open fridge 1" |
| obs = make_open_observation(rng, "fridge 1", items_on) |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
| else: |
| fridge_items = [(rng.choice(OBJECTS["coolable"]), rng.randint(1, 2)) for _ in range(rng.randint(1, 3))] |
| obs_items = ", ".join(f"a {o} {i}" for o, i in fridge_items) |
| obs = f"The fridge 1 is open. In it, you see {obs_items}." |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| call_id = _call_id(step, rng) |
| think = f"Think: I'll cool the {obj_full} with the fridge.\nAct: cool {obj_full} with fridge 1" |
| action = f"cool {obj_full} with fridge 1" |
| obs = f"You cool the {obj_full} using the fridge 1." |
| msgs.append(_assistant(think, action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| msgs, step = _go_and_place(rng, msgs, step, obj_full, target_recep, items_on) |
|
|
| return {"messages": msgs, "tools": TOOLS_DEFINITION, |
| "metadata": {"task_type": "cool_and_place", "trajectory_outcome": "success", |
| "synthetic": True, "generator_version": "v2.0"}} |
|
|
|
|
| def generate_examine(rng, idx): |
| obj = rng.choice(OBJECTS["examinable"]) |
| lamp = rng.choice(OBJECTS["lamps"]) |
| room_key = rng.choice(["bedroom_large", "bedroom_small", "livingroom"]) |
| items_on, room_desc, recep_names = generate_room_v2( |
| rng, room_key, ensure_objects=[obj] |
| ) |
|
|
| goal = f"Your task is to: look at {obj} under the {lamp}." |
| msgs = [_sys(), _user(f"{room_desc}\n{goal}")] |
|
|
| search_msgs, _, obj_full, _, step = generate_search_trajectory( |
| rng, obj, items_on, recep_names, start_step=1 |
| ) |
| msgs.extend(search_msgs) |
|
|
| |
| lamp_recep = f"{lamp} 1" |
| call_id = _call_id(step, rng) |
| think = rng.choice(THINK_EXAMINE).format(obj=obj_full, lamp=lamp_recep) |
| action = f"go to {lamp_recep}" |
| obs = make_observation_for_recep(rng, lamp_recep, items_on) |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| call_id = _call_id(step, rng) |
| think = f"Think: I'll turn on the {lamp_recep} to examine the {obj_full}.\nAct: use {lamp_recep}" |
| action = f"use {lamp_recep}" |
| obs = f"You turn on the {lamp_recep}." |
| msgs.append(_assistant(think, action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
|
|
| return {"messages": msgs, "tools": TOOLS_DEFINITION, |
| "metadata": {"task_type": "examine", "trajectory_outcome": "success", |
| "synthetic": True, "generator_version": "v2.0"}} |
|
|
|
|
| def generate_pick_two(rng, idx): |
| obj = rng.choice(OBJECTS["pickable"]) |
| target_type = rng.choice(PLACEMENT_TARGETS) |
| room_key = rng.choice(["kitchen_large", "kitchen_medium", "bedroom_large", "livingroom"]) |
| items_on, room_desc, recep_names = generate_room_v2( |
| rng, room_key, ensure_objects=[obj, obj], ensure_receptacles=[target_type] |
| ) |
|
|
| target_recep = f"{target_type} 1" if f"{target_type} 1" in recep_names else \ |
| next((r for r in recep_names if r.startswith(target_type)), f"{target_type} 1") |
|
|
| goal = f"Your task is to: find two {obj}s and put them in {target_type}." |
| msgs = [_sys(), _user(f"{room_desc}\n{goal}")] |
|
|
| |
| search_msgs, found_recep, obj_full, obj_id, step = generate_search_trajectory( |
| rng, obj, items_on, recep_names, start_step=1 |
| ) |
| msgs.extend(search_msgs) |
|
|
| msgs, step = _go_and_place(rng, msgs, step, obj_full, target_recep, items_on) |
|
|
| |
| obj_id2 = obj_id + 1 if obj_id < 3 else 1 |
| avail = [r for r in recep_names if r != found_recep and r != target_recep] |
| if not avail: |
| avail = [r for r in recep_names if r != found_recep] |
| second_recep = rng.choice(avail[:8]) |
| items_on.setdefault(second_recep, []).append((obj, obj_id2)) |
|
|
| call_id = _call_id(step, rng) |
| think = rng.choice(THINK_PICK_SECOND).format(obj=obj, recep=target_recep) |
| action = f"go to {second_recep}" |
| obs = make_observation_for_recep(rng, second_recep, items_on) |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| obj_full2 = f"{obj} {obj_id2}" |
| call_id = _call_id(step, rng) |
| think = rng.choice(THINK_FOUND_OBJECT).format(obj=obj, recep=second_recep, id=obj_id2) |
| action = f"take {obj_full2} from {second_recep}" |
| obs = f"You pick up the {obj_full2} from the {second_recep}." |
| msgs.append(_assistant(think + f"\nAct: {action}", action, call_id)) |
| msgs.append(_tool(call_id, obs)) |
| step += 1 |
|
|
| msgs, step = _go_and_place(rng, msgs, step, obj_full2, target_recep, items_on) |
|
|
| return {"messages": msgs, "tools": TOOLS_DEFINITION, |
| "metadata": {"task_type": "pick_two", "trajectory_outcome": "success", |
| "synthetic": True, "generator_version": "v2.0"}} |
|
|
|
|
| |
| |
| |
|
|
| GENERATORS = { |
| "pick_and_place": generate_pick_and_place, |
| "examine": generate_examine, |
| "clean_and_place": generate_clean_and_place, |
| "heat_and_place": generate_heat_and_place, |
| "cool_and_place": generate_cool_and_place, |
| "pick_two": generate_pick_two, |
| } |
|
|
|
|
| def validate_sample(sample): |
| msgs = sample.get("messages", []) |
| if len(msgs) < 4: |
| return False |
| roles = {m.get("role") for m in msgs} |
| if not {"system", "user", "assistant", "tool"}.issubset(roles): |
| return False |
| |
| for m in msgs: |
| if m.get("role") == "assistant" and m.get("tool_calls"): |
| content = m.get("content", "") |
| if "Think:" not in content: |
| return False |
| tc_action = json.loads(m["tool_calls"][0]["function"]["arguments"])["action"] |
| act_lines = [l.replace("Act:", "").strip() for l in content.split("\n") if l.strip().startswith("Act:")] |
| if act_lines and act_lines[-1] != tc_action: |
| return False |
| return True |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="ALFWorld 合成トラジェクトリ生成 v2") |
| parser.add_argument("--output", "-o", default="synthetic_alfworld_v2.jsonl") |
| parser.add_argument("--count", "-n", type=int, default=3000) |
| parser.add_argument("--seed", "-s", type=int, default=42) |
| parser.add_argument("--pick_and_place", type=int, default=None) |
| parser.add_argument("--examine", type=int, default=None) |
| parser.add_argument("--clean_and_place", type=int, default=None) |
| parser.add_argument("--heat_and_place", type=int, default=None) |
| parser.add_argument("--cool_and_place", type=int, default=None) |
| parser.add_argument("--pick_two", type=int, default=None) |
| parser.add_argument("--focus-weak", action="store_true") |
| args = parser.parse_args() |
|
|
| task_specific = { |
| "pick_and_place": args.pick_and_place, |
| "examine": args.examine, |
| "clean_and_place": args.clean_and_place, |
| "heat_and_place": args.heat_and_place, |
| "cool_and_place": args.cool_and_place, |
| "pick_two": args.pick_two, |
| } |
|
|
| if any(v is not None for v in task_specific.values()): |
| counts = {k: (v if v is not None else 0) for k, v in task_specific.items()} |
| elif args.focus_weak: |
| total = args.count |
| weak_each = int(total * 0.2) |
| strong_each = int(total * 0.1) |
| counts = { |
| "pick_and_place": strong_each, |
| "examine": weak_each, |
| "clean_and_place": weak_each, |
| "heat_and_place": weak_each, |
| "cool_and_place": weak_each, |
| "pick_two": strong_each, |
| } |
| else: |
| per_task = args.count // 6 |
| counts = {t: per_task for t in GENERATORS} |
| for i, t in enumerate(["clean_and_place", "heat_and_place", "cool_and_place", "examine"]): |
| if i < args.count % 6: |
| counts[t] += 1 |
|
|
| total = sum(counts.values()) |
| print(f"=== ALFWorld 合成データ生成 v2 ===") |
| for t, c in counts.items(): |
| print(f" {t}: {c} ({c/total*100:.1f}%)") |
| print(f" 合計: {total}, seed: {args.seed}") |
| print() |
|
|
| rng = random.Random(args.seed) |
| dataset = [] |
|
|
| for task_type, count in counts.items(): |
| gen = GENERATORS[task_type] |
| print(f"Generating {count} {task_type}...") |
| for i in range(count): |
| try: |
| dataset.append(gen(rng, i)) |
| except Exception as e: |
| print(f" WARN: {task_type} #{i}: {e}") |
|
|
| rng.shuffle(dataset) |
|
|
| valid = [s for s in dataset if validate_sample(s)] |
| print(f"\n有効: {len(valid)}/{len(dataset)}") |
|
|
| |
| from collections import Counter |
| print("\nタスク分布:") |
| for t, c in sorted(Counter(s["metadata"]["task_type"] for s in valid).items()): |
| print(f" {t}: {c}") |
|
|
| |
| go_targets = Counter() |
| go_target_types = Counter() |
| for s in valid: |
| for m in s["messages"]: |
| if m.get("role") == "assistant" and m.get("tool_calls"): |
| act = json.loads(m["tool_calls"][0]["function"]["arguments"])["action"] |
| if act.startswith("go to "): |
| target = act[6:] |
| go_targets[target] += 1 |
| go_target_types[target.rsplit(" ", 1)[0]] += 1 |
|
|
| print(f"\ngo to ターゲット(タイプ別 top 15):") |
| for t, c in go_target_types.most_common(15): |
| print(f" {t}: {c}") |
|
|
| print(f"\ngo to ターゲット(具体名 top 20):") |
| for t, c in go_targets.most_common(20): |
| print(f" {t}: {c}") |
|
|
| |
| print(f"\nユニークな go to ターゲット数: {len(go_targets)}") |
|
|
| msg_lens = [len(s["messages"]) for s in valid] |
| print(f"メッセージ数: min={min(msg_lens)}, max={max(msg_lens)}, avg={sum(msg_lens)/len(msg_lens):.1f}") |
|
|
| with open(args.output, "w", encoding="utf-8") as f: |
| for s in valid: |
| f.write(json.dumps(s, ensure_ascii=False) + "\n") |
| print(f"\n{args.output} に {len(valid)} 件を書き出しました。") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|