Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.
Python aiburrchatbot-frameworkdagsgenerative-aigraphshacktoberfestllmopsllmsmlopspersistent-data-structurestate-machinestate-managementvisibility
Makes examples simple + adds docs
elijahbenizzye05f9df800a9
diff --git a/docs/getting_started/install.rst b/docs/getting_started/install.rstindex 547afc82..d2ae8783 100644--- a/docs/getting_started/install.rst+++ b/docs/getting_started/install.rst@@ -2,24 +2,13 @@Installing==========-Burr requires almost no dependencies. Every "extra"/"plugin" is an additional install target.+Burr itself requires almost no dependencies. Every "extra"/"plugin" is an additional install target.-.. code-block:: bash-- pip install burr--To get visualization capabilities, you can install the `burr[graphviz]` extra:--.. code-block:: bash-- pip install burr[graphviz]--And to visualize your state machines on streamlit, you can install the `burr[streamlit]` extra:+We recommend you start with installing the ``learn`` target -- this has dependencies necessary to track burr through the UI,+along with a fully built server... code-block:: bash- pip install burr[streamlit]--Don't worry, you can always install these extras later if you need them.+ pip install burr[learn]-Note, if you're using ``zsh``, you'll need to add quotes around the install target, like `pip install "burr[graphviz]"`.+This will give you tools to visualize, track, and interact with the UI. Note, if you're using ``zsh``, you'll need to add quotes around the install target, (``pip install "burr[learn]"``).diff --git a/docs/getting_started/simple-example.rst b/docs/getting_started/simple-example.rstindex af2b091e..0a7544b6 100644--- a/docs/getting_started/simple-example.rst+++ b/docs/getting_started/simple-example.rst@@ -55,6 +55,7 @@ Next, let's put together our application. To do this, we'll use an ``Application("count", "count", expr("counter < 10")), # Keep counting if the counter is less than 10("count", "done", default) # Otherwise, we're done).with_entrypoint("count") # we have to start somewhere+ .with_tracker("my_first_app").build())@@ -123,10 +124,11 @@ If you want to copy/paste, you can open up the following code block and add to a("count", "count", expr("counter < 10")), # Keep counting if the counter is less than 10("count", "done", default) # Otherwise, we're done).with_entrypoint("count") # we have to start somewhere+ .with_tracker("my_first_app").build())app.visualize("./graph", format="png", include_conditions=True, include_state=True)- app.run(halt_after=["printer"])+ app.run(halt_after=["done"])And the output looks exactly as we expect!@@ -147,5 +149,13 @@ And the output looks exactly as we expect!counted to 10Bob's your uncle+Finally, let's open up the UI and see what it looks like (not that if you have not installed ``burr[learn]`` now is a good time...).++.. code-block:: bash++ burr++You'll see the UI pop up with projects. Navigate to `the UI <http://localhost:7241/project/my_first_app>`_ and explore!+All this to increment? Well, if all you want to do is count to 10, this might not be for you. But we imagine most of you want to do more exciting thingsthan count to 10...diff --git a/docs/getting_started/up-next.rst b/docs/getting_started/up-next.rstindex 7d3fca71..bd807ab0 100644--- a/docs/getting_started/up-next.rst+++ b/docs/getting_started/up-next.rst@@ -2,8 +2,57 @@Next Steps=================-You've written your own burr application in a few lines of code. Nice work! Let's outline a few of the capabilities-of the Burr library and where you can go to learn more about them.+You've written your own burr application in a few lines of code. Nice work! Let's look at some more powerful examples.+Note you'll need the repository cloned to run these -- you can also explore the results without running them in the UI -- it is pre+populated with sample runs.++----------+More demos+----------++Streamlit chatbot ``demo:chatbot``+------------------------------------++You'll need the env variable ``OPENAI_API_KEY`` set to your api key for this to work.++We recommend you keep the app (terminal or streamlit) open in one window while+watching the tracker in the other window. You'll see some interesting things!++.. code-block:: bash++ cd examples/gpt+ pip install -r requirements.txt+ streamlit run streamlit_app.py++Simple Counter ``demo:counter``+-------------------------------++This is just a single terminal command:++.. code-block:: bash++ cd examples/counter+ python application.py++Interactive RAG ``demo:conversational-rag``+-------------------------------------------++This is a toy interactive RAG example. You'll ask questions in the terminal about information it already has...++.. code-block:: bash++ cd examples/conversational_rag+ pip install -r requirements.txt+ python application.py++----------------------+Understanding Concepts+----------------------++If you're more comfortable learning through concepts start here.++Once you're comfortable with the UI, you may want to get a sense of a few of the capabilities+of the Burr library and where you can go to learn more about them:- :ref:`Creating custom actions <actions>` and calling out to integrated frameworks- :ref:`Running applications <applications>`, managing their lifeycyle, and inspecting the resultsdiff --git a/examples/conversational_rag/application.py b/examples/conversational_rag/application.pynew file mode 100644index 00000000..b768ce41--- /dev/null+++ b/examples/conversational_rag/application.py@@ -0,0 +1,128 @@+import pprint+from typing import List, Optional, Tuple++from hamilton import dataflows, driver, lifecycle++import burr.core+from burr.core import Action, Application, ApplicationBuilder, State, default, expr+from burr.core.action import action+from burr.lifecycle import LifecycleAdapter, PostRunStepHook, PreRunStepHook++conversational_rag = dataflows.import_module("conversational_rag")+conversational_rag_driver = (+ driver.Builder()+ .with_config({}) # replace with configuration as appropriate+ .with_modules(conversational_rag)+ .build()+)+++class PrintStepHook(PostRunStepHook, PreRunStepHook):+ """Custom hook to print the action/result after each step."""++ def pre_run_step(self, action: Action, **future_kwargs):+ if action.name == "ai_converse":+ print("🤔 AI is thinking...")+ if action.name == "human_converse":+ print("⏳Processing input from user...")++ def post_run_step(self, *, state: "State", action: Action, result: dict, **future_kwargs):+ if action.name == "ai_converse":+ print("💬", result["conversational_rag_response"], "\n")+++@action(+ reads=["input_texts", "question", "chat_history"],+ writes=["chat_history"],+)+def ai_converse(state: State) -> Tuple[dict, State]:+ """AI conversing step. This calls out to an API on the Hamilton hub (hub.dagworks.io)+ to do basic RAG"""+ result = conversational_rag_driver.execute(+ ["conversational_rag_response"],+ inputs={+ "input_texts": state["input_texts"],+ "question": state["question"],+ "chat_history": state["chat_history"],+ },+ )+ new_history = f"AI: {result['conversational_rag_response']}"+ return result, state.append(chat_history=new_history)+++@action(+ reads=[],+ writes=["question", "chat_history"],+)+def human_converse(state: State, user_question: str) -> Tuple[dict, State]:+ """Human converse step -- this simply massages the state to be the right shape"""+ state = state.update(question=user_question).append(chat_history=f"Human: {user_question}")+ return {"question": user_question}, state+++def application(+ app_id: Optional[str] = None,+ storage_dir: Optional[str] = "~/.burr",+ hooks: Optional[List[LifecycleAdapter]] = None,+) -> Application:+ app = (+ ApplicationBuilder()+ .with_state(+ **{+ "input_texts": [+ "harrison worked at kensho",+ "stefan worked at Stitch Fix",+ "stefan likes tacos",+ "elijah worked at TwoSigma",+ "elijah likes mango",+ "stefan used to work at IBM",+ "elijah likes to go biking",+ "stefan likes to bake sourdough",+ ],+ "question": "",+ "chat_history": [],+ }+ )+ .with_actions(+ ai_converse=ai_converse,+ human_converse=human_converse,+ terminal=burr.core.Result("chat_history"),+ )+ .with_transitions(+ ("ai_converse", "human_converse", default),+ ("human_converse", "terminal", expr("'exit' in question")),+ ("human_converse", "ai_converse", default),+ )+ .with_entrypoint("human_converse")+ .with_tracker(+ "demo:conversational-rag", params={"app_id": app_id, "storage_dir": storage_dir}+ )+ .with_hooks(*hooks if hooks else [])+ .build()+ )+ return app+++def main():+ """This is one way -- you provide input via the control flow"""+ app = application(hooks=[PrintStepHook()])+ # Comment back in to visualize+ # app.visualize(+ # output_file_path="conversational_rag", include_conditions=True, view=True, format="png"+ # )+ print(f"Running RAG with initial state:\n {pprint.pformat(app.state.get_all())}")+ while True:+ user_question = input("Ask something (or type exit to quit): ")+ previous_action, result, state = app.run(+ halt_before=["human_converse"],+ halt_after=["terminal"],+ inputs={"user_question": user_question},+ )+ if previous_action.name == "terminal":+ # reached the end+ pprint.pprint(result)+ return+++if __name__ == "__main__":+ main()diff --git a/examples/conversational_rag/conversational_rag.png b/examples/conversational_rag/conversational_rag.pngnew file mode 100644index 00000000..f9b17628Binary files /dev/null and b/examples/conversational_rag/conversational_rag.png differdiff --git a/examples/conversational_rag/requirements.txt b/examples/conversational_rag/requirements.txtnew file mode 100644index 00000000..b379c72c--- /dev/null+++ b/examples/conversational_rag/requirements.txt@@ -0,0 +1,6 @@+burr+faiss-cpu+hamilton+langchain+langchain-community+langchain-openaidiff --git a/examples/counter/application.py b/examples/counter/application.pyindex 0903baf3..5d7034fd 100644--- a/examples/counter/application.py+++ b/examples/counter/application.py@@ -9,11 +9,12 @@ from burr.lifecycle import LifecycleAdapter@action(reads=["counter"], writes=["counter"])def counter(state: State) -> Tuple[dict, State]:result = {"counter": state["counter"] + 1}+ print(f"counted to {result['counter']}")return result, state.update(**result)def application(- count_up_to: int = 100,+ count_up_to: int = 10,app_id: Optional[str] = None,storage_dir: Optional[str] = "~/.burr",hooks: Optional[List[LifecycleAdapter]] = None,diff --git a/pyproject.toml b/pyproject.tomlindex bc9c577e..8997cbe8 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -72,8 +72,8 @@ tracking = ["loguru",]-start = [- "burr[tracking]"+learn = [+ "burr[tracking,streamlit,graphviz]"]# just install everything for developers