coflows - v1 (issues w/ state management here)
Browse filesFiles changed (4)
- ChromaDBFlow.py+10-7
- VectorStoreFlow.py+10-8
- demo.yaml+12-79
- run.py+123-73
5 unmodified lines678910111283 unmodified lines9697989910010110210310410510610710810934 unmodified lines1441451461475 unmodified linesfrom langchain.embeddings import OpenAIEmbeddingsfrom chromadb import Client as ChromaClientfrom aiflows.base_flows import AtomicFlowimport hydra83 unmodified lines"""return self.flow_config["output_keys"]def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:""" This method runs the flow. It runs the ChromaDBFlow. It either writes or reads memories from the database.:param input_data: The input data of the flow.:type input_data: Dict[str, Any]:return: The output data of the flow.:rtype: Dict[str, Any]"""api_information = self.backend.get_key()if api_information.backend_used == "openai":34 unmodified lines)response["retrieved"] = ""return response5 unmodified lines678910111283 unmodified lines9697989910010110210310410510610710834 unmodified lines1431441451461471481491505 unmodified linesfrom langchain.embeddings import OpenAIEmbeddingsfrom chromadb import Client as ChromaClientfrom aiflows.messages import FlowMessagefrom aiflows.base_flows import AtomicFlowimport hydra83 unmodified lines"""return self.flow_config["output_keys"]def run(self, input_message: FlowMessage):""" This method runs the flow. It runs the ChromaDBFlow. It either writes or reads memories from the database.:param input_message: The input message of the flow.:type input_message: FlowMessage"""input_data = input_message.dataapi_information = self.backend.get_key()if api_information.backend_used == "openai":34 unmodified lines)response["retrieved"] = ""reply = self._package_output_message(input_message = input_message,response = response)self.reply_to_message(reply = reply, to = input_message)
7 unmodified lines891011121314126 unmodified lines14114214314414514614714814915015115215315415515612 unmodified lines1691701711727 unmodified linesfrom langchain.schema import Documentfrom langchain.vectorstores import Chroma, FAISSfrom langchain.vectorstores.base import VectorStoreRetrieverfrom aiflows.base_flows import AtomicFlowimport hydra126 unmodified lines# TODO(yeeef): support metadatareturn [Document(page_content=doc, metadata={"": ""}) for doc in documents]def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:""" This method runs the flow. It either writes or reads memories from the database.:param input_data: The input data of the flow.:type input_data: Dict[str, Any]:return: The output data of the flow.:rtype: Dict[str, Any]"""response = {}operation = input_data["operation"]assert operation in ["write", "read"], f"Operation '{operation}' not supported"12 unmodified linesself.vector_db.add_documents(documents)response["retrieved"] = ""return response7 unmodified lines891011121314126 unmodified lines14114214314414514614714814915015115215315412 unmodified lines1671681691701711721731747 unmodified linesfrom langchain.schema import Documentfrom langchain.vectorstores import Chroma, FAISSfrom langchain.vectorstores.base import VectorStoreRetrieverfrom aiflows.messages import FlowMessagefrom aiflows.base_flows import AtomicFlowimport hydra126 unmodified lines# TODO(yeeef): support metadatareturn [Document(page_content=doc, metadata={"": ""}) for doc in documents]def run(self, input_message: FlowMessage):""" This method runs the flow. It either writes or reads memories from the database.:param input_message: The input data of the flow.:type input_message: FlowMessage"""response = {}input_data = input_message.dataoperation = input_data["operation"]assert operation in ["write", "read"], f"Operation '{operation}' not supported"12 unmodified linesself.vector_db.add_documents(documents)response["retrieved"] = ""reply = self._package_output_message(input_message = input_message,response = response)self.reply_to_message(reply = reply, to = input_message)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485chroma_demo_flow:input_interface:- "operation"- "content"output_interface:- "retrieved"_target_: aiflows.base_flows.SequentialFlow.instantiate_from_default_configname: "demoChromaDBFlow"description: "An example flow of how to read and writed in a ChromaDBFlowModule."subflows_config:chroma_db:input_interface:_target_: aiflows.interfaces.KeyInterfacekeys_to_select: ["operation","content"]_target_: flow_modules.aiflows.VectorStoreFlowModule.ChromaDBFlow.instantiate_from_default_configbackend:_target_: aiflows.backends.llm_lite.LiteLLMBackendapi_infos: ???model_name: "" #Not used in current implementationn_results: 1 # number of results to retrieve when querytopology:- goal: Write content to the ChromaDBinput_interface:_target_: aiflows.interfaces.KeyInterfacekeys_to_select: ["operation","content"]flow: chroma_dboutput_interface:_target_: aiflows.interfaces.KeyInterfacekeys_to_set:operation: "read"keys_to_rename:retrieved: contentkeys_to_select: ["operation","content"]- goal: Read content from the ChromaDBinput_interface:_target_: aiflows.interfaces.KeyInterfacekeys_to_select: ["operation","content"]flow: chroma_dboutput_interface:_target_: aiflows.interfaces.KeyInterfacekeys_to_select: ["retrieved"]vector_store_demo_flow:input_interface:- "operation"- "content"output_interface:- "retrieved"name: "demoVectorStoreFlow"description: "An example flow of how to read and write in a VectorStoreFlowModule."_target_: aiflows.base_flows.SequentialFlow.instantiate_from_default_configsubflows_config:vs_db:_target_: flow_modules.aiflows.VectorStoreFlowModule.VectorStoreFlow.instantiate_from_default_configbackend:_target_: aiflows.backends.llm_lite.LiteLLMBackendapi_infos: ???model_name: "" #Not used in current implementationtopology:- goal: Write content to the VectorStoreinput_interface:_target_: aiflows.interfaces.KeyInterfacekeys_to_select: ["operation","content"]flow: vs_dboutput_interface:_target_: aiflows.interfaces.KeyInterfacekeys_to_set:operation: "read"keys_to_rename:retrieved: contentkeys_to_select: ["operation","content"]- goal: Read content from the VectorStoreinput_interface:_target_: aiflows.interfaces.KeyInterfacekeys_to_select: ["operation","content"]flow: vs_dboutput_interface:_target_: aiflows.interfaces.KeyInterfacekeys_to_select: ["retrieved"]123456789101112131415161718chroma_demo_flow:_target_: flow_modules.aiflows.VectorStoreFlowModule.ChromaDBFlow.instantiate_from_default_configbackend:_target_: aiflows.backends.llm_lite.LiteLLMBackendapi_infos: ???model_name: "" #Not used in current implementationn_results: 1 # number of results to retrieve when queryvector_store_demo_flow:_target_: flow_modules.aiflows.VectorStoreFlowModule.VectorStoreFlow.instantiate_from_default_configbackend:_target_: aiflows.backends.llm_lite.LiteLLMBackendapi_infos: ???model_name: "" #Not used in current implementation
1231 unmodified line56789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import os1 unmodified lineimport aiflowsfrom aiflows.flow_launchers import FlowLauncherfrom aiflows.utils.general_helpers import read_yaml_filefrom aiflows.backends.api_info import ApiInfofrom aiflows import loggingfrom aiflows.flow_cache import CACHING_PARAMETERS, clear_cacheCACHING_PARAMETERS.do_caching = False # Set to True to enable caching# clear_cache() # Uncomment this line to clear the cachelogging.set_verbosity_debug()dependencies = [{"url": "aiflows/VectorStoreFlowModule", "revision": os.getcwd()},]from aiflows import flow_verseflow_verse.sync_dependencies(dependencies)if __name__ == "__main__":# 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["vector_store_demo_flow"]["subflows_config"]["vs_db"]["backend"]["api_infos"] = api_informationcfg["chroma_demo_flow"]["subflows_config"]["chroma_db"]["backend"]["api_infos"] = api_information# ~~~ Get the data ~~~# This can be a list of samplesdata = {"id": 0, "operation": "write", "content": "demo of writing"} # Add your data here# ~~~ Run inference ~~~path_to_output_file = None# path_to_output_file = "output.jsonl" # Uncomment this line to save the output to disk#### CHROMA DEMO ####### DUMBY DEMO OF WRITING "demo of writing" AND READIN "" (Nothing)###print("DEMO: ChromaDBFlow")flow_with_interfaces_chroma = {"flow": hydra.utils.instantiate(cfg['chroma_demo_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)),}_, outputs = FlowLauncher.launch(flow_with_interfaces=flow_with_interfaces_chroma,data=data,path_to_output_file=path_to_output_file,)# ~~~ Print the output ~~~flow_output_data = outputs[0]print(flow_output_data)#### END CHROM DEMO ######## VECTOR STORE DEMO ####print("DEMO: VECTOR STORE DEMO")flow_with_interfaces_vstore = {"flow": hydra.utils.instantiate(cfg['vector_store_demo_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)),}_, outputs = FlowLauncher.launch(flow_with_interfaces=flow_with_interfaces_vstore,data=data,path_to_output_file=path_to_output_file,)# ~~~ Print the output ~~~flow_output_data = outputs[0]print(flow_output_data)12341 unmodified line6789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158"""A simple script to run a Flow that can be used for development and debugging."""import os1 unmodified lineimport aiflowsfrom aiflows.flow_launchers import FlowLauncherfrom 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/VectorStoreFlowModule", "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="ChromaDBFlowModule",default_config=cfg["chroma_demo_flow"],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_cdb = serve_utils.recursive_mount(cl=cl,client_id="local",flow_type="ChromaDBFlowModule",config_overrides=None,initial_state=None,dispatch_point_override=None,)#3.(2) ~~~~ Serve The Flow ~~~~serve_utils.recursive_serve_flow(cl = cl,flow_type="VectoreStoreFlowModule",default_config=cfg["vector_store_demo_flow"],default_state=None,default_dispatch_point="coflows_dispatch")#4.(2) ~~~~~Start A Worker Thread~~~~~run_dispatch_worker_thread(cl, dispatch_point="coflows_dispatch", flow_modules_base_path=FLOW_MODULES_PATH)#5.(2) ~~~~~Mount the flow and get its proxy~~~~~~proxy_flow_vs = serve_utils.recursive_mount(cl=cl,client_id="local",flow_type="VectoreStoreFlowModule",config_overrides=None,initial_state=None,dispatch_point_override=None,)#6. ~~~ Get the data ~~~data_write = {"id": 0, "operation": "write", "content": "The capital of Switzerland is Bern"} # Add your data heredata_read = {"id": 1, "operation": "read", "content": "Capital of Switzerland"} # Add your data here#option1: use the FlowMessage classinput_message_write = FlowMessage(data=data_write,)input_message_read = FlowMessage(data=data_read)#option2: use the proxy_flow#input_message = proxy_flow._package_input_message(data = data)#7. ~~~ Run inference ~~~print("##########CHROMA DB DEMO###############")#write to DBproxy_flow_cdb.send_message_async(input_message_write)#read from DBfuture = proxy_flow_cdb.send_message_blocking(input_message_read)#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)print("##########VECTOR STORE DEMO###############")#write to DBproxy_flow_vs.send_message_async(input_message_write)#read from DBfuture = proxy_flow_vs.send_message_blocking(input_message_read)#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")
ChromaDBFlow.py+10-7
VectorStoreFlow.py+10-8
demo.yaml+12-79
run.py+123-73