Upload 13 files
Browse filesFiles changed (13)
- ControllerFlow_ExtLib.pyAdded+114
- ControllerFlow_ExtLib.yamlAdded+134
- CtrlExMem_ExtLib.pyAdded+53
- CtrlExMem_ExtLib.yamlAdded+102
- ExtLibAskUserFlow.pyAdded+30
- ExtLibAskUserFlow.yamlAdded+9
- ExtendLibraryFlow.pyAdded+4
- ExtendLibraryFlow.yamlAdded+77
- SaveCodeAtomicFlow.pyAdded+37
- SaveCodeAtomicFlow.yamlAdded+11
- UpdatePlanAtomicFlow.pyAdded+29
- UpdatePlanAtomicFlow.yamlAdded+9
- __init__.pyAdded+16
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114import jsonfrom copy import deepcopyfrom typing import Any, Dict, List
from flow_modules.aiflows.ChatFlowModule import ChatAtomicFlow
from dataclasses import dataclass
@dataclassclass Command: name: str description: str input_args: List[str]
class ControllerFlow_ExtLib(ChatAtomicFlow): def __init__( self, commands: List[Command], **kwargs): super().__init__(**kwargs) self.system_message_prompt_template = self.system_message_prompt_template.partial( commands=self._build_commands_manual(commands), plan_file_location="no location yet", plan="no plan yet", logs="no logs yet", ) self.hint_for_model = """ Make sure your response is in the following format: Response Format: { "command": "call one of the commands you have e.g. `write_code`", "command_args": { "arg name": "value" } } """
@staticmethod def _build_commands_manual(commands: List[Command]) -> str: ret = "" for i, command in enumerate(commands): command_input_json_schema = json.dumps( {input_arg: f"YOUR_{input_arg.upper()}" for input_arg in command.input_args}) ret += f"{i + 1}. {command.name}: {command.description} Input arguments (given in the JSON schema): {command_input_json_schema}\n" return ret
def _get_plan_file_location(self, input_data: Dict[str, Any]): assert "memory_files" in input_data, "memory_files not passed to Extlib/Controller" assert "plan" in input_data["memory_files"], "plan not in memory files" return input_data["memory_files"]["plan"]
def _get_plan_content(self, input_data: Dict[str, Any]): assert "plan" in input_data, "plan not passed to Extlib/Controller" plan_content = input_data["plan"] if len(plan_content) == 0: plan_content = 'No plan yet' return plan_content
def _get_logs_content(self, input_data: Dict[str, Any]): assert "logs" in input_data, "logs not passed to Extlib/Controller" logs_content = input_data["logs"] if len(logs_content) == 0: logs_content = "No logs yet" return logs_content
@classmethod def instantiate_from_config(cls, config): flow_config = deepcopy(config)
kwargs = {"flow_config": flow_config}
# ~~~ Set up prompts ~~~ kwargs.update(cls._set_up_prompts(flow_config))
# ~~~Set up backend ~~~ kwargs.update(cls._set_up_backend(flow_config))
# ~~~ Set up commands ~~~ commands = flow_config["commands"] commands = [ Command(name, command_conf["description"], command_conf["input_args"]) for name, command_conf in commands.items() ] kwargs.update({"commands": commands})
# ~~~ Instantiate flow ~~~ return cls(**kwargs)
def _update_prompts_and_input(self, input_data: Dict[str, Any]): if 'goal' in input_data: input_data['goal'] += self.hint_for_model if 'result' in input_data: input_data['result'] += self.hint_for_model plan_file_location = self._get_plan_file_location(input_data) plan_content = self._get_plan_content(input_data) logs_content = self._get_logs_content(input_data) self.system_message_prompt_template = self.system_message_prompt_template.partial( plan_file_location=plan_file_location, plan=plan_content, logs=logs_content )
def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]: self._update_prompts_and_input(input_data) api_output = super().run(input_data)["api_output"].strip() try: response = json.loads(api_output) return response except json.decoder.JSONDecodeError: new_input_data = input_data.copy() new_input_data['result'] = "The previous respond cannot be parsed with json.loads. Make sure your next response is in JSON format." new_api_output = super().run(new_input_data)["api_output"].strip() return json.loads(new_api_output)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134_target_: Tachi67.ExtendLibraryFlowModule.ControllerFlow_ExtLib.instantiate_from_default_configname: "ControllerFlow_ExtendLibrary"description: "Proposes the next action to take towards achieving the goal, and prepares the input for the branching flow"enable_cache: True
######################################################## Input keys#######################################################
input_interface_non_initialized: # initial input keys - "goal"
input_interface_initialized: - "result"
######################################################## Output keys#######################################################
output_interface: - 'command' - 'command_args'
backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4
commands: write_code: description: "Write code to finish the current step of plan with user interaction" input_args: ["goal"] save_code: description: "When code is written by the coder, save the code to the library" input_args: [] re_plan: description: "When something is wrong with current plan, draft another plan based on the old plan and information about why it's bad or how to refine it." input_args: ["goal"] finish: description: "Signal that the objective has been satisfied, return the summary of what was done" input_args: ["summary"] manual_finish: description: "The user demands to quit and terminate the current process" input_args: [] ask_user: description: "Ask user a question for confirmation or assistance" input_args: ["question"] update_plan: description: "Pass the updated plan to edit plan file and override current plan" input_args: ["updated_plan"]
system_message_prompt_template: _target_: langchain.PromptTemplate template: |2- Your department is in charge of writing code and extending the code library with the code written. You are the leader of this department. You work with several subordinates, they will be in charge of the specific tasks, including writing code, saving code to the library, etc. You are given a step-by-step plan to finish the goal, **notice that, if you are informed that the plan is overriden, this plan is the new plan you should stick to.**, the plan is located in a plan file {{plan_file_location}}: {{plan}} Your **ONLY** task is to take the user's goal for you, to decide which command to call. You **must not** write code nor write plan yourself. You only decide whether to call the coder with specified goals or to finish. Each step of the plan should involve writing one function, **for each step in the plan, your workflow**: 0.1 Whenever the user demands to quit or terminate the current process, call `manual_finish` command. 0.2 Whenever in double, or you have something to ask, or confirm to the user, call `ask_user` with your question. 0.3 During the execution of the plan, if something goes wrong, call the `re_plan` with detailed information about what was wrong. 1. Based on the current step of plan, call `write_code` with the current goal in the step of plan, the code writer will write some code. 2. After code is written, call `save_code` to save the code to the code library, **you do not need to worry about the details of the code nor the library, they will be handled by your subordinates.** 3. **When workflow 1 and workflow 2 are successfully executed, that means the current step of plan is done.** Do the following: 3.1 Reflect on what plan you are having right now. 3.2 Reflect on which step of the plan you just finished. 3.3 Generate a plan, **it is exactly the same as the plan you have now, but with the current step of plan marked as done** 3.4 Call `update_plan` with the plan you just generated. 4. Proceed to the next step of the plan, go back to workflow 1. 5. When every step of the plan is done, call the `finish` command, with a summary of what functions are written and saved. ### Beginning of an example execution: ### Plan: 1. Write a function that fetches weather data from google; 2. Write a function that prints the weather data in a formatted way. You start from step 1 of the plan, execute workflow 1, code is written. You are informed that code is written, you go to workflow 2 to save the code. You are informed that the code is saved, you go to workflow 3 to update the plan: 3.1 You recall the plan you have. 3.2 You realize step 1 of the plan is done. 3.3 You generate the updated plan: 1. Write a function that fetches weather data from google;(DONE) 2. Write a function that prints the weather data in a formatted way. 3.4 You call `update_plan` with the generated plan. The updated plan will override the existing plan, you are informed of the behaviour of override. You go on with the next step of the plan, do the same as above. All steps are done, you call `finish`, with a summary of what functions are written and saved to the library. ### End of an example of execution ### Here is a list of history actions you have taken, for your reference: {{logs}} Constraints: 1. Exclusively use the commands listed in double quotes e.g. "command name" Your response **MUST** be in the following format: Response Format: { "command": "call code writer, the tester, or to finish", "command_args": { "arg name": "value" } } Ensure your responses can be parsed by Python json.loads Available Functions: {{commands}} input_variables: ["commands", "plan_file_location", "plan", "logs"] template_format: jinja2
human_message_prompt_template: _target_: flows.prompt_template.JinjaPrompt template: |2- Here is the result of your previous action: {{result}} input_variables: - "result" template_format: jinja2
init_human_message_prompt_template: _target_: flows.prompt_template.JinjaPrompt template: |2- Here is the goal you need to achieve, follow your plan to finish the goal: {{goal}} input_variables: - "goal" template_format: jinja21234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253from typing import Dict, Any
from flow_modules.Tachi67.AbstractBossFlowModule import CtrlExMemFlowfrom flows.base_flows import CircularFlow
class CtrlExMem_ExtLib(CtrlExMemFlow): def _on_reach_max_round(self): self._state_update_dict({ "answer": "the maximum amount of rounds was reached before the extend library flow has done the job", "summary": "ExtendLibraryFlow: the maximum amount of rounds was reached before the flow has done the job", "status": "unfinished" })
@CircularFlow.output_msg_payload_processor def detect_finish_or_continue(self, output_payload: Dict[str, Any], src_flow) -> Dict[str, Any]: command = output_payload["command"] if command == "finish": return { "EARLY_EXIT": True, "answer": output_payload["command_args"]["summary"], "summary": "ExtendLibrary: " + output_payload["command_args"]["summary"], "status": "finished" } elif command == "manual_finish": # ~~~ return the manual quit status ~~~ return { "EARLY_EXIT": True, "answer": "ExtendLibraryFlow was terminated explicitly by the user, process is unfinished", "summary": "ExtendLibrary: process terminated by the user explicitly, nothing generated", "status": "unfinished" } elif command == "save_code": keys_to_fetch_from_state = ["code", "memory_files"] fetched_state = self._fetch_state_attributes_by_keys(keys=keys_to_fetch_from_state) output_payload["command_args"]["code"] = fetched_state["code"] output_payload["command_args"]["memory_files"] = fetched_state["memory_files"] return output_payload
elif command == "update_plan": keys_to_fetch_from_state = ["memory_files"] fetched_state = self._fetch_state_attributes_by_keys(keys=keys_to_fetch_from_state) output_payload["command_args"]["memory_files"] = fetched_state["memory_files"] return output_payload
elif command == "re_plan": keys_to_fetch_from_state = ["plan", "memory_files"] fetched_state = self._fetch_state_attributes_by_keys(keys=keys_to_fetch_from_state) output_payload["command_args"]["plan_file_location"] = fetched_state["memory_files"]["plan"] output_payload["command_args"]["plan"] = fetched_state["plan"] return output_payload
else: return output_payload123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102_target_: Tachi67.ExtendLibraryFlowModule.CtrlExMem_ExtLib.instantiate_from_default_configname: "CtrlExMem_ExtLibFlow"description: "MemorizedControllerExecutor flow for ExtendLibrary flow"
subflows_config: Controller: _target_: Tachi67.ExtendLibraryFlowModule.ControllerFlow_ExtLib.instantiate_from_default_config backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4 Executor: _target_: flows.base_flows.BranchingFlow.instantiate_from_default_config subflows_config: write_code: _target_: Tachi67.CodeWriterFlowModule.CodeWriterFlow.instantiate_from_default_config subflows_config: Controller: backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4 Executor: subflows_config: write_code: subflows_config: CodeGenerator: backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4 save_code: _target_: Tachi67.ExtendLibraryFlowModule.SaveCodeAtomicFlow.instantiate_from_default_config ask_user: _target_: Tachi67.ExtendLibraryFlowModule.ExtLibAskUserFlow.instantiate_from_default_config re_plan: _target_: Tachi67.ReplanningFlowModule.ReplanningFlow.instantiate_from_default_config subflows_config: Controller: backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4 Executor: subflows_config: write_plan: subflows_config: PlanGenerator: backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4
update_plan: _target_: Tachi67.ExtendLibraryFlowModule.UpdatePlanAtomicFlow.instantiate_from_default_config
topology: - goal: "Select the next action and prepare the input for the executor." input_interface: _target_: flows.interfaces.KeyInterface additional_transformations: - _target_: flows.data_transformations.KeyMatchInput flow: Controller output_interface: _target_: CtrlExMem_ExtLib.detect_finish_or_continue reset: false
- goal: "Execute the action specified by the Controller." input_interface: _target_: flows.interfaces.KeyInterface keys_to_rename: command: branch command_args: branch_input_data keys_to_select: ["branch", "branch_input_data"] flow: Executor output_interface: _target_: flows.interfaces.KeyInterface keys_to_rename: branch_output_data: observation keys_to_unpack: ["observation"] reset: false
- goal: "Write memory to memory files" input_interface: _target_: flows.interfaces.KeyInterface additional_transformations: - _target_: flows.data_transformations.KeyMatchInput flow: MemoryWriting reset: false
- goal: "Read memory from memory files (flow_state)" input_interface: _target_: flows.interfaces.KeyInterface additional_transformations: - _target_: flows.data_transformations.KeyMatchInput flow: MemoryReading reset: false123456789101112131415161718192021222324252627282930from flow_modules.aiflows.HumanStandardInputFlowModule import HumanStandardInputFlow
from typing import Dict, Any
from flows.messages import UpdateMessage_Generic
from flows.utils import logging
log = logging.get_logger(f"flows.{__name__}")
class ExtLibAskUserFlow(HumanStandardInputFlow): def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
query_message = self._get_message(self.query_message_prompt_template, input_data) state_update_message = UpdateMessage_Generic( created_by=self.flow_config['name'], updated_flow=self.flow_config["name"], data={"query_message": query_message}, ) self._log_message(state_update_message)
log.info(query_message) human_input = self._read_input()
response = {} response["result"] = human_input
return response123456789_target_: Tachi67.ExtendLibraryFlowModule.ExtLibAskUserFlow.instantiate_from_default_configrequest_multi_line_input_flag: Falseend_of_input_string: EOI
query_message_prompt_template: template: |2- {{question}} input_variables: - "question"1234from flow_modules.Tachi67.AbstractBossFlowModule import AbstractBossFlow
class ExtendLibraryFlow(AbstractBossFlow): pass1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677name: ExtendLibraryFlowdescription: "A flow used to extend the content in the code library"
_target_: Tachi67.ExtendLibraryFlowModule.ExtendLibraryFlow.instantiate_from_default_config
subflows_config: MemoryReading: _target_: Tachi67.MemoryReadingFlowModule.MemoryReadingAtomicFlow.instantiate_from_default_config
Planner: _target_: Tachi67.PlanWriterFlowModule.PlanWriterFlow.instantiate_from_default_config subflows_config: Controller: backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4 Executor: subflows_config: write_plan: subflows_config: PlanGenerator: backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4
CtrlExMem: _target_: Tachi67.ExtendLibraryFlowModule.CtrlExMem_ExtLib.instantiate_from_default_config subflows_config: Controller: backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4 Executor: subflows_config: write_code: subflows_config: Controller: backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4 Executor: subflows_config: write_code: subflows_config: CodeGenerator: backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4 re_plan: subflows_config: Controller: backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4 Executor: subflows_config: write_plan: subflows_config: PlanGenerator: backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4
12345678910111213141516171819202122232425262728293031323334353637from typing import Dict, Anyfrom flows.base_flows.atomic import AtomicFlow
class SaveCodeAtomicFlow(AtomicFlow): def _check_input(self, input_data: Dict[str, Any]): assert "code" in input_data, "code is not passed to SaveCodeAtomicFlow" assert "memory_files" in input_data, "memory_files is not passed to SaveCodeFlow" assert "code_library" in input_data["memory_files"], "code_library not in memory_files" # create the code library if it doesn't exist yet code_library_location = input_data["memory_files"]["code_library"] with open(code_library_location, 'a') as file: pass
def _call(self, input_data: Dict[str, Any]): try: code_to_append = input_data["code"] code_lib_loc = input_data["memory_files"]["code_library"] with open(code_lib_loc, 'a') as file: file.write(code_to_append + '\n') return { "result": "code successfully written to the library", "summary": f"ExtendLibrayFlow/SaveCodeAtomicFlow: code written to {code_lib_loc}" } except Exception as e: error_msg = str(e) return { "result": f"error occurred: {error_msg}", "summary": f"ExtendLibrayFlow/SaveCodeAtomicFlow: error occurred: {error_msg}" }
def run( self, input_data: Dict[str, Any] ): self._check_input(input_data) return self._call(input_data)1234567891011_target_: Tachi67.ExtendLibraryFlowModule.SaveCodeAtomicFlow.instantiate_from_default_configname: "SaveCodeAtomicFlow"description: "In extend library flow, once the code is written and tested, the controller calls this flow to save the code to the library."
input_interface: - "memory_files" - "code"
output_interface: - "result" - "summary"1234567891011121314151617181920212223242526272829from typing import Dict, Anyfrom flows.base_flows.atomic import AtomicFlowclass UpdatePlanAtomicFlow(AtomicFlow): def _check_input(self, input_data: Dict[str, Any]): assert "memory_files" in input_data, "memory_files not passed to UpdatePlanAtomicFlow" assert "plan" in input_data["memory_files"], "plan not in memory_files"
def _call(self, input_data: Dict[str, Any]): try: plan_file_location = input_data["memory_files"]["plan"] plan_to_write = input_data["updated_plan"] with open(plan_file_location, 'w') as file: file.write(plan_to_write + "\n") return { "result": "updated plan saved to the plan file and has overriden the previous plan", "summary": f"ExtendLibrary/UpdatePlanFlow: updated plan saved to {plan_file_location}" } except Exception as e: return { "result": f"Error occurred: {str(e)}", "summary": f"ExtendLibrary/UpdatePlanFlow: error occurred while writing updated plan: {str(e)}" }
def run( self, input_data: Dict[str, Any] ): self._check_input(input_data) return self._call(input_data)123456789_target_: Tachi67.ExtendLibraryFlowModule.UpdatePlanAtomicFlow.instantiate_from_default_configname: "UpdatePlanAtomicFlow"description: "Writes new plan to plan file"
input_interface: - "updated_plan"
output_interface: - "result"12345678910111213141516dependencies = [ {"url": "Tachi67/AbstractBossFlowModule", "revision": "main"}, {"url": "Tachi67/MemoryReadingFlowModule", "revision": "main"}, {"url": "Tachi67/PlanWriterFlowModule", "revision": "main"}, {"url": "Tachi67/ReplanningFlowModule", "revision": "main"}, {"url": "Tachi67/CodeWriterFlowModule", "revision": "main"},]
from flows import flow_verseflow_verse.sync_dependencies(dependencies)from .ControllerFlow_ExtLib import ControllerFlow_ExtLibfrom .CtrlExMem_ExtLib import CtrlExMem_ExtLibfrom .ExtendLibraryFlow import ExtendLibraryFlowfrom .ExtLibAskUserFlow import ExtLibAskUserFlowfrom .SaveCodeAtomicFlow import SaveCodeAtomicFlowfrom .UpdatePlanAtomicFlow import UpdatePlanAtomicFlowControllerFlow_ExtLib.pyAdded+114
ControllerFlow_ExtLib.yamlAdded+134
CtrlExMem_ExtLib.pyAdded+53
CtrlExMem_ExtLib.yamlAdded+102
ExtLibAskUserFlow.pyAdded+30
ExtLibAskUserFlow.yamlAdded+9
ExtendLibraryFlow.pyAdded+4
ExtendLibraryFlow.yamlAdded+77
SaveCodeAtomicFlow.pyAdded+37
SaveCodeAtomicFlow.yamlAdded+11
UpdatePlanAtomicFlow.pyAdded+29
UpdatePlanAtomicFlow.yamlAdded+9
__init__.pyAdded+16