readme and demo
Browse filesFiles changed (8)
- .gitignore+443-1
- ChatWithDemonstrationsFlow.py+34
- ChatWithDemonstrationsFlow.yaml+8-1
- DemonstrationsAtomicFlow.py+100-1
- README.mdDeleted-3
- __init__.py+1-1
- demo.yamlAdded+76
- run.pyAdded+76
1__pycache__/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443# Created by https://www.toptal.com/developers/gitignore/api/python,java,c++,pycharm,visualstudiocode,macos,linux,windows# Edit at https://www.toptal.com/developers/gitignore?templates=python,java,c++,pycharm,visualstudiocode,macos,linux,windows### C++ #### Prerequisites*.d# Compiled Object files*.slo*.lo*.o*.obj# Precompiled Headers*.gch*.pch# Compiled Dynamic libraries*.so*.dylib*.dll# Fortran module files*.mod*.smod# Compiled Static libraries*.lai*.la*.a*.lib# Executables*.exe*.out*.app### Java #### Compiled class file*.class# Log file*.log# BlueJ files*.ctxt# Mobile Tools for Java (J2ME).mtj.tmp/# Package Files #*.jar*.war*.nar*.ear*.zip*.tar.gz*.rar# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xmlhs_err_pid*replay_pid*### Linux ###*~# temporary files which can be created if a process still has a handle open of a deleted file.fuse_hidden*# KDE directory preferences.directory# Linux trash folder which might appear on any partition or disk.Trash-*# .nfs files are created when an open file is removed but is still being accessed.nfs*### macOS #### General.DS_Store.AppleDouble.LSOverride# Icon must end with two \rIcon# Thumbnails._*# Files that might appear in the root of a volume.DocumentRevisions-V100.fseventsd.Spotlight-V100.TemporaryItems.Trashes.VolumeIcon.icns.com.apple.timemachine.donotpresent# Directories potentially created on remote AFP share.AppleDB.AppleDesktopNetwork Trash FolderTemporary Items.apdisk### macOS Patch #### iCloud generated files*.icloud### PyCharm #### Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839# User-specific stuff.idea/**/workspace.xml.idea/**/tasks.xml.idea/**/usage.statistics.xml.idea/**/dictionaries.idea/**/shelf# AWS User-specific.idea/**/aws.xml# Generated files.idea/**/contentModel.xml# Sensitive or high-churn files.idea/**/dataSources/.idea/**/dataSources.ids.idea/**/dataSources.local.xml.idea/**/sqlDataSources.xml.idea/**/dynamic.xml.idea/**/uiDesigner.xml.idea/**/dbnavigator.xml# Gradle.idea/**/gradle.xml.idea/**/libraries# Gradle and Maven with auto-import# When using Gradle or Maven with auto-import, you should exclude module files,# since they will be recreated, and may cause churn. Uncomment if using# auto-import.# .idea/artifacts# .idea/compiler.xml# .idea/jarRepositories.xml# .idea/modules.xml# .idea/*.iml# .idea/modules# *.iml# *.ipr# CMakecmake-build-*/# Mongo Explorer plugin.idea/**/mongoSettings.xml# File-based project format*.iws# IntelliJout/# mpeltonen/sbt-idea plugin.idea_modules/# JIRA pluginatlassian-ide-plugin.xml# Cursive Clojure plugin.idea/replstate.xml# SonarLint plugin.idea/sonarlint/# Crashlytics plugin (for Android Studio and IntelliJ)com_crashlytics_export_strings.xmlcrashlytics.propertiescrashlytics-build.propertiesfabric.properties# Editor-based Rest Client.idea/httpRequests# Android studio 3.1+ serialized cache file.idea/caches/build_file_checksums.ser### PyCharm Patch #### Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721# *.iml# modules.xml# .idea/misc.xml# *.ipr# Sonarlint plugin# https://plugins.jetbrains.com/plugin/7973-sonarlint.idea/**/sonarlint/# SonarQube Plugin# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin.idea/**/sonarIssues.xml# Markdown Navigator plugin# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced.idea/**/markdown-navigator.xml.idea/**/markdown-navigator-enh.xml.idea/**/markdown-navigator/# Cache file creation bug# See https://youtrack.jetbrains.com/issue/JBR-2257.idea/$CACHE_FILE$# CodeStream plugin# https://plugins.jetbrains.com/plugin/12206-codestream.idea/codestream.xml# Azure Toolkit for IntelliJ plugin# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij.idea/**/azureSettings.xml### Python #### Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class# C extensions# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec# Installer logspip-log.txtpip-delete-this-directory.txt# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/cover/# Translations*.mo*.pot# Django stuff:local_settings.pydb.sqlite3db.sqlite3-journal# Flask stuff:instance/.webassets-cache# Scrapy stuff:.scrapy# Sphinx documentationdocs/_build/# PyBuilder.pybuilder/target/# Jupyter Notebook.ipynb_checkpoints# IPythonprofile_default/ipython_config.py# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control#poetry.lock# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.#pdm.lock# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it# in version control.# https://pdm.fming.dev/#use-with-ide.pdm.toml# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/# Celery stuffcelerybeat-schedulecelerybeat.pid# SageMath parsed files*.sage.py# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/# Spyder project settings.spyderproject.spyproject# Rope project settings.ropeproject# mkdocs documentation/site# mypy.mypy_cache/.dmypy.jsondmypy.json# Pyre type checker.pyre/# pytype static type analyzer.pytype/# Cython debug symbolscython_debug/# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.#.idea/### Python Patch #### Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configurationpoetry.toml# ruff.ruff_cache/# LSP config filespyrightconfig.json### VisualStudioCode ###.vscode/*!.vscode/settings.json!.vscode/tasks.json!.vscode/launch.json!.vscode/extensions.json!.vscode/*.code-snippets# Local History for Visual Studio Code.history/# Built Visual Studio Code Extensions*.vsix### VisualStudioCode Patch #### Ignore all local history of files.history.ionide### Windows #### Windows thumbnail cache filesThumbs.dbThumbs.db:encryptableehthumbs.dbehthumbs_vista.db# Dump file*.stackdump# Folder config file[Dd]esktop.ini# Recycle Bin used on file shares$RECYCLE.BIN/# Windows Installer files*.cab*.msi*.msix*.msm*.msp# Windows shortcuts*.lnk# End of https://www.toptal.com/developers/gitignore/api/python,java,c++,pycharm,visualstudiocode,macos,linux,windows.*flow_modules/
8 unmodified lines9101112138 unmodified linesclass ChatWithDemonstrationsFlow(SequentialFlow):def __init__(self,**kwargs):super().__init__(**kwargs)8 unmodified lines910111213141516171819202122232425262728293031323334353637383940414243444546478 unmodified linesclass 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.It Contains the following subflows:- A Demonstration Flow: It is a flow that passes demonstrations to the ChatFlow- A Chat Flow: It is a flow that uses the demonstrations to answer queries asked by the user/human.An illustration of the flow is as follows:-------> Demonstration Flow -------> Chat Flow ------->*Configuration Parameters*:- `name` (str): The name of the flow. Default: "ChatAtomic_Flow_with_Demonstrations"- `description` (str): A description of the flow. This description is used to generate the help message of the flow.Default: "A sequential flow that answers questions with demonstrations"- `subflows_config` (Dict[str,Any]): A dictionary of subflows configurations of the sequential Flow. Default:- `Demonstration Flow`: The configuration of the Demonstration Flow. By default, it a DemonstrationsAtomicFlow.Its default parmaters are defined in DemonstrationsAtomicFlow).- `Chat Flow`: The configuration of the Chat Flow. By default, its a ChatAtomicFlow.Its default parmaters are defined in ChatAtomicFlowModule (see Flowcard, i.e. README.md, of ChatAtomicFlowModule).- `topology` (str): The topology of the flow which is "sequential". By default, the topology is the one shown in theillustration above (the topology is also described in ChatWithDemonstrationsFlow.yaml).*Input Interface*:- `query` (str): A query asked to the flow (e.g. "What is the capital of France?")Output Interface:- `answer` (str): The answer of the flow to the query:param \**kwargs: Arguments to be passed to the parent class SequentialFlow constructor."""def __init__(self,**kwargs):super().__init__(**kwargs)
5 unmodified lines678910111211 unmodified lines2425265 unmodified lines_target_: aiflows.ChatWithDemonstrationsFlowModule.DemonstrationsAtomicFlow.instantiate_from_default_configchat_flow:_target_: aiflows.OpenAIChatFlowModule.OpenAIChatAtomicFlow.instantiate_from_default_configtopology:- goal: Get Demonstrations11 unmodified lines_target_: flows.interfaces.KeyInterfacekeys_to_rename:api_output: answer # Rename the api_output to answer5 unmodified lines678910111211 unmodified lines242526272829303132335 unmodified lines_target_: aiflows.ChatWithDemonstrationsFlowModule.DemonstrationsAtomicFlow.instantiate_from_default_configchat_flow:_target_: aiflows.ChatFlowModule.ChatAtomicFlow.instantiate_from_default_configtopology:- goal: Get Demonstrations11 unmodified lines_target_: flows.interfaces.KeyInterfacekeys_to_rename:api_output: answer # Rename the api_output to answerinput_interface_initialized:- "query"output_interface:- "answer"
4 unmodified lines567891011121314151614 unmodified lines3132333435363 unmodified lines4041424344456 unmodified lines52535455565758596061626364655 unmodified lines71727374757677787980819 unmodified lines919293944 unmodified linesfrom typing import Dict,Any,Optional,Listfrom flows.prompt_template import JinjaPromptfrom copy import deepcopyimport numpy as npimport osimport hydralog = logging.get_logger(__name__)class DemonstrationsAtomicFlow(AtomicFlow):demonstrations_k: Optional[int] = Nonequery_prompt_template: JinjaPromptresponse_prompt_template: JinjaPrompt14 unmodified lines@classmethoddef _set_up_prompts(cls, config):kwargs = {}kwargs["query_prompt_template"] = \hydra.utils.instantiate(config['query_prompt_template'], _convert_="partial")3 unmodified lines@classmethoddef instantiate_from_config(cls, config):flow_config = deepcopy(config)kwargs = {"flow_config": flow_config}6 unmodified linesreturn cls(**kwargs)def _get_query_message_content(self, sample_data: Dict):input_variables = self.query_prompt_template.input_variablesreturn self.query_prompt_template.format(**{k: sample_data[k] for k in input_variables})def _get_response_message_content(self, sample_data: Dict):input_variables = self.response_prompt_template.input_variablesreturn self.response_prompt_template.format(**{k: sample_data[k] for k in input_variables})def _get_io_pair(self, idx):dp = self.data[idx]query_data = dp["query_data"]5 unmodified linesreturn {"idx": idx, "query": query,"response": response}def _get_io_pairs(self,input_data: Dict[str, Any]) -> List[Any]:demonstrations_k = self.demonstrations_k if self.demonstrations_k is not None else len(self.data)io_pairs = [self._get_io_pair(idx) for idx in range(demonstrations_k)]return io_pairsdef _load_data(self):demonstrations_file = os.path.join(self.params["data_dir"], f"{self.params['demonstrations_id']}.jsonl")self.data = general_helpers.read_jsonlines(demonstrations_file)9 unmodified linesdef run(self,input_data: Dict[str, Any]) -> Dict[str, Any]:return {**input_data,**{"demonstrations": self._get_io_pairs(input_data=input_data)}}4 unmodified lines56789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646514 unmodified lines808182838485868788899091923 unmodified lines969798991001011021031041051061071086 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481495 unmodified lines1551561571581591601611621631641651661671681691701711721739 unmodified lines1831841851861871881891901911921934 unmodified linesfrom typing import Dict,Any,Optional,Listfrom flows.prompt_template import JinjaPromptfrom copy import deepcopyimport osimport hydralog = logging.get_logger(__name__)class DemonstrationsAtomicFlow(AtomicFlow):""" This class implements a Demonstrations Atomic Flow. It is a flow which is usually used to pass demonstrations (of user assistant interactions)to the ChatAtomicFlow.*Configuration Parameters*:- `name` (str): The name of the flow. Default: "DemonstrationsAtomicFlow"- `description` (str): A description of the flow. This description is used to generate the help message of the flow.Default: "A flow that passes demonstrations to the ChatFlow"- `data` (List[Dict[str, Any]]): The data of the demonstrations.If data is None, the data is loaded from the file specified in the params["data_dir"].Default: No default value this field must be set.- `params` (Dict[str, Any]): The parameters specific to the dataset of the demonstrations. Its default parameters are:- `data_dir` (str): The directory where the demonstrations are stored. If the data is not directly passed to the flow through `data` thenthe data is loaded from this directory. Default: No default value this field must be set.- `demonstrations_id` (str): The id of the demonstrations (name of the data file). If the data is not directly passed to the flow through `data` thenthe data is loaded from this file. Default: No default value this field must be set.- `demonstrations_k` (int): The number of demonstrations to pass to the ChatFlow.If None, all the demonstrations are passed to the ChatFlow. Default: None- `query_prompt_template` (Dict[str, Any]): The prompt template used to generate the query of the demonstrations.By default its of type flows.prompt_template.JinjaPrompt. None of the parameters of the prompt are defined by default and therefore need to be defined if onewants to use the query_prompt_template. Default parameters are defined in flows.prompt_template.jinja2_prompts.JinjaPrompt.- `response_prompt_template` (Dict[str, Any]): The prompt template used to generate the response of the demonstrations. By default its of type flows.prompt_template.JinjaPrompt.None of the parameters of the prompt are defined by default and therefore need to be defined if onewants to use the response_prompt_template. Default parameters are defined in flows.prompt_template.jinja2_prompts.JinjaPrompt.*Input Interface*:- The input interface expected by its successor flow (e.g. typically ChatAtomicFlow so the input interface is the one expected by ChatAtomicFlow)*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 demonstration- response (str): The response of the demonstration:param params: The parameters specific to the dataset of the demonstrations. It must sould contain the following keys:- 'data_dir' (str): The directory where the demonstrations are stored. This field is used if the data is not directly passed to the flow through the 'data' field.- 'demonstrations_id' (str): The id of the demonstrations (name of the data file). This field is used if the data is not directly passed to the flow through the 'data' field.- 'demonstrations_k' (int): The number of demonstrations to pass to the ChatFlow. If None, all the demonstrations are passed to the ChatFlow.- 'ids_to_keep' (Optional[Union[str, List[str]]]): The ids of the demonstrations to keep. If None, all the demonstrations are kept.:type params: Dict[str, Any]:param query_prompt_template: The prompt template used to generate the query of the demonstrations.:type query_prompt_template: JinjaPrompt:param response_prompt_template: The prompt template used to generate the response of the demonstrations.:type response_prompt_template: JinjaPrompt:param data: The data of the demonstrations. If None, the data is loaded from the file specified in the params.:type data: Optional[List[Dict[str, Any]]]"""demonstrations_k: Optional[int] = Nonequery_prompt_template: JinjaPromptresponse_prompt_template: JinjaPrompt14 unmodified lines@classmethoddef _set_up_prompts(cls, config):""" This method instantiates the prompt templates of the flow (used when instantiating the flow from a config file):param config: The configuration of the flow.:type config: Dict[str, Any]:return: A dictionary of keyword arguments to pass to the constructor of the flow.:rtype: Dict[str, Any]"""kwargs = {}kwargs["query_prompt_template"] = \hydra.utils.instantiate(config['query_prompt_template'], _convert_="partial")3 unmodified lines@classmethoddef instantiate_from_config(cls, config):""" This method instantiates the flow from a config file.:param config: The configuration of the flow.:type config: Dict[str, Any]:return: The instantiated flow.:rtype: Flow"""flow_config = deepcopy(config)kwargs = {"flow_config": flow_config}6 unmodified linesreturn cls(**kwargs)def _get_query_message_content(self, sample_data: Dict):""" This method returns the query message content of a demonstration given the sample data (by rendering the query prompt template).:param sample_data: The sample data of the demonstration.:type sample_data: Dict[str, Any]:return: The query message content of the demonstration.:rtype: str"""input_variables = self.query_prompt_template.input_variablesreturn self.query_prompt_template.format(**{k: sample_data[k] for k in input_variables})def _get_response_message_content(self, sample_data: Dict):""" This method returns the response message content of a demonstration given the sample data (by rendering the response prompt template).:param sample_data: The sample data of the demonstration.:type sample_data: Dict[str, Any]:return: The response message content of the demonstration.:rtype: str"""input_variables = self.response_prompt_template.input_variablesreturn self.response_prompt_template.format(**{k: sample_data[k] for k in input_variables})def _get_io_pair(self, idx):""" This method, given the index of a demonstration, returns an query-response pair from the demonstrations data.:param idx: The index of the demonstration.:type idx: int:return: The query-response pair at idx from the demonstrations data.:rtype: Dict[str, Any]"""dp = self.data[idx]query_data = dp["query_data"]5 unmodified linesreturn {"idx": idx, "query": query,"response": response}def _get_io_pairs(self,input_data: Dict[str, Any]) -> List[Any]:""" This method returns the demonstrations that are passed to the destination flow (typically ChatAtomicFlow).:param input_data: The input data of the flow.:type input_data: Dict[str, Any]:return: The demonstrations that are passed to the destination flow.:rtype: List[Any]"""demonstrations_k = self.demonstrations_k if self.demonstrations_k is not None else len(self.data)io_pairs = [self._get_io_pair(idx) for idx in range(demonstrations_k)]return io_pairsdef _load_data(self):""" This method loads the demonstrations from the file specified in the params. It also filters the demonstrations if the ids_to_keep parameter is specified."""demonstrations_file = os.path.join(self.params["data_dir"], f"{self.params['demonstrations_id']}.jsonl")self.data = general_helpers.read_jsonlines(demonstrations_file)9 unmodified linesdef 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)}}
123---license: mit---123456# ~~~ Specify the dependencies ~~dependencies = [{"url": "aiflows/OpenAIChatFlowModule", "revision": "d69ba2125de99d2edb631dd51d22225ed9e3446c"},]from flows import flow_verseflow_verse.sync_dependencies(dependencies)123456# ~~~ Specify the dependencies ~~dependencies = [{"url": "aiflows/ChatFlowModule", "revision": "a749ad10ed39776ba6721c37d0dc22af49ca0f17"},]from flows import flow_verseflow_verse.sync_dependencies(dependencies)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576flow: # Overrides the OpenAIChatAtomicFlow config _target_: aiflows.ChatWithDemonstrationsFlowModule.ChatWithDemonstrationsFlow.instantiate_from_default_config name: "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: null demonstrations_id: my_sir_demo query_prompt_template: template: |2- Answer the following question: {{query}} input_variables: - "query" response_prompt_template: template: |2- {{response}} input_variables: - response
chat_flow: name: "SimpleQA_Flow" # ~~~ Input interface specification ~~~ input_interface_non_initialized: - "question"
# ~~~ backend model parameters ~~ backend: _target_: flows.backends.llm_lite.LiteLLMBackend api_infos: ??? model_name: openai: "gpt-3.5-turbo" azure: "azure/gpt-4" # ~~~ generation_parameters ~~ n: 1 max_tokens: 3000 temperature: 0.3
top_p: 0.2 frequency_penalty: 0 presence_penalty: 0
n_api_retries: 6 wait_time_between_retries: 20
# ~~~ Prompt specification ~~~ system_message_prompt_template: _target_: flows.prompt_template.JinjaPrompt template: |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_: flows.prompt_template.JinjaPrompt template: |2- Answer the following question: {{question}} input_variables: ["question"] partial_variables: {}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import os
import hydra
import flowsfrom flows.flow_launchers import FlowLauncherfrom flows.backends.api_info import ApiInfofrom flows.utils.general_helpers import read_yaml_file
from flows import loggingfrom flows.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() # Uncomment this line to see verbose logs
from flows import flow_verse
dependencies = [ {"url": "aiflows/ChatWithDemonstrationsFlowModule", "revision": os.getcwd()},]
flow_verse.sync_dependencies(dependencies)
if __name__ == "__main__": # ~~~ Set the API information ~~~ # OpenAI backend
api_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": ( None if cfg.get( "input_interface", None) is None else hydra.utils.instantiate(cfg['input_interface'], _recursive_=False) ), "output_interface": ( None if cfg.get( "output_interface", None) is None else 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).gitignore+443-1
ChatWithDemonstrationsFlow.py+34
ChatWithDemonstrationsFlow.yaml+8-1
DemonstrationsAtomicFlow.py+100-1
README.mdDeleted-3
__init__.py+1-1
demo.yamlAdded+76
run.pyAdded+76