merge with coflows
Browse filesFiles changed (7)
- ChatWithDemonstrationsFlow.py+69-5
- ChatWithDemonstrationsFlow.yaml+12-28
- DemonstrationsAtomicFlow.py+12-8
- DemonstrationsAtomicFlow.yaml+1-4
- __init__.py+4-1
- demo.yaml+68-70
- run.py+71-41
123456789101112131429 unmodified lines44454647from aiflows.base_flows import SequentialFlowfrom aiflows.utils import logginglogging.set_verbosity_debug()log = logging.get_logger(__name__)class ChatWithDemonstrationsFlow(SequentialFlow):""" A Chat with Demonstrations Flow. It is a flow that consists of multiple sub-flows that are executed sequentially.It's parent class is SequentialFlow.29 unmodified lines:param \**kwargs: Arguments to be passed to the parent class SequentialFlow constructor."""def __init__(self,**kwargs):super().__init__(**kwargs)123456789101112131429 unmodified lines4445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111from aiflows.base_flows import CompositeFlowfrom aiflows.utils import loggingfrom aiflows.interfaces import KeyInterfacelogging.set_verbosity_debug()from aiflows.messages import FlowMessagelog = logging.get_logger(__name__)class ChatWithDemonstrationsFlow(CompositeFlow):""" A Chat with Demonstrations Flow. It is a flow that consists of multiple sub-flows that are executed sequentially.It's parent class is SequentialFlow.29 unmodified lines:param \**kwargs: Arguments to be passed to the parent class SequentialFlow constructor."""def __init__(self,**kwargs):super().__init__(**kwargs)self.output_interface = KeyInterface(keys_to_rename={"api_output": "answer"})def set_up_flow_state(self):""" Set up the flow state. It sets the last state of the flow to None."""super().set_up_flow_state()self.flow_state["last_state"] = Nonedef run(self,input_message):""" Runs the flow.:param input_message: The input message of the flow.:type input_message: FlowMessage"""# #~~~~~~~~~~~Solution 1 - Blocking ~~~~~~~# future = self.subflows["demonstration_flow"].get_reply_future(input_message)# answer = self.subflows["chat_flow"].get_reply_future(future.get_message())#reply = self.package_output_message(input_message, self.output_interface(answer.get_data()))# self.send_message(reply)# #~~~~~~~~~~~Solution 2 - Non-Blocking ~~~~~~~if self.flow_state["last_state"] is None:self.flow_state["initial_message"] = input_messagemsg = self.package_input_message(input_message.data)self.subflows["demonstration_flow"].get_reply(msg,)self.flow_state["last_state"] = "demonstration_flow"elif self.flow_state["last_state"] == "demonstration_flow":msg = self.package_input_message(input_message.data)self.subflows["chat_flow"].get_reply(msg,)self.flow_state["last_state"] = "chat_flow"else:self.flow_state["last_state"] = Nonereply = self.package_output_message(self.flow_state["initial_message"],response = self.output_interface(input_message).data)self.send_message(reply)
123456789101112131415161718192021222324252627282930313233name: "ChatAtomic_Flow_with_Demonstrations"description: "A sequential flow that answers questions with demonstrations"subflows_config:demonstration_flow:_target_: flow_modules.aiflows.ChatWithDemonstrationsFlowModule.DemonstrationsAtomicFlow.instantiate_from_default_configchat_flow:_target_: flow_modules.aiflows.ChatFlowModule.ChatAtomicFlow.instantiate_from_default_configtopology:- goal: Get Demonstrationsinput_interface:_target_: aiflows.interfaces.KeyInterfaceflow: demonstration_flowoutput_interface:_target_: aiflows.interfaces.KeyInterface- goal: Answer the questioninput_interface:_target_: aiflows.interfaces.KeyInterfaceflow: chat_flowoutput_interface:_target_: aiflows.interfaces.KeyInterfacekeys_to_rename:api_output: answer # Rename the api_output to answerinput_interface_initialized:- "query"output_interface:- "answer"1234567891011121314151617name: "ChatAtomic_Flow_with_Demonstrations"description: "A sequential flow that answers questions with demonstrations"_target_: flow_modules.aiflows.ChatWithDemonstrationsFlowModule.ChatWithDemonstrationsFlow.instantiate_from_default_configsubflows_config:demonstration_flow:flow_class_name: flow_modules.aiflows.ChatWithDemonstrationsFlowModule.DemonstrationsAtomicFlowflow_endpoint: DemonstrationsAtomicFlowuser_id: localname: "DemonstrationsAtomicFlow"description: "A flow that answers questions with demonstrations"chat_flow:name: "ChatAtomicFlow"description: "A flow that answers questions"flow_class_name: flow_modules.aiflows.ChatFlowModule.ChatAtomicFlowflow_endpoint: ChatAtomicFlowuser_id: local
4 unmodified lines567891030 unmodified lines41424344454647134 unmodified lines1821831841851861871881891901911921934 unmodified linesfrom typing import Dict,Any,Optional,Listfrom aiflows.prompt_template import JinjaPromptfrom copy import deepcopyimport osimport hydralog = logging.get_logger(__name__)30 unmodified lines*Output Interface*:- The input interface expected by its successor flow (e.g. typically ChatAtomicFlow so the input interface expected by ChatAtomicFlow))- `demonstrations` (List[Dict[str, Any]]): A list of demonstrations. Each demonstration is a dictionary with the following keys:- idx (int): The index of the demonstration- query (str): The query of the demonstration134 unmodified lineslog.info("Loaded the demonstrations for %d datapoints from %s", len(self.data), self.params["data_dir"])def run(self,input_data: Dict[str, Any]) -> Dict[str, Any]:""" This method runs the flow. It returns the input data of the flow with the demonstrations added to it.:param input_data: The input data of the flow.:type input_data: Dict[str, Any]:return: The input data of the flow with the demonstrations added to it.:rtype: Dict[str, Any]"""return {**input_data,**{"demonstrations": self._get_io_pairs(input_data=input_data)}}4 unmodified lines56789101130 unmodified lines42434445464748134 unmodified lines1831841851861871881891901911921931941951961974 unmodified linesfrom typing import Dict,Any,Optional,Listfrom aiflows.prompt_template import JinjaPromptfrom copy import deepcopyfrom aiflows.messages import FlowMessageimport osimport hydralog = logging.get_logger(__name__)30 unmodified lines*Output Interface*:- Whichever data that was passed in the input_message (e.g. typically ChatAtomicFlow so the input interface expected by ChatAtomicFlow))- `demonstrations` (List[Dict[str, Any]]): A list of demonstrations. Each demonstration is a dictionary with the following keys:- idx (int): The index of the demonstration- query (str): The query of the demonstration134 unmodified lineslog.info("Loaded the demonstrations for %d datapoints from %s", len(self.data), self.params["data_dir"])def run(self,input_message: FlowMessage):""" This method runs the flow. It returns the data of the input_message with the demonstrations added to it.:param input_message: The input message of the flow.:type input_message: FlowMessage"""input_data = input_message.datareply = self.package_output_message(input_message=input_message,response = {**{"demonstrations": self._get_io_pairs(input_data=input_data)},**input_data})self.send_message(reply)
123456789name: "DemonstrationAtomicFlow"description: "A flow which returns Demonstrations"data: ??? #e.g. [{"query_data": {"query": "What is the capital of France?"}, "response_data": {"response": "Paris, my sir."}}]params:data_dir: ???123456name: "DemonstrationAtomicFlow"description: "A flow which returns Demonstrations"_target_: flow_modules.aiflows.ChatWithDemonstrationsFlowModule.DemonstrationsAtomicFlow.instantiate_from_default_configdata: ??? #e.g. [{"query_data": {"query": "What is the capital of France?"}, "response_data": {"response": "Paris, my sir."}}]params:data_dir: ???
12345678# ~~~ Specify the dependencies ~~dependencies = [{"url": "aiflows/ChatFlowModule", "revision": "main"},]from aiflows import flow_verseflow_verse.sync_dependencies(dependencies)from .ChatWithDemonstrationsFlow import ChatWithDemonstrationsFlowfrom .DemonstrationsAtomicFlow import DemonstrationsAtomicFlow1234567891011# ~~~ Specify the dependencies ~~dependencies = [{"url": "aiflows/ChatFlowModule", "revision": "main"},]from aiflows import flow_verseflow_verse.sync_dependencies(dependencies)from .ChatWithDemonstrationsFlow import ChatWithDemonstrationsFlowfrom .DemonstrationsAtomicFlow import DemonstrationsAtomicFlow
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576flow: # Overrides the OpenAIChatAtomicFlow config_target_: flow_modules.aiflows.ChatWithDemonstrationsFlowModule.ChatWithDemonstrationsFlow.instantiate_from_default_configname: "SimpleQA_Flow_with_Demonstrations"description: "A sequential flow that answers questions with demonstrations"input_interface: # Connector between the "input data" and the Flow- "questions"output_interface: # Connector between the Flow's output and the caller- "answer"subflows_config:demonstration_flow:data:- query_data:query: "What is the capital of Turkey?"response_data:response: "Istambul, my sir."- query_data:query: "what is the capital of Germany?"response_data:response: "Berlin, my sir."params:data_dir: nulldemonstrations_id: my_sir_demoquery_prompt_template:template: |2-Answer the following question: {{query}}input_variables:- "query"response_prompt_template:template: |2-{{response}}input_variables:- responsechat_flow:name: "SimpleQA_Flow"# ~~~ Input interface specification ~~~input_interface_non_initialized:- "question"# ~~~ backend model parameters ~~backend:_target_: aiflows.backends.llm_lite.LiteLLMBackendapi_infos: ???model_name:openai: "gpt-3.5-turbo"azure: "azure/gpt-4"# ~~~ generation_parameters ~~n: 1max_tokens: 3000temperature: 0.3top_p: 0.2frequency_penalty: 0presence_penalty: 0n_api_retries: 6wait_time_between_retries: 20# ~~~ Prompt specification ~~~system_message_prompt_template:_target_: aiflows.prompt_template.JinjaPrompttemplate: |2-You are a helpful chatbot that truthfully answers questions. Answer in a similar way to your previous replies.input_variables: []partial_variables: {}init_human_message_prompt_template:_target_: aiflows.prompt_template.JinjaPrompttemplate: |2-Answer the following question: {{question}}input_variables: ["question"]partial_variables: {}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374_target_: flow_modules.aiflows.ChatWithDemonstrationsFlowModule.ChatWithDemonstrationsFlow.instantiate_from_default_configname: "SimpleQA_Flow_with_Demonstrations"description: "A sequential flow that answers questions with demonstrations"input_interface: # Connector between the "input data" and the Flow- "questions"output_interface: # Connector between the Flow's output and the caller- "answer"subflows_config:demonstration_flow:name: "proxy of DemonstrationsAtomicFlow"description: "A flow that answers questions with demonstrations"data:- query_data:query: "What is the capital of Turkey?"response_data:response: "Istambul, my sir."- query_data:query: "what is the capital of Germany?"response_data:response: "Berlin, my sir."query_prompt_template:template: |2-Answer the following question: {{query}}input_variables:- "query"response_prompt_template:template: |2-{{response}}input_variables:- responsechat_flow:name: "proxy SimpleQA_Flow"description: "A flow that answers questions"# ~~~ Input interface specification ~~~input_interface_non_initialized:- "question"# ~~~ backend model parameters ~~backend:_target_: aiflows.backends.llm_lite.LiteLLMBackendapi_infos: ???model_name:openai: "gpt-3.5-turbo"azure: "azure/gpt-4"# ~~~ generation_parameters ~~n: 1max_tokens: 3000temperature: 0.3top_p: 0.2frequency_penalty: 0presence_penalty: 0n_api_retries: 6wait_time_between_retries: 20# ~~~ Prompt specification ~~~system_message_prompt_template:_target_: aiflows.prompt_template.JinjaPrompttemplate: |2-You are a helpful chatbot that truthfully answers questions. Answer in a similar way to your previous replies.input_variables: []partial_variables: {}init_human_message_prompt_template:_target_: aiflows.prompt_template.JinjaPrompttemplate: |2-Answer the following question: {{question}}input_variables: ["question"]partial_variables: {}
3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374753 unmodified linesimport aiflowsfrom aiflows.backends.api_info import ApiInfofrom aiflows.utils.general_helpers import read_yaml_filefrom aiflows import loggingfrom aiflows.flow_cache import CACHING_PARAMETERS, clear_cacheCACHING_PARAMETERS.do_caching = False # Set to True in order to disable caching# clear_cache() # Uncomment this line to clear the cachelogging.set_verbosity_debug() # Uncomment this line to see verbose logsfrom aiflows import flow_versedependencies = [{"url": "aiflows/ChatWithDemonstrationsFlowModule", "revision": os.getcwd()},]flow_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"]["chat_flow"]["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": "What's the capital of France?"} # 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 = None# path_to_output_file = "output.jsonl" # Uncomment this line to save the output to disk_, 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)3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041053 unmodified linesimport aiflowsfrom aiflows.backends.api_info import ApiInfofrom aiflows.utils.general_helpers import read_yaml_file, quick_load_api_keysfrom aiflows import loggingfrom aiflows.flow_cache import CACHING_PARAMETERS, clear_cachefrom aiflows.utils import serve_utilsfrom aiflows.workers import run_dispatch_worker_threadfrom aiflows.messages import FlowMessagefrom aiflows.interfaces import KeyInterfacefrom aiflows.utils.colink_utils import start_colink_serverfrom aiflows.workers import run_dispatch_worker_threadCACHING_PARAMETERS.do_caching = False # Set to True in order to disable caching# clear_cache() # Uncomment this line to clear the cachelogging.set_verbosity_debug()dependencies = [{"url": "aiflows/ChatWithDemonstrationsFlowModule", "revision": os.getcwd()}]from aiflows import flow_verseflow_verse.sync_dependencies(dependencies)if __name__ == "__main__":#1. ~~~~~ Set up a colink server ~~~~FLOW_MODULES_PATH = "./"cl = start_colink_server()#2. ~~~~~Load flow config~~~~~~root_dir = "."cfg_path = os.path.join(root_dir, "demo.yaml")cfg = read_yaml_file(cfg_path)#2.1 ~~~ 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") )quick_load_api_keys(cfg, api_information, key="api_infos")#3. ~~~~ Serve The Flow ~~~~serve_utils.recursive_serve_flow(cl = cl,flow_class_name="flow_modules.aiflows.ChatWithDemonstrationsFlowModule.ChatWithDemonstrationsFlow",flow_endpoint="ChatWithDemonstrationsFlow",)#4. ~~~~~Start A Worker Thread~~~~~run_dispatch_worker_thread(cl)#5. ~~~~~Mount the flow and get its proxy~~~~~~proxy_flow= serve_utils.get_flow_instance(cl=cl,flow_endpoint="ChatWithDemonstrationsFlow",user_id="local",config_overrides = cfg)#6. ~~~ Get the data ~~~data = {"id": 0, "question": "What is the capital of France?"} # This can be a list of samples# data = {"id": 0, "question": "Who was the NBA champion in 2023?"} # This can be a list of samplesinput_message = proxy_flow.package_input_message(data = data)#7. ~~~ Run inference ~~~future = proxy_flow.get_reply_future(input_message)#uncomment this line if you would like to get the full message back#reply_message = future.get_message()reply_data = future.get_data()# ~~~ Print the output ~~~print("~~~~~~Reply~~~~~~")print(reply_data)#8. ~~~~ (Optional) apply output interface on reply ~~~~# output_interface = KeyInterface(# keys_to_rename={"api_output": "answer"},# )# print("Output: ", output_interface(reply_data))#9. ~~~~~Optional: Unserve Flow~~~~~~# serve_utils.delete_served_flow(cl, "ChatWithDemonstrationFlowModule")
ChatWithDemonstrationsFlow.py+69-5
ChatWithDemonstrationsFlow.yaml+12-28
DemonstrationsAtomicFlow.py+12-8
DemonstrationsAtomicFlow.yaml+1-4
__init__.py+4-1
demo.yaml+68-70
run.py+71-41