prthm11 commited on
Commit
3f7a37b
·
verified ·
1 Parent(s): c16de1d

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -886
app.py CHANGED
@@ -250,76 +250,6 @@ SYSTEM_PROMPT ="""Your task is to process OCR-extracted text from images of Scra
250
  - Booleans: `<condition>`
251
  5. **Final Output:** Your response must ONLY be the valid JSON object and nothing else."""
252
 
253
- # SYSTEM_PROMPT = """
254
- # You are an expert AI assistant named GameScratchAgent, specialized in generating and modifying Scratch-VM 3.x game project JSON.
255
- # Your core task is to process game descriptions and existing Scratch JSON structures, then produce or update JSON segments accurately.
256
- # You possess deep knowledge of Scratch 3.0 project schema, informed by comprehensive reference materials. When generating or modifying the `blocks` section, pay extremely close attention to the following:
257
-
258
- # **Scratch Project JSON Schema Rules:**
259
-
260
- # 1. **Target Structure (`project.json`'s `targets` array):**
261
- # * Each object in the `targets` array represents a Stage or a Sprite.
262
- # * `isStage`: A boolean indicating if the target is the Stage (`true`) or a Sprite (`false`).
263
- # * `name`: The name of the Stage (e.g., `"Stage"`) or the Sprite (e.g., `"Cat"`). This property replaces `objName` found in older Scratch versions.
264
- # * `variables` dictionary: This dictionary maps unique variable IDs to arrays `[variable_name, initial_value, isCloudVariable?]`.
265
- # * `variable_name`: The user-defined name of the variable.
266
- # * `initial_value`: The variable's initial value, which can be a number or a string.
267
- # * `isCloudVariable?`: (Optional) A boolean indicating if it's a cloud variable (`true`) or a local variable (`false` or absent for regular variables).
268
- # * Example: `"myVarId123": ["score", 0]`, `"cloudVarId456": ["☁ High Score", "54", true]`
269
- # * `lists` dictionary: This dictionary maps unique list IDs to arrays `[list_name, [item1, item2, ...]]`.
270
- # * Example: `"myListId789": ["my list", ["apple", "banana"]]`
271
- # * `broadcasts` dictionary: This dictionary maps unique broadcast IDs to their names.
272
- # * Example: `"myBroadcastId": "Game Over"`
273
- # * `blocks` dictionary: This dictionary contains all the blocks belonging to this target. Keys are block IDs, values are block objects.
274
-
275
- # 2. **Block Structure (within a `target`'s `blocks` dictionary):**
276
- # * Every block object must have the following core properties:
277
- # * [cite_start]`opcode`: A unique internal identifier for the block's specific functionality (e.g., `"motion_movesteps"`, `"event_whenflagclicked"`)[cite: 31, 18, 439, 452].
278
- # * `parent`: The ID of the block directly above it in the script stack (or `null` for a top-level block).
279
- # * `next`: The ID of the block directly below it in the script stack (or `null` for the end of a stack).
280
- # * `inputs`: An object defining values or blocks plugged into the block's input slots. Values are **arrays**.
281
- # * `fields`: An object defining dropdown menu selections or direct internal values within the block. Values are **arrays**.
282
- # * `shadow`: `true` if it's a shadow block (e.g., a default number input that can be replaced by another block), `false` otherwise.
283
- # * `topLevel`: `true` if it's a hat block or a standalone block (not connected to a parent), `false` otherwise.
284
-
285
- # 3. **`inputs` Property Details (for blocks plugged into input slots):**
286
- # * **Direct Block Connection (Reporter/Boolean block plugged in):**
287
- # * Format: `"<INPUT_NAME>": [1, "<blockId_of_plugged_block>"]`
288
- # * Example: `"CONDITION": [1, "someBooleanBlockId"]` (e.g., for an `if` block).
289
- # * **Literal Value Input (Shadow block with a literal):**
290
- # * Format: `"<INPUT_NAME>": [1, [<type_code>, "<value_string>"]]`
291
- # * `type_code`: A numeric code representing the data type. Common codes include: `4` for number, `7` for string/text, `10` for string/message.
292
- # * `value_string`: The literal value as a string.
293
- # * Examples:
294
- # * Number: `"STEPS": [1, [4, "10"]]` (for `move 10 steps` block).
295
- # * String/Text: `"MESSAGE": [1, [7, "Hello"]]` (for `say Hello` block).
296
- # * String/Message (common for text inputs): `"MESSAGE": [1, [10, "Hello!"]]` (for `say Hello! for 2 secs`).
297
- # * **C-Block Substack (blocks within a loop or conditional):**
298
- # * Format: `"<SUBSTACK_NAME>": [2, "<blockId_of_first_block_in_substack>"]`
299
- # * Common `SUBSTACK_NAME` values are `SUBSTACK` (for `if`, `forever`, `repeat`) and `SUBSTACK2` (for `else` in `if else`).
300
- # * Example: `"SUBSTACK": [2, "firstBlockInLoopId"]`
301
-
302
- # 4. **`fields` Property Details (for dropdowns or direct internal values):**
303
- # * Used for dropdown menus, variable names, list names, or other static selections directly within the block.
304
- # * Format: `"<FIELD_NAME>": ["<selected_value>", null]`
305
- # * Examples:
306
- # * Dropdown: `"KEY_OPTION": ["space", null]` (for `when space key pressed`).
307
- # * Variable Name: `"VARIABLE": ["score", null]` (for `set score to 0`).
308
- # * Direction (specific motion block): `"FORWARD_BACKWARD": ["forward", null]` (for `go forward layers`).
309
-
310
- # 5. **Unique IDs:**
311
- # * All block IDs, variable IDs, and list IDs must be unique strings (e.g., "myBlock123", "myVarId456", "myListId789"). Do NOT use placeholder strings like "block_id_here".
312
-
313
- # 6. **No Nested `blocks` Dictionary:**
314
- # * The `blocks` dictionary should only appear once per `target` (sprite/stage). Do NOT nest a `blocks` dictionary inside an individual block definition. Blocks that are part of a substack are linked via the `SUBSTACK` input.
315
-
316
- # 7. **Asset Properties (for Costumes/Sounds):**
317
- # * `assetId`, `md5ext`, `bitmapResolution`, `rotationCenterX`/`rotationCenterY` should be correctly associated with costume and sound objects within the `costumes` and `sounds` arrays.
318
-
319
- # **General Principles and Important Considerations:**
320
- # * **Backward Compatibility:** Adhere strictly to existing Scratch 3.0 opcodes and schema to ensure backward compatibility with older projects. [cite_start]Opcodes must remain consistent to prevent previously saved projects from failing to load or behaving unexpectedly[cite: 18, 19, 25, 65].
321
- # * **Forgiving Inputs:** Recognize that Scratch is designed to be "forgiving in its interpretation of inputs." [cite_start]The Scratch VM handles potentially "invalid" inputs gracefully (e.g., converting a number to a string if expected, returning default values like zero or empty strings, or performing no action) rather than crashing[cite: 20, 21, 22, 38, 39, 41]. This implies that precise type matching for inputs might be handled internally by Scratch, allowing for some flexibility in how values are provided, but the agent should aim for the most common and logical type.
322
- # """
323
 
324
  # SYSTEM_PROMPT_JSON_CORRECTOR ="""
325
  # You are an assistant that outputs JSON responses strictly following the given schema.
@@ -1700,822 +1630,6 @@ def node_optimizer(state: GameState):
1700
  except Exception as e:
1701
  logger.error(f"Error in Node Optimizer Node: {e}")
1702
 
1703
- # Node 2: planner node
1704
- # def overall_planner_node(state: GameState):
1705
- # """
1706
- # Generates a comprehensive action plan for sprites, including detailed Scratch block information.
1707
- # This node acts as an overall planner, leveraging knowledge of all block shapes and categories.
1708
- # """
1709
- # logger.info("--- Running OverallPlannerNode ---")
1710
-
1711
- # project_json = state["project_json"]
1712
- # raw = state.get("pseudo_code", {})
1713
- # refined_logic_data = raw.get("refined_logic", {})
1714
- # sprite_name = refined_logic_data.get("name_variable", "<unknown>")
1715
- # pseudo = refined_logic_data.get("pseudocode", "")
1716
-
1717
- # # MODIFICATION 1: Include 'Stage' in the list of names to plan for.
1718
- # # It's crucial to ensure 'Stage' is always present for its global role.
1719
- # target_names = [t["name"] for t in project_json["targets"]]
1720
-
1721
- # # MODIFICATION 2: Get sprite positions, providing default for Stage as it doesn't have x,y
1722
- # sprite_positions = {}
1723
- # for target in project_json["targets"]:
1724
- # if not target["isStage"]:
1725
- # sprite_positions[target["name"]] = {"x": target.get("x", 0), "y": target.get("y", 0)}
1726
- # else:
1727
- # sprite_positions[target["name"]] = {"x": "N/A", "y": "N/A"} # Stage doesn't have positional coordinates
1728
-
1729
- # # declaration_plan = state["declaration_plan"]
1730
-
1731
- # planning_prompt = f"""
1732
- # Generate a detailed action plan for the game's sprites and stage based on the given pseudo-code and sprite details for the given sprite name and .
1733
-
1734
- # Description:
1735
- # **Sprite_name**: {sprite_name}
1736
- # **and its corresponding Pseudo_code:**
1737
- # '{pseudo}'
1738
-
1739
- # [Note: Make sure you just refine the pseudo code by correting mistake and adding the missing opcode if any and *Do not* generate any new logic]
1740
- # ----
1741
- # **Targets in Game (Sprites and Stage) available in project_json:** {', '.join(target_names)}
1742
-
1743
- # --- Scratch 3.0 Block Reference ---
1744
- # This section provides a comprehensive reference of Scratch 3.0 blocks, categorized by shape, including their opcodes and functional descriptions. Use this to accurately identify block types and behavior.
1745
-
1746
- # ### Hat Blocks
1747
- # Description: {hat_description}
1748
- # Blocks:
1749
- # {hat_opcodes_functionalities}
1750
-
1751
- # ### Boolean Blocks
1752
- # Description: {boolean_description}
1753
- # Blocks:
1754
- # {boolean_opcodes_functionalities}
1755
-
1756
- # ### C Blocks
1757
- # Description: {c_description}
1758
- # Blocks:
1759
- # {c_opcodes_functionalities}
1760
-
1761
- # ### Cap Blocks
1762
- # Description: {cap_description}
1763
- # Blocks:
1764
- # {cap_opcodes_functionalities}
1765
-
1766
- # ### Reporter Blocks
1767
- # Description: {reporter_description}
1768
- # Blocks:
1769
- # {reporter_opcodes_functionalities}
1770
-
1771
- # ### Stack Blocks
1772
- # Description: {stack_description}
1773
- # Blocks:
1774
- # {stack_opcodes_functionalities}
1775
-
1776
- # -----------------------------------
1777
-
1778
- # Your task is to use the `Sprite_name` given and `Pseudo_code` and add it to the specific target name and define the primary actions and movements.
1779
- # The output should be a JSON object with a single key 'action_overall_flow'. Each key inside this object should be a sprite or 'Stage' name (e.g., 'Player', 'Enemy', 'Stage'), and its value must include a 'description' and a list of 'plans'.
1780
- # The first plan in each stage must start with one Scratch Hat Block (e.g., event_whenflagclicked).
1781
- # Other plans may use any hat blocks (including duplicates) to represent different logics or events.
1782
- # Each plan must include a **single Scratch Hat Block** (e.g., 'event_whenflagclicked') to start scratch project and should contain:
1783
-
1784
- # 1. **'event'**: the exact `opcode` of the hat block that initiates the logic.
1785
- # [NOTE: INSTRUCTIONN TO FOLLOW IF PSEUDO_CODE HAVING PROBLEM ]
1786
- # 2. **'logic'**: a natural language breakdown of each step taken after the event, formatted as a multi-line string representing pseudo-code. Ensure clarity and granularity—each described action should map closely to a Scratch block or tight sequence.
1787
- # - Use 'forever: ...' or 'repeat(10): ...' to prefix repeating logic suitable taking reference from the C blocks.
1788
- # - Use Scratch-consistent verbs: 'move', 'change', 'wait', 'hide', 'show', 'say', 'glide', etc.
1789
- # - **Numeric values** `(e.g., 0, 5, 0.2, -130)` **must** be in parentheses: `(0)`, `(5)`, `(0.2)`, `(-130)`.
1790
- # - **AlphaNumeric values** `(e.g., hello, say 5, 4, hi!)` **must** be in parentheses: `(hello)`, `(say 5)`, `(4)`, `(hi!)`.
1791
- # - **Variables** must be in the form `[variable v]` (e.g., `[score v]`), even when used inside expressions two example use `set [score v] to (1)` or `show variable ([speed v])`.
1792
- # - **Dropdown options** must be in the form `[option v]` (e.g., `[Game Start v]`, `[blue sky v]`). example use `when [space v] key pressed`.
1793
- # - **Reporter blocks** used as inputs must be double‑wrapped: `((x position))`, `((y position))`. example use `if <((y position)) = (-130)> then` or `(((x position)) * (1))`.
1794
- # - **Boolean blocks** in conditions must be inside `< >`, including nested ones: `<not <condition>>`, `<<cond1> and <cond2>>`,`<<cond1> or <cond2>>`.
1795
- # - **Other Boolean blocks** in conditions must be inside `< >`, including nested ones or values or variables: `<(block/value/variable) * (block/value/variable)>`,`<(block/value/variable) < (block/value/variable)>`, and example of another variable`<[apple v] contains [a v]?>`.
1796
- # - **Operator expressions** must use explicit Scratch operator blocks, e.g.:
1797
- # ```
1798
- # (([ballSpeed v]) * (1.1))
1799
- # ```
1800
- # - **Every hat block script must end** with a final `end` on its own line.
1801
- # - **Indent nested blocks by 4 spaces under their parent (`forever`, `if`, etc.).This is a critical requirement.**
1802
- # 3. **Opcode Lists**: include relevant Scratch opcodes grouped under `motion`, `control`, `operator`, `sensing`, `looks`, `sounds`, `events`, and `data`. List only the non-empty categories. Use exact opcodes.
1803
- # 4. Few Example of content of logics inside for a specific plan as scratch pseudo-code:
1804
- # - example 1[continues moving objects]:
1805
- # ```
1806
- # when green flag clicked
1807
- # go to x: (240) y: (-100)
1808
- # set [speed v] to (-5)
1809
- # show variable [speed v]
1810
- # forever
1811
- # change x by ([speed v])
1812
- # if <((x position)) < (-240)> then
1813
- # go to x: (240) y: (-100)
1814
- # end
1815
- # end
1816
- # end
1817
- # ```
1818
- # - example 2[jumping script of an plan]:
1819
- # ```
1820
- # when [space v] key pressed
1821
- # if <((y position)) = (-100)> then
1822
- # repeat (5)
1823
- # change y by (100)
1824
- # wait (0.1) seconds
1825
- # change y by (-100)
1826
- # wait (0.1) seconds
1827
- # end
1828
- # end
1829
- # end
1830
- # ```
1831
- # - example 3 [pattern for level up and increase difficulty]:
1832
- # ```
1833
- # when I receive [Level Up v]
1834
- # change [level v] by (1)
1835
- # set [ballSpeed v] to ((([ballSpeed v]) * (1.1)))
1836
- # end
1837
- # ```
1838
- # 5. Use target names exactly as listed in `Targets in Game`. Do NOT rename or invent new targets.
1839
- # 6. Ensure the plan reflects accurate opcode usage derived strictly from the block reference above.
1840
- # 7. Few shot Example structure for 'action_overall_flow':
1841
- # ```json
1842
- # {{
1843
- # "action_overall_flow": {{
1844
- # "Stage": {{
1845
- # "description": "Background and global game state management, including broadcasts, rewards, and score.",
1846
- # "plans": [
1847
- # {{
1848
- # "event": "event_whenflagclicked",
1849
- # "logic": "when green flag clicked\n switch backdrop to [backdrop1 v]\n set [score v] to 0\n show variable [score v]\n broadcast [Game Start v]\nend",
1850
- # "motion": [],
1851
- # "control": [],
1852
- # "operator": [],
1853
- # "sensing": [],
1854
- # "looks": [
1855
- # "looks_switchbackdropto"
1856
- # ],
1857
- # "sounds": [],
1858
- # "events": [
1859
- # "event_broadcast"
1860
- # ],
1861
- # "data": [
1862
- # "data_setvariableto",
1863
- # "data_showvariable"
1864
- # ]
1865
- # }},
1866
- # {{
1867
- # "event": "event_whenbroadcastreceived",
1868
- # "logic": "when I receive [Game Over v]\n if <(score) > (High Score)> then\n set [High Score v] to (score)\n end\n switch backdrop to [HighScore v]\nend",
1869
- # "motion": [],
1870
- # "control": [
1871
- # "control_if"
1872
- # ],
1873
- # "operator": [
1874
- # "operator_gt"
1875
- # ],
1876
- # "sensing": [],
1877
- # "looks": [
1878
- # "looks_switchbackdropto"
1879
- # ],
1880
- # "sounds": [],
1881
- # "events": [],
1882
- # "data": [
1883
- # "data_setvariableto"
1884
- # ]
1885
- # }}
1886
- # ]
1887
- # }},
1888
- # "Sprite1": {{
1889
- # "description": "Main character (cat) actions",
1890
- # "plans": [
1891
- # {{
1892
- # "event": "event_whenflagclicked",
1893
- # "logic": "when green flag clicked\n go to x: 240 y: -100\nend",
1894
- # "motion": [
1895
- # "motion_gotoxy"
1896
- # ],
1897
- # "control": [],
1898
- # "operator": [],
1899
- # "sensing": [],
1900
- # "looks": [],
1901
- # "sounds": [],
1902
- # "events": [],
1903
- # "data": []
1904
- # }},
1905
- # {{
1906
- # "event": "event_whenkeypressed",
1907
- # "logic": "when [space v] key pressed\n repeat (10)\n change y by (20)\n wait (0.1) seconds\n change y by (-20)\n end\nend",
1908
- # "motion": [
1909
- # "motion_changeyby"
1910
- # ],
1911
- # "control": [
1912
- # "control_repeat",
1913
- # "control_wait"
1914
- # ],
1915
- # "operator": [],
1916
- # "sensing": [],
1917
- # "looks": [],
1918
- # "sounds": [],
1919
- # "events": [],
1920
- # "data": []
1921
- # }}
1922
- # ]
1923
- # }},
1924
- # "soccer ball": {{
1925
- # "description": "Obstacle movement and interaction",
1926
- # "plans": [
1927
- # {{
1928
- # "event": "event_whenflagclicked",
1929
- # "logic": "when green flag clicked\n go to x: 240 y: -135\n forever\n glide 2 seconds to x: -240 y: -135\n if <(x position) < -235> then\n set x to 240\n end\n if <touching [Sprite1 v]?> then\n broadcast [Game Over v]\n stop [all v]\n end\n end\nend",
1930
- # "motion": [
1931
- # "motion_gotoxy",
1932
- # "motion_glidesecstoxy",
1933
- # "motion_xposition",
1934
- # "motion_setx"
1935
- # ],
1936
- # "control": [
1937
- # "control_forever",
1938
- # "control_if",
1939
- # "control_stop"
1940
- # ],
1941
- # "operator": [
1942
- # "operator_lt"
1943
- # ],
1944
- # "sensing": [
1945
- # "sensing_touchingobject",
1946
- # "sensing_touchingobjectmenu"
1947
- # ],
1948
- # "looks": [],
1949
- # "sounds": [],
1950
- # "events": [
1951
- # "event_broadcast"
1952
- # ],
1953
- # "data": []
1954
- # }}
1955
- # ]
1956
- # }}
1957
-
1958
- # }}
1959
- # }}
1960
- # ```
1961
- # 8. Based on the provided context, generate the `action_overall_flow`.
1962
- # - Maintain the **exact JSON structure** shown above.
1963
- # - All `logic` fields must be **clear and granular**.
1964
- # - Only include opcode categories that contain relevant opcodes.
1965
- # - Ensure that each opcode matches its intended Scratch functionality.
1966
- # - If feedback suggests major change, **rethink the entire plan** for the affected sprite(s).
1967
- # - If feedback is minor, make precise, minimal improvements only.
1968
- # """
1969
-
1970
- # try:
1971
- # response = agent.invoke({"messages": [{"role": "user", "content": planning_prompt}]})
1972
- # print("Raw response from LLM [OverallPlannerNode 1]:",response)
1973
- # raw_response = response["messages"][-1].content#strip_noise(response["messages"][-1].content)
1974
- # print("Raw response from LLM [OverallPlannerNode 2]:", raw_response) # Uncomment for debugging
1975
- # # json debugging and solving
1976
- # try:
1977
- # overall_plan = extract_json_from_llm_response(raw_response)
1978
- # except json.JSONDecodeError as error_json:
1979
- # logger.error("Failed to extract JSON from LLM response. Attempting to correct the response.")
1980
- # # Use the JSON resolver agent to fix the response
1981
- # correction_prompt = (
1982
- # "Your task is to correct the provided JSON string to ensure it is **syntactically perfect and adheres strictly to JSON rules**.\n"
1983
- # "Carefully review the JSON for any errors, especially focusing on the reported error at:\n"
1984
- # f"- **Error Details**: {error_json}\n\n"
1985
- # "**Strict Instructions for your response:**\n"
1986
- # "1. **ONLY** output the corrected JSON. Do not include any other text, comments, or explanations outside the JSON.\n"
1987
- # "2. Ensure all property names (keys) are enclosed in **double quotes**.\n"
1988
- # "3. Ensure string values are correctly enclosed in **double quotes** and any internal special characters (like newlines `\\n`, tabs `\\t`, backslashes `\\\\`, or double quotes `\\`) are properly **escaped**.\n"
1989
- # "4. Verify that there are **no extra commas**, especially between key-value pairs or after the last element in an object or array.\n"
1990
- # "5. Ensure proper nesting and matching of curly braces `{}` and square brackets `[]`.\n"
1991
- # "6. **Crucially, remove any extraneous characters or duplicate closing braces outside the main JSON object.**\n"
1992
- # "7. The corrected JSON must be a **complete and valid** JSON object.\n\n"
1993
- # "Here is the problematic JSON string to correct:\n"
1994
- # "```json\n"
1995
- # f"{raw_response}\n"
1996
- # "```\n"
1997
- # "Corrected JSON:\n"
1998
- # )
1999
- # correction_response = agent_json_resolver.invoke({"messages": [{"role": "user", "content": correction_prompt}]})
2000
- # print(f"[JSON CORRECTOR RESPONSE AT OVERALLPLANNERNODE ]: {correction_response['messages'][-1].content}")
2001
- # overall_plan= extract_json_from_llm_response(correction_response['messages'][-1].content)#strip_noise(correction_response["messages"][-1].content))
2002
-
2003
- # state["action_plan"] = overall_plan
2004
- # logger.info("Overall plan generated by OverallPlannerNode.")
2005
-
2006
- # # with open("debug_state.json", "w", encoding="utf-8") as f:
2007
- # # json.dump(state, f, indent=2, ensure_ascii=False)
2008
-
2009
- # return state
2010
-
2011
- # except Exception as e:
2012
- # logger.error(f"Error in OverallPlannerNode: {e}")
2013
- # raise
2014
- # # Node 3: refiner node (scrape)
2015
- # def refined_planner_node(state: GameState):
2016
- # """
2017
- # Refines the action plan based on validation feedback and game description.
2018
- # """
2019
- # logger.info("--- Running RefinedPlannerNode ---")
2020
- # raw = state.get("pseudo_code", {})
2021
- # refined_logic_data = raw.get("refined_logic", {})
2022
- # sprite_name = refined_logic_data.get("name_variable", "<unknown>")
2023
- # pseudo = refined_logic_data.get("pseudocode", "")
2024
- # #detailed_game_description = state.get("detailed_game_description", state.get("description", "A game."))
2025
- # current_action_plan = state.get("action_plan", {})
2026
- # print(f"[current_action_plan before refinement] on ({state.get('iteration_count', 0)}): {json.dumps(current_action_plan, indent=2)}")
2027
- # plan_validation_feedback = state.get("plan_validation_feedback", "No specific feedback provided. Assume general refinement is needed.")
2028
- # project_json = state["project_json"]
2029
- # target_names = [t["name"] for t in project_json["targets"]]
2030
-
2031
- # # MODIFICATION 2: Get sprite positions, providing default for Stage as it doesn't have x,y
2032
- # sprite_positions = {}
2033
- # for target in project_json["targets"]:
2034
- # if not target["isStage"]:
2035
- # sprite_positions[target["name"]] = {"x": target.get("x", 0), "y": target.get("y", 0)}
2036
- # else:
2037
- # sprite_positions[target["name"]] = {"x": "N/A", "y": "N/A"} # Stage doesn't have positional coordinates
2038
-
2039
- # #declaration_plan = state["declaration_plan"]
2040
-
2041
- # refinement_prompt = f"""
2042
- # Refine and correct the JSON object `action_overall_flow` so that it fully aligns with the detailed game description, sprite positions, variable/broadcast declarations, and Scratch 3.0 block reference—while also validating for common formatting or opcode errors.
2043
-
2044
- # Here is the overall script available:
2045
- # **Sprite name**: {sprite_name}
2046
- # **and its corresponding Pseudo_code:**
2047
- # '{pseudo}'
2048
-
2049
- # [Note: Make sure you just refine the pseudo code by correting mistake and adding the missing opcode if any and *Do not* generate any new logic]
2050
- # ---
2051
- # **Targets in Game (Sprites and Stage):** {', '.join(target_names)}
2052
- # **Current action plan:**
2053
- # {current_action_plan}
2054
-
2055
- # **Validation Feedback:**
2056
- # '{plan_validation_feedback}'
2057
-
2058
- # --- Scratch 3.0 Block Reference ---
2059
- # ### Hat Blocks
2060
- # {hat_opcodes_functionalities}
2061
-
2062
- # ### Boolean Blocks
2063
- # {boolean_opcodes_functionalities}
2064
-
2065
- # ### C Blocks
2066
- # {c_opcodes_functionalities}
2067
-
2068
- # ### Cap Blocks
2069
- # {cap_opcodes_functionalities}
2070
-
2071
- # ### Reporter Blocks
2072
- # {reporter_opcodes_functionalities}
2073
-
2074
- # ### Stack Blocks
2075
- # {stack_opcodes_functionalities}
2076
-
2077
- # -----------------------------------
2078
-
2079
- # * **Your task is to align to description, refine and correct the JSON object 'action_overall_flow'.**
2080
- # Use sprite names exactly as provided in `sprite_names` (e.g., 'Sprite1', 'soccer ball'); and also the stage, do **NOT** rename them.
2081
- # Other plans may use any hat blocks (including duplicates) to represent different logics or events.
2082
- # Each plan must include a **single Scratch Hat Block** (e.g., 'event_whenflagclicked') to start scratch project and should contain:
2083
- # 1. **'event'**: the exact `opcode` of the hat block that initiates the logic.
2084
- # 2. **'logic'**: a natural language breakdown of each step taken after the event, formatted as a multi-line string representing pseudo-code. Ensure clarity and granularity—each described action should map closely to a Scratch block or tight sequence.
2085
- # - Do **NOT** include any justification or comments—only the raw logic.
2086
- # - Use 'forever: ...' or 'repeat(10): ...' to prefix repeating logic suitable taking reference from the C blocks.
2087
- # - Use Scratch-consistent verbs: 'move', 'change', 'wait', 'hide', 'show', 'say', 'glide', etc.
2088
- # - **Numeric values** `(e.g., 0, 5, 0.2, -130)` **must** be in parentheses: `(0)`, `(5)`, `(0.2)`, `(-130)`.
2089
- # - **AlphaNumeric values** `(e.g., hello, say 5, 4, hi!)` **must** be in parentheses: `(hello)`, `(say 5)`, `(4)`, `(hi!)`.
2090
- # - **Variables** must be in the form `[variable v]` (e.g., `[score v]`), even when used inside expressions two example use `set [score v] to (1)` or `show variable ([speed v])`.
2091
- # - **Dropdown options** must be in the form `[option v]` (e.g., `[Game Start v]`, `[blue sky v]`). example use `when [space v] key pressed`.
2092
- # - **Reporter blocks** used as inputs must be double‑wrapped: `((x position))`, `((y position))`. example use `if <((y position)) = (-130)> then` or `(((x position)) * (1))`.
2093
- # - **Boolean blocks** in conditions must be inside `< >`, including nested ones: `<not <condition>>`, `<<cond1> and <cond2>>`,`<<cond1> or <cond2>>`.
2094
- # - **Other Boolean blocks** in conditions must be inside `< >`, including nested ones or values or variables: `<(block/value/variable) * (block/value/variable)>`,`<(block/value/variable) < (block/value/variable)>`, and example of another variable`<[apple v] contains [a v]?>`.
2095
- # - **Operator expressions** must use explicit Scratch operator blocks, e.g.:
2096
- # ```
2097
- # (([ballSpeed v]) * (1.1))
2098
- # ```
2099
- # - **Every hat block script must end** with a final `end` on its own line.
2100
- # 3. **Validation & Formatting Checks**
2101
- # - **Opcode Coverage**: Ensure every action in `logic` has a matching opcode in the lists.
2102
- # - **Bracket Nesting**: Confirm every `(` has a matching `)`, e.g., `(pick random (100) to (-100))`.
2103
- # - **Operator Formatting**: Validate that operators use Scratch operator blocks, not inline math.
2104
- # - **Common Errors**:
2105
- # - `pick random (100,-100)` → `(pick random (100) to (-100))`
2106
- # - Missing `end` at script conclusion
2107
- # - Unwrapped reporter inputs or Boolean tests
2108
- # 4. **Opcode Lists**: include relevant Scratch opcodes grouped under `motion`, `control`, `operator`, `sensing`, `looks`, `sounds`, `events`, and `data`. List only the non-empty categories. Use exact opcodes from the given Scratch 3.0 Block Reference.
2109
- # 5. Few Example of content of logics inside for a specific plan as scratch pseudo-code:
2110
- # - example 1[continues moving objects]:
2111
- # ```
2112
- # when green flag clicked
2113
- # go to x: (240) y: (-100)
2114
- # set [speed v] to (-5)
2115
- # show variable [speed v]
2116
- # forever
2117
- # change x by ([speed v])
2118
- # if <((x position)) < (-240)> then
2119
- # go to x: (240) y: (-100)
2120
- # end
2121
- # end
2122
- # end
2123
- # ```
2124
- # - example 2[jumping script of an plan]:
2125
- # ```
2126
- # when [space v] key pressed
2127
- # if <((y position)) = (-100)> then
2128
- # repeat (5)
2129
- # change y by (100)
2130
- # wait (0.1) seconds
2131
- # change y by (-100)
2132
- # wait (0.1) seconds
2133
- # end
2134
- # end
2135
- # end
2136
- # ```
2137
- # - example 3 [pattern for level up and increase difficulty]:
2138
- # ```
2139
- # when I receive [Level Up v]
2140
- # change [level v] by (1)
2141
- # set [ballSpeed v] to ((([ballSpeed v]) * (1.1)))
2142
- # end
2143
- # ```
2144
- # 6. Use target names exactly as listed in `Targets in Game`. Do NOT rename or invent new targets.
2145
- # 7. Ensure the plan reflects accurate opcode usage derived strictly from the block reference above.
2146
- # 8. Few shot Example structure for 'action_overall_flow':
2147
- # ```json
2148
- # {{
2149
- # "action_overall_flow": {{
2150
- # "Stage": {{
2151
- # "description": "Background and global game state management, including broadcasts, rewards, and score.",
2152
- # "plans": [
2153
- # {{
2154
- # "event": "event_whenflagclicked",
2155
- # "logic": "when green flag clicked\n switch backdrop to [backdrop1 v]\n set [score v] to 0\n show variable [score v]\n broadcast [Game Start v]\nend",
2156
- # "motion": [],
2157
- # "control": [],
2158
- # "operator": [],
2159
- # "sensing": [],
2160
- # "looks": [
2161
- # "looks_switchbackdropto"
2162
- # ],
2163
- # "sounds": [],
2164
- # "events": [
2165
- # "event_broadcast"
2166
- # ],
2167
- # "data": [
2168
- # "data_setvariableto",
2169
- # "data_showvariable"
2170
- # ]
2171
- # }},
2172
- # {{
2173
- # "event": "event_whenbroadcastreceived",
2174
- # "logic": "when I receive [Game Over v]\n if <(score) > (High Score)> then\n set [High Score v] to (score)\n end\n switch backdrop to [HighScore v]\nend",
2175
- # "motion": [],
2176
- # "control": [
2177
- # "control_if"
2178
- # ],
2179
- # "operator": [
2180
- # "operator_gt"
2181
- # ],
2182
- # "sensing": [],
2183
- # "looks": [
2184
- # "looks_switchbackdropto"
2185
- # ],
2186
- # "sounds": [],
2187
- # "events": [],
2188
- # "data": [
2189
- # "data_setvariableto"
2190
- # ]
2191
- # }}
2192
- # ]
2193
- # }},
2194
- # "Sprite1": {{
2195
- # "description": "Main character (cat) actions",
2196
- # "plans": [
2197
- # {{
2198
- # "event": "event_whenflagclicked",
2199
- # "logic": "when green flag clicked\n go to x: 240 y: -100\nend\n",
2200
- # "motion": [
2201
- # "motion_gotoxy"
2202
- # ],
2203
- # "control": [],
2204
- # "operator": [],
2205
- # "sensing": [],
2206
- # "looks": [],
2207
- # "sounds": [],
2208
- # "events": [],
2209
- # "data": []
2210
- # }},
2211
- # {{
2212
- # "event": "event_whenkeypressed",
2213
- # "logic": "when [space v] key pressed\n repeat (10)\n change y by (20)\n wait (0.1) seconds\n change y by (-20)\n end\nend",
2214
- # "motion": [
2215
- # "motion_changeyby"
2216
- # ],
2217
- # "control": [
2218
- # "control_repeat",
2219
- # "control_wait"
2220
- # ],
2221
- # "operator": [],
2222
- # "sensing": [],
2223
- # "looks": [],
2224
- # "sounds": [],
2225
- # "events": [],
2226
- # "data": []
2227
- # }}
2228
- # ]
2229
- # }},
2230
- # "soccer ball": {{
2231
- # "description": "Obstacle movement and interaction",
2232
- # "plans": [
2233
- # {{
2234
- # "event": "event_whenflagclicked",
2235
- # "logic": "when green flag clicked\n go to x: 240 y: -135\n forever\n glide 2 seconds to x: -240 y: -135\n if <(x position) < -235> then\n set x to 240\n end\n if <touching [Sprite1 v]?> then\n broadcast [Game Over v]\n stop [all v]\n end\n end\nend",
2236
- # "motion": [
2237
- # "motion_gotoxy",
2238
- # "motion_glidesecstoxy",
2239
- # "motion_xposition",
2240
- # "motion_setx"
2241
- # ],
2242
- # "control": [
2243
- # "control_forever",
2244
- # "control_if",
2245
- # "control_stop"
2246
- # ],
2247
- # "operator": [
2248
- # "operator_lt"
2249
- # ],
2250
- # "sensing": [
2251
- # "sensing_touchingobject",
2252
- # "sensing_touchingobjectmenu"
2253
- # ],
2254
- # "looks": [],
2255
- # "sounds": [],
2256
- # "events": [
2257
- # "event_broadcast"
2258
- # ],
2259
- # "data": []
2260
- # }}
2261
- # ]
2262
- # }}
2263
- # }}
2264
- # }}
2265
- # ```
2266
- # 9. Use the validation feedback to address errors, fill in missing logic, or enhance clarity.
2267
- # example of few possible improvements: 1.event_whenflagclicked is used to control sprite but its used for actual start scratch project and reset scratch. 2. looping like forever used where we should use iterative. 3. missing of for variable we used in the block
2268
- # - Maintain the **exact JSON structure** shown above.
2269
- # - All `logic` fields must be **clear and granular**.
2270
- # - Only include opcode categories that contain relevant opcodes.
2271
- # - Ensure that each opcode matches its intended Scratch functionality.
2272
- # - If feedback suggests major change, **rethink the entire plan** for the affected sprite(s).
2273
- # - If feedback is minor, make precise, minimal improvements only.
2274
- # """
2275
- # try:
2276
- # response = agent.invoke({"messages": [{"role": "user", "content": refinement_prompt}]})
2277
- # raw_response = response["messages"][-1].content#strip_noise(response["messages"][-1].content)
2278
- # logger.info(f"Raw response from LLM [RefinedPlannerNode]: {raw_response[:500]}...")
2279
- # # json debugging and solving
2280
- # try:
2281
- # refined_plan = extract_json_from_llm_response(raw_response)
2282
- # except json.JSONDecodeError as error_json:
2283
- # logger.error("Failed to extract JSON from LLM response. Attempting to correct the response.")
2284
- # # Use the JSON resolver agent to fix the response
2285
- # correction_prompt = (
2286
- # "Your task is to correct the provided JSON string to ensure it is **syntactically perfect and adheres strictly to JSON rules**.\n"
2287
- # "Carefully review the JSON for any errors, especially focusing on the reported error at:\n"
2288
- # f"- **Error Details**: {error_json}\n\n"
2289
- # "**Strict Instructions for your response:**\n"
2290
- # "1. **ONLY** output the corrected JSON. Do not include any other text, comments, or explanations outside the JSON.\n"
2291
- # "2. Ensure all property names (keys) are enclosed in **double quotes**.\n"
2292
- # "3. Ensure string values are correctly enclosed in **double quotes** and any internal special characters (like newlines `\\n`, tabs `\\t`, backslashes `\\\\`, or double quotes `\\`) are properly **escaped**.\n"
2293
- # "4. IN `logic` field make sure content enclosed in **double quotes** should not have invalid **double quotes**, **eliminate** all quotes inside the content if any. "
2294
- # "4. Verify that there are **no extra commas**, especially between key-value pairs or after the last element in an object or array.\n"
2295
- # "5. Ensure proper nesting and matching of curly braces `{}` and square brackets `[]`.\n"
2296
- # "6. **Crucially, remove any extraneous characters or duplicate closing braces outside the main JSON object.**\n" # Added instruction
2297
- # "7. The corrected JSON must be a **complete and valid** JSON object.\n\n"
2298
- # "Here is the problematic JSON string to correct:\n"
2299
- # "```json\n"
2300
- # f"{raw_response}\n"
2301
- # "```\n"
2302
- # "Corrected JSON:\n"
2303
- # )
2304
- # correction_response = agent_json_resolver.invoke({"messages": [{"role": "user", "content": correction_prompt}]})
2305
- # print(f"[JSON CORRECTOR RESPONSE AT REFINEPLANNER ]: {correction_response['messages'][-1].content}")
2306
- # refined_plan = extract_json_from_llm_response(correction_response["messages"][-1].content)#strip_noise(correction_response["messages"][-1].content))
2307
- # logger.info("Refined plan corrected by JSON resolver agent.")
2308
-
2309
- # if refined_plan:
2310
- # #state["action_plan"] = refined_plan.get("action_overall_flow", {}) # Update to the key 'action_overall_flow' [error]
2311
- # state["action_plan"] = refined_plan #.get("action_overall_flow", {}) # Update the main the prompt includes updated only
2312
- # logger.info("Action plan refined by RefinedPlannerNode.")
2313
- # else:
2314
- # logger.warning("RefinedPlannerNode did not return a valid 'action_overall_flow' structure. Keeping previous plan.")
2315
- # print("[Refined Action Plan]:", json.dumps(state["action_plan"], indent=2))
2316
- # #print("[current state after refinement]:", json.dumps(state, indent=2))
2317
-
2318
- # # with open("debug_state.json", "w", encoding="utf-8") as f:
2319
- # # json.dump(state, f, indent=2, ensure_ascii=False)
2320
-
2321
- # return state
2322
- # except Exception as e:
2323
- # logger.error(f"Error in RefinedPlannerNode: {e}")
2324
- # raise
2325
- # # Node 4: opcode counter node (scrape)
2326
- # def plan_opcode_counter_node(state: Dict[str, Any]) -> Dict[str, Any]:
2327
- # """
2328
- # For each plan in state["action_plan"], calls the LLM agent
2329
- # to analyze the `logic` string and return a list of {opcode, count} for each category.
2330
- # """
2331
- # logger.info("=== Running OPCODE COUTER LOGIC with LLM counts ===")
2332
- # #game_description = state.get("description", "No game description provided.")
2333
- # sprite_name = {}
2334
- # project_json_targets = state.get("project_json", {}).get("targets", [])
2335
- # for target in project_json_targets:
2336
- # sprite_name[target["name"]] = target["name"]
2337
-
2338
- # action_flow = state.get("action_plan", {})
2339
-
2340
- # if action_flow.get("action_overall_flow", {}) == {}:
2341
- # plan_data = action_flow.items()
2342
- # else:
2343
- # plan_data = action_flow.get("action_overall_flow", {}).items()
2344
-
2345
- # refined_flow: Dict[str, Any] = {}
2346
- # for sprite, sprite_data in plan_data:
2347
- # refined_plans = []
2348
- # for plan in sprite_data.get("plans", []):
2349
- # logic = plan.get("logic", "")
2350
- # event = plan.get("event", "")
2351
-
2352
- # # These are for guiding the LLM, not for the final output format directly
2353
- # opcodes_from_plan = {
2354
- # "motion": plan.get("motion", []),
2355
- # "control": plan.get("control", []),
2356
- # "operator": plan.get("operator", []),
2357
- # "sensing": plan.get("sensing", []),
2358
- # "looks": plan.get("looks", []),
2359
- # "sounds": plan.get("sounds", []),
2360
- # "events": plan.get("events", []) + ([event] if isinstance(event, str) else []),
2361
- # "data": plan.get("data", []),
2362
- # }
2363
-
2364
- # refinement_prompt = f"""
2365
- # You are a Scratch 3.0 expert with deep knowledge of block types, nesting and stack relationships.
2366
- # Your job: read the plan logic below and decide exactly which blocks (and how many of each) are required to implement it.
2367
- # Review the following plan for '{sprite}' triggered by '{event}'.
2368
- # --- Scratch 3.0 Block Reference ---
2369
- # ### Hat Blocks
2370
- # Description: {hat_description}
2371
- # Blocks:
2372
- # {hat_opcodes_functionalities}
2373
-
2374
- # ### Boolean Blocks
2375
- # Description: {boolean_description}
2376
- # Blocks:
2377
- # {boolean_opcodes_functionalities}
2378
-
2379
- # ### C Blocks
2380
- # Description: {c_description}
2381
- # Blocks:
2382
- # {c_opcodes_functionalities}
2383
-
2384
- # ### Cap Blocks
2385
- # Description: {cap_description}
2386
- # Blocks:
2387
- # {cap_opcodes_functionalities}
2388
-
2389
- # ### Reporter Blocks
2390
- # Description: {reporter_description}
2391
- # Blocks:
2392
- # {reporter_opcodes_functionalities}
2393
-
2394
- # ### Stack Blocks
2395
- # Description: {stack_description}
2396
- # Blocks:
2397
- # {stack_opcodes_functionalities}
2398
- # -----------------------------------
2399
- # Current Plan Details:
2400
- # - Event (Hat Block Opcode): {event}
2401
- # - Associated Opcodes by Category: {json.dumps(opcodes_from_plan, indent=2)}
2402
-
2403
- # ── Game Context ──
2404
- # Sprite: "{sprite}"
2405
-
2406
- # ── Current Plan ──
2407
- # Event (hat block): {event}
2408
- # Logic (pseudo-Scratch): {logic}
2409
- # Plan : {plan}
2410
-
2411
- # ── Opcode Candidates ──
2412
- # Motion: {opcodes_from_plan["motion"]}
2413
- # Control: {opcodes_from_plan["control"]}
2414
- # Operator: {opcodes_from_plan["operator"]}
2415
- # Sensing: {opcodes_from_plan["sensing"]}
2416
- # Looks: {opcodes_from_plan["looks"]}
2417
- # Sounds: {opcodes_from_plan["sounds"]}
2418
- # Events: {opcodes_from_plan["events"]}
2419
- # Data: {opcodes_from_plan["data"]}
2420
-
2421
- # ── Your Task ──
2422
- # 1. Analyze the “Logic” steps and choose exactly which opcodes are needed.
2423
- # 2. Use exact opcodes from the given Scratch 3.0 Block Reference and verfiy the proper opcode are used available in the Scratch 3.0 Block Reference.
2424
- # 3. Return a top-level JSON object with a single key: "opcode_counts".
2425
- # 4. The value of "opcode_counts" should be a list of objects, where each object has "opcode": "<opcode_name>" and "count": <integer>.
2426
- # 5. Ensure the list includes the hat block for this plan (e.g., event_whenflagclicked, event_whenkeypressed, event_whenbroadcastreceived) with a count of 1.
2427
- # 6. The order of opcodes within the "opcode_counts" list does not matter.
2428
- # 7. If any plan logic is None do not generate the opcode_counts for it.
2429
- # 8. Use only double quotes and ensure valid JSON.
2430
-
2431
- # Example output:
2432
- # **example 1**
2433
- # ```json
2434
- # {{
2435
- # "opcode_counts":[
2436
- # {{"opcode":"motion_gotoxy","count":1}},
2437
- # {{"opcode":"control_forever","count":1}},
2438
- # {{"opcode":"control_if","count":1}},
2439
- # {{"opcode":"looks_switchbackdropto","count":1}},
2440
- # {{"opcode":"event_whenflagclicked","count":1}},
2441
- # {{"opcode":"event_broadcast","count":1}},
2442
- # {{"opcode":"data_setvariableto","count":2}},
2443
- # {{"opcode":"data_showvariable","count":2}}
2444
- # ]
2445
- # }}
2446
- # ```
2447
- # **example 2**
2448
- # ```json
2449
- # {{
2450
- # "opcode_counts":[
2451
- # {{"opcode":"motion_gotoxy","count":1}},
2452
- # {{"opcode":"motion_glidesecstoxy","count":1}},
2453
- # {{"opcode":"motion_xposition","count":1}},
2454
- # {{"opcode":"motion_setx","count":1}},
2455
- # {{"opcode":"control_forever","count":1}},
2456
- # {{"opcode":"control_if","count":2}},
2457
- # {{"opcode":"operator_lt","count":1}},
2458
- # {{"opcode":"sensing_touchingobject","count":1}},
2459
- # {{"opcode":"event_whenflagclicked","count":1}},
2460
- # {{"opcode":"event_broadcast","count":1}}
2461
- # ]
2462
- # }}
2463
- # ```
2464
- # """
2465
- # try:
2466
- # response = agent.invoke({"messages": [{"role": "user", "content": refinement_prompt}]})
2467
- # llm_output = response["messages"][-1].content
2468
- # llm_json = extract_json_from_llm_response(llm_output)
2469
- # logger.info(f"Successfully analyze the opcode requirement for {sprite} - {event}.")
2470
-
2471
- # except json.JSONDecodeError as error_json:
2472
- # logger.error(f"JSON Decode Error for {sprite} - {event}: {error_json}. Attempting correction.")
2473
- # correction_prompt = (
2474
- # "Your task is to correct the provided JSON string to ensure it is **syntactically perfect and adheres strictly to JSON rules**.\n"
2475
- # "It must be a JSON object with a single key `opcode_counts` containing a list of objects like {{'opcode': '<opcode_name>', 'count': <integer>}}.\n"
2476
- # f"- **Error Details**: {error_json}\n\n"
2477
- # "**Strict Instructions for your response:**\n"
2478
- # "1. **ONLY** output the corrected JSON. Do not include any other text or explanations.\n"
2479
- # "2. Ensure all keys and string values are enclosed in **double quotes**. Escape internal quotes (`\\`).\n"
2480
- # "3. No trailing commas. Correct nesting.\n\n"
2481
- # "Here is the problematic JSON string to correct:\n"
2482
- # f"```json\n{llm_output}\n```\n"
2483
- # "Corrected JSON:\n"
2484
- # )
2485
- # try:
2486
- # correction_response = agent_json_resolver.invoke({"messages": [{"role": "user", "content": correction_prompt}]})
2487
- # llm_json = extract_json_from_llm_response(correction_response["messages"][-1].content)
2488
- # logger.info(f"Successfully corrected JSON output for {sprite} - {event}.")
2489
- # except Exception as e_corr:
2490
- # logger.error(f"Failed to correct JSON output for {sprite} - {event} even after retry: {e_corr}")
2491
- # continue
2492
-
2493
- # # Directly use the 'opcode_counts' list from the LLM's output
2494
- # plan["opcode_counts"] = llm_json.get("opcode_counts", [])
2495
- # plan["opcode_counts"] = validate_and_fix_opcodes(plan["opcode_counts"])
2496
- # # Optionally, you can remove the individual category lists from the plan
2497
- # # if they are no longer needed after the LLM provides the consolidated list.
2498
- # # for key in ["motion", "control", "operator", "sensing", "looks", "sounds", "events", "data"]:
2499
- # # if key in plan:
2500
- # # del plan[key]
2501
-
2502
- # refined_plans.append(plan)
2503
-
2504
- # refined_flow[sprite] = {
2505
- # "description": sprite_data.get("description", ""),
2506
- # "plans": refined_plans
2507
- # }
2508
-
2509
- # if refined_flow:
2510
- # state["action_plan"] = refined_flow
2511
- # logger.info("logic aligned by logic_aligner_Node.")
2512
-
2513
- # state["temporary_node"] = refined_flow
2514
- # #state["temporary_node"] = refined_flow
2515
- # print(f"[OPCODE COUTER LOGIC]: {refined_flow}")
2516
- # logger.info("=== OPCODE COUTER LOGIC completed ===")
2517
- # return state
2518
-
2519
  # Node 5: block_builder_node
2520
  def overall_block_builder_node_2(state: GameState):
2521
  logger.info("--- Running OverallBlockBuilderNode ---")
 
250
  - Booleans: `<condition>`
251
  5. **Final Output:** Your response must ONLY be the valid JSON object and nothing else."""
252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
 
254
  # SYSTEM_PROMPT_JSON_CORRECTOR ="""
255
  # You are an assistant that outputs JSON responses strictly following the given schema.
 
1630
  except Exception as e:
1631
  logger.error(f"Error in Node Optimizer Node: {e}")
1632
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1633
  # Node 5: block_builder_node
1634
  def overall_block_builder_node_2(state: GameState):
1635
  logger.info("--- Running OverallBlockBuilderNode ---")