### Interface with TextWorld Environments Source: https://context7.com/airi-institute/arigraph/llms.txt Shows how to initialize a TextWorld environment, perform game actions, retrieve state information, and convert game facts into a NetworkX graph. ```python from utils.textworld_adapter import TextWorldWrapper, graph_from_facts env = TextWorldWrapper("./envs/hunt/hunt.z8") observation, info = env.reset() observation, reward, done, info = env.step("take Key 1") inventory = env.get_inventory() location = env.get_player_location() max_score = env.get_max_score() valid_actions = env.get_valid_actions() expanded_actions = env.expand_action_space() walkthrough = env.walkthrough() G = graph_from_facts(info, only_entities=False, verbose=False) ``` -------------------------------- ### Episodic Memory Example Source: https://github.com/airi-institute/arigraph/blob/main/logs/hunt_arigraph.txt The system maintains episodic memory, storing past game steps and observations. This memory can be used for context or to recall previous events. The example shows a snippet from 'Game step #6' describing the player's entry into 'Room C' and the discovery of a 'Red locker'. ```text Game step #6 -= Room C =- You've entered a Room C. You smell an awful smell, and follow it to a Red locker. You need an unguarded exit? You should try going east. There is an exit to the north. Don't worry, it is unblocked. There is an exit to the south. Don't worry, it is unblocked. ``` -------------------------------- ### Initialize and Use GPTagent for LLM Interaction Source: https://context7.com/airi-institute/arigraph/llms.txt Demonstrates how to initialize the GPTagent class to interact with OpenAI models. It covers generating text responses, structured JSON outputs, and processing observations to extract entity relevance scores. ```python from agents.parent_agent import GPTagent agent = GPTagent( model="gpt-4o", system_prompt="You play at the text game. Please try to achieve the goal fast and effective.", api_key="your-openai-api-key" ) response, cost = agent.generate( prompt="What action should I take to find the treasure?", jsn=False, t=0.7 ) action_response, cost = agent.generate( prompt='''Choose an action from: ["go north", "take key", "open door"] Respond in JSON format with "action_to_take" key.''', jsn=True, t=0.2 ) observation = "You are in the kitchen. There is a knife on the table and an apple in the refrigerator." plan = '{"main_goal": "Prepare meal", "plan_steps": [{"sub_goal_1": "Find ingredients"}]}' entities, cost = agent.item_processing_scores(observation, plan) ``` -------------------------------- ### AI Planning Logic for Game Progression Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_hard_arigraph_without_episodic.txt Defines the strategic plan for achieving the main goal, breaking it down into actionable sub-goals with justifications. This logic guides the AI's decision-making process. ```json { "main_goal": "Prepare the meal by following the recipe from a cookbook and eat it afterwards.", "plan_steps": [ { "sub_goal_1": "Go west from the kitchen to explore the unexplored exit.", "reason": "All other locations have been explored according to the history of observations. The kitchen has an unexplored exit that might lead to finding the red onion." }, { "sub_goal_2": "Find and gather red onion.", "reason": "Red onion is still needed for the recipe and has not been found yet. Exploring new areas might help locate it." }, { "sub_goal_3": "Process the ingredients as per the recipe.", "reason": "Processing ingredients is necessary before they can be cooked. Need to gather all ingredients first." }, { "sub_goal_4": "Cook the meal according to the recipe instructions.", "reason": "Cooking is the final step in meal preparation. Ingredients must be processed before cooking." }, { "sub_goal_5": "Eat the meal.", "reason": "Eating the meal completes the main goal. The meal must be cooked first." } ], "your_emotion": { "your_current_emotion": "motivated", "reason_behind_emotion": "Successfully gathered another required ingredient. Progressing well towards the main goal." } } ``` -------------------------------- ### Define Action Plan Structure Source: https://github.com/airi-institute/arigraph/blob/main/logs/hunt_arigraph_without_episodic.txt Defines the JSON structure for the agent's action plan, including the main goal, sequential steps, and current emotional state. This structure is used to guide the agent's decision-making process. ```json { "main_goal": "Find the treasure", "plan_steps": [ { "sub_goal_1": "Check the contents of the White locker in Room G", "reason": "..." } ], "your_emotion": { "your_current_emotion": "anticipatory", "reason_behind_emotion": "..." } } ``` -------------------------------- ### Initialize and Run Text-Based Game with AriGraph Source: https://context7.com/airi-institute/arigraph/llms.txt Initializes TextWorld environment, ContrieverGraph, and GPT agents for planning and action. The loop processes observations, updates the knowledge graph, generates plans, and executes actions within the game environment. It tracks player inventory, locations, and game progress. ```python from textworld.gym import TextWorldWrapper from graphs.contriever_graph import ContrieverGraph from agents.parent_agent import GPTagent # Assume ENV_NAMES, model, api_key, default_system_prompt, system_plan_agent, system_action_agent_sub_expl, MAIN_GOALS, max_steps are defined elsewhere # Initialize components env = TextWorldWrapper(ENV_NAMES[env_name]) graph = ContrieverGraph(model, "You are a helpful assistant", api_key, device="cpu") agent = GPTagent(model, default_system_prompt, api_key) agent_plan = GPTagent("gpt-4-0125-preview", system_plan_agent, api_key) agent_action = GPTagent("gpt-4-0125-preview", system_action_agent_sub_expl, api_key) # Game loop observation, info = env.reset() locations = set() subgraph = [] main_goal = MAIN_GOALS[env_name] for step in range(max_steps): # Process observation inventory = env.get_inventory() locations.add(env.get_player_location().lower()) # Extract entities and update knowledge graph items, _ = agent.item_processing_scores(observation, str(main_goal)) subgraph, episodic = graph.update( observation=observation, observations=[], plan=str(main_goal), prev_subgraph=subgraph, locations=list(locations), curr_location=env.get_player_location().lower(), previous_location="", action="start", items1=items, log=print, topk_episodic=2 ) # Generate plan plan_prompt = f"""Main goal: {main_goal} Current observation: {observation} Memory: {subgraph} Episodic: {episodic}""" plan, _ = agent_plan.generate(plan_prompt, jsn=True, t=0.2) # Choose action valid_actions = env.get_valid_actions() action_prompt = f"""Plan: {plan} Observation: {observation} Valid actions: {valid_actions}""" action_response, _ = agent_action.generate(action_prompt, jsn=True, t=0.2) action = json.loads(action_response)["action_to_take"] # Execute action observation, reward, done, info = env.step(action) if done: print(f"Game completed with score: {env.score}") break ``` -------------------------------- ### ARIGraph Planning Logic Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_arigraph_without_episodic.txt This snippet details the planning mechanism within the ARIGraph project. It outlines the main goal, breaks it down into sequential sub-goals with justifications, and includes the agent's emotional state and its reasoning. This structured approach guides the agent's decision-making process. ```json Plan0: { "main_goal": "Prepare the meal by following the recipe from a cookbook and eat it afterwards.", "plan_steps": [ { "sub_goal_1": "Gather all necessary ingredients for the recipe.", "reason": "The recipe has been examined. Need to collect green bell pepper, orange bell pepper, and yellow potato." }, { "sub_goal_2": "Prepare the meal according to the recipe.", "reason": "Ingredients need to be prepared and cooked as per the recipe instructions." }, { "sub_goal_3": "Eat the meal.", "reason": "The final step of the main goal is to enjoy the meal that has been prepared." } ], "your_emotion": { "your_current_emotion": "motivated", "reason_behind_emotion": "The recipe is known, and it's time to gather the ingredients." } } ``` -------------------------------- ### Game Action and Reasoning Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_hard_arigraph_without_episodic.txt This snippet details the agent's reasoning for performing an action and the action itself. It includes token counts for prompt and completion, and the cost associated with the step. ```json { "reason_for_action": "Need to collect the raw red potato to have all necessary ingredients for the recipe.", "action_to_take": "take red potato" } ``` -------------------------------- ### Action Selection Based on Game Plan Source: https://github.com/airi-institute/arigraph/blob/main/logs/hunt_arigraph.txt This snippet demonstrates the process of selecting the next action to take based on the current game plan. It extracts the recommended action and its reasoning from the plan. ```python def select_next_action(plan): # Extract the next action to take from the plan # Return the action and its reasoning action = plan['action_to_take'] reason = plan['reason_for_action'] return action, reason # Example usage: # next_action, action_reason = select_next_action(plan) # print(f"Action: {next_action}, Reason: {action_reason}") ``` -------------------------------- ### Perform Semantic Search with Retriever Source: https://context7.com/airi-institute/arigraph/llms.txt Explains how to initialize the Retriever class, generate embeddings for strings, and perform similarity-based search using top-k or threshold filtering. ```python from utils.contriever import Retriever retriever = Retriever(device="cuda") embeddings = retriever.embed(["apple is red", "banana is yellow"]) results = retriever.search(key_strings=key_strings, query_strings=query_strings, topk=2, return_scores=True) results = retriever.search(key_strings=key_strings, query_strings="food items", similarity_threshold=0.7, return_scores=True) ``` -------------------------------- ### Action to Take: Go to Kitchen Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_hard_arigraph_without_episodic.txt This action is triggered by the completion of ingredient gathering and the need to proceed with meal preparation. It specifies the immediate next step in the overall plan. ```JSON { "reason_for_action": "All required ingredients for the recipe are now collected. Next step is to process them according to the recipe instructions.", "action_to_take": "go to kitchen" } ``` -------------------------------- ### Recipe Ingredient Preparation Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_arigraph_without_episodic.txt This section details the steps and reasoning behind preparing ingredients for a meal according to a recipe. It includes gathering, processing, and cooking steps. ```json { "sub_goal_1": "Gather all necessary ingredients for the recipe.", "reason": "The recipe has been examined. Need to collect green bell pepper, orange bell pepper, and yellow potato. Orange bell pepper is already found." }, { "sub_goal_2": "Find a green bell pepper.", "reason": "Green bell pepper is required for the recipe but was not seen in the fridge. Need to find it." }, { "sub_goal_3": "Find a yellow potato.", "reason": "Yellow potato is required for the recipe but was not seen in the kitchen. Need to find it." }, { "sub_goal_4": "Process the ingredients as per the recipe.", "reason": "Some ingredients may need to be processed (chopped, mixed, etc.) before cooking. This can only be done after all ingredients are gathered." }, { "sub_goal_5": "Cook the meal using the appropriate kitchen appliance.", "reason": "The meal needs to be cooked as per the instructions in the recipe. This includes frying, grilling, etc., using the correct appliances." }, { "sub_goal_6": "Eat the prepared meal.", "reason": "The final step of the main goal is to enjoy the meal that has been prepared." } ``` -------------------------------- ### Action Planning and Reasoning Source: https://github.com/airi-institute/arigraph/blob/main/logs/hunt_arigraph_without_episodic.txt Defines the main goal, sub-goals, and the reasoning behind the plan. Also includes the current emotion and its justification. ```json plan0 = {\n "main_goal": "Find the treasure",\n "plan_steps": [\n {\n "sub_goal_1": "Explore the east exit in Room C",\n "reason": "With the south exit in Room B explored, leading to Room C, the next logical step is to explore the east exit in Room C to continue the search for the white locker or additional keys."},\n {\n "sub_goal_2": "Explore the south exit in Room C",\n "reason": "After exploring the east exit in Room C, if the search for the white locker or additional keys is still ongoing, the south exit in Room C should be explored next."}],\n "your_emotion": {\n "your_current_emotion": "curious",\n "reason_behind_emotion": "Eager to discover what lies beyond the unexplored exits in Room C and hopeful to find items that will lead to the treasure."} }\n ``` -------------------------------- ### AI Agent Plan Generation and Execution Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_hard_arigraph_without_episodic.txt This snippet illustrates the AI agent's planning mechanism, outlining the main goal, step-by-step sub-goals, and the reasoning behind each. It also shows the selected action to take based on the current plan and game state. ```JSON { "main_goal": "Prepare the meal by following the recipe from a cookbook and eat it afterwards.", "plan_steps": [ { "sub_goal_1": "Take red hot pepper from the showcase.", "reason": "Red hot pepper is another ingredient that might be required for the recipe or for enhancing the meal, considering the inventory and recipe requirements." }, { "sub_goal_2": "Return to the kitchen to start processing the ingredients.", "reason": "All required ingredients for the recipe are gathered. Need to go to the kitchen to begin preparation." }, { "sub_goal_3": "Process the ingredients as per the recipe.", "reason": "Processing ingredients is a step in cooking the meal. Ready to start after returning to the kitchen." }, { "sub_goal_4": "Cook the meal using the appropriate kitchen appliance.", "reason": "Cooking is the final step in preparing the meal. Need to process ingredients first." }, { "sub_goal_5": "Eat the meal.", "reason": "Eating the meal completes the main goal. Need to cook the meal first." } ], "your_emotion": { "your_current_emotion": "hopeful", "reason_behind_emotion": "All ingredients for the recipe have been collected, moving on to the preparation phase." } } ``` ```JSON { "reason_for_action": "Red hot pepper is another ingredient that might be required for the recipe or for enhancing the meal, considering the inventory and recipe requirements.", "action_to_take": "take red hot pepper from showcase" } ``` -------------------------------- ### Action: Prepare Meal Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_arigraph.txt Details the reasoning behind the next action to be taken, which is to 'prepare meal', based on the completion of ingredient processing. ```JSON { "reason_for_action": "All ingredients have been processed as required by the recipe, and the next step according to the plan is to prepare the meal.", "action_to_take": "prepare meal" } ``` -------------------------------- ### Episodic Memory: Recipe and Initial Task Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_arigraph.txt Contains episodic memory entries, including the detailed recipe from a cookbook and the initial task description for preparing and eating a meal. ```Text Game step #4 You open the copy of "Cooking: A Modern Approach (3rd Ed.)" and start reading: Recipe --------- Gather all following ingredients and follow the directions to prepare this tasty meal. Ingredients: green bell pepper orange bell pepper yellow potato Directions: dice the green bell pepper fry the green bell pepper dice the orange bell pepper grill the orange bell pepper slice the yellow potato grill the yellow potato prepare meal Game step #1 $ You are hungry! Let's cook a delicious meal. Check the cookbook in the kitchen for the recipe. Once done, enjoy your meal! -= Living room =- You're now in the living room. You see a sofa. Looks like someone's already been here and taken everything off it, though. There is an exit to the east. You need an exit without a door? You should try going south. Your task is to prepare the meal by following the recipe from a cookbook and eating it aftewards. Do not forget the content of recipe when you find it. When you will prepare food, remember that frying is done only with stove, roasting is done only with oven and grilling is done only with BBQ. Meal shoud be prepared in the kitchen. Do not forget to prepate meal after you gathered and processed all individual ingredients. ``` -------------------------------- ### Goal Planning (Plan0) Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_arigraph_without_episodic.txt Defines the main goal and breaks it down into sequential sub-goals with justifications. It also includes the agent's emotional state and the reasoning behind it. ```json Plan0: { "main_goal": "Prepare the meal by following the recipe from a cookbook and eat it afterwards.", "plan_steps": [ { "sub_goal_1": "Gather all necessary ingredients for the recipe.", "reason": "Orange bell pepper has been collected. Still need to collect green bell pepper and yellow potato. The pantry and the bathroom did not contain these items, need to explore other areas." }, { "sub_goal_2": "Explore the unexplored north exit from the corridor.", "reason": "Since the south exit from the corridor led to the bathroom which did not have the ingredients, the next step is to explore the north exit from the corridor." }, { "sub_goal_3": "Prepare the meal according to the recipe.", "reason": "Ingredients need to be prepared and cooked as per the recipe instructions. This step can only begin once all ingredients are gathered." }, { "sub_goal_4": "Eat the meal.", "reason": "The final step of the main goal is to enjoy the meal that has been prepared." } ], "your_emotion": { "your_current_emotion": "motivated", "reason_behind_emotion": "One ingredient has been successfully gathered. Focused on finding the remaining ingredients." } } ``` -------------------------------- ### Action Selection Logic - Python Source: https://github.com/airi-institute/arigraph/blob/main/logs/hunt_arigraph_without_episodic.txt Determines the next action to take based on the current game state and the formulated plan. This includes the reasoning behind the chosen action. ```python action = { "reason_for_action": "Since the attempt to use Key 2 on the Brown locker did not work due to a verb recognition issue, the next logical step is to try using Key 3, as it also looks useful and is in the inventory.", "action_to_take": "examine Key 3" } ``` -------------------------------- ### Game Plan and Action Execution Source: https://github.com/airi-institute/arigraph/blob/main/logs/hunt_arigraph_without_episodic.txt This snippet outlines the strategic plan for achieving the main goal in the game, including sub-goals and the reasoning behind them. It also details the current action being taken based on the plan and game state. ```python plan0 = { "main_goal": "Find the treasure", "plan_steps": [ { "sub_goal_1": "Go to Room A to find the golden locker", "reason": "With the Golden key now in the inventory, the next immediate step is to head to Room A where the golden locker is located." }, { "sub_goal_2": "Unlock the golden locker with the Golden key", "reason": "Once in Room A, use the Golden key to unlock the golden locker, which contains the treasure." } ], "your_emotion": { "your_current_emotion": "anticipatory", "reason_behind_emotion": "The plan is in motion towards unlocking the golden locker and discovering the treasure." } } Action = { "reason_for_action": "With the Golden key now in the inventory, the next immediate step is to head to Room A where the golden locker is located.", "action_to_take": "go to room a" } ``` -------------------------------- ### Task Plan and Goal Decomposition Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_arigraph.txt This snippet outlines a plan to achieve a main goal, breaking it down into sub-goals. It includes reasoning for each step and the agent's current emotional state. ```json { "main_goal": "Prepare the meal by following the recipe from a cookbook and eat it afterwards.", "plan_steps": [ { "sub_goal_1": "Find a yellow potato and a green bell pepper.", "reason": "The pantry did not contain any ingredients. Need to explore other areas, possibly by checking unexplored exits in the corridor or living room." }, { "sub_goal_2": "Process the ingredients as per the recipe.", "reason": "Processing ingredients is necessary before they can be combined to prepare the meal. Still need to gather all ingredients." }, { "sub_goal_3": "Cook the meal using the appropriate kitchen appliance.", "reason": "The meal needs to be cooked before it can be eaten. Ingredients must be processed first." }, { "sub_goal_4": "Eat the prepared meal.", "reason": "The final step of the main goal is to enjoy the meal. Cooking must be completed first." } ], "your_emotion": { "your_current_emotion": "focused", "reason_behind_emotion": "Focused on finding the remaining ingredients to complete the meal preparation." } } ``` -------------------------------- ### Performance Metrics Source: https://github.com/airi-institute/arigraph/blob/main/logs/hunt_arigraph_without_episodic.txt Tracks the total and attempt amounts for currency and time, as well as the amount and time spent per step. ```text Total amount: 0.42$, attempt amount: 0.42$, step amount: 0.06$ Total time: 285.73 sec, attempt time: 285.73 sec, step time: 39.24 sec ``` -------------------------------- ### Execute Navigation Action Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_arigraph.txt Defines the action to be taken by the agent based on the current reasoning and environmental state. ```json { "reason_for_action": "The yellow potato has been sliced, so the next step is to grill it using the BBQ in the backyard.", "action_to_take": "go to backyard" } ``` -------------------------------- ### Meal Preparation Plan Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_hard_arigraph_without_episodic.txt This section details a plan for preparing a meal. It outlines the main goal, sequential steps, and the emotional state associated with the plan. The plan involves gathering ingredients, processing them, cooking, and finally eating. ```JSON { "main_goal": "Prepare the meal by following the recipe from a cookbook and eat it afterwards.", "plan_steps": [ { "sub_goal_1": "Return to the kitchen to start processing the ingredients.", "reason": "All required ingredients for the recipe are now collected. Next step is to process them according to the recipe instructions." }, { "sub_goal_2": "Process the ingredients as per the recipe.", "reason": "Ingredients may need to be processed (e.g., chopped, mixed) before cooking. This step will follow after gathering all ingredients." }, { "sub_goal_3": "Cook the meal using the appropriate kitchen appliance.", "reason": "Depending on the recipe, the meal may need to be fried, roasted, or grilled. This includes roasting bell pepper and onion, grilling tuna, and frying potato." }, { "sub_goal_4": "Eat the prepared meal.", "reason": "The final step to fulfill the main goal after the meal is prepared." } ], "your_emotion": { "your_current_emotion": "excited", "reason_behind_emotion": "All ingredients for the recipe have been collected, and I'm ready to start cooking." } } ``` -------------------------------- ### Action Selection for Navigation Source: https://github.com/airi-institute/arigraph/blob/main/logs/cook_arigraph.txt This snippet represents a decision-making process for taking an action, specifically in the context of navigation. It includes the reasoning behind the chosen action. ```json { "reason_for_action": "The pantry did not contain any ingredients. Need to explore other areas, possibly by checking unexplored exits in the corridor or living room.", "action_to_take": "go to corridor" } ``` -------------------------------- ### Manage Knowledge Graphs with TripletGraph Source: https://context7.com/airi-institute/arigraph/llms.txt Shows how to manage a knowledge graph by adding, querying, and deleting triplets. It also includes methods for spatial navigation, such as computing spatial graphs and finding the shortest path between locations. ```python from graphs.parent_graph import TripletGraph graph = TripletGraph( model="gpt-4o", system_prompt="You are a helpful assistant", api_key="your-openai-api-key" ) triplets = [ ["kitchen", "room b", {"label": "is west of"}], ["knife", "kitchen", {"label": "is in"}], ["apple", "refrigerator", {"label": "is in"}], ["refrigerator", "kitchen", {"label": "is in"}] ] graph.add_triplets(triplets) all_facts = graph.get_all_triplets() associated = graph.get_associated_triplets(["knife", "apple"], steps=2) spatial_graph = graph.compute_spatial_graph(["kitchen", "room b", "living room"]) path = graph.find_path("kitchen", "living room", ["kitchen", "room b", "living room"]) graph.delete_triplets([["apple", "refrigerator", {"label": "is in"}]], ["kitchen", "room b", "living room"]) ```