added demo and readme
Browse filesFiles changed (7)
- ChatHumanFlowModule.pyAdded+55
- OpenAIChatHumanFlowModule.yaml → ChatHumanFlowModule.yamlRenamed+13-9
- OpenAIChatHumanFlowModule.pyDeleted-14
- README.mdDeleted-24
- __init__.py+3-3
- demo.yamlAdded+31
- run.py+28-14
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455from flows.base_flows import CircularFlowfrom flows.utils import logging
log = logging.get_logger(f"flows.{__name__}")
class ChatHumanFlowModule(CircularFlow): """ This class implements a Chat Human Flow Module. It is a flow that consists of two sub-flows that are executed circularly. It Contains the following subflows: - A User Flow: A flow makes queries to the Assistant Flow. E.g. The user asks the assistant (LLM) a question. - A Assistant Flow: A flow that responds to queries made by the User Flow. E.g. The assistant (LLM) answers the user's question. To end the interaction, the user must type "\<END\>" An illustration of the flow is as follows: |------> User Flow -----------> | ^ | | | | v |<------ Assistant Flow <-------| *Configuration Parameters*: - `name` (str): The name of the flow. Default: "ChatHumanFlowModule" - `description` (str): A description of the flow. This description is used to generate the help message of the flow. Default: "Flow that enables chatting between a ChatAtomicFlow and a user providing the input." - `max_rounds` (int): The maximum number of rounds the flow can run for. Default: None, which means that there is no limit on the number of rounds. - `early_exit_key` (str): The key that is used to exit the flow. Default: "end_of_interaction" - `subflows_config` (Dict[str,Any]): A dictionary of subflows configurations. Default: - `Assistant Flow`: The configuration of the Assistant Flow. By default, it a ChatAtomicFlow. It default parmaters are defined in ChatAtomicFlowModule. - `User Flow`: The configuration of the User Flow. By default, it a HumanStandardInputFlow. It default parmaters are defined in HumanStandardInputFlowModule. - `topology` (str): (List[Dict[str,Any]]): The topology of the flow which is "circular". By default, the topology is the one shown in the illustration above (the topology is also described in ChatHumanFlowModule.yaml).
*Input Interface*: - None. By default, the input interface doesn't expect any input. *Output Interface*:
- `end_of_interaction` (bool): Whether the interaction is finished or not. :param \**kwargs: Arguments to be passed to the parent class CircularFlow constructor. :type \**kwargs: Dict[str, Any] """
def __init__(self, **kwargs): super().__init__(**kwargs)
@classmethod def type(cls): """ This method returns the type of the flow.""" return "OpenAIChatHumanFlowModule"1234567891011121314151631 unmodified lines48495051525354555657585960616263name: "OpenAIChatInteractiveFlow"description: "Flow for chatting with an OpenAI Flow and a user providing the input."max_rounds: null # Run until early exit is detectedinput_keys: null # Should be specified by the useroutput_keys: null # Should be specified by the usersubflows_config:Assistant:_target_: aiflows.OpenAIChatFlowModule.OpenAIChatAtomicFlow.instantiate_from_default_configmodel_name: "gpt-4"User:_target_: aiflows.HumanStandardInputFlowModule.HumanStandardInputFlow.instantiate_from_default_config31 unmodified lines### Output Interfaceoutput_interface:_target_: flows.interfaces.KeyInterfaceadditional_transformations:- _target_: flows.data_transformations.RegexFirstOccurrenceExtractorregex: '(?<=```answer)([\s\S]*?)(?=```)'input_key: "human_input"output_key: "answer"strip: Trueassert_unique: True- _target_: flows.data_transformations.EndOfInteractionend_of_interaction_string: "<END>"input_key: "human_input"output_key: "end_of_interaction"early_exit_key: "end_of_interaction"12345678910111213141516171831 unmodified lines505152535455565758596061626364656667name: "ChatInteractiveFlow"description: "Flow that enables chatting between a ChatAtomicFlow and a user providing the input."max_rounds: null # Run until early exit is detectedinput_interface:_target_: flows.interfaces.KeyInterfaceoutput_interface:- "end_of_interaction"- "answer"subflows_config:Assistant:_target_: aiflows.ChatFlowModule.ChatAtomicFlow.instantiate_from_default_configUser:_target_: aiflows.HumanStandardInputFlowModule.HumanStandardInputFlow.instantiate_from_default_config31 unmodified lines### Output Interfaceoutput_interface:_target_: flows.interfaces.KeyInterfacekeys_to_rename:human_input: queryadditional_transformations:- _target_: flows.data_transformations.RegexFirstOccurrenceExtractorregex: '(?<=```answer)([\s\S]*?)(?=```)'input_key: "query"output_key: "answer"strip: Trueassert_unique: True- _target_: flows.data_transformations.EndOfInteractionend_of_interaction_string: "<END>"input_key: "query"output_key: "end_of_interaction"early_exit_key: "end_of_interaction"
1234567891011121314from flows.base_flows import CircularFlowfrom flows.utils import logging
log = logging.get_logger(__name__)
class OpenAIChatHumanFlowModule(CircularFlow):
def __init__(self, **kwargs): super().__init__(**kwargs)
@classmethod def type(cls): return "OpenAIChatHumanFlowModule"123456789101112131415161718192021222324---license: mit---## Description
< Flow description >
## Configuration parameters
< Name 1 > (< Type 1 >): < Description 1 >. Required parameter.
< Name 2 > (< Type 2 >): < Description 2 >. Default value is: < value 2 >
## Input interface
< Name 1 > (< Type 1 >): < Description 1 >.
(Note that the interface might depend on the state of the Flow.)
## Output interface
< Name 1 > (< Type 1 >): < Description 1 >.
(Note that the interface might depend on the state of the Flow.)1234567891011# ~~~ Specify the dependencies ~~~dependencies = [{"url": "aiflows/OpenAIChatFlowModule", "revision": "6a1e351a915f00193f18f3da3b61c497df1d31a3"},{"url": "aiflows/HumanStandardInputFlowModule", "revision": "890e92da1fefbae642fd84296e31bca7f61ea710"},]from flows import flow_verseflow_verse.sync_dependencies(dependencies)# ~~~from .OpenAIChatHumanFlowModule import OpenAIChatHumanFlowModule1234567891011# ~~~ Specify the dependencies ~~~dependencies = [{"url": "aiflows/ChatFlowModule", "revision": "a749ad10ed39776ba6721c37d0dc22af49ca0f17"},{"url": "aiflows/HumanStandardInputFlowModule", "revision": "5683a922372c5fa90be9f6447d6662d8d80341fc"},]from flows import flow_verseflow_verse.sync_dependencies(dependencies)# ~~~from .ChatHumanFlowModule import ChatHumanFlowModule
12345678910111213141516171819202122232425262728293031
flow: max_rounds: 5 _target_: aiflows.ChatInteractiveFlowModule.ChatHumanFlowModule.instantiate_from_default_config subflows_config: Assistant: _target_: aiflows.ChatFlowModule.ChatAtomicFlow.instantiate_from_default_config backend: _target_: flows.backends.llm_lite.LiteLLMBackend api_infos: ??? model_name: openai: "gpt-4" azure: "azure/gpt-4" input_interface_non_initialized: [] User: _target_: aiflows.HumanStandardInputFlowModule.HumanStandardInputFlow.instantiate_from_default_config request_multi_line_input_flag: False query_message_prompt_template: _target_: flows.prompt_template.JinjaPrompt template: |2- {{api_output}} To end an Interaction, type <END> and press enter. input_variables: ["api_output"] input_interface: - "api_output" output_interface: - "human_input"4 unmodified lines5678910114 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950512 unmodified lines545556575859606162634 unmodified linesimport hydraimport flowsfrom flows.flow_launchers import FlowLauncher, ApiInfofrom flows.utils.general_helpers import read_yaml_filefrom flows import logging4 unmodified lineslogging.set_verbosity_debug()if __name__ == "__main__":# ~~~ Set the API information ~~~# OpenAI backend# api_information = ApiInfo("openai", os.getenv("OPENAI_API_KEY"))# Azure backendapi_information = ApiInfo("azure", os.getenv("AZURE_OPENAI_KEY"), os.getenv("AZURE_OPENAI_ENDPOINT"))# ~~~ Instantiate the Flow ~~~root_dir = "."cfg_path = os.path.join(root_dir, "FlowName.yaml")cfg = read_yaml_file(cfg_path)flow_with_interfaces = {"flow": hydra.utils.instantiate(cfg['flow'], _recursive_=False, _convert_="partial"),"input_interface": (Noneif getattr(cfg, "input_interface", None) is Noneelse hydra.utils.instantiate(cfg['input_interface'], _recursive_=False)),"output_interface": (Noneif getattr(cfg, "output_interface", None) is Noneelse hydra.utils.instantiate(cfg['output_interface'], _recursive_=False)),}# ~~~ Get the data ~~~# This can be a list of samplesdata = {"id": 0} # Add your data here# ~~~ Run inference ~~~path_to_output_file = None2 unmodified lines_, outputs = FlowLauncher.launch(flow_with_interfaces=flow_with_interfaces,data=data,path_to_output_file=path_to_output_file,api_information=api_information,)# ~~~ Print the output ~~~flow_output_data = outputs[0]print(flow_output_data)4 unmodified lines567891011124 unmodified lines171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364652 unmodified lines686970717273747576774 unmodified linesimport hydraimport flowsfrom flows.flow_launchers import FlowLauncherfrom flows.backends.api_info import ApiInfofrom flows.utils.general_helpers import read_yaml_filefrom flows import logging4 unmodified lineslogging.set_verbosity_debug()dependencies = [{"url": "aiflows/ChatInteractiveFlowModule", "revision": os.getcwd()},]from flows import flow_verseflow_verse.sync_dependencies(dependencies)if __name__ == "__main__":# ~~~ Set the API information ~~~# OpenAI backendapi_information = [ApiInfo(backend_used="openai",api_key = os.getenv("OPENAI_API_KEY"))]# # Azure backend# api_information = ApiInfo(backend_used = "azure",# api_base = os.getenv("AZURE_API_BASE"),# api_key = os.getenv("AZURE_OPENAI_KEY"),# api_version = os.getenv("AZURE_API_VERSION") )root_dir = "."cfg_path = os.path.join(root_dir, "demo.yaml")cfg = read_yaml_file(cfg_path)cfg["flow"]["subflows_config"]["Assistant"]["backend"]["api_infos"] = api_information# ~~~ Instantiate the Flow ~~~flow_with_interfaces = {"flow": hydra.utils.instantiate(cfg['flow'], _recursive_=False, _convert_="partial"),"input_interface": (Noneif cfg.get( "input_interface", None) is Noneelse hydra.utils.instantiate(cfg['input_interface'], _recursive_=False)),"output_interface": (Noneif cfg.get( "output_interface", None) is Noneelse hydra.utils.instantiate(cfg['output_interface'], _recursive_=False)),}# ~~~ Get the data ~~~data = {"id": 0, "question": "Generate a short random sentence"} # This can be a list of samples# data = {"id": 0, "question": "Who was the NBA champion in 2023?"} # This can be a list of samples# ~~~ Run inference ~~~path_to_output_file = None2 unmodified lines_, outputs = FlowLauncher.launch(flow_with_interfaces=flow_with_interfaces,data=data,path_to_output_file=path_to_output_file)# ~~~ Print the output ~~~flow_output_data = outputs[0]print(flow_output_data)
ChatHumanFlowModule.pyAdded+55
OpenAIChatHumanFlowModule.yaml → ChatHumanFlowModule.yamlRenamed+13-9
OpenAIChatHumanFlowModule.pyDeleted-14
README.mdDeleted-24
__init__.py+3-3
demo.yamlAdded+31
run.py+28-14