Upload 10 files
Browse filesFiles changed (10)
- CodeWriterAskUserFlow.pyAdded+43
- CodeWriterAskUserFlow.yamlAdded+9
- CodeWriterCtrlFlow.pyAdded+96
- CodeWriterCtrlFlow.yamlAdded+123
- CodeWriterFlow.pyAdded+88
- CodeWriterFlow.yamlAdded+80
- README.md+145-3
- __init__.pyAdded+14
- pip_requirements.txtAdded+15
- run_codewriter.pyAdded+61
12345678910111213141516171819202122232425262728293031323334353637383940414243from flow_modules.aiflows.HumanStandardInputFlowModule import HumanStandardInputFlow
from typing import Dict, Any
from aiflows.messages import UpdateMessage_Generic
from aiflows.utils import logging
log = logging.get_logger(f"aiflows.{__name__}")
class CodeWriterAskUserFlow(HumanStandardInputFlow): """This class is used to ask for user feedback whenever the controller is unsure of something, or need confirmation, etc. *Expected Input*: - `question`: The question asked by the controller *Expected Behaviour*: - The question is displayed, and the user gives feedback by inputing string. *Expected Ouput*: - `feedback`: The input of the user. - `code`: No code was written. """ def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]: """Run the flow. :param input_data: The input data. :return: The output data. """ 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["feedback"] = human_input response["code"] = "no code was written"
return response123456789_target_: flow_modules.aiflows.CodeWriterFlowModule.CodeWriterAskUserFlow.instantiate_from_default_configrequest_multi_line_input_flag: Falseend_of_input_string: EOI
query_message_prompt_template: template: |2- {{question}} input_variables: - "question"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import 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 CodeWriterCtrlFlow(ChatAtomicFlow): """refer to https://huggingface.co/Tachi67/JarvisFlowModule/blob/main/Controller_JarvisFlow.py""" 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), ) self.hint_for_model = """ Make sure your response is in the following format: Response Format: { "command": "call code writer, the tester, or to finish", "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
@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 'feedback' in input_data: input_data['feedback'] += self.hint_for_model
def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]: self._update_prompts_and_input(input_data)
# ~~~when conversation is initialized, append the updated system prompts to the chat history ~~~ if self._is_conversation_initialized(): updated_system_message_content = self._get_message(self.system_message_prompt_template, input_data) self._state_update_add_chat_message(content=updated_system_message_content, role=self.flow_config["system_name"])
while True: api_output = super().run(input_data)["api_output"].strip() try: response = json.loads(api_output) return response except (json.decoder.JSONDecodeError, json.JSONDecodeError): updated_system_message_content = self._get_message(self.system_message_prompt_template, input_data) self._state_update_add_chat_message(content=updated_system_message_content, role=self.flow_config["system_name"]) new_goal = "The previous respond cannot be parsed with json.loads. Next time, do not provide any comments or code blocks. Make sure your next response is purely json parsable." new_input_data = input_data.copy() new_input_data['feedback'] = new_goal input_data = new_input_data123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123_target_: flow_modules.aiflows.CodeWriterFlowModule.CodeWriterCtrlFlow.instantiate_from_default_configname: "CodeWriterControllerFlow"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: - "goal" - "code" - "feedback"
######################################################## 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 goal with user interaction" input_args: ["goal"] finish: description: "Signal that the objective has been satisfied, return the summary of what functions are written, and what are their uses" 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"] test: description: "test the code generated from write_code" input_args: []
system_message_prompt_template: _target_: langchain.PromptTemplate template: |2- You are in charge of a department of writing code to solve a certain goal. You work with a coder, who does all the coding job; and a code tester, who does all the testing job. Your **ONLY** task is to take the user's goal for you, to decide whether to call the coder to write or re-write the code, to call the tester to test the code, or to finish the current task. Here is the goal you need to achieve: {{goal}} When you need to call the code writer, call the `write_code` command with the goal specified. When you need to call the code tester, call the `test` command to test the code written. When the code is written and the user is satisfied, call the `finish` command to terminate the current process with a summary of what functions are written, and what are their uses. Whenever you are in doubt, or need to confirm something to the user, call `ask_user` with the question. The coder will only write one function per goal, make sure you are not asking the coder to write more than one function. You **must not** write code yourself. You only decide whether to call the coder with specified goals or to finish. Your workflow: 0. Whenever the user demands to quit or terminate the current process, call `manual_finish` command. 1. Upon user request, call the `write_code` with the goal given. 2. The coder will write code, which is a function. The user will examine the code, and provide feedback. 3. Depending on the feedback of the user: 3.1. The user provides feedback on how to change the code, **call the coder with user's specific requirements again, to ask the coder to refine the code**. Go back to step 2. 3.2. The user does not provide details about refining the code, for example, just stating the fact that the user has updated the code, **this means the user is satisfied with the code written, call the `finish` command.** 4. If the user is satisfied with the code, call `test` to test the code 5. Depending on the result of the test: 5.1 Test passes, terminate the current process with the `finish` command, with a summary of what functions are written, and what are their uses. 5.2 Test fails, **call the coder with details of the test results to instruct the coder to refine the code**, go back to step 2. If you have completed all your tasks, make sure to use the "finish" command, with a summary of what functions are written, and what are their uses. 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", "goal"] template_format: jinja2
human_message_prompt_template: _target_: aiflows.prompt_template.JinjaPrompt template: |2- Here is the code written by the coder, it might have been updated by the user, depending on the user's feedback: {{code}} Here is the feedback, depending on the last command you called, it either came from the user or the tester: {{feedback}} input_variables: - "code" - "feedback" template_format: jinja2
init_human_message_prompt_template: _target_: aiflows.prompt_template.JinjaPrompt template: |2- Here is the goal you need to achieve: {{goal}} input_variables: - "goal" template_format: jinja2
previous_messages: last_k: 312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788from typing import Dict, Anyimport os
from flow_modules.aiflows.ContentWriterFlowModule import ContentWriterFlowfrom aiflows.base_flows import CircularFlow
class CodeWriterFlow(ContentWriterFlow): """This flow inherits from ContentWriterFlow, it is used to write code in an interactive way. In the subflow of the executor, we specify an InteractiveCodeGenFlow (https://huggingface.co/Tachi67/InteractiveCodeGenFlowModule)
*Input Interface*: - `goal`
*Output Interface*: - `code` - `result` - `summary` - `status` """ def _on_reach_max_round(self): self._state_update_dict({ "code": "The maximum amount of rounds was reached before the model generated the code.", "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": # ~~~ delete the temp code file ~~~ keys_to_fetch_from_state = ["temp_code_file_location", "code"] fetched_state = self._fetch_state_attributes_by_keys(keys=keys_to_fetch_from_state) temp_code_file_location = fetched_state["temp_code_file_location"] code_content = fetched_state["code"] if os.path.exists(temp_code_file_location): os.remove(temp_code_file_location) # ~~~ return the code content ~~~ return { "EARLY_EXIT": True, "code": code_content, "result": output_payload["command_args"]["summary"], "summary": "ExtendLibrary/CodeWriter: " + output_payload["command_args"]["summary"], "status": "finished" } elif command == "manual_finish": # ~~~ delete the temp code file ~~~ keys_to_fetch_from_state = ["temp_code_file_location"] fetched_state = self._fetch_state_attributes_by_keys(keys=keys_to_fetch_from_state) temp_code_file_location = fetched_state["temp_code_file_location"] if os.path.exists(temp_code_file_location): os.remove(temp_code_file_location) # ~~~ return the manual quit status ~~~ return { "EARLY_EXIT": True, "code": "no code was generated", "result": "CodeWriter was terminated explicitly by the user, process is unfinished", "summary": "ExtendLibrary/CodeWriter: CodeWriter was terminated explicitly by the user, process is unfinished", "status": "unfinished" } elif command == "test": # ~~~ fetch code string from flow state ~~~ keys_to_fetch_from_state = ["code"] fetched_state = self._fetch_state_attributes_by_keys(keys=keys_to_fetch_from_state)
# ~~~ add code content to the command args (branch input data) ~~~ code_content = fetched_state["code"] output_payload["command_args"]["code"] = code_content
return output_payload else: return output_payload
def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]: # ~~~ sets the input_data in the flow_state dict ~~~ self._state_update_dict(update_data=input_data)
max_rounds = self.flow_config.get("max_rounds", 1) if max_rounds is None: log.info(f"Running {self.flow_config['name']} without `max_rounds` until the early exit condition is met.")
self._sequential_run(max_rounds=max_rounds)
output = self._get_output_from_state()
self.reset(full_reset=True, recursive=True, src_flow=self)
return output1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980name: "CodeWriter"description: "Generates code with interactions with the user"
_target_: flow_modules.aiflows.CodeWriterFlowModule.CodeWriterFlow.instantiate_from_default_config
output_interface: - "code" - "status" - "summary" - "result"
### Subflows specificationsubflows_config: Controller: _target_: flow_modules.aiflows.CodeWriterFlowModule.CodeWriterCtrlFlow.instantiate_from_default_config backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4
Executor: _target_: aiflows.base_flows.BranchingFlow.instantiate_from_default_config subflows_config: write_code: _target_: flow_modules.aiflows.InteractiveCodeGenFlowModule.InteractiveCodeGenFlow.instantiate_from_default_config subflows_config: MemoryReading: _target_: flow_modules.aiflows.MemoryReadingFlowModule.MemoryReadingAtomicFlow.instantiate_from_default_config
CodeGenerator: _target_: flow_modules.aiflows.CodeGeneratorFlowModule.CodeGeneratorAtomicFlow.instantiate_from_default_config backend: api_infos: ??? model_name: openai: gpt-4 azure: azure/gpt-4
CodeFileEditor: _target_: flow_modules.aiflows.CodeFileEditFlowModule.CodeFileEditAtomicFlow.instantiate_from_default_config
ParseFeedback: _target_: flow_modules.aiflows.ParseFeedbackFlowModule.ParseFeedbackAtomicFlow.instantiate_from_default_config
ask_user: _target_: flow_modules.aiflows.CodeWriterFlowModule.CodeWriterAskUserFlow.instantiate_from_default_config
test: _target_: flow_modules.aiflows.TestCodeFlowModule.TestCodeFlow.instantiate_from_default_config
early_exit_key: "EARLY_EXIT"
topology: - goal: "Select the next action and prepare the input for the executor." input_interface: _target_: aiflows.interfaces.KeyInterface additional_transformations: - _target_: aiflows.data_transformations.KeyMatchInput flow: Controller output_interface: _target_: CodeWriterFlow.detect_finish_or_continue reset: false
- goal: "Execute the action specified by the Controller." input_interface: _target_: aiflows.interfaces.KeyInterface keys_to_rename: command: branch command_args: branch_input_data keys_to_select: ["branch", "branch_input_data"] flow: Executor output_interface: _target_: aiflows.interfaces.KeyInterface keys_to_rename: branch_output_data.code: code branch_output_data.feedback: feedback branch_output_data.temp_code_file_location: temp_code_file_location keys_to_delete: ["branch_output_data"] reset: false123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145---license: mit---### Structure of CodeWriterFlow
``` goal | v +---------------+ | Controller | --------<<<<-----------+ +---------------+ | | | | (command, command args) | | | v | +------------------+ | | Executor | Each branch is an | | (Tree Structure) | executor | +------------------+ | | ^ | (summary) | | | v | | | +-> goes back to the Controller>-+
```
Structure of the Executors:``` +-------------------+ | Branching | | Executor | +-------------------+ / | \ / | \ / | \ / | \write_code ask_user test
```
About the branches:- [ask_user](https://huggingface.co/Tachi67/CodeWriterFlowModule/blob/main/CodeWriterAskUserFlow.py): Ask user for info / confirmation, etc.- [write_code](https://huggingface.co/Tachi67/InteractiveCodeGenFlowModule): Generates code (user edit is allowed) and fetches user feedback.- [test](https://huggingface.co/Tachi67/TestCodeFlowModule): Test the code, user can provide test suites, if nothing is provided, syntax of the code is checked.
How it works:Controller calls write_code until user is satisfied in the feedback, then controller calls test to test the code, if test passes, finish.
# Table of Contents
* [run\_codewriter](#run_codewriter)* [CodeWriterCtrlFlow](#CodeWriterCtrlFlow) * [CodeWriterCtrlFlow](#CodeWriterCtrlFlow.CodeWriterCtrlFlow)* [CodeWriterAskUserFlow](#CodeWriterAskUserFlow) * [CodeWriterAskUserFlow](#CodeWriterAskUserFlow.CodeWriterAskUserFlow) * [run](#CodeWriterAskUserFlow.CodeWriterAskUserFlow.run)* [CodeWriterFlow](#CodeWriterFlow) * [CodeWriterFlow](#CodeWriterFlow.CodeWriterFlow)* [\_\_init\_\_](#__init__)
<a id="run_codewriter"></a>
# run\_codewriter
<a id="CodeWriterCtrlFlow"></a>
# CodeWriterCtrlFlow
<a id="CodeWriterCtrlFlow.CodeWriterCtrlFlow"></a>
## CodeWriterCtrlFlow Objects
```pythonclass CodeWriterCtrlFlow(ChatAtomicFlow)```
refer to https://huggingface.co/Tachi67/JarvisFlowModule/blob/main/Controller_JarvisFlow.py
<a id="CodeWriterAskUserFlow"></a>
# CodeWriterAskUserFlow
<a id="CodeWriterAskUserFlow.CodeWriterAskUserFlow"></a>
## CodeWriterAskUserFlow Objects
```pythonclass CodeWriterAskUserFlow(HumanStandardInputFlow)```
This class is used to ask for user feedback whenever the controller is unsure of something, or need confirmation, etc.*Expected Input*:- `question`: The question asked by the controller*Expected Behaviour*:- The question is displayed, and the user gives feedback by inputing string.*Expected Ouput*:- `feedback`: The input of the user.- `code`: No code was written.
<a id="CodeWriterAskUserFlow.CodeWriterAskUserFlow.run"></a>
#### run
```pythondef run(input_data: Dict[str, Any]) -> Dict[str, Any]```
Run the flow.
**Arguments**:
- `input_data`: The input data.
**Returns**:
The output data.
<a id="CodeWriterFlow"></a>
# CodeWriterFlow
<a id="CodeWriterFlow.CodeWriterFlow"></a>
## CodeWriterFlow Objects
```pythonclass CodeWriterFlow(ContentWriterFlow)```
This flow inherits from ContentWriterFlow, it is used to write code in an interactive way.In the subflow of the executor, we specify an InteractiveCodeGenFlow (https://huggingface.co/Tachi67/InteractiveCodeGenFlowModule)
*Input Interface*:- `goal`
*Output Interface*:- `code`- `result`- `summary`- `status`
<a id="__init__"></a>
# \_\_init\_\_
1234567891011121314dependencies = [ {"url": "aiflows/ContentWriterFlowModule", "revision": "main"}, {"url": "aiflows/InteractiveCodeGenFlowModule", "revision": "main"}, {"url": "aiflows/TestCodeFlowModule", "revision": "main"}, {"url": "aiflows/ChatFlowModule", "revision": "297c90d08087d9ff3139521f11d1a48d7dc63ed4"}, {"url": "aiflows/HumanStandardInputFlowModule", "revision": "4ff043522c89a964ea3a928ce09811c51a2b5b98"}]from aiflows import flow_verse
flow_verse.sync_dependencies(dependencies)
from .CodeWriterFlow import CodeWriterFlowfrom .CodeWriterCtrlFlow import CodeWriterCtrlFlowfrom .CodeWriterAskUserFlow import CodeWriterAskUserFlow123456789101112131415colorama==0.4.6pytest==7.3.1pytest-cov==4.1.0hydra-core==1.3.2hydra-colorlog==1.1.0wrapt-timeout-decorator==1.3.12.2diskcache==5.6.1openai==1.0.0huggingface_hub==0.19.4jsonlines==3.1.0jinja2==3.1.2mock==5.0.2rich==12.6.0litellm==1.0.0aiflows12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import os
import hydra
from aiflows.backends.api_info import ApiInfofrom aiflows.messages import InputMessagefrom aiflows.utils.general_helpers import read_yaml_file, quick_load
from aiflows import loggingfrom aiflows.flow_cache import CACHING_PARAMETERS, clear_cache
CACHING_PARAMETERS.do_caching = False # Set to True in order to disable caching# clear_cache() # Uncomment this line to clear the cache
logging.set_verbosity_debug()logging.auto_set_dir()
dependencies = [ {"url": "aiflows/ContentWriterFlowModule", "revision": "main"}, {"url": "aiflows/InteractiveCodeGenFlowModule", "revision": "main"}, {"url": "aiflows/CodeWriterFlowModule", "revision": "main"}, {"url": "aiflows/ChatFlowModule", "revision": "297c90d08087d9ff3139521f11d1a48d7dc63ed4"},]
from aiflows import flow_verse
flow_verse.sync_dependencies(dependencies)
if __name__ == "__main__": # ~~~ make sure to set the openai api key in the envs ~~~ key = os.getenv("OPENAI_API_KEY") api_information = [ApiInfo(backend_used="openai", api_key=os.getenv("OPENAI_API_KEY"))] path_to_output_file = None
# ~~~ setting api information into config ~~~ current_dir = os.getcwd() cfg_path = os.path.join(current_dir, "CodeWriterFlow.yaml") cfg = read_yaml_file(cfg_path) quick_load(cfg, api_information)
# ~~~ setting code library into config ~~~ code_lib_file_loc = os.path.join(current_dir, "library.py") with open(code_lib_file_loc, 'w') as file: pass cfg["subflows_config"]["Executor"]["subflows_config"]["write_code"]["memory_files"] = {"code_library": code_lib_file_loc} cfg["subflows_config"]["Executor"]["subflows_config"]["test"]["memory_files"] = {"code_library": code_lib_file_loc}
# ~~~ instantiating the flow and input data ~~~ CodeWriterFlow = hydra.utils.instantiate(cfg, _recursive_=False, _convert_="partial") input_data = { "goal": "create a function that adds two numbers and returns the result", } input_message = InputMessage.build( data_dict=input_data, src_flow="Launcher", dst_flow=CodeWriterFlow.name )
# ~~~ calling the flow ~~~ output_message = CodeWriterFlow(input_message)CodeWriterAskUserFlow.pyAdded+43
CodeWriterAskUserFlow.yamlAdded+9
CodeWriterCtrlFlow.pyAdded+96
CodeWriterCtrlFlow.yamlAdded+123
CodeWriterFlow.pyAdded+88
CodeWriterFlow.yamlAdded+80
README.md+145-3
__init__.pyAdded+14
pip_requirements.txtAdded+15
run_codewriter.pyAdded+61