PR #21
#21
by dzakaathif - opened
This view is limited to 50 files because it contains too many changes. See the raw diff here.
Files changed (50)
- rewards/__init__.pyAdded+37
- rewards/__pycache__/amazon.cpython-312.pycAdded
- rewards/__pycache__/game_2048.cpython-312.pycAdded
- rewards/__pycache__/jd.cpython-312.pycAdded
- rewards/__pycache__/linear.cpython-312.pycAdded
- rewards/__pycache__/linkedin.cpython-312.pycAdded
- rewards/__pycache__/minesweeper.cpython-312.pycAdded
- rewards/__pycache__/salesforce.cpython-312.pycAdded
- rewards/__pycache__/tic_tac_toe.cpython-312.pycAdded
- rewards/__pycache__/weibo.cpython-312.pycAdded
- rewards/__pycache__/xiaohongshu.cpython-312.pycAdded
- rewards/amazon.pyAdded+2223
- rewards/game_2048.pyAdded+168
- rewards/jd.pyAdded+569
- rewards/linear.pyAdded+255
- rewards/linkedin.pyAdded+88
- rewards/minesweeper.pyAdded+255
- rewards/salesforce.pyAdded+423
- rewards/tic_tac_toe.pyAdded+82
- rewards/weibo.pyAdded+924
- rewards/xiaohongshu.pyAdded+491
- tasks/2048/create-two-high-tiles.json+2-1
- tasks/2048/get-128-tile.json+2-1
- tasks/2048/get-2048.json+2-1
- tasks/2048/get-256-tile.json+2-1
- tasks/2048/get-32-tile.json+2-1
- tasks/2048/get-512-tile.json+2-1
- tasks/2048/make-first-move.json+2-1
- tasks/2048/move-tiles-right.json+2-1
- tasks/2048/reach-540-sum.json+2-1
- tasks/2048/strategic-32.json+3-2
- tasks/action-tester/must-click.json+2-1
- tasks/action-tester/must-complete-all-actions.json+2-1
- tasks/action-tester/must-double-click.json+2-1
- tasks/action-tester/must-drag.json+2-1
- tasks/action-tester/must-hotkey.json+2-1
- tasks/action-tester/must-middle-click.json+2-1
- tasks/action-tester/must-perform-three-medium-actions.json+2-1
- tasks/action-tester/must-right-click.json+2-1
- tasks/action-tester/must-scroll.json+2-1
- tasks/action-tester/must-type.json+2-1
- tasks/amazon/customer-reviews-that-have-4-stars-and-above.jsonAdded
- tasks/amazon/customer-reviews-that-have-5-stars.jsonAdded
- tasks/amazon/entering-pod-in-the-search-bar.jsonAdded
- tasks/amazon/filter-on-amazon-global-store.jsonAdded
- tasks/amazon/filter-on-include-out-of-stock.jsonAdded
- tasks/amazon/filter-on-product-condition-renewed.jsonAdded
- tasks/amazon/filter-on-products-condition-new.jsonAdded
- tasks/amazon/filter-on-products-condition-used.jsonAdded
- tasks/amazon/filter-products-based-on-prime-delivery.jsonAdded
12345678910111213141516171819202122232425262728293031323334353637"""Modular reward functions organized by game/application.
This package contains reward validation functions for different dojos,organized into separate modules for maintainability."""
from dojo_sdk_core.dojos.rewards.amazon import REWARD_FUNCTIONS_AMAZONfrom dojo_sdk_core.dojos.rewards.game_2048 import REWARD_FUNCTIONS_2048from dojo_sdk_core.dojos.rewards.linear import REWARD_FUNCTIONS_LINEARfrom dojo_sdk_core.dojos.rewards.linkedin import REWARD_FUNCTIONS_LINKEDINfrom dojo_sdk_core.dojos.rewards.minesweeper import REWARD_FUNCTIONS_MINESWEEPERfrom dojo_sdk_core.dojos.rewards.salesforce import REWARD_FUNCTIONS_SALESFORCEfrom dojo_sdk_core.dojos.rewards.tic_tac_toe import REWARD_FUNCTIONS_TIC_TAC_TOEfrom dojo_sdk_core.dojos.rewards.xiaohongshu import REWARD_FUNCTIONS_XIAOHONGSHUfrom dojo_sdk_core.dojos.rewards.weibo import REWARD_FUNCTIONS_WEIBO
# Unified registry of all reward functionsREWARD_FUNCTIONS = { **REWARD_FUNCTIONS_AMAZON, **REWARD_FUNCTIONS_2048, **REWARD_FUNCTIONS_LINEAR, **REWARD_FUNCTIONS_LINKEDIN, **REWARD_FUNCTIONS_SALESFORCE, **REWARD_FUNCTIONS_TIC_TAC_TOE, **REWARD_FUNCTIONS_MINESWEEPER, **REWARD_FUNCTIONS_XIAOHONGSHU, **REWARD_FUNCTIONS_WEIBO,}
def get_reward_function(name: str): """Get a reward function by name from the unified registry.""" return REWARD_FUNCTIONS.get(name)
__all__ = ["REWARD_FUNCTIONS", "get_reward_function"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223"""Reward functions for Amazon app tasks."""
import loggingfrom typing import Any, Dict, Tuple
logger = logging.getLogger(__name__)
def _validate_entering_pod_in_the_search_bar( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully entered "pod" in the search bar and navigated to search results.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "pod" 3. The filteredProducts contains a product with id "B09G9FPHY6"
Args: initial_state: The initial state before the search final_state: The final state after the search
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "pod" search_query = final_state.get("searchQuery", "") if search_query.lower() != "pod": return ( 0.0, f"Expected searchQuery to be 'pod', got '{search_query}'", )
# Check 3: filteredProducts should contain product with id "B09G9FPHY6" filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
product_found = any( product.get("id") == "B09G9FPHY6" for product in filtered_products )
if not product_found: return ( 0.0, f"Product with id 'B09G9FPHY6' not found in filteredProducts. Found {len(filtered_products)} products.", )
# All checks passed return 1.0, "Successfully entered 'pod' in search bar and navigated to search results"
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_filter_products_based_on_prime_delivery( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products based on "Ships from United States" filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has shipsFromUnitedStates: true, minPrice: 0, maxPrice: 1000000, condition: [], and all other keys set to false 4. The filteredProducts contains all expected product IDs
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("shipsFromUnitedStates") is not True: errors.append("shipsFromUnitedStates should be True")
if filters.get("minPrice") != 0: errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 1000000: errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "freeDelivery", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain expected product IDs filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Expected product IDs expected_product_ids = { "B08N5WRWNW", "B09G9FPHY6", "B0BSHF7WHW", "B08L5VNJ2P", "B0B2QJZF8D", "CLOTH001", "CLOTH002", "ACC001", "BOOK001", "BEAUTY001", "SPORTS001", "PET001", "GARDEN001", "HEALTH001", "OFFICE001", "CLOTH003", "GROCERY001", }
# Extract product IDs from filtered products actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
# Check if all expected products are present missing_ids = expected_product_ids - actual_ids
if missing_ids: return ( 0.0, f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))[:10]}", )
# All checks passed return ( 1.0, f"Successfully filtered products based on 'Ships from United States'. Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_filter_products_based_on_single_day_delivery( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products based on "Get it within two days" filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has deliveryTomorrow: true, minPrice: 0, maxPrice: 1000000, condition: [], and all other keys set to false 4. The filteredProducts contains products with ids: B09G9FPHY6, HEALTH001
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("deliveryTomorrow") is not True: errors.append("deliveryTomorrow should be True")
if filters.get("minPrice") != 0: errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 1000000: errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTwoDays", "freeDelivery", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain expected product IDs filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Expected product IDs expected_product_ids = { "B09G9FPHY6", "HEALTH001", }
# Extract product IDs from filtered products actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
# Check if all expected products are present missing_ids = expected_product_ids - actual_ids
if missing_ids: return ( 0.0, f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))}", )
# All checks passed return ( 1.0, f"Successfully filtered products based on 'Get it within two days'. Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_filter_products_on_two_day_delivery( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products based on "Get it within two days" filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has deliveryTwoDays: true, minPrice: 0, maxPrice: 1000000, condition: [], and all other keys set to false 4. The filteredProducts contains products with ids: B09G9FPHY6, HEALTH001
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("deliveryTwoDays") is not True: errors.append("deliveryTwoDays should be True")
if filters.get("minPrice") != 0: errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 1000000: errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "freeDelivery", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain expected product IDs filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Expected product IDs expected_product_ids = { "B09G9FPHY6", "HEALTH001", }
# Extract product IDs from filtered products actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
# Check if all expected products are present missing_ids = expected_product_ids - actual_ids
if missing_ids: return ( 0.0, f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))}", )
# All checks passed return ( 1.0, f"Successfully filtered products based on 'Get it within two days'. Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_filter_products_on_free_delivery( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products based on "Free delivery" filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has freeDelivery: true, minPrice: 0, maxPrice: 1000000, condition: [], and all other keys set to false 4. The filteredProducts contains all expected product IDs
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("freeDelivery") is not True: errors.append("freeDelivery should be True")
if filters.get("minPrice") != 0: errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 1000000: errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain expected product IDs filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Expected product IDs expected_product_ids = { "B08N5WRWNW", "B09G9FPHY6", "B0BSHF7WHW", "B08L5VNJ2P", "B0B2QJZF8D", "CLOTH001", "CLOTH002", "BOOK001", "BEAUTY001", "SPORTS001", "PET001", "GARDEN001", "HEALTH001", "OFFICE001", "CLOTH003", "GROCERY001", }
# Extract product IDs from filtered products actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
# Check if all expected products are present missing_ids = expected_product_ids - actual_ids
if missing_ids: return ( 0.0, f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))[:10]}", )
# All checks passed return ( 1.0, f"Successfully filtered products based on 'Free delivery'. Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_customer_reviews_that_have_5_stars( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products based on "Top Rated" (5 stars) filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has minRating: 5, minPrice: 0, maxPrice: 1000000, condition: [], and all other keys set to false 4. The filteredProducts contains product with id: B0BSHF7WHW
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("minRating") != 5: errors.append(f"minRating should be 5, got {filters.get('minRating')}")
if filters.get("minPrice") != 0: errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 1000000: errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "freeDelivery", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain expected product ID filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Expected product ID expected_product_id = "B0BSHF7WHW"
# Check if the expected product is present product_found = any( product.get("id") == expected_product_id for product in filtered_products )
if not product_found: return ( 0.0, f"Product with id '{expected_product_id}' not found in filteredProducts. Found {len(filtered_products)} products.", )
# All checks passed return ( 1.0, f"Successfully filtered products based on 'Top Rated' (5 stars). Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_customer_reviews_that_have_4_stars_and_above( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products based on "4 & Up" (4 stars and above) filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has minRating: 4, minPrice: 0, maxPrice: 1000000, condition: [], and all other keys set to false 4. The filteredProducts contains all expected product IDs
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("minRating") != 4: errors.append(f"minRating should be 4, got {filters.get('minRating')}")
if filters.get("minPrice") != 0: errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 1000000: errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "freeDelivery", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain expected product IDs filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Expected product IDs expected_product_ids = { "B09G9FPHY6", "B0BSHF7WHW", "B09B9VFKH5", "B08L5VNJ2P", "B0B2QJZF8D", "CLOTH001", "CLOTH002", "ACC001", "BOOK001", "BEAUTY001", "SPORTS001", "PET001", "GARDEN001", "HEALTH001", "OFFICE001", "CLOTH003", "GROCERY001", }
# Extract product IDs from filtered products actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
# Check if all expected products are present missing_ids = expected_product_ids - actual_ids
if missing_ids: return ( 0.0, f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))[:10]}", )
# All checks passed return ( 1.0, f"Successfully filtered products based on '4 & Up' (4 stars and above). Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_filter_products_with_prices_between_99_and_204( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products using price range slider (99-204).
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has minPrice: 99, maxPrice: 204, condition: [], and all other keys set to false 4. The filteredProducts contains all expected product IDs
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("minPrice") != 99: errors.append(f"minPrice should be 99, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 204: errors.append(f"maxPrice should be 204, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "freeDelivery", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain expected product IDs filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Expected product IDs expected_product_ids = { "B0BSHF7WHW", "B08L5VNJ2P", "CLOTH001", "CLOTH002", "HEALTH001", }
# Extract product IDs from filtered products actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
# Check if all expected products are present missing_ids = expected_product_ids - actual_ids
if missing_ids: return ( 0.0, f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))}", )
# All checks passed return ( 1.0, f"Successfully filtered products using price range slider (99-204). Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_product_prices_up_to_90( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products using "Up to $90" price filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has minPrice: 0, maxPrice: 90, condition: [], and all other keys set to false 4. The filteredProducts contains all expected product IDs
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("minPrice") != 0: errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 90: errors.append(f"maxPrice should be 90, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "freeDelivery", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain expected product IDs filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Expected product IDs expected_product_ids = { "B0B2QJZF8D", "BOOK001", "BEAUTY001", "SPORTS001", "PET001", "GARDEN001", "OFFICE001", "CLOTH003", "GROCERY001", }
# Extract product IDs from filtered products actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
# Check if all expected products are present missing_ids = expected_product_ids - actual_ids
if missing_ids: return ( 0.0, f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))}", )
# All checks passed return ( 1.0, f"Successfully filtered products using price filter (Up to $90). Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_products_prices_between_150_and_300( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products using price range button ($150 to $350).
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has minPrice: 150, maxPrice: 300, condition: [], and all other keys set to false 4. The filteredProducts contains all expected product IDs
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("minPrice") != 150: errors.append(f"minPrice should be 150, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 300: errors.append(f"maxPrice should be 300, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "freeDelivery", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain expected product IDs filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Expected product IDs expected_product_ids = { "B08L5VNJ2P", "CLOTH002", }
# Extract product IDs from filtered products actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
# Check if all expected products are present missing_ids = expected_product_ids - actual_ids
if missing_ids: return ( 0.0, f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))}", )
# All checks passed return ( 1.0, f"Successfully filtered products using price range button ($150 to $350). Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_products_with_prices_greater_than_700( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products using "$700 and above" price filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has minPrice: 700, maxPrice: 1000000, condition: [], and all other keys set to false 4. The filteredProducts contains product with id: B09B9VFKH5
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("minPrice") != 700: errors.append(f"minPrice should be 700, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 1000000: errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "freeDelivery", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain expected product ID filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Expected product ID expected_product_id = "B09B9VFKH5"
# Check if the expected product is present product_found = any( product.get("id") == expected_product_id for product in filtered_products )
if not product_found: return ( 0.0, f"Product with id '{expected_product_id}' not found in filteredProducts. Found {len(filtered_products)} products.", )
# All checks passed return ( 1.0, f"Successfully filtered products using '$700 and above' price filter. Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_filter_on_products_condition_new( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products using "New" condition filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has condition: ['new'], minPrice: 0, maxPrice: 1000000, and all other keys set to false 4. The filteredProducts contains all expected product IDs
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values condition = filters.get("condition", []) if not isinstance(condition, list) or condition != ["new"]: errors.append(f"condition should be ['new'], got {condition}")
if filters.get("minPrice") != 0: errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 1000000: errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "freeDelivery", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain expected product IDs filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Expected product IDs expected_product_ids = { "B08N5WRWNW", "B09G9FPHY6", "B0BSHF7WHW", "B09B9VFKH5", "B08L5VNJ2P", "B0B2QJZF8D", "CLOTH001", "CLOTH002", "ACC001", "BOOK001", "BEAUTY001", "SPORTS001", "PET001", "GARDEN001", "HEALTH001", "OFFICE001", "CLOTH003", "GROCERY001", }
# Extract product IDs from filtered products actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
# Check if all expected products are present missing_ids = expected_product_ids - actual_ids
if missing_ids: return ( 0.0, f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))[:10]}", )
# All checks passed return ( 1.0, f"Successfully filtered products using 'New' condition filter. Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_filter_on_product_condition_renewed( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products using "Renewed" condition filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has condition: ['renewed'], minPrice: 0, maxPrice: 1000000, and all other keys set to false 4. The filteredProducts contains objects that have condition 'renewed'
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values condition = filters.get("condition", []) if not isinstance(condition, list) or condition != ["renewed"]: errors.append(f"condition should be ['renewed'], got {condition}")
if filters.get("minPrice") != 0: errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 1000000: errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "freeDelivery", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain objects with condition 'renewed' filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Check that all products have condition 'renewed' products_without_renewed = [ product.get("id", "unknown") for product in filtered_products if product.get("condition") != "renewed" ]
if products_without_renewed: return ( 0.0, f"Found {len(products_without_renewed)} products without condition 'renewed': {products_without_renewed[:5]}", )
# All checks passed return ( 1.0, f"Successfully filtered products using 'Renewed' condition filter. Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_filter_on_products_condition_used( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products using "Used" condition filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has condition: ['used'], minPrice: 0, maxPrice: 1000000, and all other keys set to false 4. The filteredProducts contains objects that have condition 'used'
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values condition = filters.get("condition", []) if not isinstance(condition, list) or condition != ["used"]: errors.append(f"condition should be ['used'], got {condition}")
if filters.get("minPrice") != 0: errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 1000000: errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "freeDelivery", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain objects with condition 'used' filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Check that all products have condition 'used' products_without_used = [ product.get("id", "unknown") for product in filtered_products if product.get("condition") != "used" ]
if products_without_used: return ( 0.0, f"Found {len(products_without_used)} products without condition 'used': {products_without_used[:5]}", )
# All checks passed return ( 1.0, f"Successfully filtered products using 'Used' condition filter. Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_filter_on_include_out_of_stock( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully enabled "Include Out of Stock" filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has includeOutOfStock: true, minPrice: 0, maxPrice: 1000000, condition: [], and all other keys set to false 4. The filteredProducts contains objects that have inStock key (can be True or False)
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("includeOutOfStock") is not True: errors.append("includeOutOfStock should be True")
if filters.get("minPrice") != 0: errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 1000000: errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "freeDelivery", "isGlobalStore", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain objects with inStock key filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Check that all products have inStock key (can be True or False) products_without_inStock = [ product.get("id", "unknown") for product in filtered_products if "inStock" not in product ]
if products_without_inStock: return ( 0.0, f"Found {len(products_without_inStock)} products without 'inStock' key: {products_without_inStock[:5]}", )
# All checks passed return ( 1.0, f"Successfully enabled 'Include Out of Stock' filter. Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_filter_on_amazon_global_store( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully filtered products using "Amazon Global Store" filter.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has isGlobalStore: true, minPrice: 0, maxPrice: 1000000, condition: [], and all other keys set to false 4. The filteredProducts contains objects that have isGlobalStore: True
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("isGlobalStore") is not True: errors.append("isGlobalStore should be True")
if filters.get("minPrice") != 0: errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 1000000: errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "shipsFromUnitedStates", "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "freeDelivery", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
# Check minRating should be null if filters.get("minRating") is not None: errors.append(f"minRating should be null, got {filters.get('minRating')}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts contain objects with isGlobalStore: True filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Check that all products have isGlobalStore: True products_without_global_store = [ product.get("id", "unknown") for product in filtered_products if product.get("isGlobalStore") is not True ]
if products_without_global_store: return ( 0.0, f"Found {len(products_without_global_store)} products without isGlobalStore=True: {products_without_global_store[:5]}", )
# All checks passed return ( 1.0, f"Successfully filtered products using 'Amazon Global Store' filter. Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_multiple_filters( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully applied multiple filters simultaneously.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "a" 3. The filters object has shipsFromUnitedStates: true, freeDelivery: true, minRating: 4, minPrice: 90, maxPrice: 150, condition: [], and all other keys set to false 4. The filteredProducts contains objects that match all filter criteria
Args: initial_state: The initial state before filtering final_state: The final state after filtering
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "a" search_query = final_state.get("searchQuery", "") if search_query.lower() != "a": return ( 0.0, f"Expected searchQuery to be 'a', got '{search_query}'", )
# Check 3: Validate filters object filters = final_state.get("filters", {}) if not filters: return 0.0, "No filters found in final state"
errors = []
# Check required filter values if filters.get("shipsFromUnitedStates") is not True: errors.append("shipsFromUnitedStates should be True")
if filters.get("freeDelivery") is not True: errors.append("freeDelivery should be True")
if filters.get("minRating") != 4: errors.append(f"minRating should be 4, got {filters.get('minRating')}")
if filters.get("minPrice") != 90: errors.append(f"minPrice should be 90, got {filters.get('minPrice')}")
if filters.get("maxPrice") != 150: errors.append(f"maxPrice should be 150, got {filters.get('maxPrice')}")
condition = filters.get("condition", []) if not isinstance(condition, list) or len(condition) != 0: errors.append(f"condition should be empty array [], got {condition}")
# Check that all other boolean filters are False boolean_filters_should_be_false = [ "internationalShipping", "deliveryTomorrow", "deliveryTwoDays", "isGlobalStore", "includeOutOfStock", ]
for filter_key in boolean_filters_should_be_false: if filters.get(filter_key) is not False: errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
if errors: return 0.0, "; ".join(errors)
# Check 4: Validate filteredProducts match all filter criteria filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
# Validate each product matches all criteria invalid_products = []
for product in filtered_products: product_id = product.get("id", "unknown") product_errors = []
# Check shipsFromUnitedStates if product.get("shipsFromUnitedStates") is not True: product_errors.append("shipsFromUnitedStates != True")
# Check rating >= 4 rating = product.get("rating") if rating is None or rating < 4: product_errors.append(f"rating={rating} (expected >= 4)")
# Check price between 90 and 150 (inclusive) price = product.get("price") if price is None or price < 90 or price > 150: product_errors.append(f"price={price} (expected 90 <= price <= 150)")
# Check freeDelivery if product.get("freeDelivery") is not True: product_errors.append("freeDelivery != True")
if product_errors: invalid_products.append(f"{product_id}: {', '.join(product_errors)}")
if invalid_products: return ( 0.0, f"Found {len(invalid_products)} products that don't match all filter criteria: {invalid_products[:3]}", )
# All checks passed return ( 1.0, f"Successfully applied multiple filters (Ships from United States, Free Delivery, 4* & Up, $90-$150). Found {len(filtered_products)} matching products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_navigate_from_search_page_to_product_page( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated from search page to a product page.
This function checks: 1. The currentPage is "product" 2. The selectedProduct has id "OFFICE001" 3. The searchQuery is "book" (preserved from search page)
Args: initial_state: The initial state before navigation final_state: The final state after navigation
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "product" current_page = final_state.get("currentPage") if current_page != "product": return ( 0.0, f"Expected currentPage to be 'product', got '{current_page}'", )
# Check 2: selectedProduct should have id "OFFICE001" selected_product = final_state.get("selectedProduct") if selected_product is None: return 0.0, "Expected selectedProduct to be set, got null"
product_id = selected_product.get("id") if product_id != "OFFICE001": return ( 0.0, f"Expected selectedProduct id to be 'OFFICE001', got '{product_id}'", )
# Check 3: searchQuery should be "book" (preserved from search page) search_query = final_state.get("searchQuery", "") if search_query.lower() != "book": return ( 0.0, f"Expected searchQuery to be 'book', got '{search_query}'", )
# All checks passed product_name = selected_product.get("name", "Unknown Product") return ( 1.0, f"Successfully navigated from search page to product page for '{product_name}' (ID: {product_id})", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_navigate_from_home_to_product_page( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated from home page to a product page.
This function checks: 1. The currentPage is "product" 2. The selectedProduct has id "CLOTH002" 3. The searchQuery is empty string "" (since navigation is from home page)
Args: initial_state: The initial state before navigation final_state: The final state after navigation
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "product" current_page = final_state.get("currentPage") if current_page != "product": return ( 0.0, f"Expected currentPage to be 'product', got '{current_page}'", )
# Check 2: selectedProduct should have id "CLOTH002" selected_product = final_state.get("selectedProduct") if selected_product is None: return 0.0, "Expected selectedProduct to be set, got null"
product_id = selected_product.get("id") if product_id != "CLOTH002": return ( 0.0, f"Expected selectedProduct id to be 'CLOTH002', got '{product_id}'", )
# Check 3: searchQuery should be empty string (from home page) search_query = final_state.get("searchQuery", "") if search_query != "": return ( 0.0, f"Expected searchQuery to be empty string '', got '{search_query}'", )
# All checks passed product_name = selected_product.get("name", "Unknown Product") return ( 1.0, f"Successfully navigated from home page to product page for '{product_name}' (ID: {product_id})", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_navigate_from_product_page_to_product_page( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated from one product page to another product page.
This function checks: 1. The currentPage is "product" 2. The selectedProduct has id "B08N5WRWNW" 3. The searchQuery is empty string "" (since navigation is from product page)
Args: initial_state: The initial state before navigation final_state: The final state after navigation
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "product" current_page = final_state.get("currentPage") if current_page != "product": return ( 0.0, f"Expected currentPage to be 'product', got '{current_page}'", )
# Check 2: selectedProduct should have id "B08N5WRWNW" selected_product = final_state.get("selectedProduct") if selected_product is None: return 0.0, "Expected selectedProduct to be set, got null"
product_id = selected_product.get("id") if product_id != "B08N5WRWNW": return ( 0.0, f"Expected selectedProduct id to be 'B08N5WRWNW', got '{product_id}'", )
# Check 3: searchQuery should be empty string (from product page) search_query = final_state.get("searchQuery", "") if search_query != "": return ( 0.0, f"Expected searchQuery to be empty string '', got '{search_query}'", )
# All checks passed product_name = selected_product.get("name", "Unknown Product") return ( 1.0, f"Successfully navigated from product page to product page for '{product_name}' (ID: {product_id})", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_navigate_from_product_page_to_search_page( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated from product page to search page.
This function checks: 1. The currentPage is "search" 2. The searchQuery is "seven" (case-insensitive) 3. The filteredProducts contains a product with id "BOOK001"
Args: initial_state: The initial state before navigation final_state: The final state after navigation
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentPage should be "search" current_page = final_state.get("currentPage") if current_page != "search": return ( 0.0, f"Expected currentPage to be 'search', got '{current_page}'", )
# Check 2: searchQuery should be "seven" (case-insensitive) search_query = final_state.get("searchQuery", "") if search_query.lower() != "seven": return ( 0.0, f"Expected searchQuery to be 'seven', got '{search_query}'", )
# Check 3: filteredProducts should contain product with id "BOOK001" filtered_products = final_state.get("filteredProducts", []) if not filtered_products: return 0.0, "No filtered products found in final state"
product_found = any( product.get("id") == "BOOK001" for product in filtered_products )
if not product_found: return ( 0.0, f"Product with id 'BOOK001' not found in filteredProducts. Found {len(filtered_products)} products.", )
# All checks passed return ( 1.0, f"Successfully navigated from product page to search page with query 'seven'. Found {len(filtered_products)} products.", )
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
# Registry of all Amazon reward functionsREWARD_FUNCTIONS_AMAZON = { "_validate_entering_pod_in_the_search_bar": _validate_entering_pod_in_the_search_bar, "_validate_filter_products_based_on_prime_delivery": _validate_filter_products_based_on_prime_delivery, "_validate_filter_products_based_on_single_day_delivery": _validate_filter_products_based_on_single_day_delivery, "_validate_filter_products_on_two_day_delivery": _validate_filter_products_on_two_day_delivery, "_validate_filter_products_on_free_delivery": _validate_filter_products_on_free_delivery, "_validate_customer_reviews_that_have_5_stars": _validate_customer_reviews_that_have_5_stars, "_validate_customer_reviews_that_have_4_stars_and_above": _validate_customer_reviews_that_have_4_stars_and_above, "_validate_filter_products_with_prices_between_99_and_204": _validate_filter_products_with_prices_between_99_and_204, "_validate_product_prices_up_to_90": _validate_product_prices_up_to_90, "_validate_products_prices_between_150_and_300": _validate_products_prices_between_150_and_300, "_validate_products_with_prices_greater_than_700": _validate_products_with_prices_greater_than_700, "_validate_filter_on_products_condition_new": _validate_filter_on_products_condition_new, "_validate_filter_on_product_condition_renewed": _validate_filter_on_product_condition_renewed, "_validate_filter_on_products_condition_used": _validate_filter_on_products_condition_used, "_validate_filter_on_include_out_of_stock": _validate_filter_on_include_out_of_stock, "_validate_filter_on_amazon_global_store": _validate_filter_on_amazon_global_store, "_validate_multiple_filters": _validate_multiple_filters, "_validate_navigate_from_search_page_to_product_page": _validate_navigate_from_search_page_to_product_page, "_validate_navigate_from_home_to_product_page": _validate_navigate_from_home_to_product_page, "_validate_navigate_from_product_page_to_product_page": _validate_navigate_from_product_page_to_product_page, "_validate_navigate_from_product_page_to_search_page": _validate_navigate_from_product_page_to_search_page,}
__all__ = [ "REWARD_FUNCTIONS_AMAZON", "_validate_entering_pod_in_the_search_bar", "_validate_filter_products_based_on_prime_delivery", "_validate_filter_products_based_on_single_day_delivery", "_validate_filter_products_on_two_day_delivery", "_validate_filter_products_on_free_delivery", "_validate_customer_reviews_that_have_5_stars", "_validate_customer_reviews_that_have_4_stars_and_above", "_validate_filter_products_with_prices_between_99_and_204", "_validate_product_prices_up_to_90", "_validate_products_prices_between_150_and_300", "_validate_products_with_prices_greater_than_700", "_validate_filter_on_products_condition_new", "_validate_filter_on_product_condition_renewed", "_validate_filter_on_products_condition_used", "_validate_filter_on_include_out_of_stock", "_validate_filter_on_amazon_global_store", "_validate_multiple_filters", "_validate_navigate_from_search_page_to_product_page", "_validate_navigate_from_home_to_product_page", "_validate_navigate_from_product_page_to_product_page", "_validate_navigate_from_product_page_to_search_page",]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""Reward functions for 2048 game tasks.
All functions validate the final board state, accounting for randomly spawned tiles.Board is a 16-element array representing a 4x4 grid: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]"""
import loggingfrom typing import Any, Dict, Tuple
logger = logging.getLogger(__name__)
def _validate_get_2048(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that a 2048 tile is present on the board.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}") if 2048 in final_state["board"]: return 1.0, "A 2048 tile is present." return 0.0, "No 2048 tile is present."
def _validate_2048_make_first_move(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that any valid move was made from the initial board state.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
# Check if board changed (has non-zero tiles) if any(tile != 0 for tile in final_state["board"]): return 1.0, "Board changed from initial state - move was made successfully."
return 0.0, "Board is still empty - no move was made."
def _validate_move_tiles_right(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that all tiles are in the rightmost column (positions 3, 7, 11, 15).""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
board = final_state["board"] rightmost_positions = [3, 7, 11, 15]
# Get all non-zero tiles and their positions non_zero_positions = [i for i, tile in enumerate(board) if tile != 0]
# Check if all non-zero tiles are in rightmost column if all(pos in rightmost_positions for pos in non_zero_positions): return 1.0, f"All tiles successfully moved to rightmost column at positions {non_zero_positions}."
# Find which tiles are not in the rightmost column misplaced = [pos for pos in non_zero_positions if pos not in rightmost_positions] return 0.0, f"Some tiles are not in rightmost column. Misplaced at positions: {misplaced}"
def _validate_get_32_tile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that a 32 tile is present on the board.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
if 32 in final_state["board"]: return 1.0, "A 32 tile is present." return 0.0, "No 32 tile is present."
def _validate_get_128_tile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that a 128 tile is present on the board.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
if 128 in final_state["board"]: return 1.0, "A 128 tile is present." return 0.0, "No 128 tile is present."
def _validate_get_256_tile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that a 256 tile is present on the board.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
if 256 in final_state["board"]: return 1.0, "A 256 tile is present." return 0.0, "No 256 tile is present."
def _validate_get_512_tile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that a 512 tile is present on the board.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
if 512 in final_state["board"]: return 1.0, "A 512 tile is present." return 0.0, "No 512 tile is present."
def _validate_create_two_high_tiles(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that at least two tiles with value 128 or higher are present.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
high_tiles = [tile for tile in final_state["board"] if tile >= 128] count = len(high_tiles)
if count >= 2: return 1.0, f"Board contains {count} tiles with value 128 or higher: {high_tiles}."
return 0.0, f"Board contains only {count} tile(s) with value 128 or higher. Need at least 2."
def _validate_reach_540_sum(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that the sum of all tile values is 540 or greater.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
total_sum = sum(final_state["board"])
if total_sum >= 540: return 1.0, f"Board sum is {total_sum}, which meets the requirement of 540 or greater."
return 0.0, f"Board sum is {total_sum}, which is below the required 540."
def _validate_strategic_32(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that a 32 tile was created strategically from an empty board.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
if 32 in final_state["board"]: return 1.0, "A 32 tile was successfully created from empty board." return 0.0, "No 32 tile is present."
# Registry of all 2048 reward functionsREWARD_FUNCTIONS_2048 = { "_validate_get_2048": _validate_get_2048, "_validate_2048_make_first_move": _validate_2048_make_first_move, "_validate_move_tiles_right": _validate_move_tiles_right, "_validate_get_32_tile": _validate_get_32_tile, "_validate_get_128_tile": _validate_get_128_tile, "_validate_get_256_tile": _validate_get_256_tile, "_validate_get_512_tile": _validate_get_512_tile, "_validate_create_two_high_tiles": _validate_create_two_high_tiles, "_validate_reach_540_sum": _validate_reach_540_sum, "_validate_strategic_32": _validate_strategic_32,}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569"""Reward functions for JD (JingDong) e-commerce SPA tasks."""
import loggingfrom typing import Tuple
logger = logging.getLogger(__name__)
def _validate_go_to_the_cart_page_from_the_homepage( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate navigation from homepage to cart page.""" try: if "page" not in final_state: return 0.0, "Missing 'page' field in final state" if final_state["page"] != "cart": return 0.0, f"Expected page='cart', got page='{final_state['page']}'" return 1.0, "Successfully navigated to cart page" except Exception as e: logger.error(f"Error in _validate_go_to_the_cart_page_from_the_homepage: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_go_to_a_product_page_from_home( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate navigation from homepage to a product page.""" try: if "page" not in final_state: return 0.0, "Missing 'page' field in final state" if final_state["page"] != "product": return 0.0, f"Expected page='product', got page='{final_state['page']}'" if "selectedProductId" not in final_state: return 0.0, "Missing 'selectedProductId' in final state" if final_state["selectedProductId"] != "2": return 0.0, f"Expected selectedProductId='2', got '{final_state['selectedProductId']}'" return 1.0, "Successfully navigated to product page with correct product" except Exception as e: logger.error(f"Error in _validate_go_to_a_product_page_from_home: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_go_to_homepage_from_product_page( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate navigation from product page to homepage.""" try: if "page" not in final_state: return 0.0, "Missing 'page' field in final state" if final_state["page"] != "home": return 0.0, f"Expected page='home', got page='{final_state['page']}'" return 1.0, "Successfully navigated to homepage" except Exception as e: logger.error(f"Error in _validate_go_to_homepage_from_product_page: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_go_to_cart_page_from_product_detail_page( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate navigation from product detail page to cart page.""" try: if "page" not in final_state: return 0.0, "Missing 'page' field in final state" if final_state["page"] != "cart": return 0.0, f"Expected page='cart', got page='{final_state['page']}'" return 1.0, "Successfully navigated to cart page from product detail" except Exception as e: logger.error(f"Error in _validate_go_to_cart_page_from_product_detail_page: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_go_to_product_detail_from_search( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate navigation from search page to product detail page.""" try: if "page" not in final_state: return 0.0, "Missing 'page' field in final state" if final_state["page"] != "product": return 0.0, f"Expected page='product', got page='{final_state['page']}'" if "selectedProductId" not in final_state: return 0.0, "Missing 'selectedProductId' in final state" if not final_state["selectedProductId"]: return 0.0, "selectedProductId is empty" return 1.0, "Successfully navigated to product detail from search" except Exception as e: logger.error(f"Error in _validate_go_to_product_detail_from_search: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_find_a_product_using_search_from_homepage( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate searching for a product and navigating to its detail page.""" try: if "page" not in final_state: return 0.0, "Missing 'page' field in final state" if final_state["page"] != "product": return 0.0, f"Expected page='product', got page='{final_state['page']}'" if "searchQuery" not in final_state: return 0.0, "Missing 'searchQuery' in final state" if "吉普衬衫" not in final_state["searchQuery"]: return 0.0, f"Expected search query to contain '吉普衬衫', got '{final_state['searchQuery']}'" if "selectedProductId" not in final_state: return 0.0, "Missing 'selectedProductId' in final state" if final_state["selectedProductId"] != "2": return 0.0, f"Expected selectedProductId='2', got '{final_state['selectedProductId']}'" return 1.0, "Successfully searched for product and navigated to detail page" except Exception as e: logger.error(f"Error in _validate_find_a_product_using_search_from_homepage: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_search_吉普衬衫( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate searching for '吉普衬衫' (JEEP shirt).""" try: if "searchQuery" not in final_state: return 0.0, "Missing 'searchQuery' in final state" if "吉普衬衫" not in final_state["searchQuery"]: return 0.0, f"Expected search query to contain '吉普衬衫', got '{final_state['searchQuery']}'" if "page" not in final_state: return 0.0, "Missing 'page' field in final state" if final_state["page"] != "search": return 0.0, f"Expected page='search', got page='{final_state['page']}'" return 1.0, "Successfully searched for 吉普衬衫" except Exception as e: logger.error(f"Error in _validate_search_吉普衬衫: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_search_a_product_from_another_product_page( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate searching for a product from another product page and navigating to it.""" try: if "page" not in final_state: return 0.0, "Missing 'page' field in final state" if final_state["page"] != "product": return 0.0, f"Expected page='product', got page='{final_state['page']}'" if "searchQuery" not in final_state: return 0.0, "Missing 'searchQuery' in final state" if not final_state["searchQuery"]: return 0.0, "searchQuery is empty" if "selectedProductId" not in final_state: return 0.0, "Missing 'selectedProductId' in final state" if final_state["selectedProductId"] != "3": return 0.0, f"Expected selectedProductId='3', got '{final_state['selectedProductId']}'" return 1.0, "Successfully searched for product and navigated to detail page" except Exception as e: logger.error(f"Error in _validate_search_a_product_from_another_product_page: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_add_a_product_to_cart( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate adding a product to cart.""" try: if "cart" not in final_state: return 0.0, "Missing 'cart' field in final state" cart = final_state["cart"] if not isinstance(cart, list): return 0.0, "cart is not a list" # Check if product with id "2" is in cart with qty=1 product_in_cart = False for item in cart: if item.get("productId") == "2" and item.get("qty") == 1: product_in_cart = True break if not product_in_cart: return 0.0, "Expected product with id '2' and qty=1 in cart" return 1.0, "Successfully added product to cart" except Exception as e: logger.error(f"Error in _validate_add_a_product_to_cart: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_add_a_product_from_search_result_to_cart( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate adding a product from search results to cart.""" try: if "cart" not in final_state: return 0.0, "Missing 'cart' field in final state" cart = final_state["cart"] if not isinstance(cart, list): return 0.0, "cart is not a list" # Check if any product is in cart if len(cart) == 0: return 0.0, "Cart is empty" # Check if at least one item has qty >= 1 has_valid_item = False for item in cart: if item.get("qty", 0) >= 1: has_valid_item = True break if not has_valid_item: return 0.0, "No valid items in cart" return 1.0, "Successfully added product from search to cart" except Exception as e: logger.error(f"Error in _validate_add_a_product_from_search_result_to_cart: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_add_an_item_from_the_homepage( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate adding an item from the homepage to cart.""" try: if "cart" not in final_state: return 0.0, "Missing 'cart' field in final state" cart = final_state["cart"] if not isinstance(cart, list): return 0.0, "cart is not a list" if len(cart) == 0: return 0.0, "Cart is empty" # Check if any item was added initial_cart_len = len(initial_state.get("cart", [])) if len(cart) <= initial_cart_len: return 0.0, "No new items added to cart" return 1.0, "Successfully added item from homepage to cart" except Exception as e: logger.error(f"Error in _validate_add_an_item_from_the_homepage: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_add_an_item_with_3_quantity( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate adding an item with quantity 3 to cart.""" try: if "cart" not in final_state: return 0.0, "Missing 'cart' field in final state" cart = final_state["cart"] if not isinstance(cart, list): return 0.0, "cart is not a list" # Check if any item has qty=3 has_qty_3 = False for item in cart: if item.get("qty") == 3: has_qty_3 = True break if not has_qty_3: return 0.0, "No item with qty=3 found in cart" return 1.0, "Successfully added item with quantity 3" except Exception as e: logger.error(f"Error in _validate_add_an_item_with_3_quantity: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_remove_one_item_from_cart( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate removing one item from cart.""" try: if "cart" not in final_state: return 0.0, "Missing 'cart' field in final state" cart = final_state["cart"] if not isinstance(cart, list): return 0.0, "cart is not a list" if len(cart) != 0: return 0.0, f"Expected empty cart, but found {len(cart)} items" return 1.0, "Successfully removed item from cart" except Exception as e: logger.error(f"Error in _validate_remove_one_item_from_cart: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_remove_multiple_items_in_the_cart( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate removing multiple items from cart.""" try: if "cart" not in final_state: return 0.0, "Missing 'cart' field in final state" cart = final_state["cart"] if not isinstance(cart, list): return 0.0, "cart is not a list" if len(cart) != 0: return 0.0, f"Expected empty cart, but found {len(cart)} items" return 1.0, "Successfully removed all items from cart" except Exception as e: logger.error(f"Error in _validate_remove_multiple_items_in_the_cart: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_increase_an_item_and_reduce_another_item( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate increasing quantity of one item and reducing another.""" try: if "cart" not in final_state or "cart" not in initial_state: return 0.0, "Missing 'cart' field in states" initial_cart = initial_state["cart"] final_cart = final_state["cart"] if not isinstance(initial_cart, list) or not isinstance(final_cart, list): return 0.0, "cart is not a list" # Build dictionaries for comparison initial_quantities = {item["productId"]: item["qty"] for item in initial_cart} final_quantities = {item["productId"]: item["qty"] for item in final_cart} increased_count = 0 decreased_count = 0 for product_id in set(initial_quantities.keys()) | set(final_quantities.keys()): initial_qty = initial_quantities.get(product_id, 0) final_qty = final_quantities.get(product_id, 0) if final_qty > initial_qty: increased_count += 1 elif final_qty < initial_qty: decreased_count += 1 if increased_count < 1: return 0.0, "No item quantity was increased" if decreased_count < 1: return 0.0, "No item quantity was decreased" return 1.0, "Successfully increased one item and reduced another" except Exception as e: logger.error(f"Error in _validate_increase_an_item_and_reduce_another_item: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_reduce_an_item_quantity_in_the_cart( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate reducing quantity of an item in cart.""" try: if "cart" not in final_state or "cart" not in initial_state: return 0.0, "Missing 'cart' field in states" initial_cart = initial_state["cart"] final_cart = final_state["cart"] if not isinstance(initial_cart, list) or not isinstance(final_cart, list): return 0.0, "cart is not a list" # Build dictionaries for comparison initial_quantities = {item["productId"]: item["qty"] for item in initial_cart} final_quantities = {item["productId"]: item["qty"] for item in final_cart} # Check if any item quantity was reduced reduced = False for product_id in initial_quantities: if final_quantities.get(product_id, 0) < initial_quantities[product_id]: reduced = True break if not reduced: return 0.0, "No item quantity was reduced" return 1.0, "Successfully reduced item quantity" except Exception as e: logger.error(f"Error in _validate_reduce_an_item_quantity_in_the_cart: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_search_and_add_two_items_to_cart( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate searching and adding two items to cart.""" try: if "cart" not in final_state: return 0.0, "Missing 'cart' field in final state" cart = final_state["cart"] if not isinstance(cart, list): return 0.0, "cart is not a list" if len(cart) < 2: return 0.0, f"Expected at least 2 items in cart, found {len(cart)}" return 1.0, "Successfully added two items to cart" except Exception as e: logger.error(f"Error in _validate_search_and_add_two_items_to_cart: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_search_and_add_item_to_cart_and_back_to_home( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate searching, adding item to cart, and returning to homepage.""" try: if "page" not in final_state: return 0.0, "Missing 'page' field in final state" if final_state["page"] != "home": return 0.0, f"Expected page='home', got page='{final_state['page']}'" if "cart" not in final_state: return 0.0, "Missing 'cart' field in final state" cart = final_state["cart"] if not isinstance(cart, list): return 0.0, "cart is not a list" if len(cart) == 0: return 0.0, "Cart is empty" return 1.0, "Successfully added item to cart and returned to homepage" except Exception as e: logger.error(f"Error in _validate_search_and_add_item_to_cart_and_back_to_home: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_remove_item_from_cart_then_search_and_add_item( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate removing item from cart, then searching and adding new item.""" try: if "cart" not in final_state: return 0.0, "Missing 'cart' field in final state" cart = final_state["cart"] if not isinstance(cart, list): return 0.0, "cart is not a list" # Verify cart has items (should have new item added) if len(cart) == 0: return 0.0, "Cart is empty, expected new item" return 1.0, "Successfully removed old item and added new item" except Exception as e: logger.error(f"Error in _validate_remove_item_from_cart_then_search_and_add_item: {e}") return 0.0, f"Validation error: {str(e)}"
def _validate_use_homepage_to_navigate_and_add_items( initial_state: dict, final_state: dict) -> Tuple[float, str]: """Validate using homepage to navigate and add multiple items to cart.""" try: if "page" not in final_state: return 0.0, "Missing 'page' field in final state" if final_state["page"] != "cart": return 0.0, f"Expected page='cart', got page='{final_state['page']}'" if "cart" not in final_state: return 0.0, "Missing 'cart' field in final state" cart = final_state["cart"] if not isinstance(cart, list): return 0.0, "cart is not a list" if len(cart) < 2: return 0.0, f"Expected at least 2 items in cart, found {len(cart)}" # Check for specific product IDs (3 and 4) product_ids = [item.get("productId") for item in cart] if "4" not in product_ids or "3" not in product_ids: return 0.0, "Expected products with IDs '3' and '4' in cart" return 1.0, "Successfully navigated and added multiple items to cart" except Exception as e: logger.error(f"Error in _validate_use_homepage_to_navigate_and_add_items: {e}") return 0.0, f"Validation error: {str(e)}"
# Registry of all reward functionsREWARD_FUNCTIONS_JD = { "_validate_go_to_the_cart_page_from_the_homepage": _validate_go_to_the_cart_page_from_the_homepage, "_validate_go_to_a_product_page_from_home": _validate_go_to_a_product_page_from_home, "_validate_go_to_homepage_from_product_page": _validate_go_to_homepage_from_product_page, "_validate_go_to_cart_page_from_product_detail_page": _validate_go_to_cart_page_from_product_detail_page, "_validate_go_to_product_detail_from_search": _validate_go_to_product_detail_from_search, "_validate_find_a_product_using_search_from_homepage": _validate_find_a_product_using_search_from_homepage, "_validate_search_吉普衬衫": _validate_search_吉普衬衫, "_validate_search_a_product_from_another_product_page": _validate_search_a_product_from_another_product_page, "_validate_add_a_product_to_cart": _validate_add_a_product_to_cart, "_validate_add_a_product_from_search_result_to_cart": _validate_add_a_product_from_search_result_to_cart, "_validate_add_an_item_from_the_homepage": _validate_add_an_item_from_the_homepage, "_validate_add_an_item_with_3_quantity": _validate_add_an_item_with_3_quantity, "_validate_remove_one_item_from_cart": _validate_remove_one_item_from_cart, "_validate_remove_multiple_items_in_the_cart": _validate_remove_multiple_items_in_the_cart, "_validate_increase_an_item_and_reduce_another_item": _validate_increase_an_item_and_reduce_another_item, "_validate_reduce_an_item_quantity_in_the_cart": _validate_reduce_an_item_quantity_in_the_cart, "_validate_search_and_add_two_items_to_cart": _validate_search_and_add_two_items_to_cart, "_validate_search_and_add_item_to_cart_and_back_to_home": _validate_search_and_add_item_to_cart_and_back_to_home, "_validate_remove_item_from_cart_then_search_and_add_item": _validate_remove_item_from_cart_then_search_and_add_item, "_validate_use_homepage_to_navigate_and_add_items": _validate_use_homepage_to_navigate_and_add_items,}
__all__ = [ "_validate_go_to_the_cart_page_from_the_homepage", "_validate_go_to_a_product_page_from_home", "_validate_go_to_homepage_from_product_page", "_validate_go_to_cart_page_from_product_detail_page", "_validate_go_to_product_detail_from_search", "_validate_find_a_product_using_search_from_homepage", "_validate_search_吉普衬衫", "_validate_search_a_product_from_another_product_page", "_validate_add_a_product_to_cart", "_validate_add_a_product_from_search_result_to_cart", "_validate_add_an_item_from_the_homepage", "_validate_add_an_item_with_3_quantity", "_validate_remove_one_item_from_cart", "_validate_remove_multiple_items_in_the_cart", "_validate_increase_an_item_and_reduce_another_item", "_validate_reduce_an_item_quantity_in_the_cart", "_validate_search_and_add_two_items_to_cart", "_validate_search_and_add_item_to_cart_and_back_to_home", "_validate_remove_item_from_cart_then_search_and_add_item", "_validate_use_homepage_to_navigate_and_add_items", "REWARD_FUNCTIONS_JD",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255"""Reward functions for Linear app tasks."""
import loggingfrom typing import Any, Dict, Tuple
logger = logging.getLogger(__name__)
def _validate_drag_to_different_column(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that an issue was moved to a different column.""" if "issues" not in final_state: return 0.0, "No issues in final state"
logger.debug(f"Running reward function on state: {final_state}")
# Find the issue we're tracking (VSS-101) target_issue = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-101"), None)
if not target_issue: return 0.0, "Target issue VSS-101 not found in final state"
# Check if it moved to in_progress status if target_issue.get("status") == "in_progress" and target_issue.get("assigneeId") == "1": return 1.0, "Issue VSS-101 successfully moved to In Progress column for user 1"
return ( 0.0, f"Issue VSS-101 has status={target_issue.get('status')}, " f"assigneeId={target_issue.get('assigneeId')}, expected status=in_progress, assigneeId=1", )
def _validate_drag_two_issues_same_user(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that two issues were moved within the same user's board.""" if "issues" not in final_state: return 0.0, "No issues in final state"
logger.debug(f"Running reward function on state: {final_state}")
# Find both target issues issue_101 = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-101"), None) issue_106 = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-106"), None)
if not issue_101: return 0.0, "Target issue VSS-101 not found in final state" if not issue_106: return 0.0, "Target issue VSS-106 not found in final state"
# Check both issues issue_101_correct = issue_101.get("status") == "in_progress" and issue_101.get("assigneeId") == "1" issue_106_correct = issue_106.get("status") == "queued" and issue_106.get("assigneeId") == "1"
if issue_101_correct and issue_106_correct: return 1.0, "Both issues successfully moved to target columns for user 1"
errors = [] if not issue_101_correct: errors.append( f"VSS-101: status={issue_101.get('status')}, assigneeId={issue_101.get('assigneeId')} (expected in_progress, 1)" ) if not issue_106_correct: errors.append( f"VSS-106: status={issue_106.get('status')}, assigneeId={issue_106.get('assigneeId')} (expected queued, 1)" )
return 0.0, "; ".join(errors)
def _validate_create_new_issue(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that a new issue was created with correct properties.""" if "issues" not in final_state: return 0.0, "No issues in final state"
logger.debug(f"Running reward function on state: {final_state}")
# Find issue by title target_issue = next( (issue for issue in final_state["issues"] if issue.get("title") == "Implement user authentication system"), None )
if not target_issue: return 0.0, "Issue with title 'Implement user authentication system' not found in final state"
# Validate properties errors = []
if target_issue.get("assigneeId") != "2": errors.append(f"assigneeId={target_issue.get('assigneeId')} (expected '2')")
if target_issue.get("priority") != "high": errors.append(f"priority={target_issue.get('priority')} (expected 'high')")
description = target_issue.get("description", "") if "JWT-based authentication" not in description: errors.append("description does not contain 'JWT-based authentication'")
if errors: return 0.0, "; ".join(errors)
return 1.0, "Issue successfully created with correct properties"
def _validate_drag_and_reassign_issue(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that issue VSS-106 was dragged to different status and assignee.""" if "issues" not in final_state: return 0.0, "No issues in final state"
logger.debug(f"Running reward function on state: {final_state}")
# Find the target issue target_issue = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-106"), None)
if not target_issue: return 0.0, "Target issue VSS-106 not found in final state"
# Check if it has correct status and assigneeId if target_issue.get("status") == "in_progress" and target_issue.get("assigneeId") == "2": return 1.0, "Issue VSS-106 successfully moved to In Progress column for Chen (assigneeId=2)"
return ( 0.0, f"Issue VSS-106 has status={target_issue.get('status')}, " f"assigneeId={target_issue.get('assigneeId')}, expected status=in_progress, assigneeId=2", )
def _validate_update_issue_properties(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that issue VSS-105 has updated priority and label.""" if "issues" not in final_state: return 0.0, "No issues in final state"
logger.debug(f"Running reward function on state: {final_state}")
# Find the target issue target_issue = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-105"), None)
if not target_issue: return 0.0, "Target issue VSS-105 not found in final state"
# Validate properties errors = []
if target_issue.get("priority") != "urgent": errors.append(f"priority={target_issue.get('priority')} (expected 'urgent')")
labels = target_issue.get("labels", []) has_operations_label = any(label.get("id") == "label2" for label in labels) if not has_operations_label: errors.append("Operations label (id='label2') not found in labels array")
if errors: return 0.0, "; ".join(errors)
return 1.0, "Issue VSS-105 successfully updated with urgent priority and Operations label"
def _validate_multi_issue_reorganization(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that three issues were reorganized to different columns and assignees.""" if "issues" not in final_state: return 0.0, "No issues in final state"
logger.debug(f"Running reward function on state: {final_state}")
# Find all three target issues issue_101 = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-101"), None) issue_102 = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-102"), None) issue_103 = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-103"), None)
if not issue_101: return 0.0, "Target issue VSS-101 not found in final state" if not issue_102: return 0.0, "Target issue VSS-102 not found in final state" if not issue_103: return 0.0, "Target issue VSS-103 not found in final state"
# Check all issues issue_101_correct = issue_101.get("status") == "in_progress" and issue_101.get("assigneeId") == "2" issue_102_correct = issue_102.get("status") == "blocked" and issue_102.get("assigneeId") == "3" issue_103_correct = issue_103.get("status") == "in_review" and issue_103.get("assigneeId") == "1"
if issue_101_correct and issue_102_correct and issue_103_correct: return 1.0, "All three issues successfully reorganized to target columns and assignees"
errors = [] if not issue_101_correct: errors.append( f"VSS-101: status={issue_101.get('status')}, assigneeId={issue_101.get('assigneeId')} (expected in_progress, 2)" ) if not issue_102_correct: errors.append( f"VSS-102: status={issue_102.get('status')}, assigneeId={issue_102.get('assigneeId')} (expected blocked, 3)" ) if not issue_103_correct: errors.append( f"VSS-103: status={issue_103.get('status')}, assigneeId={issue_103.get('assigneeId')} (expected in_review, 1)" )
return 0.0, "; ".join(errors)
def _validate_complete_issue_workflow(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that a complete issue workflow was executed.""" if "issues" not in final_state: return 0.0, "No issues in final state"
logger.debug(f"Running reward function on state: {final_state}")
# Find issue by title target_issue = next( (issue for issue in final_state["issues"] if issue.get("title") == "Fix critical database connection bug"), None )
if not target_issue: return 0.0, "Issue with title 'Fix critical database connection bug' not found in final state"
# Validate all properties errors = []
if target_issue.get("priority") != "high": errors.append(f"priority={target_issue.get('priority')} (expected 'high')")
if target_issue.get("assigneeId") != "2": errors.append(f"assigneeId={target_issue.get('assigneeId')} (expected '2')")
if target_issue.get("status") != "in_progress": errors.append(f"status={target_issue.get('status')} (expected 'in_progress')")
labels = target_issue.get("labels", []) has_bug_label = any(label.get("id") == "label1" for label in labels) if not has_bug_label: errors.append("Bug label (id='label1') not found in labels array")
comments = target_issue.get("comments", []) has_comment = any("Starting investigation" in comment.get("text", "") for comment in comments) if not has_comment: errors.append("Comment containing 'Starting investigation' not found")
if errors: return 0.0, "; ".join(errors)
return 1.0, "Complete issue workflow successfully executed"
# Registry of all Linear reward functionsREWARD_FUNCTIONS_LINEAR = { "_validate_drag_to_different_column": _validate_drag_to_different_column, "_validate_drag_two_issues_same_user": _validate_drag_two_issues_same_user, "_validate_create_new_issue": _validate_create_new_issue, "_validate_drag_and_reassign_issue": _validate_drag_and_reassign_issue, "_validate_update_issue_properties": _validate_update_issue_properties, "_validate_multi_issue_reorganization": _validate_multi_issue_reorganization, "_validate_complete_issue_workflow": _validate_complete_issue_workflow,}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788"""Reward functions for LinkedIn app tasks."""
import loggingfrom typing import Any, Dict, Tuple
logger = logging.getLogger(__name__)
def _validate_search_for_dzaka(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that the user successfully searched for Dzaka Athif.""" logger.debug(f"Running reward function on state: {final_state}")
# Check 1: currentView is "search" if final_state.get("currentView") != "search": return 0.0, f"Not on search page, current view: {final_state.get('currentView')}"
# Check 2: searchQuery contains "dzaka" (case insensitive) query = final_state.get("searchQuery", "").lower() if "dzaka" not in query: return 0.0, f"Search query doesn't contain 'dzaka': {final_state.get('searchQuery')}"
# Check 3: Dzaka Athif in search results search_results = final_state.get("searchResults", {}) people = search_results.get("allPeople", [])
dzaka_found = any(user.get("name") == "Dzaka Athif" for user in people)
if dzaka_found: return 1.0, "Successfully searched for Dzaka Athif"
return 0.0, f"Dzaka Athif not found in search results. Found {len(people)} people."
def _validate_fractional_find_user_profile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate LinkedIn profile navigation with fractional scoring.
Awards 0.33 points for each criterion met: - currentView is 'profile' - viewedUserId is '2' (John Smith) - searchQuery contains 'john smith' """ logger.debug(f"Running reward function on state: {final_state}")
score = 0.0 passed = [] failed = []
# Check 1: currentView is 'profile' (0.33 points) if final_state.get("currentView") == "profile": score += 0.33 passed.append("currentView='profile'") else: failed.append(f"currentView='{final_state.get('currentView')}' (expected 'profile')")
# Check 2: viewedUserId is '2' (0.33 points) if final_state.get("viewedUserId") == "2": score += 0.33 passed.append("viewedUserId='2'") else: failed.append(f"viewedUserId='{final_state.get('viewedUserId')}' (expected '2')")
# Check 3: searchQuery contains 'john smith' (0.33 points) query = final_state.get("searchQuery", "").lower() if "john smith" in query: score += 0.34 # Make it add up to 1.0 passed.append("searchQuery contains 'john smith'") else: failed.append(f"searchQuery='{final_state.get('searchQuery')}' (expected to contain 'john smith')")
# Build reason string reason_parts = [] if passed: reason_parts.append(f"Passed: {', '.join(passed)}") if failed: reason_parts.append(f"Failed: {', '.join(failed)}")
reason = "; ".join(reason_parts) if reason_parts else "No criteria evaluated"
return round(score, 2), reason
# Registry of all LinkedIn reward functionsREWARD_FUNCTIONS_LINKEDIN = { "_validate_search_for_dzaka": _validate_search_for_dzaka, "_validate_fractional_find_user_profile": _validate_fractional_find_user_profile,}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255"""Reward functions for Minesweeper game tasks.
Board is a 9x9 grid (2D array) of Cell objects: Cell: { isMine: boolean, isRevealed: boolean, isFlagged: boolean, neighborMineCount: number }
Game statuses: "not_started", "playing", "won", "lost""""
import loggingfrom typing import Any, Dict, List, Tuple
logger = logging.getLogger(__name__)
# Helper functions for common validation patterns
def _check_cells_flagged(board: List[List[Dict[str, Any]]], positions: List[Tuple[int, int]]) -> Tuple[float, str]: """ Helper function to check if specific cells are flagged.
Args: board: The game board (2D array) positions: List of (row, col) tuples to check
Returns: (1.0, success_message) if all positions are flagged (0.0, error_message) otherwise """ flagged = [] unflagged = []
for row, col in positions: # Check if position exists if row >= len(board) or col >= len(board[row]): return 0.0, f"Position [{row}][{col}] does not exist on board"
if board[row][col].get("isFlagged"): flagged.append(f"[{row}][{col}]") else: unflagged.append(f"[{row}][{col}]")
if len(flagged) == len(positions): cells_str = ", ".join(flagged) return 1.0, f"All {len(positions)} cell(s) flagged successfully: {cells_str}."
return 0.0, f"Not all cells flagged. Flagged: {flagged}, Not flagged: {unflagged}"
def _check_cells_revealed(board: List[List[Dict[str, Any]]], min_count: int, check_for_mines: bool = True) -> Tuple[float, str]: """ Helper function to check if minimum number of cells are revealed.
Args: board: The game board (2D array) min_count: Minimum number of cells that should be revealed check_for_mines: If True, fail if any revealed cell is a mine
Returns: (1.0, success_message) if criteria met (0.0, error_message) otherwise """ revealed_count = 0 revealed_mine = False
for row in board: for cell in row: if cell.get("isRevealed"): revealed_count += 1 if check_for_mines and cell.get("isMine"): revealed_mine = True
if check_for_mines and revealed_mine: return 0.0, "A mine was revealed - task failed"
if revealed_count >= min_count: return 1.0, f"Successfully revealed {revealed_count} safe cells (target: {min_count}+)."
return 0.0, f"Only {revealed_count} cells revealed, need at least {min_count}"
# Task-specific validation functions
def _validate_minesweeper_reveal_first_cell(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that first move was made - at least one cell revealed and game is playing.""" if "gameStatus" not in final_state: return 0.0, "No gameStatus in final state"
if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
# Check if game status changed to playing if final_state["gameStatus"] != "playing": return 0.0, f"Game status is '{final_state['gameStatus']}', expected 'playing'"
# Check if at least one cell is revealed board = final_state["board"] revealed_count = 0
for row in board: for cell in row: if cell.get("isRevealed"): revealed_count += 1
if revealed_count > 0: return 1.0, f"First move successful - {revealed_count} cell(s) revealed and game is playing."
return 0.0, "No cells revealed yet."
def _validate_minesweeper_reveal_numbered_cell(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that a numbered cell (with neighborMineCount > 0) was revealed at position [1][1].""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
board = final_state["board"]
# Check if position [1][1] exists if len(board) < 2 or len(board[1]) < 2: return 0.0, "Board does not have position [1][1]"
target_cell = board[1][1]
# Check if cell is revealed if not target_cell.get("isRevealed"): return 0.0, "Cell at [1][1] is not revealed"
# Check if cell shows a number (neighborMineCount > 0) neighbor_count = target_cell.get("neighborMineCount", 0)
if neighbor_count > 0: return 1.0, f"Cell at [1][1] revealed successfully showing {neighbor_count} neighboring mine(s)."
return 0.0, f"Cell at [1][1] has neighborMineCount of {neighbor_count}, expected > 0"
def _validate_minesweeper_reveal_10_cells(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that at least 10 cells are revealed, none are mines, and game is still playing.""" if "board" not in final_state: return 0.0, "No board in final state"
if "gameStatus" not in final_state: return 0.0, "No gameStatus in final state"
logger.debug(f"running reward function on state: {final_state}")
# Check if game is still playing if final_state["gameStatus"] != "playing": return 0.0, f"Game status is '{final_state['gameStatus']}', expected 'playing'"
return _check_cells_revealed(final_state["board"], 10, check_for_mines=True)
def _validate_minesweeper_reveal_20_cells(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that at least 20 cells are revealed and game is still playing.""" if "board" not in final_state: return 0.0, "No board in final state"
if "gameStatus" not in final_state: return 0.0, "No gameStatus in final state"
logger.debug(f"running reward function on state: {final_state}")
# Check if game is still playing if final_state["gameStatus"] != "playing": return 0.0, f"Game status is '{final_state['gameStatus']}', expected 'playing' (game should not be won or lost yet)"
return _check_cells_revealed(final_state["board"], 20, check_for_mines=True)
def _validate_minesweeper_flag_single_mine(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that cell at position [0][0] is flagged.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
return _check_cells_flagged(final_state["board"], [(0, 0)])
def _validate_minesweeper_flag_three_mines(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that cells at [0][0], [0][8], and [8][0] are all flagged.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
target_positions = [(0, 0), (0, 8), (8, 0)] return _check_cells_flagged(final_state["board"], target_positions)
def _validate_minesweeper_flag_corner_mines(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that all four corner cells [0][0], [0][8], [8][0], [8][8] are flagged.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
corner_positions = [(0, 0), (0, 8), (8, 0), (8, 8)] return _check_cells_flagged(final_state["board"], corner_positions)
def _validate_minesweeper_reveal_safe_cell(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that cell at position [4][4] is revealed and has 0 neighboring mines.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
board = final_state["board"]
# Check if position [4][4] exists if len(board) < 5 or len(board[4]) < 5: return 0.0, "Board does not have position [4][4]"
target_cell = board[4][4]
# Check if cell is revealed if not target_cell.get("isRevealed"): return 0.0, "Cell at [4][4] is not revealed"
# Check if it's not a mine if target_cell.get("isMine"): return 0.0, "Cell at [4][4] is a mine - task failed!"
# Check if it has 0 neighboring mines neighbor_count = target_cell.get("neighborMineCount", -1) if neighbor_count == 0: return 1.0, "Cell at [4][4] revealed successfully with 0 neighboring mines."
return 0.0, f"Cell at [4][4] has {neighbor_count} neighboring mines, expected 0"
# Registry of all minesweeper reward functionsREWARD_FUNCTIONS_MINESWEEPER = { "_validate_minesweeper_reveal_first_cell": _validate_minesweeper_reveal_first_cell, "_validate_minesweeper_reveal_numbered_cell": _validate_minesweeper_reveal_numbered_cell, "_validate_minesweeper_reveal_10_cells": _validate_minesweeper_reveal_10_cells, "_validate_minesweeper_reveal_20_cells": _validate_minesweeper_reveal_20_cells, "_validate_minesweeper_flag_single_mine": _validate_minesweeper_flag_single_mine, "_validate_minesweeper_flag_three_mines": _validate_minesweeper_flag_three_mines, "_validate_minesweeper_flag_corner_mines": _validate_minesweeper_flag_corner_mines, "_validate_minesweeper_reveal_safe_cell": _validate_minesweeper_reveal_safe_cell,}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423"""Salesforce reward functions for CRM task validation.
This module contains reward validation functions for Salesforce CRM tasks,particularly for complex workflows like lead conversion."""
from typing import Any, Dict, Tuple
def _validate_salesforce_convert_lead(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that a lead has been successfully converted to a contact.
This function checks: 1. The active tab is the leads list page 2. The lead has status 'Converted' and a convertedToContactId 3. A new contact exists with the lead's information (name: Michael Brown)
Args: initial_state: The initial state before the conversion final_state: The final state after the conversion
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: # Check 1: Active tab should be the leads list page active_tab_id = final_state.get("activeTabId") if active_tab_id != "home-listLeads": return 0.0, f"Expected activeTabId to be 'home-listLeads', got '{active_tab_id}'"
# Check 2: Lead should be marked as converted leads = final_state.get("leads", []) if not leads: return 0.0, "No leads found in final state"
# Find the lead (should be lead-001) lead = None for temp_lead in leads: if temp_lead.get("id") == "lead-001": lead = temp_lead break
if not lead: return 0.0, "Lead with id 'lead-001' not found"
# Check lead status and convertedToContactId lead_status = lead.get("leadStatus") converted_to_contact_id = lead.get("convertedToContactId")
if lead_status != "Converted": return 0.0, f"Expected leadStatus to be 'Converted', got '{lead_status}'"
if not converted_to_contact_id: return 0.0, "Expected convertedToContactId to be set, but it's missing"
# Check 3: Contact should exist with the lead's information contacts = final_state.get("contacts", []) if not contacts: return 0.0, "No contacts found in final state"
# Find the contact by the convertedToContactId contact = None for c in contacts: if c.get("id") == converted_to_contact_id: contact = c break
if not contact: return 0.0, f"Contact with id '{converted_to_contact_id}' not found"
# Verify the contact has the correct information (name should be Michael Brown) contact_name = contact.get("name") if contact_name != "Michael Brown": return 0.0, f"Expected contact name to be 'Michael Brown', got '{contact_name}'"
# Additional validation: check that contact has the lead's company contact_company = contact.get("company") lead_company = lead.get("company") if contact_company != lead_company: return 0.0, f"Contact company '{contact_company}' doesn't match lead company '{lead_company}'"
# All checks passed return 1.0, "Lead successfully converted to contact with correct information"
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_salesforce_create_and_convert_lead( initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that a lead has been created and successfully converted to a contact.
This function checks: 1. The active tab is the leads list page 2. A lead exists with name 'Robert Taylor' and status 'Converted' 3. The lead has a convertedToContactId set 4. A new contact exists with the lead's information 5. The contact has the correct name and company
Args: initial_state: The initial state before the creation and conversion final_state: The final state after the creation and conversion
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: # Check 1: Active tab should be the leads list page active_tab_id = final_state.get("activeTabId") if active_tab_id != "home-listLeads": return 0.0, f"Expected activeTabId to be 'home-listLeads', got '{active_tab_id}'"
# Check 2: Lead should exist and be marked as converted leads = final_state.get("leads", []) if not leads: return 0.0, "No leads found in final state"
# Find the lead with name 'Robert Taylor' robert_lead = None for lead in leads: if lead.get("name") == "Robert Taylor": robert_lead = lead break
if not robert_lead: return 0.0, "Lead with name 'Robert Taylor' not found"
# Check lead status and convertedToContactId lead_status = robert_lead.get("leadStatus") converted_to_contact_id = robert_lead.get("convertedToContactId")
if lead_status != "Converted": return 0.0, f"Expected leadStatus to be 'Converted', got '{lead_status}'"
if not converted_to_contact_id: return 0.0, "Expected convertedToContactId to be set, but it's missing"
# Check 3: Contact should exist with the lead's information contacts = final_state.get("contacts", []) if not contacts: return 0.0, "No contacts found in final state"
# Find the contact by the convertedToContactId contact = None for c in contacts: if c.get("id") == converted_to_contact_id: contact = c break
if not contact: return 0.0, f"Contact with id '{converted_to_contact_id}' not found"
# Verify the contact has the correct information contact_name = contact.get("name") if contact_name != "Robert Taylor": return 0.0, f"Expected contact name to be 'Robert Taylor', got '{contact_name}'"
# Check that contact has the lead's company contact_company = contact.get("company") lead_company = robert_lead.get("company") if contact_company != lead_company: return 0.0, f"Contact company '{contact_company}' doesn't match lead company '{lead_company}'"
# Additional validation: check that contact has the lead's email contact_email = contact.get("email") lead_email = robert_lead.get("email") if contact_email != lead_email: return 0.0, f"Contact email '{contact_email}' doesn't match lead email '{lead_email}'"
# Verify the lead was created from scratch (not in initial state) initial_leads = initial_state.get("leads", []) initial_robert_exists = any(lead.get("name") == "Robert Taylor" for lead in initial_leads) if initial_robert_exists: return 0.0, "Lead 'Robert Taylor' already existed in initial state - should be newly created"
# All checks passed return 1.0, "Lead 'Robert Taylor' successfully created and converted to contact with correct information"
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_salesforce_create_new_lead(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that a new lead has been successfully created.
This function checks: 1. The active tab is a lead details page 2. A lead exists with name 'Jane Smith' and company 'Innovation Labs' 3. The lead was not in the initial state (proves it was created)
Args: initial_state: The initial state before the lead creation final_state: The final state after the lead creation
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: # Check 1: Active tab should be a lead details page active_tab_id = final_state.get("activeTabId") if not active_tab_id or not active_tab_id.startswith("lead-"): return 0.0, f"Expected activeTabId to start with 'lead-', got '{active_tab_id}'"
# Check 2: Lead should exist with correct information leads = final_state.get("leads", []) if not leads: return 0.0, "No leads found in final state"
# Find the lead with name 'Jane Smith' jane_lead = None for lead in leads: if lead.get("name") == "Jane Smith": jane_lead = lead break
if not jane_lead: return 0.0, "Lead with name 'Jane Smith' not found"
# Check company if jane_lead.get("company") != "Innovation Labs": return 0.0, f"Expected company to be 'Innovation Labs', got '{jane_lead.get('company')}'"
# Check 3: Verify the lead was created from scratch initial_leads = initial_state.get("leads", []) initial_jane_exists = any(lead.get("name") == "Jane Smith" for lead in initial_leads) if initial_jane_exists: return 0.0, "Lead 'Jane Smith' already existed in initial state - should be newly created"
# All checks passed return 1.0, "Lead 'Jane Smith' successfully created with correct information"
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_salesforce_create_new_case(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that a new case has been successfully created.
This function checks: 1. The active tab is a case details page 2. A case exists with subject 'Technical support request' 3. The case was not in the initial state (proves it was created)
Args: initial_state: The initial state before the case creation final_state: The final state after the case creation
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: # Check 1: Active tab should be a case details page active_tab_id = final_state.get("activeTabId") if not active_tab_id or not active_tab_id.startswith("case-"): return 0.0, f"Expected activeTabId to start with 'case-', got '{active_tab_id}'"
# Check 2: Case should exist with correct subject cases = final_state.get("cases", []) if not cases: return 0.0, "No cases found in final state"
# Find the case with subject 'Technical support request' support_case = None for case in cases: if case.get("subject") == "Technical support request": support_case = case break
if not support_case: return 0.0, "Case with subject 'Technical support request' not found"
# Check 3: Verify the case was created from scratch initial_cases = initial_state.get("cases", []) initial_case_exists = any(case.get("subject") == "Technical support request" for case in initial_cases) if initial_case_exists: return 0.0, "Case 'Technical support request' already existed in initial state - should be newly created"
# All checks passed return 1.0, "Case 'Technical support request' successfully created"
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_salesforce_edit_lead_inline(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that a lead's title has been successfully edited inline.
This function checks: 1. Lead with id 'lead-001' exists 2. The lead's title has been changed from 'VP of Sales' to 'Senior VP of Sales' 3. Other lead fields remain unchanged
Args: initial_state: The initial state before the edit final_state: The final state after the edit
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: # Get the lead from both states initial_leads = initial_state.get("leads", []) final_leads = final_state.get("leads", [])
initial_lead = None for lead in initial_leads: if lead.get("id") == "lead-001": initial_lead = lead break
final_lead = None for lead in final_leads: if lead.get("id") == "lead-001": final_lead = lead break
if not initial_lead: return 0.0, "Lead 'lead-001' not found in initial state"
if not final_lead: return 0.0, "Lead 'lead-001' not found in final state"
# Check that title was updated correctly if initial_lead.get("title") != "VP of Sales": return 0.0, f"Initial title should be 'VP of Sales', got '{initial_lead.get('title')}'"
if final_lead.get("title") != "Senior VP of Sales": return 0.0, f"Expected title to be 'Senior VP of Sales', got '{final_lead.get('title')}'"
# Check that other important fields remain unchanged fields_to_check = ["name", "company", "email", "phone", "leadStatus"] for field in fields_to_check: if initial_lead.get(field) != final_lead.get(field): return 0.0, f"Field '{field}' should not have changed, but it did"
# All checks passed return 1.0, "Lead title successfully updated to 'Senior VP of Sales'"
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
def _validate_salesforce_create_and_close_case(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that a case has been created and successfully closed.
This function checks: 1. The active tab is still a case details page 2. A case exists with subject 'Customer complaint resolved' and status 'Closed' 3. The case was not in the initial state (proves it was created)
Args: initial_state: The initial state before the case creation and closure final_state: The final state after the case creation and closure
Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ try: # Check 1: Active tab should still be a case details page active_tab_id = final_state.get("activeTabId") if not active_tab_id or not active_tab_id.startswith("case-"): return 0.0, f"Expected activeTabId to start with 'case-', got '{active_tab_id}'"
# Check 2: Case should exist with correct subject and be closed cases = final_state.get("cases", []) if not cases: return 0.0, "No cases found in final state"
# Find the case with subject 'Customer complaint resolved' complaint_case = None for case in cases: if case.get("subject") == "Customer complaint resolved": complaint_case = case break
if not complaint_case: return 0.0, "Case with subject 'Customer complaint resolved' not found"
# Check case status case_status = complaint_case.get("status") if case_status != "Closed": return 0.0, f"Expected case status to be 'Closed', got '{case_status}'"
# Check 3: Verify the case was created from scratch initial_cases = initial_state.get("cases", []) initial_case_exists = any(case.get("subject") == "Customer complaint resolved" for case in initial_cases) if initial_case_exists: return 0.0, "Case 'Customer complaint resolved' already existed in initial state - should be newly created"
# All checks passed return 1.0, "Case 'Customer complaint resolved' successfully created and closed"
except Exception as e: return 0.0, f"Error during validation: {str(e)}"
# Registry of Salesforce reward functionsREWARD_FUNCTIONS_SALESFORCE = { "_validate_salesforce_convert_lead": _validate_salesforce_convert_lead, "_validate_salesforce_create_and_convert_lead": _validate_salesforce_create_and_convert_lead, "_validate_salesforce_create_new_lead": _validate_salesforce_create_new_lead, "_validate_salesforce_create_new_case": _validate_salesforce_create_new_case, "_validate_salesforce_edit_lead_inline": _validate_salesforce_edit_lead_inline, "_validate_salesforce_create_and_close_case": _validate_salesforce_create_and_close_case,}
__all__ = [ "REWARD_FUNCTIONS_SALESFORCE", "_validate_salesforce_convert_lead", "_validate_salesforce_create_and_convert_lead", "_validate_salesforce_create_new_lead", "_validate_salesforce_create_new_case", "_validate_salesforce_edit_lead_inline", "_validate_salesforce_create_and_close_case",]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""Reward functions for tic-tac-toe game tasks.
Board is a 9-element array representing a 3x3 grid: [0, 1, 2, 3, 4, 5, 6, 7, 8]
Players: "X" (human), "O" (computer), or null (empty)"""
import loggingfrom typing import Any, Dict, Tuple
logger = logging.getLogger(__name__)
def _validate_tic_tac_toe_make_first_move(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that a move was made on previously empty board.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
board = final_state["board"]
# Check if board has any non-null values if all(cell is None for cell in board): return 0.0, "Board is still empty - no move was made."
# Check if board has at least one X if "X" in board: return 1.0, "First move made successfully - X placed on board."
return 0.0, "No X found on board."
def _validate_take_center(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that X was placed in center position (index 4).""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
board = final_state["board"]
# Check if center position (index 4) contains X if board[4] == "X": return 1.0, "Center square successfully taken by X."
center_value = board[4] if board[4] is not None else "empty" return 0.0, f"Center square not taken by X. Center is: {center_value}"
def _validate_block_computer_win(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """Validate that X blocked computer's win at position 2.""" if "board" not in final_state: return 0.0, "No board in final state"
logger.debug(f"running reward function on state: {final_state}")
board = final_state["board"]
# Check if position 2 (top-right) contains X if board[2] != "X": position_value = board[2] if board[2] is not None else "empty" return 0.0, f"Position 2 not blocked by X. Position 2 is: {position_value}"
# Check that game is still ongoing (player hasn't lost) winner = final_state.get("winner") if winner == "O": return 0.0, "Computer (O) won - blocking was unsuccessful."
return 1.0, "Successfully blocked computer's winning move at position 2."
# Registry of all tic-tac-toe reward functionsREWARD_FUNCTIONS_TIC_TAC_TOE = { "_validate_tic_tac_toe_make_first_move": _validate_tic_tac_toe_make_first_move, "_validate_take_center": _validate_take_center, "_validate_block_computer_win": _validate_block_computer_win,}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924"""Reward functions for Weibo app tasks."""
import loggingfrom typing import Any, Dict, Tuple
logger = logging.getLogger(__name__)
def _validate_navigateprofile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated to a profile page. This function validates the final state matches the expected target state: - currentView should be "profile" - viewedUserId should match the expected user ID - profileTab should be set appropriately Args: initial_state: The initial state before navigation final_state: The final state after navigation Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "profile" current_view = final_state.get("currentView") if current_view != "profile": return 0.0, f"Not on profile page, current view: {current_view}" # Check 2: viewedUserId is "user2" viewed_user_id = final_state.get("viewedUserId") if viewed_user_id != "user2": return 0.0, f"Expected viewedUserId to be 'user2', got '{viewed_user_id}'" # Check 3: profileTab is "posts" (optional but good to validate) profile_tab = final_state.get("profileTab") if profile_tab != "posts": return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'" return 1.0, "Successfully navigated to user2's profile page"
def _validate_navigatepost(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated to a post detail page. This function validates the final state matches the expected target state: - currentView should be "post" - viewedPostId should match the expected post ID - commentTab should be set appropriately Args: initial_state: The initial state before navigation final_state: The final state after navigation Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "post" current_view = final_state.get("currentView") if current_view != "post": return 0.0, f"Not on post detail page, current view: {current_view}" # Check 2: viewedPostId is "4" viewed_post_id = final_state.get("viewedPostId") if viewed_post_id != "4": return 0.0, f"Expected viewedPostId to be '4', got '{viewed_post_id}'" # Check 3: commentTab is "hot" (default tab for post detail) comment_tab = final_state.get("commentTab") if comment_tab != "hot": return 0.0, f"Expected commentTab to be 'hot', got '{comment_tab}'" return 1.0, "Successfully navigated to post 4 detail page"
def _validate_loadmoreposts(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that more posts were successfully loaded in the feed. This function validates the final state matches the expected target state: - currentView should remain "feed" - displayedPosts should have increased (from 10 to 30 posts) - isLoadingPosts should be False (loading completed) Args: initial_state: The initial state before loading more posts final_state: The final state after loading more posts Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "feed" current_view = final_state.get("currentView") if current_view != "feed": return 0.0, f"Not on feed page, current view: {current_view}" # Check 2: displayedPosts has increased initial_posts = initial_state.get("displayedPosts", []) final_posts = final_state.get("displayedPosts", []) initial_count = len(initial_posts) final_count = len(final_posts) if final_count <= initial_count: return 0.0, f"Posts did not increase: {initial_count} -> {final_count} (expected increase)" # Check 3: Final count should be 30 posts if final_count != 30: return 0.0, f"Expected 30 posts in final state, got {final_count}" # Check 4: isLoadingPosts should be False (loading completed) is_loading = final_state.get("isLoadingPosts") if is_loading: return 0.0, f"Expected isLoadingPosts to be False after loading, got {is_loading}" return 1.0, f"Successfully loaded more posts: {initial_count} -> {final_count} posts"
def _validate_postfromprofile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated to a post detail page from a profile page. This function validates the final state matches the expected target state: - currentView should be "post" - viewedPostId should match the expected post ID (31) - commentTab should be "hot" (default tab) - viewedUserId should be None (cleared when navigating to post detail) - displayedPosts should remain unchanged (persisted across pages) Args: initial_state: The initial state before navigation final_state: The final state after navigation Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "post" current_view = final_state.get("currentView") if current_view != "post": return 0.0, f"Not on post detail page, current view: {current_view}" # Check 2: viewedPostId is "31" viewed_post_id = final_state.get("viewedPostId") if viewed_post_id != "31": return 0.0, f"Expected viewedPostId to be '31', got '{viewed_post_id}'" # Check 3: commentTab is "hot" (default tab for post detail) comment_tab = final_state.get("commentTab") if comment_tab != "hot": return 0.0, f"Expected commentTab to be 'hot', got '{comment_tab}'" # Check 4: viewedUserId should be None (cleared when navigating to post) viewed_user_id = final_state.get("viewedUserId") if viewed_user_id is not None: return 0.0, f"Expected viewedUserId to be None after navigating to post, got '{viewed_user_id}'" # Check 5: displayedPosts should remain unchanged (persisted across pages) initial_posts = initial_state.get("displayedPosts", []) final_posts = final_state.get("displayedPosts", []) initial_count = len(initial_posts) final_count = len(final_posts) if initial_count != final_count: return 0.0, f"displayedPosts count changed: {initial_count} -> {final_count} (should remain unchanged)" return 1.0, "Successfully navigated to post 31 detail page from profile"
def _validate_partialsearchquery(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully typed a partial search query and the dropdown shows results. This function validates the final state matches the expected target state: - searchQuery should be "电影" - searchDropdownOpen should be True - searchBarFocused should be True - searchDropdownResults.suggestions should have exactly 1 item containing "电影" - searchDropdownResults.users should have exactly 1 user whose name or bio contains "电影" Args: initial_state: The initial state before typing the query final_state: The final state after typing the query Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: searchQuery is "电影" search_query = final_state.get("searchQuery") if search_query != "电影": return 0.0, f"Expected searchQuery to be '电影', got '{search_query}'" # Check 2: searchDropdownOpen is True search_dropdown_open = final_state.get("searchDropdownOpen") if search_dropdown_open is not True: return 0.0, f"Expected searchDropdownOpen to be True, got {search_dropdown_open}" # Check 3: searchBarFocused is True search_bar_focused = final_state.get("searchBarFocused") if search_bar_focused is not True: return 0.0, f"Expected searchBarFocused to be True, got {search_bar_focused}" # Check 4: searchDropdownResults exists and has suggestions search_dropdown_results = final_state.get("searchDropdownResults", {}) suggestions = search_dropdown_results.get("suggestions", []) if len(suggestions) != 1: return 0.0, f"Expected 1 search suggestion, got {len(suggestions)}" # Check 5: The suggestion contains "电影" as a substring suggestion = suggestions[0] if "电影" not in suggestion: return 0.0, f"Expected suggestion to contain '电影', got '{suggestion}'" # Check 6: searchDropdownResults has users users = search_dropdown_results.get("users", []) if len(users) != 1: return 0.0, f"Expected 1 suggested user, got {len(users)}" # Check 7: The user's name or bio contains "电影" as a substring user = users[0] user_name = user.get("name", "") user_bio = user.get("bio", "") if "电影" not in user_name and "电影" not in user_bio: return 0.0, f"Expected user name or bio to contain '电影', got name='{user_name}', bio='{user_bio}'" return 1.0, f"Successfully typed search query '电影' with 1 suggestion '{suggestion}' and 1 user '{user_name}'"
def _validate_searchdropdownprofile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated to a profile page from the search dropdown. This function validates the final state matches the expected target state: - currentView should be "profile" - viewedUserId should match the expected user ID (user13) - profileTab should be "posts" (default tab) - searchQuery should be empty (cleared after navigation) - searchDropdownOpen should be False (closed after navigation) Args: initial_state: The initial state before navigation final_state: The final state after navigation Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "profile" current_view = final_state.get("currentView") if current_view != "profile": return 0.0, f"Not on profile page, current view: {current_view}" # Check 2: viewedUserId is "user13" viewed_user_id = final_state.get("viewedUserId") if viewed_user_id != "user13": return 0.0, f"Expected viewedUserId to be 'user13', got '{viewed_user_id}'" # Check 3: profileTab is "posts" (default tab) profile_tab = final_state.get("profileTab") if profile_tab != "posts": return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'" # Check 4: searchQuery should be empty (cleared after navigation) search_query = final_state.get("searchQuery") if search_query != "": return 0.0, f"Expected searchQuery to be empty after navigation, got '{search_query}'" # Check 5: searchDropdownOpen should be False (closed after navigation) search_dropdown_open = final_state.get("searchDropdownOpen") if search_dropdown_open is not False: return 0.0, f"Expected searchDropdownOpen to be False after navigation, got {search_dropdown_open}" return 1.0, "Successfully navigated to user13's profile page from search dropdown"
def _validate_profilefrompost(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated to a profile page from a post detail page. This function validates the final state matches the expected target state: - currentView should be "profile" - viewedUserId should match the expected user ID (user5) - profileTab should be "posts" (default tab) - viewedPostId should be None (cleared when navigating to profile) Args: initial_state: The initial state before navigation (on post detail page) final_state: The final state after navigation (on profile page) Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "profile" current_view = final_state.get("currentView") if current_view != "profile": return 0.0, f"Not on profile page, current view: {current_view}" # Check 2: viewedUserId is "user5" viewed_user_id = final_state.get("viewedUserId") if viewed_user_id != "user5": return 0.0, f"Expected viewedUserId to be 'user5', got '{viewed_user_id}'" # Check 3: profileTab is "posts" (default tab) profile_tab = final_state.get("profileTab") if profile_tab != "posts": return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'" # Check 4: viewedPostId should be None (cleared when navigating to profile) viewed_post_id = final_state.get("viewedPostId") if viewed_post_id is not None: return 0.0, f"Expected viewedPostId to be None after navigating to profile, got '{viewed_post_id}'" return 1.0, "Successfully navigated to user5's profile page from post detail page"
def _validate_nosearchsuggestions(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user typed a search query that yields no suggestions or users in the dropdown. This function validates the final state matches the expected target state: - searchQuery should be "asdf" - searchDropdownOpen should be True - searchBarFocused should be True - searchDropdownResults.suggestions should be empty (no suggestions) - searchDropdownResults.users should be empty (no users) Args: initial_state: The initial state before typing the query final_state: The final state after typing the query Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: searchQuery is "asdf" search_query = final_state.get("searchQuery") if search_query != "asdf": return 0.0, f"Expected searchQuery to be 'asdf', got '{search_query}'" # Check 2: searchDropdownOpen is True search_dropdown_open = final_state.get("searchDropdownOpen") if search_dropdown_open is not True: return 0.0, f"Expected searchDropdownOpen to be True, got {search_dropdown_open}" # Check 3: searchBarFocused is True search_bar_focused = final_state.get("searchBarFocused") if search_bar_focused is not True: return 0.0, f"Expected searchBarFocused to be True, got {search_bar_focused}" # Check 4: searchDropdownResults exists and has no suggestions search_dropdown_results = final_state.get("searchDropdownResults", {}) suggestions = search_dropdown_results.get("suggestions", []) if len(suggestions) != 0: return 0.0, f"Expected 0 search suggestions, got {len(suggestions)}" # Check 5: searchDropdownResults has no users users = search_dropdown_results.get("users", []) if len(users) != 0: return 0.0, f"Expected 0 suggested users, got {len(users)}" return 1.0, "Successfully typed search query 'asdf' with no suggestions or users in dropdown"
def _validate_postfromsearch(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated to a post detail page from the search results page. This function validates the final state matches the expected target state: - currentView should be "post" - viewedPostId should match the expected post ID (35) - commentTab should be "hot" (default tab) - searchQuery should be empty (cleared after navigation) - viewedUserId should be None (cleared when navigating to post detail) Args: initial_state: The initial state before navigation (on search results page) final_state: The final state after navigation (on post detail page) Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "post" current_view = final_state.get("currentView") if current_view != "post": return 0.0, f"Not on post detail page, current view: {current_view}" # Check 2: viewedPostId is "35" viewed_post_id = final_state.get("viewedPostId") if viewed_post_id != "35": return 0.0, f"Expected viewedPostId to be '35', got '{viewed_post_id}'" # Check 3: commentTab is "hot" (default tab for post detail) comment_tab = final_state.get("commentTab") if comment_tab != "hot": return 0.0, f"Expected commentTab to be 'hot', got '{comment_tab}'" # Check 4: searchQuery should be empty (cleared after navigation) search_query = final_state.get("searchQuery") if search_query != "": return 0.0, f"Expected searchQuery to be empty after navigation, got '{search_query}'" # Check 5: viewedUserId should be None (cleared when navigating to post) viewed_user_id = final_state.get("viewedUserId") if viewed_user_id is not None: return 0.0, f"Expected viewedUserId to be None after navigating to post, got '{viewed_user_id}'" return 1.0, "Successfully navigated to post 35 detail page from search results"
def _validate_acceptsearchsuggestion(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully selected a search suggestion and navigated to search results. This function validates the final state matches the expected target state: - currentView should be "search" (navigated to search results page) - searchQuery should match the selected suggestion ("用户小王") - searchCategory should be "comprehensive" (default category) - searchDropdownOpen should be False (closed after selection) Args: initial_state: The initial state before selecting the suggestion final_state: The final state after selecting the suggestion Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "search" current_view = final_state.get("currentView") if current_view != "search": return 0.0, f"Not on search results page, current view: {current_view}" # Check 2: searchQuery is "用户小王" (the selected suggestion) search_query = final_state.get("searchQuery") if search_query != "用户小王": return 0.0, f"Expected searchQuery to be '用户小王', got '{search_query}'" # Check 3: searchCategory is "comprehensive" (default category) search_category = final_state.get("searchCategory") if search_category != "comprehensive": return 0.0, f"Expected searchCategory to be 'comprehensive', got '{search_category}'" # Check 4: searchDropdownOpen should be False (closed after selection) search_dropdown_open = final_state.get("searchDropdownOpen") if search_dropdown_open is not False: return 0.0, f"Expected searchDropdownOpen to be False after selection, got {search_dropdown_open}" return 1.0, "Successfully selected search suggestion '用户小王' and navigated to search results"
def _validate_changesearchcategories(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully changed the search category from comprehensive to users. This function validates the final state matches the expected target state: - currentView should remain "search" (stays on search page) - searchQuery should remain unchanged ("用户小王") - searchCategory should be "users" (changed from comprehensive) - searchPageResults.users should have exactly 1 user Args: initial_state: The initial state before changing category (comprehensive) final_state: The final state after changing category (users) Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "search" (stays on search page) current_view = final_state.get("currentView") if current_view != "search": return 0.0, f"Not on search results page, current view: {current_view}" # Check 2: searchQuery remains unchanged ("用户小王") search_query = final_state.get("searchQuery") if search_query != "用户小王": return 0.0, f"Expected searchQuery to remain '用户小王', got '{search_query}'" # Check 3: searchCategory is "users" (changed from comprehensive) search_category = final_state.get("searchCategory") if search_category != "users": return 0.0, f"Expected searchCategory to be 'users', got '{search_category}'" # Check 4: searchPageResults has exactly 1 user search_page_results = final_state.get("searchPageResults", {}) users = search_page_results.get("users", []) if len(users) != 1: return 0.0, f"Expected 1 user in search results, got {len(users)}" return 1.0, "Successfully changed search category from comprehensive to users"
def _validate_profilefromsearch(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated to a profile page from the search results page. This function validates the final state matches the expected target state: - currentView should be "profile" - viewedUserId should match the expected user ID (user16 - 新用户) - profileTab should be "posts" (default tab) - searchQuery should be empty (cleared after navigation) Args: initial_state: The initial state before navigation (on search results page) final_state: The final state after navigation (on profile page) Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "profile" current_view = final_state.get("currentView") if current_view != "profile": return 0.0, f"Not on profile page, current view: {current_view}" # Check 2: viewedUserId is "user16" (the user with name "新用户") viewed_user_id = final_state.get("viewedUserId") if viewed_user_id != "user16": return 0.0, f"Expected viewedUserId to be 'user16', got '{viewed_user_id}'" # Check 3: profileTab is "posts" (default tab) profile_tab = final_state.get("profileTab") if profile_tab != "posts": return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'" # Check 4: searchQuery should be empty (cleared after navigation) search_query = final_state.get("searchQuery") if search_query != "": return 0.0, f"Expected searchQuery to be empty after navigation, got '{search_query}'" return 1.0, "Successfully navigated to user16's (新用户) profile page from search results"
def _validate_profilefromcomments(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated to a profile page from a comment on a post detail page. This function validates the final state matches the expected target state: - currentView should be "profile" - viewedUserId should match the expected user ID (user14 - 日常分享) - profileTab should be "posts" (default tab) - viewedPostId should be None (cleared when navigating to profile) Args: initial_state: The initial state before navigation (on post detail page with comments) final_state: The final state after navigation (on profile page) Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "profile" current_view = final_state.get("currentView") if current_view != "profile": return 0.0, f"Not on profile page, current view: {current_view}" # Check 2: viewedUserId is "user14" (the user with name "日常分享") viewed_user_id = final_state.get("viewedUserId") if viewed_user_id != "user14": return 0.0, f"Expected viewedUserId to be 'user14', got '{viewed_user_id}'" # Check 3: profileTab is "posts" (default tab) profile_tab = final_state.get("profileTab") if profile_tab != "posts": return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'" # Check 4: viewedPostId should be None (cleared when navigating to profile) viewed_post_id = final_state.get("viewedPostId") if viewed_post_id is not None: return 0.0, f"Expected viewedPostId to be None after navigating to profile, got '{viewed_post_id}'" return 1.0, "Successfully navigated to user14's (日常分享) profile page from comments"
def _validate_loadmanyposts(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully loaded more posts and navigated to a specific post detail page. This function validates the final state matches the expected target state: - currentView should be "post" - viewedPostId should match the expected post ID (23) - commentTab should be "hot" (default tab) - The post should be from user "读书笔记" - The post should have exactly 3 attachments (media items) Args: initial_state: The initial state before loading more posts (on feed page) final_state: The final state after navigating to post detail page Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "post" current_view = final_state.get("currentView") if current_view != "post": return 0.0, f"Not on post detail page, current view: {current_view}" # Check 2: viewedPostId is "23" viewed_post_id = final_state.get("viewedPostId") if viewed_post_id != "23": return 0.0, f"Expected viewedPostId to be '23', got '{viewed_post_id}'" # Check 3: commentTab is "hot" (default tab for post detail) comment_tab = final_state.get("commentTab") if comment_tab != "hot": return 0.0, f"Expected commentTab to be 'hot', got '{comment_tab}'" # Check 4: Find the post in allPosts and validate user name and attachments all_posts = final_state.get("allPosts", []) target_post = next((p for p in all_posts if p.get("id") == "23"), None) if target_post is None: return 0.0, "Post with ID '23' not found in allPosts" # Check 5: Post should be from user "读书笔记" post_user = target_post.get("user", {}) user_name = post_user.get("name", "") if user_name != "读书笔记": return 0.0, f"Expected post to be from user '读书笔记', got '{user_name}'" # Check 6: Post should have exactly 3 attachments (media items) media = target_post.get("media", []) media_count = len(media) if media_count != 3: return 0.0, f"Expected post to have 3 attachments, got {media_count}" return 1.0, f"Successfully navigated to post 23 detail page (from 读书笔记 with {media_count} attachments)"
def _validate_profilefromsortedcomments(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated to a profile page from a comment after sorting comments by time. This function validates the final state matches the expected target state: - currentView should be "profile" - viewedUserId should match the expected user ID (user13 - 电影评论) - profileTab should be "posts" (default tab) - viewedPostId should be None (cleared when navigating to profile) Args: initial_state: The initial state before navigation (on post detail page with sorted comments) final_state: The final state after navigation (on profile page) Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "profile" current_view = final_state.get("currentView") if current_view != "profile": return 0.0, f"Not on profile page, current view: {current_view}" # Check 2: viewedUserId is "user13" (the user with name "电影评论") viewed_user_id = final_state.get("viewedUserId") if viewed_user_id != "user13": return 0.0, f"Expected viewedUserId to be 'user13', got '{viewed_user_id}'" # Check 3: profileTab is "posts" (default tab) profile_tab = final_state.get("profileTab") if profile_tab != "posts": return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'" # Check 4: viewedPostId should be None (cleared when navigating to profile) viewed_post_id = final_state.get("viewedPostId") if viewed_post_id is not None: return 0.0, f"Expected viewedPostId to be None after navigating to profile, got '{viewed_post_id}'" return 1.0, "Successfully navigated to user13's (电影评论) profile page from sorted comments"
def _validate_switchtheme(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully switched the theme from light mode to dark mode. This function validates the final state matches the expected target state: - theme should be "dark" (changed from "light") Args: initial_state: The initial state before switching theme (light mode) final_state: The final state after switching theme (dark mode) Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: theme is "dark" theme = final_state.get("theme") if theme != "dark": return 0.0, f"Expected theme to be 'dark', got '{theme}'" return 1.0, "Successfully switched theme from light to dark"
def _validate_homefromsearch(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated from the search results page to the home feed. This function validates the final state matches the expected target state: - currentView should be "feed" (navigated to home feed) - searchQuery should be empty (cleared after navigation) Args: initial_state: The initial state before navigation (on search results page) final_state: The final state after navigation (on home feed) Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "feed" current_view = final_state.get("currentView") if current_view != "feed": return 0.0, f"Not on home feed page, current view: {current_view}" # Check 2: searchQuery should be empty (cleared after navigation) search_query = final_state.get("searchQuery") if search_query != "": return 0.0, f"Expected searchQuery to be empty after navigation, got '{search_query}'" return 1.0, "Successfully navigated from search results to home feed"
def _validate_videopostfromprofile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated to a video post detail page from a profile page. This function validates the final state matches the expected target state: - currentView should be "post" - viewedPostId should match the expected post ID (23) - commentTab should be "hot" (default tab) - The post should be from user "读书笔记" - The post should have at least one video attachment (media item with type "video") Args: initial_state: The initial state before navigation (on profile page with video tab selected) final_state: The final state after navigation (on post detail page) Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "post" current_view = final_state.get("currentView") if current_view != "post": return 0.0, f"Not on post detail page, current view: {current_view}" # Check 2: viewedPostId is "23" viewed_post_id = final_state.get("viewedPostId") if viewed_post_id != "23": return 0.0, f"Expected viewedPostId to be '23', got '{viewed_post_id}'" # Check 3: commentTab is "hot" (default tab for post detail) comment_tab = final_state.get("commentTab") if comment_tab != "hot": return 0.0, f"Expected commentTab to be 'hot', got '{comment_tab}'" # Check 4: Find the post in allPosts and validate user name and video attachment all_posts = final_state.get("allPosts", []) target_post = next((p for p in all_posts if p.get("id") == "23"), None) if target_post is None: return 0.0, "Post with ID '23' not found in allPosts" # Check 5: Post should be from user "读书笔记" post_user = target_post.get("user", {}) user_name = post_user.get("name", "") if user_name != "读书笔记": return 0.0, f"Expected post to be from user '读书笔记', got '{user_name}'" # Check 6: Post should have at least one video attachment media = target_post.get("media", []) video_media = [m for m in media if m.get("type") == "video"] if len(video_media) == 0: return 0.0, f"Expected post to have at least one video attachment, got {len(media)} media items with {len(video_media)} videos" return 1.0, f"Successfully navigated to post 23 detail page (from 读书笔记 with video attachment)"
def _validate_profilefromreply(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully navigated to a profile page from a reply to a comment on a post detail page. This function validates the final state matches the expected target state: - currentView should be "profile" - viewedUserId should match the expected user ID (user4 - 旅行达人) - profileTab should be "posts" (default tab) - viewedPostId should be None (cleared when navigating to profile) Args: initial_state: The initial state before navigation (on post detail page with replies) final_state: The final state after navigation (on profile page) Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "profile" current_view = final_state.get("currentView") if current_view != "profile": return 0.0, f"Not on profile page, current view: {current_view}" # Check 2: viewedUserId is "user4" (the user with name "旅行达人") viewed_user_id = final_state.get("viewedUserId") if viewed_user_id != "user4": return 0.0, f"Expected viewedUserId to be 'user4', got '{viewed_user_id}'" # Check 3: profileTab is "posts" (default tab) profile_tab = final_state.get("profileTab") if profile_tab != "posts": return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'" # Check 4: viewedPostId should be None (cleared when navigating to profile) viewed_post_id = final_state.get("viewedPostId") if viewed_post_id is not None: return 0.0, f"Expected viewedPostId to be None after navigating to profile, got '{viewed_post_id}'" return 1.0, "Successfully navigated to user4's (旅行达人) profile page from reply"
def _validate_searchusers(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: """ Validate that the user successfully searched for users and navigated to the users category of search results. This function validates the final state matches the expected target state: - currentView should be "search" (navigated to search results page) - searchQuery should be "好" (the search term) - searchCategory should be "users" (users category selected) - searchPageResults.users should have at least one user (list of users in search results) Args: initial_state: The initial state before searching (on feed page) final_state: The final state after navigating to users search results Returns: Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure """ logger.debug(f"Running reward function on state: {final_state}") # Check 1: currentView is "search" (navigated to search results page) current_view = final_state.get("currentView") if current_view != "search": return 0.0, f"Not on search results page, current view: {current_view}" # Check 2: searchQuery is "好" (the search term) search_query = final_state.get("searchQuery") if search_query != "好": return 0.0, f"Expected searchQuery to be '好', got '{search_query}'" # Check 3: searchCategory is "users" (users category selected) search_category = final_state.get("searchCategory") if search_category != "users": return 0.0, f"Expected searchCategory to be 'users', got '{search_category}'" # Check 4: searchPageResults has at least one user (list of users in search results) search_page_results = final_state.get("searchPageResults", {}) users = search_page_results.get("users", []) if len(users) == 0: return 0.0, f"Expected at least one user in search results, got {len(users)} users" return 1.0, f"Successfully navigated to users search results page with {len(users)} users"
# Registry of all Weibo reward functionsREWARD_FUNCTIONS_WEIBO = { "_validate_navigateprofile": _validate_navigateprofile, "_validate_navigatepost": _validate_navigatepost, "_validate_loadmoreposts": _validate_loadmoreposts, "_validate_postfromprofile": _validate_postfromprofile, "_validate_partialsearchquery": _validate_partialsearchquery, "_validate_searchdropdownprofile": _validate_searchdropdownprofile, "_validate_profilefrompost": _validate_profilefrompost, "_validate_nosearchsuggestions": _validate_nosearchsuggestions, "_validate_postfromsearch": _validate_postfromsearch, "_validate_acceptsearchsuggestion": _validate_acceptsearchsuggestion, "_validate_changesearchcategories": _validate_changesearchcategories, "_validate_profilefromsearch": _validate_profilefromsearch, "_validate_profilefromcomments": _validate_profilefromcomments, "_validate_loadmanyposts": _validate_loadmanyposts, "_validate_profilefromsortedcomments": _validate_profilefromsortedcomments, "_validate_switchtheme": _validate_switchtheme, "_validate_homefromsearch": _validate_homefromsearch, "_validate_videopostfromprofile": _validate_videopostfromprofile, "_validate_profilefromreply": _validate_profilefromreply, "_validate_searchusers": _validate_searchusers,}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491"""Reward functions for Xiaohongshu (Little Red Book) app tasks."""
import loggingfrom typing import Any, Dict, Optional, Tuple
logger = logging.getLogger(__name__)
def _find_post(final_state: Dict[str, Any], post_id: str) -> Tuple[Optional[Dict[str, Any]], str]: posts = final_state.get("posts") if not isinstance(posts, list): return None, "Posts array missing in final state" for post in posts: if post.get("id") == post_id: return post, "" return None, f"Post with id '{post_id}' not found in final state"
def _find_user(final_state: Dict[str, Any], user_id: str) -> Tuple[Optional[Dict[str, Any]], str]: users = final_state.get("users") if not isinstance(users, list): return None, "Users array missing in final state" for user in users: if user.get("id") == user_id: return user, "" return None, f"User with id '{user_id}' not found in final state"
def _get_current_user(final_state: Dict[str, Any]) -> Tuple[Optional[Dict[str, Any]], str]: current_user = final_state.get("currentUser") if not isinstance(current_user, dict): return None, "currentUser object missing in final state" return current_user, ""
def _validate_single_comment( post: Dict[str, Any], expected_text: str, *, expected_author: Optional[str] = None) -> Tuple[bool, str]: comments = post.get("comments") if not isinstance(comments, list): return False, f"Post {post.get('id')} comments array missing" if len(comments) != 1: return False, f"Post {post.get('id')} has {len(comments)} comments, expected 1" comment = comments[0] content = comment.get("content", "") if expected_text.lower() not in content.lower(): return False, f"Post {post.get('id')} comment content '{content}' missing '{expected_text}'" if expected_author is not None and comment.get("authorId") != expected_author: return False, f"Post {post.get('id')} comment authorId={comment.get('authorId')} expected {expected_author}" return True, ""
def _check_exact_list(values: Any, expected: Tuple[str, ...], field_name: str) -> Tuple[bool, str]: if not isinstance(values, list): return False, f"{field_name} is not a list" if len(values) != len(expected): return False, f"{field_name} has length {len(values)}, expected {len(expected)}" if sorted(values) != sorted(expected): return False, f"{field_name}={values} does not match expected {list(expected)}" return True, ""
def _validate_bookmarkpost(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: current_user, error = _get_current_user(final_state) if not current_user: return 0.0, error
ok, error = _check_exact_list(current_user.get("bookmarks"), ("1",), "currentUser.bookmarks") if not ok: return 0.0, error
post, error = _find_post(final_state, "1") if not post: return 0.0, error if post.get("bookmarks") != 1: return 0.0, f"Post 1 bookmarks={post.get('bookmarks')} expected 1"
user, error = _find_user(final_state, "1") if not user: return 0.0, error if user.get("bookmarkedCount") != 1: return 0.0, f"User 1 bookmarkedCount={user.get('bookmarkedCount')} expected 1"
return 1.0, "Post 1 bookmarked and counts updated"
def _validate_commentontwoseparateposts(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: post1, error = _find_post(final_state, "1") if not post1: return 0.0, error ok, error = _validate_single_comment(post1, "nice song!") if not ok: return 0.0, error
post2, error = _find_post(final_state, "2") if not post2: return 0.0, error ok, error = _validate_single_comment(post2, "what the dog doing?") if not ok: return 0.0, error
if final_state.get("page") != "explore": return 0.0, f"page is {final_state.get('page')} expected 'explore'"
return 1.0, "Posted correct comments on posts 1 and 2 while staying on explore page"
def _validate_commentonvideo(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: post, error = _find_post(final_state, "4") if not post: return 0.0, error ok, error = _validate_single_comment(post, "this cat so cute!", expected_author="0") if not ok: return 0.0, error return 1.0, "Successfully commented 'this cat so cute!' on post 4"
def _validate_comprehensiveuserinteraction(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: if final_state.get("page") != "explore": return 0.0, f"page is {final_state.get('page')} expected 'explore'"
post1, error = _find_post(final_state, "1") if not post1: return 0.0, error if post1.get("likes") != 1: return 0.0, f"Post 1 likes={post1.get('likes')} expected 1" ok, error = _validate_single_comment(post1, "nice") if not ok: return 0.0, error
post2, error = _find_post(final_state, "2") if not post2: return 0.0, error if post2.get("likes") != 1 or post2.get("bookmarks") != 1: return 0.0, f"Post 2 likes={post2.get('likes')} bookmarks={post2.get('bookmarks')} expected 1/1"
post7, error = _find_post(final_state, "7") if not post7: return 0.0, error if post7.get("likes") != 1: return 0.0, f"Post 7 likes={post7.get('likes')} expected 1"
user1, error = _find_user(final_state, "1") if not user1: return 0.0, error if user1.get("likeCount") != 1: return 0.0, f"User 1 likeCount={user1.get('likeCount')} expected 1"
user2, error = _find_user(final_state, "2") if not user2: return 0.0, error if user2.get("likeCount") != 2 or user2.get("bookmarkedCount") != 1: return 0.0, ( f"User 2 likeCount={user2.get('likeCount')} bookmarkedCount={user2.get('bookmarkedCount')} expected 2/1" )
current_user, error = _get_current_user(final_state) if not current_user: return 0.0, error ok, error = _check_exact_list(current_user.get("likedPosts"), ("1", "2", "7"), "currentUser.likedPosts") if not ok: return 0.0, error ok, error = _check_exact_list(current_user.get("following"), ("2",), "currentUser.following") if not ok: return 0.0, error
return 1.0, "Completed comprehensive multi-post interaction requirements"
def _validate_crossuserengagement(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: post_ids = { "1": {"likes": 1}, "2": {"likes": 1, "bookmarks": 1}, "3": {"likes": 1}, "4": {"likes": 1, "bookmarks": 1}, "5": {"likes": 1}, }
for pid, expectations in post_ids.items(): post, error = _find_post(final_state, pid) if not post: return 0.0, error for field, expected_value in expectations.items(): if post.get(field) != expected_value: return 0.0, f"Post {pid} {field}={post.get(field)} expected {expected_value}"
post3, _ = _find_post(final_state, "3") ok, error = _validate_single_comment(post3, "nice") if not ok: return 0.0, error
post4, _ = _find_post(final_state, "4") ok, error = _validate_single_comment(post4, "meow") if not ok: return 0.0, error
user5, error = _find_user(final_state, "5") if not user5: return 0.0, error followers = user5.get("followers") if not isinstance(followers, list) or "0" not in followers: return 0.0, f"User 5 followers={followers} expected to include '0'"
if final_state.get("page") != "profile" or final_state.get("profileUserId") != "5": return 0.0, ( f"page={final_state.get('page')} profileUserId={final_state.get('profileUserId')} expected profile/5" )
return 1.0, "Completed cross-user engagement interactions and viewed user 5 profile"
def _validate_follownavigatehome(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: current_user, error = _get_current_user(final_state) if not current_user: return 0.0, error following = current_user.get("following") if not isinstance(following, list) or "2" not in following: return 0.0, f"currentUser.following={following} expected to include '2'"
user2, error = _find_user(final_state, "2") if not user2: return 0.0, error followers = user2.get("followers") if not isinstance(followers, list) or "0" not in followers: return 0.0, f"User 2 followers={followers} expected to include '0'"
if final_state.get("page") != "explore": return 0.0, f"page is {final_state.get('page')} expected 'explore'"
return 1.0, "Followed user 2 and returned to explore page"
def _validate_followuser(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: current_user, error = _get_current_user(final_state) if not current_user: return 0.0, error ok, err = _check_exact_list(current_user.get("following"), ("1",), "currentUser.following") if not ok: return 0.0, err
user1, error = _find_user(final_state, "1") if not user1: return 0.0, error ok, err = _check_exact_list(user1.get("followers"), ("0",), "User 1 followers") if not ok: return 0.0, err
return 1.0, "Successfully followed user 1"
def _validate_like3sequential(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: for pid in ("1", "2", "3"): post, error = _find_post(final_state, pid) if not post: return 0.0, error if post.get("likes") != 1: return 0.0, f"Post {pid} likes={post.get('likes')} expected 1"
current_user, error = _get_current_user(final_state) if not current_user: return 0.0, error ok, err = _check_exact_list(current_user.get("likedPosts"), ("1", "2", "3"), "currentUser.likedPosts") if not ok: return 0.0, err
for uid in ("1", "2", "3"): user, error = _find_user(final_state, uid) if not user: return 0.0, error if user.get("likeCount") != 1: return 0.0, f"User {uid} likeCount={user.get('likeCount')} expected 1"
return 1.0, "Sequentially liked posts 1, 2, and 3"
def _validate_likeandbookmark(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: post, error = _find_post(final_state, "2") if not post: return 0.0, error if post.get("likes") != 1 or post.get("bookmarks") != 1: return 0.0, f"Post 2 likes={post.get('likes')} bookmarks={post.get('bookmarks')} expected 1/1"
user2, error = _find_user(final_state, "2") if not user2: return 0.0, error if user2.get("likeCount") != 1 or user2.get("bookmarkedCount") != 1: return 0.0, ( f"User 2 likeCount={user2.get('likeCount')} bookmarkedCount={user2.get('bookmarkedCount')} expected 1/1" )
current_user, error = _get_current_user(final_state) if not current_user: return 0.0, error ok, err = _check_exact_list(current_user.get("likedPosts"), ("2",), "currentUser.likedPosts") if not ok: return 0.0, err ok, err = _check_exact_list(current_user.get("bookmarks"), ("2",), "currentUser.bookmarks") if not ok: return 0.0, err
return 1.0, "Liked and bookmarked post 2 with correct counts"
def _validate_likepost(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: post, error = _find_post(final_state, "1") if not post: return 0.0, error if post.get("likes") != 1: return 0.0, f"Post 1 likes={post.get('likes')} expected 1"
user1, error = _find_user(final_state, "1") if not user1: return 0.0, error if user1.get("likeCount") != 1: return 0.0, f"User 1 likeCount={user1.get('likeCount')} expected 1"
return 1.0, "Liked post 1"
def _validate_navigateownprofile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: if final_state.get("page") != "profile": return 0.0, f"page is {final_state.get('page')} expected 'profile'" if final_state.get("profileUserId") != "0": return 0.0, f"profileUserId={final_state.get('profileUserId')} expected '0'" return 1.0, "Navigated to current user's profile"
def _validate_openpostmodal(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: if not final_state.get("activePostId"): return 0.0, "activePostId is missing or null" if final_state.get("isVideoPaused") is True: return 0.0, "isVideoPaused is True; expected False while modal open" return 1.0, "Opened a post modal with video playing"
def _validate_openvideopause(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: if final_state.get("activePostId") != "2": return 0.0, f"activePostId={final_state.get('activePostId')} expected '2'" if final_state.get("isVideoPaused") is not True: return 0.0, "Video is not paused after opening post 2" return 1.0, "Opened post 2 video and paused it"
def _validate_searchandfollowall(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: current_user, error = _get_current_user(final_state) if not current_user: return 0.0, error ok, err = _check_exact_list( current_user.get("following"), ("1", "2", "3", "4", "5"), "currentUser.following", ) if not ok: return 0.0, err
for uid in ("1", "2", "3", "4", "5"): user, error = _find_user(final_state, uid) if not user: return 0.0, error followers = user.get("followers") if not isinstance(followers, list) or "0" not in followers: return 0.0, f"User {uid} followers={followers} expected to include '0'"
if final_state.get("page") != "explore": return 0.0, f"page is {final_state.get('page')} expected 'explore'"
return 1.0, "Followed all users 1-5 and returned to explore"
def _validate_search_and_like(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: post, error = _find_post(final_state, "1") if not post: return 0.0, error if post.get("likes") != 1: return 0.0, f"Post 1 likes={post.get('likes')} expected 1"
user1, error = _find_user(final_state, "1") if not user1: return 0.0, error if user1.get("likeCount") != 1: return 0.0, f"User 1 likeCount={user1.get('likeCount')} expected 1"
return 1.0, "Searched and liked post 1"
def _validate_search_input(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: if final_state.get("searchQuery") != "hello": return 0.0, f"searchQuery={final_state.get('searchQuery')} expected 'hello'" return 1.0, "Updated search input to 'hello'"
def _validate_searchuserandlikeall(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: target_posts = ("2", "7", "12", "17") for pid in target_posts: post, error = _find_post(final_state, pid) if not post: return 0.0, error if post.get("likes") != 1: return 0.0, f"Post {pid} likes={post.get('likes')} expected 1"
user2, error = _find_user(final_state, "2") if not user2: return 0.0, error if user2.get("likeCount") != 4: return 0.0, f"User 2 likeCount={user2.get('likeCount')} expected 4"
current_user, error = _get_current_user(final_state) if not current_user: return 0.0, error ok, err = _check_exact_list(current_user.get("likedPosts"), target_posts, "currentUser.likedPosts") if not ok: return 0.0, err
return 1.0, "Liked all posts from user 2"
def _validate_unfollowuser(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: current_user, error = _get_current_user(final_state) if not current_user: return 0.0, error following = current_user.get("following") if not isinstance(following, list) or len(following) != 0: return 0.0, f"currentUser.following={following} expected empty list"
user1, error = _find_user(final_state, "1") if not user1: return 0.0, error followers = user1.get("followers") if not isinstance(followers, list) or len(followers) != 0: return 0.0, f"User 1 followers={followers} expected empty list"
if final_state.get("page") != "profile" or final_state.get("profileUserId") != "1": return 0.0, ( f"page={final_state.get('page')} profileUserId={final_state.get('profileUserId')} expected profile/1" )
return 1.0, "Successfully unfollowed user 1 while viewing their profile"
def _validate_unlikepost(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: post, error = _find_post(final_state, "10") if not post: return 0.0, error if post.get("likes") != 0: return 0.0, f"Post 10 likes={post.get('likes')} expected 0"
current_user, error = _get_current_user(final_state) if not current_user: return 0.0, error liked_posts = current_user.get("likedPosts") if not isinstance(liked_posts, list) or len(liked_posts) != 0: return 0.0, f"currentUser.likedPosts={liked_posts} expected empty list"
return 1.0, "Unliked post 10 and cleared likedPosts"
def _validate_watchfullvideo(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]: if final_state.get("activePostId") != "2": return 0.0, f"activePostId={final_state.get('activePostId')} expected '2'" if final_state.get("isVideoPaused") is not True: return 0.0, "Video is not paused at completion" if final_state.get("isVideoEnded") is not True: return 0.0, "isVideoEnded is not True after watching video" return 1.0, "Watched post 2 video through completion"
# Registry of all Xiaohongshu reward functionsREWARD_FUNCTIONS_XIAOHONGSHU = { "_validate_bookmarkpost": _validate_bookmarkpost, "_validate_commentontwoseparateposts": _validate_commentontwoseparateposts, "_validate_commentonvideo": _validate_commentonvideo, "_validate_comprehensiveuserinteraction": _validate_comprehensiveuserinteraction, "_validate_crossuserengagement": _validate_crossuserengagement, "_validate_follownavigatehome": _validate_follownavigatehome, "_validate_followuser": _validate_followuser, "_validate_like3sequential": _validate_like3sequential, "_validate_likeandbookmark": _validate_likeandbookmark, "_validate_likepost": _validate_likepost, "_validate_navigateownprofile": _validate_navigateownprofile, "_validate_openpostmodal": _validate_openpostmodal, "_validate_openvideopause": _validate_openvideopause, "_validate_searchandfollowall": _validate_searchandfollowall, "_validate_search_and_like": _validate_search_and_like, "_validate_search_input": _validate_search_input, "_validate_searchuserandlikeall": _validate_searchuserandlikeall, "_validate_unfollowuser": _validate_unfollowuser, "_validate_unlikepost": _validate_unlikepost, "_validate_watchfullvideo": _validate_watchfullvideo,}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "create-two-high-tiles", "name": "Create Two 128 Tiles", "description": "Get at least two tiles with value 128 or higher on the board", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}", "initial_state": "{\"board\": [64, 64, 0, 0, 32, 32, 0, 0, 16, 16, 0, 0, 16, 4, 0, 0], \"gameOver\": false, \"gameInitialized\": true}", "instructions": "{\"user_prompt\": \"Create at least two tiles with value 128 or higher on the board. You'll need to combine smaller tiles strategically to reach this goal.\", \"success_criteria\": \"The board must contain at least two tiles with value 128 or higher.\"}",2 unmodified lines "max_steps": 10, "timeout_seconds": 120, "metadata": "{\"category\": \"games\", \"difficulty\": \"medium\", \"action\": \"two_high_tiles\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "get-128-tile", "name": "Get 128 Tile", "description": "Create a 128 tile in one move", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}", "initial_state": "{\"board\": [0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0], \"gameOver\": false, \"gameInitialized\": true}", "instructions": "{\"user_prompt\": \"Create a 128 tile by combining the two 64-tiles in the middle column. Make the move that will merge them together.\", \"success_criteria\": \"The board must contain a 128-tile after the move.\"}",2 unmodified lines "max_steps": 2, "timeout_seconds": 60, "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\", \"action\": \"create_128\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "get-2048", "name": "Get 2048 in one move", "description": "Make the next move to score 2048.", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}", "initial_state": "{\"board\": [0, 0, 0, 0, 0, 1024, 0, 1024, 0, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}", "instructions": "{\"user_prompt\": \"Play 2048 and make the next move that would cause a 2048 tile to appear.\", \"success_criteria\": \"The game board must contain a 2048 tile.\"}",2 unmodified lines "max_steps": 2, "timeout_seconds": 120, "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "get-256-tile", "name": "Get 256 Tile", "description": "Create a 256 tile in three moves", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}", "initial_state": "{\"board\": [0, 0, 32, 32, 0, 0, 32, 32, 0, 32, 0, 32, 0, 0, 32, 32], \"gameOver\": false, \"gameInitialized\": true}", "instructions": "{\"user_prompt\": \"Create a 256 tile by combining 32-tiles to make 64-tiles, then combining those 64-tiles to make 128-tiles, and finally combining those 128-tiles to make a 256-tile. This requires three strategic moves.\", \"success_criteria\": \"The board must contain a 256-tile after completing the three moves.\"}",2 unmodified lines "max_steps": 10, "timeout_seconds": 60, "metadata": "{\"category\": \"games\", \"difficulty\": \"medium\", \"action\": \"create_256\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "get-32-tile", "name": "Get 32 Tile", "description": "Combine two 16-tiles to create a 32-tile", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}", "initial_state": "{\"board\": [0, 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}", "instructions": "{\"user_prompt\": \"Combine the two 16-tiles in the middle row to create a 32-tile. Move the tiles so they merge together.\", \"success_criteria\": \"The board must contain a 32-tile after the move.\"}",2 unmodified lines "max_steps": 3, "timeout_seconds": 30, "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\", \"action\": \"create_32\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "get-512-tile", "name": "Get 512 Tile", "description": "Create a 512 tile in three moves", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}", "initial_state": "{\"board\": [64, 64, 0, 0, 64, 0, 64, 0, 64, 64, 0, 0, 64, 0, 0, 64], \"gameOver\": false, \"gameInitialized\": true}", "instructions": "{\"user_prompt\": \"Create a 512 tile by combining 64-tiles to make 128-tiles, then combining those 128-tiles to make 256-tiles, and finally combining those 256-tiles to make a 512-tile. This requires three strategic moves.\", \"success_criteria\": \"The board must contain a 512-tile after completing the three moves.\"}",2 unmodified lines "max_steps": 10, "timeout_seconds": 60, "metadata": "{\"category\": \"games\", \"difficulty\": \"medium\", \"action\": \"create_512\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "make-first-move", "name": "Make First Move", "description": "Make any valid move from the initial board state", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}", "initial_state": "{\"board\": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}", "instructions": "{\"user_prompt\": \"Make any valid move in the 2048 game. Use the arrow keys to move tiles in any direction (up, down, left, or right).\", \"success_criteria\": \"The board must change from its initial state after making a move.\"}",2 unmodified lines "max_steps": 5, "timeout_seconds": 30, "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\", \"action\": \"first_move\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "move-tiles-right", "name": "Move Tiles Right", "description": "Move all tiles to the right side of the board", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}", "initial_state": "{\"board\": [2, 0, 0, 0, 4, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}", "instructions": "{\"user_prompt\": \"Move all tiles to the right side of the board using the right arrow key. All tiles should be positioned in the rightmost column.\", \"success_criteria\": \"All tiles must be in the rightmost column (positions 3, 7, 11, 15).\"}",2 unmodified lines "max_steps": 3, "timeout_seconds": 30, "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\", \"action\": \"move_right\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "reach-540-sum", "name": "Reach 540 Sum", "description": "Achieve a board with tiles summing to 540 or more", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}", "initial_state": "{\"board\": [256, 128, 64, 32, 16, 8, 4, 2, 2, 2, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}", "instructions": "{\"user_prompt\": \"Achieve a board where the sum of all tile values is 540 or more. Combine tiles strategically to increase the total value.\", \"success_criteria\": \"The sum of all tile values on the board must be 540 or greater.\"}",2 unmodified lines "max_steps": 20, "timeout_seconds": 120, "metadata": "{\"category\": \"games\", \"difficulty\": \"hard\", \"action\": \"target_540_sum\"}"}}2 unmodified lines34567889101112131414152 unmodified lines "id": "strategic-32", "name": "Strategic 32", "description": "Create a 32 tile from a sparse board with strategic moves", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}", "initial_state": "{\"board\": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}", "instructions": "{\"user_prompt\": \"Starting from an empty board, strategically create a 32 tile. You'll need to build up from smaller tiles through careful planning and multiple moves. This requires combining tiles multiple times: 2\u21924\u21928\u219216\u219232.\", \"success_criteria\": \"The board must contain a 32-tile after completing the strategic moves.\"}", "instructions": "{\"user_prompt\": \"Starting from an empty board, strategically create a 32 tile. You'll need to build up from smaller tiles through careful planning and multiple moves. This requires combining tiles multiple times: 2→4→8→16→32.\", \"success_criteria\": \"The board must contain a 32-tile after completing the strategic moves.\"}", "reward_function": "_validate_strategic_32", "valid_target_states": "", "max_steps": 40, "timeout_seconds": 180, "metadata": "{\"category\": \"games\", \"difficulty\": \"hard\", \"action\": \"strategic_32\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "must-click", "name": "Click Action Test", "description": "Test the agent's ability to perform a single click action on a button", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}", "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}", "instructions": "{\"user_prompt\": \"Click the blue 'Click Me!' button to complete this task. You need to perform a single left-click on the button.\", \"success_criteria\": \"The hasClicked state must be set to True after clicking the button\"}",2 unmodified lines "max_steps": 5, "timeout_seconds": 30, "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"click\", \"target_element\": \"blue button with text 'Click Me!'\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "must-complete-all-actions", "name": "Complete All Actions Test", "description": "Test the agent's ability to perform all computer use actions in sequence - click, double-click, right-click, middle-click, drag, type, hotkey, and scroll", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}", "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}", "instructions": "{\"user_prompt\": \"Complete all 8 computer use actions to finish this comprehensive test: 1) Click the blue 'Click Me!' button, 2) Double-click the purple 'Double Click Me!' button, 3) Right-click the orange area, 4) Middle-click the teal area, 5) Drag the red box to a new position, 6) Type at least 5 characters in the input field, 7) Press Ctrl+S (or Cmd+S on Mac), and 8) Scroll down the page by at least 100 pixels. All actions must be completed successfully.\", \"success_criteria\": \"All action states must be set to True: hasClicked, hasDoubleClicked, hasRightClicked, hasMiddleClicked, hasDragged, hasTyped, hasHotkeyed, and hasScrolled\"}",2 unmodified lines "max_steps": 15, "timeout_seconds": 120, "metadata": "{\"difficulty\": \"hard\", \"action_type\": \"comprehensive\", \"target_element\": \"all interactive elements in the action tester\", \"actions_required\": [\"click\", \"double_click\", \"right_click\", \"middle_click\", \"drag\", \"type\", \"hotkey\", \"scroll\"]}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "must-double-click", "name": "Double Click Action Test", "description": "Test the agent's ability to perform a double-click action on a button", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}", "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}", "instructions": "{\"user_prompt\": \"Double-click the purple 'Double Click Me!' button to complete this task. You need to perform two quick clicks in succession on the button.\", \"success_criteria\": \"The hasDoubleClicked state must be set to True after double-clicking the button\"}",2 unmodified lines "max_steps": 5, "timeout_seconds": 30, "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"double_click\", \"target_element\": \"purple button with text 'Double Click Me!'\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "must-drag", "name": "Drag Action Test", "description": "Test the agent's ability to perform a drag and drop action", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}", "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}", "instructions": "{\"user_prompt\": \"Drag the red 'Drag Me' box to a new position to complete this task. You need to click and hold the red box, then move it to a different location (at least 10 pixels away) before releasing.\", \"success_criteria\": \"The hasDragged state must be set to True after successfully dragging the red box to a new position\"}",2 unmodified lines "max_steps": 10, "timeout_seconds": 45, "metadata": "{\"difficulty\": \"medium\", \"action_type\": \"drag\", \"target_element\": \"red draggable box with text 'Drag Me'\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "must-hotkey", "name": "Hotkey Action Test", "description": "Test the agent's ability to use keyboard shortcuts (hotkeys)", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}", "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}", "instructions": "{\"user_prompt\": \"Press the keyboard shortcut Ctrl+S (or Cmd+S on Mac) to complete this task. You need to hold down the Ctrl key (or Cmd key on Mac) and press the S key simultaneously.\", \"success_criteria\": \"The hasHotkeyed state must be set to True after pressing the Ctrl+S (or Cmd+S) key combination\"}",2 unmodified lines "max_steps": 5, "timeout_seconds": 30, "metadata": "{\"difficulty\": \"medium\", \"action_type\": \"hotkey\", \"target_element\": \"keyboard shortcut Ctrl+S or Cmd+S\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "must-middle-click", "name": "Middle Click Action Test", "description": "Test the agent's ability to perform a middle-click (scroll wheel click) action", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}", "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}", "instructions": "{\"user_prompt\": \"Middle-click (scroll wheel click) on the teal area labeled 'Middle Click Here' to complete this task. You need to press down the scroll wheel on the designated area.\", \"success_criteria\": \"The hasMiddleClicked state must be set to True after middle-clicking the teal area\"}",2 unmodified lines "max_steps": 5, "timeout_seconds": 30, "metadata": "{\"difficulty\": \"medium\", \"action_type\": \"middle_click\", \"target_element\": \"teal area with text 'Middle Click Here'\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "must-perform-three-medium-actions", "name": "Three Medium Actions Test", "description": "Test the agent's ability to perform three medium-difficulty actions in sequence: drag, hotkey, and middle-click", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}", "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}", "instructions": "{\"user_prompt\": \"Complete three medium-difficulty computer use actions to finish this test: 1) Drag the red 'Drag Me' box to a new position (at least 10 pixels away), 2) Press the keyboard shortcut Ctrl+S (or Cmd+S on Mac), and 3) Middle-click (scroll wheel click) on the teal area labeled 'Middle Click Here'. All three actions must be completed successfully in any order.\", \"success_criteria\": \"The hasDragged, hasHotkeyed, and hasMiddleClicked states must all be set to True\"}",2 unmodified lines "max_steps": 15, "timeout_seconds": 90, "metadata": "{\"difficulty\": \"hard\", \"action_type\": \"combined_medium_actions\", \"target_element\": \"multiple interactive elements requiring drag, hotkey, and middle-click\", \"actions_required\": [\"drag\", \"hotkey\", \"middle_click\"]}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "must-right-click", "name": "Right Click Action Test", "description": "Test the agent's ability to perform a right-click (context menu) action", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}", "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}", "instructions": "{\"user_prompt\": \"Right-click on the orange area labeled 'Right Click Here' to complete this task. You need to perform a right-click (context menu click) on the designated area.\", \"success_criteria\": \"The hasRightClicked state must be set to True after right-clicking the orange area\"}",2 unmodified lines "max_steps": 5, "timeout_seconds": 30, "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"right_click\", \"target_element\": \"orange area with text 'Right Click Here'\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "must-scroll", "name": "Scroll Action Test", "description": "Test the agent's ability to scroll the page", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}", "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}", "instructions": "{\"user_prompt\": \"Scroll down on the page by at least 100 pixels to complete this task. You can use the scroll wheel, arrow keys, or drag the scrollbar to scroll down the page.\", \"success_criteria\": \"The hasScrolled state must be set to True after scrolling down the page by 100 pixels or more\"}",2 unmodified lines "max_steps": 5, "timeout_seconds": 30, "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"scroll\", \"target_element\": \"page scroll area\"}"}}2 unmodified lines34567892 unmodified lines12131414152 unmodified lines "id": "must-type", "name": "Type Action Test", "description": "Test the agent's ability to type text into an input field", "tier": "free", "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}", "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}", "instructions": "{\"user_prompt\": \"Type at least 5 characters in the text input field to complete this task. Click on the input field with placeholder 'Type here...' and enter at least 5 characters of text.\", \"success_criteria\": \"The hasTyped state must be set to True after typing at least 5 characters in the input field\"}",2 unmodified lines "max_steps": 10, "timeout_seconds": 30, "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"type\", \"target_element\": \"text input field with placeholder 'Type here...'\"}"}}rewards/__init__.pyAdded+37
rewards/__pycache__/amazon.cpython-312.pycAdded
rewards/__pycache__/game_2048.cpython-312.pycAdded
rewards/__pycache__/jd.cpython-312.pycAdded
rewards/__pycache__/linear.cpython-312.pycAdded
rewards/__pycache__/linkedin.cpython-312.pycAdded
rewards/__pycache__/minesweeper.cpython-312.pycAdded
rewards/__pycache__/salesforce.cpython-312.pycAdded
rewards/__pycache__/tic_tac_toe.cpython-312.pycAdded
rewards/__pycache__/weibo.cpython-312.pycAdded
rewards/__pycache__/xiaohongshu.cpython-312.pycAdded
rewards/amazon.pyAdded+2223
rewards/game_2048.pyAdded+168
rewards/jd.pyAdded+569
rewards/linear.pyAdded+255
rewards/linkedin.pyAdded+88
rewards/minesweeper.pyAdded+255
rewards/salesforce.pyAdded+423
rewards/tic_tac_toe.pyAdded+82
rewards/weibo.pyAdded+924
rewards/xiaohongshu.pyAdded+491
tasks/2048/create-two-high-tiles.json+2-1
tasks/2048/get-128-tile.json+2-1
tasks/2048/get-2048.json+2-1
tasks/2048/get-256-tile.json+2-1
tasks/2048/get-32-tile.json+2-1
tasks/2048/get-512-tile.json+2-1
tasks/2048/make-first-move.json+2-1
tasks/2048/move-tiles-right.json+2-1
tasks/2048/reach-540-sum.json+2-1
tasks/2048/strategic-32.json+3-2
tasks/action-tester/must-click.json+2-1
tasks/action-tester/must-complete-all-actions.json+2-1
tasks/action-tester/must-double-click.json+2-1
tasks/action-tester/must-drag.json+2-1
tasks/action-tester/must-hotkey.json+2-1
tasks/action-tester/must-middle-click.json+2-1
tasks/action-tester/must-perform-three-medium-actions.json+2-1
tasks/action-tester/must-right-click.json+2-1
tasks/action-tester/must-scroll.json+2-1
tasks/action-tester/must-type.json+2-1
tasks/amazon/customer-reviews-that-have-4-stars-and-above.jsonAdded
tasks/amazon/customer-reviews-that-have-5-stars.jsonAdded
tasks/amazon/entering-pod-in-the-search-bar.jsonAdded
tasks/amazon/filter-on-amazon-global-store.jsonAdded
tasks/amazon/filter-on-include-out-of-stock.jsonAdded
tasks/amazon/filter-on-product-condition-renewed.jsonAdded
tasks/amazon/filter-on-products-condition-new.jsonAdded
tasks/amazon/filter-on-products-condition-used.jsonAdded
tasks/amazon/filter-products-based-on-prime-delivery.jsonAdded