coflows compatible+
Browse filesFiles changed (8)
1 unmodified line2345678108 unmodified lines1171181191201211221231241251261271281291301 unmodified linefrom copy import deepcopyfrom typing import Any, Dict, Listfrom flow_modules.aiflows.ChatFlowModule import ChatAtomicFlowfrom dataclasses import dataclass108 unmodified lines# ~~~ Instantiate flow ~~~return cls(**kwargs)def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:""" This method runs the flow. Note that the response of the LLM is in the JSON format, but it's not a hard constraint (it can hallucinate and return an invalid JSON):param input_data: The input data of the flow.:type input_data: Dict[str, Any]:return: The output data of the flow (thought, reasoning, criticism, command, command_args):rtype: Dict[str, Any]"""api_output = super().run(input_data)["api_output"].strip()response = json.loads(api_output)return response1 unmodified line2345678108 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441 unmodified linefrom copy import deepcopyfrom typing import Any, Dict, Listfrom flow_modules.aiflows.ChatFlowModule import ChatAtomicFlowfrom aiflows.messages import FlowMessagefrom dataclasses import dataclass108 unmodified lines# ~~~ Instantiate flow ~~~return cls(**kwargs)def run(self, input_message: FlowMessage):""" This method runs the flow. Note that the response of the LLM is in the JSON format, but it's not a hard constraint (it can hallucinate and return an invalid JSON):param input_message: The input data of the flow.:type input_message: FlowMessage"""input_data = input_message.dataif "goal" in input_data:self.flow_state["goal"] = input_data["goal"]else:input_data["goal"] = self.flow_state["goal"]api_output = self.query_llm(input_data)response = json.loads(api_output)reply = self._package_output_message(input_message=input_message,response=response)self.reply_to_message(reply = reply, to = input_message)
10 unmodified lines11121314151650 unmodified lines6768697071727374757610 unmodified linesinput_interface_initialized: # input_keys- "observation"######################################################## Output keys50 unmodified lineshuman_message_prompt_template:_target_: aiflows.prompt_template.JinjaPrompttemplate: |2-Here is the response to your last action:{{observation}}input_variables:- "observation"init_human_message_prompt_template:_target_: aiflows.prompt_template.JinjaPrompt10 unmodified lines1112131415161750 unmodified lines6869707172737475767778798010 unmodified linesinput_interface_initialized: # input_keys- "observation"- "goal"######################################################## Output keys50 unmodified lineshuman_message_prompt_template:_target_: aiflows.prompt_template.JinjaPrompttemplate: |2-Here is the goal you need to achieve:{{goal}}Here is the response to your last action:{{observation}}input_variables:- "observation"- "goal"init_human_message_prompt_template:_target_: aiflows.prompt_template.JinjaPrompt
3 unmodified lines45678955 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141153 unmodified linesfrom aiflows.utils import loggingfrom .ControllerAtomicFlow import ControllerAtomicFlowfrom aiflows.interfaces import KeyInterfacelogging.set_verbosity_debug()log = logging.get_logger(__name__)55 unmodified lines:param subflows: A list of subflows. Required when instantiating the subflow programmatically (it replaces subflows_config from flow_config)."""def _on_reach_max_round(self):""" This method is called when the flow reaches the maximum amount of rounds. It updates the state of the flow and starts the process of terminating the flow."""self._state_update_dict({"answer": "The maximum amount of rounds was reached before the model found an answer.","status": "unfinished"})def _single_round_controller_executor(self, reply: Dict[str,Any]) -> Dict[str,Any]:in_data = reply["executor_reply"]controller_reply = self.ask_subflow("Controller", in_data).get_data()if controller_reply["command"] == "finish":return {"EARLY_EXIT": True,"answer": controller_reply["command_args"]["answer"],"status": "finished"}executor_reply = {"observation": self.ask_subflow(controller_reply["command"], controller_reply["command_args"]).get_data()}return {"controller_reply": controller_reply,"executor_reply": executor_reply}def run(self,input_data):reply = {"executor_reply": input_data,"controller_reply": None}for round in range(self.flow_config["max_rounds"]):reply = self._single_round_controller_executor(reply)if reply.get("EARLY_EXIT",False):return replyself._on_reach_max_round()return {"EARLY_EXIT": False,"answer": reply["executor_reply"]["observation"],"status": "unfinished"}3 unmodified lines4567891055 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971983 unmodified linesfrom aiflows.utils import loggingfrom .ControllerAtomicFlow import ControllerAtomicFlowfrom aiflows.messages import FlowMessagefrom aiflows.interfaces import KeyInterfacelogging.set_verbosity_debug()log = logging.get_logger(__name__)55 unmodified lines:param subflows: A list of subflows. Required when instantiating the subflow programmatically (it replaces subflows_config from flow_config)."""def __init__(self,**kwargs):super().__init__(**kwargs)self.input_interface_controller = KeyInterface(keys_to_select = ["goal","observation"],)self.input_interface_first_round_controller = KeyInterface(keys_to_select = ["goal"],)self.reply_interface = KeyInterface(keys_to_select = ["answer","status", "EARLY_EXIT"],)self.next_flow_to_call = {None: "Controller","Controller": "Executor","Executor": "Controller"}def generate_reply(self):""" This method generates the reply of the flow. It's called when the flow is finished. """reply = self._package_output_message(input_message = self.flow_state["input_message"],response = self.reply_interface(self.flow_state))self.reply_to_message(reply,to=self.flow_state["input_message"])def get_next_flow_to_call(self):if self.flow_config["max_rounds"] is not None and self.flow_state["current_round"] >= self.flow_config["max_rounds"]:return Nonereturn self.next_flow_to_call[self.flow_state["last_called"]]def _on_reach_max_round(self):""" This method is called when the flow reaches the maximum amount of rounds. It updates the state of the flow and starts the process of terminating the flow."""self._state_update_dict({"EARLY_EXIT": False,"answer": "The maximum amount of rounds was reached before the model found an answer.","status": "unfinished"})def set_up_flow_state(self):super().set_up_flow_state()self.flow_state["last_called"] = Noneself.flow_state["current_round"] = 0def call_controller(self):#first_roundif self.flow_state["last_called"] is None:input_interface = self.input_interface_first_round_controllerelse:input_interface = self.input_interface_controllermessage = self._package_input_message(data = input_interface(self.flow_state),dst_flow = "Controller")self.subflows["Controller"].send_message_async(message, pipe_to= self.flow_config["flow_ref"])def call_executor(self):#detect and early exitif self.flow_state["command"] == "finish":self._state_update_dict({"EARLY_EXIT": True,"answer": self.flow_state["command_args"]["answer"],"status": "finished"})self.generate_reply()#call executorelse:executor_branch_to_call = self.flow_state["command"]message = self._package_input_message(data = self.flow_state["command_args"],dst_flow = executor_branch_to_call)self.subflows[executor_branch_to_call].send_message_async(message, pipe_to= self.flow_config["flow_ref"])def register_data_to_state(self, input_message):last_called = self.flow_state["last_called"]if last_called is None:self.flow_state["input_message"] = input_messageself.flow_state["goal"] = input_message.data["goal"]elif last_called == "Executor":self.flow_state["observation"] = input_message.dataelse:self._state_update_dict({"command": input_message.data["command"],"command_args": input_message.data["command_args"]})def run(self,input_message: FlowMessage):""" Runs the WikiSearch Atomic Flow. It's used to execute a Wikipedia search and get page summaries.:param input_message: The input message:type input_message: FlowMessage"""self.register_data_to_state(input_message)flow_to_call = self.get_next_flow_to_call()if flow_to_call == "Controller":self.flow_state["observation"] = input_message.dataself.call_controller()elif flow_to_call == "Executor":self.call_executor()self.flow_state["current_round"] += 1else:self._on_reach_max_round()self.generate_reply()self.flow_state["last_called"] = flow_to_call
14 unmodified lines1516171819202122235 unmodified lines29303132333414 unmodified linesname: "ControllerAtomicFlow"description: "A flow that calls other flows to solve a problem."_target_: flow_modules.aiflows.ControllerAtomicFlow.instantiate_from_default_configfinish:description: "Signal that the objective has been satisfied, and returns the answer to the user."input_args: ["answer"]# E.g.,# commands:# wiki_search:5 unmodified lines# wiki_search:# _target_: .WikiSearchAtomicFlow.instantiate_from_default_configearly_exit_key: "EARLY_EXIT"14 unmodified lines151617181920212223245 unmodified lines30313214 unmodified linesname: "ControllerAtomicFlow"description: "A flow that calls other flows to solve a problem."_target_: flow_modules.aiflows.ControllerAtomicFlow.instantiate_from_default_configcommands:finish:description: "Signal that the objective has been satisfied, and returns the answer to the user."input_args: ["answer"]# E.g.,# commands:# wiki_search:5 unmodified lines# wiki_search:# _target_: .WikiSearchAtomicFlow.instantiate_from_default_config
2 unmodified lines345678934 unmodified lines44454647484950515253545556575811 unmodified lines707172732 unmodified linesfrom typing import List, Dict, Optional, Anyfrom aiflows.base_flows import AtomicFlowfrom aiflows.utils import loggingfrom .wikipediaAPI import WikipediaAPIWrapper34 unmodified linessuper().__init__(**kwargs)def run(self,input_data: Dict[str, Any]) -> Dict[str, Any]:""" Runs the WikiSearch Atomic Flow. It's used to execute a Wikipedia search and get page summaries.:param input_data: The input data dictionary:type input_data: Dict[str, Any]:return: The output data dictionary:rtype: Dict[str, Any]"""# ~~~ Process input ~~~term = input_data.get("search_term", None)api_wrapper = WikipediaAPIWrapper(11 unmodified lines# Log the update to the flow messages listobservation = search_response["wiki_content"] if search_response["wiki_content"] else search_response["relevant_pages"]return {"wiki_content": observation}2 unmodified lines345678934 unmodified lines4445464748495051525354555611 unmodified lines686970717273747576772 unmodified linesfrom typing import List, Dict, Optional, Anyfrom aiflows.base_flows import AtomicFlowfrom aiflows.messages import FlowMessagefrom aiflows.utils import loggingfrom .wikipediaAPI import WikipediaAPIWrapper34 unmodified linessuper().__init__(**kwargs)def run(self,input_message: FlowMessage):""" Runs the WikiSearch Atomic Flow. It's used to execute a Wikipedia search and get page summaries.:param input_message: The input message:type input_message: FlowMessage"""input_data = input_message.data# ~~~ Process input ~~~term = input_data.get("search_term", None)api_wrapper = WikipediaAPIWrapper(11 unmodified lines# Log the update to the flow messages listobservation = search_response["wiki_content"] if search_response["wiki_content"] else search_response["relevant_pages"]reply = self._package_output_message(input_message = input_message,response = {"wiki_content": observation},)self.reply_to_message(reply=reply, to=input_message)
123456# ~~~ Specify the dependencies ~~~dependencies = [{"url": "aiflows/ChatFlowModule", "revision": "main"},]from aiflows import flow_verse123456# ~~~ Specify the dependencies ~~~dependencies = [{"url": "aiflows/ChatFlowModule", "revision": "coflows"},]from aiflows import flow_verse
8 unmodified lines910111213141516171819208 unmodified lineswiki_search:description: "Performs a search on Wikipedia."input_args: ["search_term"]ddg_search:description: "Query the search engine DuckDuckGo."input_args: ["query"]finish:description: "Signal that the objective has been satisfied, and returns the answer to the user."input_args: ["answer"]backend:_target_: aiflows.backends.llm_lite.LiteLLMBackendapi_infos: ???8 unmodified lines91011121314151617188 unmodified lineswiki_search:description: "Performs a search on Wikipedia."input_args: ["search_term"]# ddg_search:# description: "Query the search engine DuckDuckGo."# input_args: ["query"]backend:_target_: aiflows.backends.llm_lite.LiteLLMBackendapi_infos: ???
1235 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import osimport hydra5 unmodified linesfrom 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 KeyInterfaceCACHING_PARAMETERS.do_caching = False # Set to True in order to disable caching# clear_cache() # Uncomment this line to clear the cachelogging.set_verbosity_debug()from aiflows import flow_verse# ~~~ Load Flow dependecies from FlowVerse ~~~dependencies = [{"url": "aiflows/ControllerExecutorFlowModule", "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") )]FLOW_MODULES_PATH = "./"jwt = os.getenv("COLINK_JWT")addr = os.getenv("LOCAL_COLINK_ADDRESS")cl = serve_utils.start_colink_component("Reverse Number Demo",{"jwt": jwt, "addr": addr})# path_to_output_file = "output.jsonl" # Uncomment this line to save the output to diskroot_dir = "."cfg_path = os.path.join(root_dir, "demo.yaml")cfg = read_yaml_file(cfg_path)# put the API information in the configserve_utils.recursive_serve_flow(cl = cl,flow_type="ReAct_served",default_config=cfg,default_state=None,default_dispatch_point="coflows_dispatch",)#in case you haven't started the dispatch worker thread, uncomment#run_dispatch_worker_thread(cl, dispatch_point="coflows_dispatch", flow_modules_base_path=FLOW_MODULES_PATH)quick_load_api_keys(cfg, api_information, key="api_infos")# ~~~ Get the data ~~~# This can be a list of samples# data = {"id": 0, "goal": "Answer the following question: What is the population of Canada?"} # Uses wikipedia# data = {"id": 0, "goal": "Answer the following question: Who was the NBA champion in 2023?"}data = {"id": 0,"goal": "Answer the following question: What is the profession and date of birth of Michael Jordan?",}# ~~~ Run inference ~~~proxy_flow = serve_utils.recursive_mount(cl=cl,client_id="local",flow_type="ReAct_served",config_overrides=cfg,initial_state=None,dispatch_point_override=None,)# ~~~ Print the output ~~~input_message = FlowMessage(data= data,src_flow="Coflows team",dst_flow=proxy_flow,is_input_msg=True)future = proxy_flow.ask(input_message)print(future.get_data())123455 unmodified lines1112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""A simple script to run a Flow that can be used for development and debugging."""import osimport hydra5 unmodified linesfrom 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/ControllerExecutorFlowModule", "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_type="ControllerExecutorFlowModule",default_config=cfg,default_state=None,default_dispatch_point="coflows_dispatch")#4. ~~~~~Start A Worker Thread~~~~~run_dispatch_worker_thread(cl, dispatch_point="coflows_dispatch", flow_modules_base_path=FLOW_MODULES_PATH)#5. ~~~~~Mount the flow and get its proxy~~~~~~proxy_flow = serve_utils.recursive_mount(cl=cl,client_id="local",flow_type="ControllerExecutorFlowModule",config_overrides=None,initial_state=None,dispatch_point_override=None,)#6. ~~~ Get the data ~~~data = {"id": 0,"goal": "Answer the following question: What is the profession and date of birth of Michael Jordan?",}#option1: use the FlowMessage classinput_message = FlowMessage(data=data,)#option2: use the proxy_flow#input_message = proxy_flow._package_input_message(data = data)#7. ~~~ Run inference ~~~future = proxy_flow.send_message_blocking(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, "FlowModule")
ControllerAtomicFlow.py+22-8
ControllerAtomicFlow.yaml+4
ControllerExecutorFlow.py+118-35
ControllerExecutorFlow.yaml+4-6
WikiSearchAtomicFlow.py+12-8
__init__.py+1-1
demo.yaml+4-6
run.py+70-46