I've modified langgraph_assistant function to take dictionary of values
{metadata: Dict[str, str]
object_definition: str
import_statements: str
clarifier_info: Dict[str, str]
clarifier_questions: Dict[str, list[str]]
test_scenarios_str: str
test_scenarios_json: Dict[str, str]
fmc_code: str
test_code: str
pytest_report_json: Dict
pytest_report_str: str
fca_remaining_iterations: int
code_reviewer_suggestions: str
global_variables_and_custom_objects: str
dependency_descriptions: Dict[str, str]
scenario_codes:Dict[str, str]}
code
instead of taking a langgraph state.modify the changes required. due to change there is no need of find_langgraph_state_for_step simply pass the dictionary with required step.
instead of update_langgraph_values_based_on_step modify the dictionary before passing.
for process_langgraph_state use the completed step instead of langgraph_state["next"] to etermine the loop, since langgraph_state is removed
def process_langgraph_state(app_manager):
"""
Process the latest state of the LangGraph.
code
Args:
app_manager: Instance of AppManager class
"""
if not app_manager.langgraph_states:
logger.warning("No LangGraph states to process.")
return
try:
node, langgraph_state = app_manager.langgraph_states[-1]
langgraph_values = langgraph_state["values"]
if len(langgraph_state["next"]) == 0:
app_manager.pytest_results = langgraph_values["pytest_report_str"]
app_manager.components = [
"scenarios_section",
"code_section",
"results_section",
]
elif langgraph_state["next"] == "ScenarioGenerator":
app_manager.questions = [
f"**Types of dependencies**\n{langgraph_values['dependency_descriptions'].get(app_manager.method_name, '')}\n\n **Please verify the io types and suggest the changes if necessary:** "
]
app_manager.components = ["verify_io_user_input"]
elif langgraph_state["next"] == "FMCGenerator":
app_manager.test_cases_full = langgraph_values["test_scenarios_json"][
"test_scenarios"
]
app_manager.test_cases = [
case["scenario_name"] for case in app_manager.test_cases_full
]
app_manager.components = ["scenarios_section"]
elif langgraph_state["next"] == "CodeRunner":
app_manager.pytest_codes = langgraph_values["test_code"]
app_manager.components = ["scenarios_section", "code_section"]
except KeyError as ke:
logger.error(
f"KeyError encountered while processing state {langgraph_state}: {ke}"
)
raise
except Exception as ex:
logger.error(f"Unexpected error occurred while processing state {ex}")
raise
def find_langgraph_state_for_step(app_manager, step):
"""Find langgraph state node matching the step target node."""
target_nodes = {
"verified_io_types": "DependencyAnalyser",
"clarification_completed": "Clarifier",
"code_generation": "ScenarioGenerator",
"run_pytest_code": "CodeReviewer",
"self_correction": "CodeRunner",
}
target_node = target_nodes.get(step)
while app_manager.langgraph_states:
node, state = app_manager.langgraph_states.pop()
if node == target_node:
app_manager.langgraph_states.append([node, state])
return node, state
return None, None
def update_langgraph_values_based_on_step(step, values, app_manager):
"""Update langgraph values dict based on the current step."""
if step == "verified_io_types":
values["user_provided_info"] = app_manager.answers[0]
elif step == "clarification_completed":
# Build clarifier_info dict matching questions to answers
clarifier_questions = values.get("clarifier_questions", {}).get("questions", [])
values["clarifier_info"] = {
question: app_manager.answers[i]
for i, question in enumerate(clarifier_questions)
}
elif step == "code_generation":
filtered_str = filter_selected_scenarios(
scenarios_string=values.get("test_scenarios_str", ""),
scenario_names=app_manager.selected_scenarios,
)
values["test_scenarios_str"] = filtered_str
values["test_scenarios_json"] = parse_scenarios(filtered_str)
elif step == "run_pytest_code":
values["test_code"] = app_manager.pytest_codes
def generate_results(app_manager, step):
"""
Generate Response from LangGraph based on the user's input.
code
Args:
app_manager: Instance of AppManager class
step: Current step in the process
Returns:
Updated app_manager instance as dict
"""
try:
prev_nodes = {
"ScenarioGenerator": "DependencyAnalyser",
"FMCGenerator": "ScenarioGenerator",
"CodeRunner": "CodeReviewer",
"CodeReviewer": "TestCodeGenerator",
}
if step == "start":
app_manager.langgraph_states.clear()
repo_path_abs = os.path.abspath(app_manager.repo_path)
file_path_abs = os.path.abspath(app_manager.file_path)
inputs = {
"object_definition": app_manager.method_definition,
"metadata": {
"language": app_manager.language.lower(),
"repo_path": repo_path_abs,
"file_path": file_path_abs,
"file_name": app_manager.file_name,
"object_name": app_manager.method_name,
"test_dir": os.path.join(repo_path_abs, "test"),
},
"fca_remaining_iterations": FCA_ITERATION,
}
langgraph_state = langgraph_assistant(inputs=inputs)
node = None
else:
node, langgraph_state = find_langgraph_state_for_step(app_manager, step)
update_langgraph_values_based_on_step(step, langgraph_state["values"], app_manager)
langgraph_state = langgraph_assistant(output=langgraph_state["values"], as_node=node)
prev_node = prev_nodes.get(langgraph_state.get("next")) if langgraph_state.get("next") else None
app_manager.langgraph_states.append([prev_node, langgraph_state])
process_langgraph_state(app_manager)
return app_manager.__dict__
except Exception as ex:
logger.error(f"Error occurred while generating results for step '{step}': {ex}")
raise
To accommodate your requested changes (i.e., passing the dictionary directly instead of full langgraph state, no longer needing find_langgraph_state_for_step and modifying the dictionary before passing, and changing process_langgraph_state to use the completed step name rather than langgraph_state["next"]), here is a refactor outline with example code updates:
Key Changes Summary:
langgraph_assistant:
Now accepts dictionary of values directly (previously it accepted a full langgraph state with metadata about the node etc.). So calls to it will pass a dictionary containing required values.
Remove find_langgraph_state_for_step entirely — you no longer need to scan or pop langgraph_states by step.
Prepare / update dictionary values before calling langgraph_assistant instead of calling update_langgraph_values_based_on_step inside generate_results.
process_langgraph_state takes both the app state and the completed step (string), not the langgraph state with "next". Logic branches based on completed step.
When appending to langgraph_states, append the completed step string and the dictionary of values, no node name or full langgraph_state needed.
Revised generate_results function example:
python
def generate_results(app_manager, step):
"""
Generate Response from LangGraph based on the user's input.
Args:
app_manager: Instance of AppManager class
step: Current step in the process
Returns:
Updated app_manager instance as dict
"""
try:
if step == "start":
app_manager.langgraph_states.clear()
repo_path_abs = os.path.abspath(app_manager.repo_path)
file_path_abs = os.path.abspath(app_manager.file_path)
inputs = {
"object_definition": app_manager.method_definition,
"metadata": {
"language": app_manager.language.lower(),
"repo_path": repo_path_abs,
"file_path": file_path_abs,
"file_name": app_manager.file_name,
"object_name": app_manager.method_name,
"test_dir": os.path.join(repo_path_abs, "test"),
},
"fca_remaining_iterations": FCA_ITERATION,
# plus all other required keys initialized to defaults or empty
}
# Call langgraph_assistant passing inputs dict, expecting output dict response
langgraph_values = langgraph_assistant(inputs=inputs)
completed_step = "start"
else:
# Instead of find_langgraph_state_for_step and fetching values from old langgraph state,
# just grab the last state dict from app_manager.langgraph_states[-1][1]
if app_manager.langgraph_states:
_, last_values = app_manager.langgraph_states[-1]
else:
last_values = {}
# Prepare a copy to avoid mutation of previous state
new_values = last_values.copy()
# Update values according to the current step here:
if step == "verified_io_types":
new_values["user_provided_info"] = app_manager.answers[0] if app_manager.answers else ""
elif step == "clarification_completed":
clarifier_questions = new_values.get("clarifier_questions", {}).get("questions", [])
new_values["clarifier_info"] = {
question: app_manager.answers[i] if i < len(app_manager.answers) else ""
for i, question in enumerate(clarifier_questions)
}
elif step == "code_generation":
filtered_str = filter_selected_scenarios(
scenarios_string=new_values.get("test_scenarios_str", ""),
scenario_names=app_manager.selected_scenarios,
)
new_values["test_scenarios_str"] = filtered_str
new_values["test_scenarios_json"] = parse_scenarios(filtered_str)
elif step == "run_pytest_code":
new_values["test_code"] = app_manager.pytest_codes
# Call langgraph_assistant passing updated dict
langgraph_values = langgraph_assistant(output=new_values, as_node=None)
completed_step = step
# Append the completed step and new langgraph values dict to states
app_manager.langgraph_states.append((completed_step, langgraph_values))
# Instead of process_langgraph_state using next, pass completed_step to process_langgraph_state
process_langgraph_state(app_manager, completed_step)
return app_manager.__dict__
except Exception as ex:
logger.error(f"Error occurred while generating results for step '{step}': {ex}")
raise
Revised process_langgraph_state
Modify it to take both app_manager and the completed step string:
python
def process_langgraph_state(app_manager, completed_step):
"""
Process the latest state of the LangGraph based on completed step.
Args:
app_manager: Instance of AppManager class
completed_step: The step string that was just completed
"""
if not app_manager.langgraph_states:
logger.warning("No LangGraph states to process.")
return
# Grab latest values dict
_, langgraph_values = app_manager.langgraph_states[-1]
# Branch on completed step string instead of langgraph_state["next"]
if completed_step == "run_pytest_code":
app_manager.pytest_results = langgraph_values.get("pytest_report_str", "")
app_manager.components = [
"scenarios_section",
"code_section",
"results_section",
]
elif completed_step == "verified_io_types":
app_manager.questions = [
f"**Types of dependencies**\n{langgraph_values.get('dependency_descriptions', {}).get(app_manager.method_name, '')}\n\n"
"**Please verify the io types and suggest the changes if necessary:** "
]
app_manager.components = ["verify_io_user_input"]
elif completed_step == "code_generation":
app_manager.test_cases_full = langgraph_values.get("test_scenarios_json", {}).get("test_scenarios", [])
app_manager.test_cases = [
case["scenario_name"] for case in app_manager.test_cases_full
]
app_manager.components = ["scenarios_section"]
elif completed_step == "FMCGenerator": # If you still have steps like this
# Add your actual logic here if needed based on new design
pass
elif completed_step == "ScenarioGenerator": # Or other steps
pass
# Add other step handlers as necessary
Remove these functions completely:
You can safely delete:
find_langgraph_state_for_step
update_langgraph_values_based_on_step
since their logic is now moved inline inside generate_results, or handled externally before calling langgraph_assistant.
Summary
Prepare/update the dictionary of values before calling langgraph_assistant (no searching for langgraph states needed).
Track states by (step, values_dict) tuples.
Use step string in process_langgraph_state to decide behavior.
Keep langgraph_assistant calls simpler, passing just the dict of values (input/output).
Simplify flow; langgraph_states holds step and dict now.
If you'd like, I can provide a full snippet with the rewritten functions or help with refactoring any other parts. Let me know!