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
Fixes up examples for burr demo setup
elijahbenizzy8f94e7dfe9dc
diff --git a/examples/conversational-rag/application.py b/examples/conversational-rag/application.pydeleted file mode 100644index b051c445..00000000--- a/examples/conversational-rag/application.py+++ /dev/null@@ -1,131 +0,0 @@-from typing import Tuple--import burr.core-from burr.core import Action, ApplicationBuilder, State, default, expr-from burr.core.action import action-from burr.lifecycle import PostRunStepHook-from hamilton import dataflows, driver, lifecycle--conversational_rag = dataflows.import_module("conversational_rag")-converasation_rag_dr = (- driver.Builder()- .with_config({}) # replace with configuration as appropriate- .with_modules(conversational_rag)- .with_adapters(lifecycle.PrintLn(verbosity=2))- .build()-)---class PrintStepHook(PostRunStepHook):- """Custom hook to print the state and action after each step."""-- def post_run_step(self, *, state: "State", action: "Action", **future_kwargs):- print("action=====\n", action)- print("state======\n", state)---# procedural way to do this-@action(- reads=["input_texts", "question", "chat_history"],- writes=["chat_history"],-)-def ai_converse(state: State) -> Tuple[dict, State]:- result = converasation_rag_dr.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]:- state = state.update(question=user_question).append(chat_history=f"Human: {user_question}")- return {"question": user_question}, state---@action(- reads=[],- writes=["question", "chat_history"],-)-def human_converse_input(state: State) -> Tuple[dict, State]:- user_question = input("What is your question?: ")- state = state.update(question=user_question).append(chat_history=f"Human: {user_question}")- return {"question": user_question}, state---def main(input_via_control_flow: bool):- """This is one way -- you provide input via the control flow"""- if input_via_control_flow:- human_action = human_converse- else:- human_action = human_converse_input- app = (- ApplicationBuilder()- .with_state(- **{- "input_texts": [- "harrison worked at kensho",- "stefan worked at Stitch Fix",- "stefan likes tacos",- "elijah worked at TwoSigma",- ],- "question": "",- "chat_history": [],- }- )- .with_actions(- ai_converse=ai_converse,- human_converse=human_action,- 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")- .with_hooks(PrintStepHook())- .build()- )- app.visualize(- output_file_path="conversational_rag", include_conditions=True, view=True, format="png"- )- if input_via_control_flow:- while True:- user_question = input("What is your question: ")- action, result, state = app.run(- halt_before=["human_converse"],- halt_after=["terminal"],- inputs={"user_question": user_question},- )- if action.name == "terminal":- # reached the end- print(result)- break- else:- # async way to run things- # import asyncio- # action, result, state = asyncio.run(app.arun(- # halt_after=["terminal"],- # ))- action, result, state = app.run(- halt_after=["terminal"],- )- print(result)- return---if __name__ == "__main__":- import random-- choice = random.choice([True, False])- main(choice)diff --git a/examples/conversational-rag/conversational_rag.png b/examples/conversational-rag/conversational_rag.pngdeleted file mode 100644index f9b17628..00000000Binary files a/examples/conversational-rag/conversational_rag.png and /dev/null differdiff --git a/examples/counter/application.py b/examples/counter/application.pyindex e41f4aab..0903baf3 100644--- a/examples/counter/application.py+++ b/examples/counter/application.py@@ -1,9 +1,9 @@-from typing import Tuple+from typing import List, Optional, Tupleimport burr.core-from burr.core import Result, State, default, expr+from burr.core import Application, Result, State, default, exprfrom burr.core.action import action-from burr.lifecycle import StateAndResultsFullLogger+from burr.lifecycle import LifecycleAdapter@action(reads=["counter"], writes=["counter"])@@ -12,7 +12,12 @@ def counter(state: State) -> Tuple[dict, State]:return result, state.update(**result)-def application(count_up_to: int = 100, log_file: str = None):+def application(+ count_up_to: int = 100,+ app_id: Optional[str] = None,+ storage_dir: Optional[str] = "~/.burr",+ hooks: Optional[List[LifecycleAdapter]] = None,+) -> Application:return (burr.core.ApplicationBuilder().with_state(counter=0)@@ -20,18 +25,16 @@ def application(count_up_to: int = 100, log_file: str = None):.with_transitions(("counter", "counter", expr(f"counter < {count_up_to}")),("counter", "result", default),- ("result", "counter", expr("counter == 0")), # when we've reset, manually).with_entrypoint("counter")- .with_tracker("counter")- .with_hooks(*[StateAndResultsFullLogger(log_file)] if log_file else [])+ .with_tracker("demo:counter", params={"app_id": app_id, "storage_dir": storage_dir})+ .with_hooks(*hooks if hooks else []).build())if __name__ == "__main__":- app = application(log_file="counter.jsonl")+ app = application()action, state, result = app.run(halt_after=["result"])- app.visualize(output_file_path="digraph", include_conditions=True, view=False, format="png")- assert state["counter"] == 100+ # app.visualize(output_file_path="digraph", include_conditions=True, view=False, format="png")print(state["counter"])diff --git a/examples/gpt/application.py b/examples/gpt/application.pyindex 4e46ae9d..10f732cf 100644--- a/examples/gpt/application.py+++ b/examples/gpt/application.py@@ -1,10 +1,9 @@-import functools-from typing import List, Tuple+from typing import List, Optional, Tupleimport dagimport openai-from burr.core import Application, ApplicationBuilder, State, default, expr, when+from burr.core import Application, ApplicationBuilder, State, default, whenfrom burr.core.action import actionfrom burr.integrations.hamilton import Hamilton, append_state, from_state, update_statefrom burr.lifecycle import LifecycleAdapter@@ -32,7 +31,6 @@ def check_safety(state: State) -> Tuple[dict, State]:return result, state.update(safe=result["safe"])[email protected]_cache(maxsize=None)def _get_openai_client():return openai.Client()@@ -125,13 +123,14 @@ def response(state: State) -> Tuple[dict, State]:return result, state.append(chat_history=result["processed_response"])-@action(reads=["error"], writes=["chat_history"])-def error(state: State) -> Tuple[dict, State]:- result = {"chat_record": {"role": "assistant", "content": str(state["error"]), "type": "error"}}- return result, state.append(chat_history=result["chat_record"])+# TODO -- add in error handling+# @action(reads=["error"], writes=["chat_history"])+# def error(state: State) -> Tuple[dict, State]:+# result = {"chat_record": {"role": "assistant", "content": str(state["error"]), "type": "error"}}+# return result, state.append(chat_history=result["chat_record"])-def base_application(hooks: List[LifecycleAdapter] = None):+def base_application(hooks: List[LifecycleAdapter], app_id: str, storage_dir: str):if hooks is None:hooks = []return (@@ -149,7 +148,6 @@ def base_application(hooks: List[LifecycleAdapter] = None):),prompt_for_more=prompt_for_more,response=response,- error=error,).with_entrypoint("prompt").with_state(chat_history=[])@@ -164,25 +162,16 @@ def base_application(hooks: List[LifecycleAdapter] = None):(["generate_image", "answer_question", "generate_code", "prompt_for_more"],"response",- when(error=None),- ),- (- ["generate_image", "answer_question", "generate_code", "prompt_for_more"],- "error",- expr("error is not None"),),("response", "prompt", default),- ("error", "prompt", default),).with_hooks(*hooks)- .with_tracker("demo:chatbot")+ .with_tracker("demo:chatbot", params={"app_id": app_id, "storage_dir": storage_dir}).build())-def hamilton_application(hooks: List[LifecycleAdapter] = None):- if hooks is None:- hooks = []+def hamilton_application(hooks: List[LifecycleAdapter], app_id: str, storage_dir: str):dr = driver.Driver({"provider": "openai"}, dag) # TODO -- add modulesHamilton.set_driver(dr)application = (@@ -227,7 +216,6 @@ def hamilton_application(hooks: List[LifecycleAdapter] = None):},outputs={"processed_response": append_state("chat_history")},),- error=error,).with_transitions(("prompt", "check_safety", default),@@ -240,27 +228,25 @@ def hamilton_application(hooks: List[LifecycleAdapter] = None):(["generate_image", "answer_question", "generate_code", "prompt_for_more"],"response",- when(error=None),- ),- (- ["generate_image", "answer_question", "generate_code", "prompt_for_more"],- "error",- expr("error is not None"),),("response", "prompt", default),- ("error", "prompt", default),).with_hooks(*hooks)- .with_tracker("demo:chatbot")+ .with_tracker("demo:chatbot", params={"app_id": app_id, "storage_dir": storage_dir}).build())return application-def application(use_hamilton: bool, hooks: List[LifecycleAdapter] = []) -> Application:+def application(+ use_hamilton: bool,+ app_id: Optional[str] = None,+ storage_dir: Optional[str] = "~/.burr",+ hooks: Optional[List[LifecycleAdapter]] = None,+) -> Application:if use_hamilton:- return hamilton_application(hooks)- return base_application(hooks)+ return hamilton_application(hooks, app_id, storage_dir)+ return base_application(hooks, app_id, storage_dir)if __name__ == "__main__":diff --git a/examples/image-telephone/README.md b/examples/image_telephone/README.mdsimilarity index 100%rename from examples/image-telephone/README.mdrename to examples/image_telephone/README.mddiff --git a/examples/image-telephone/application.py b/examples/image_telephone/application.pysimilarity index 100%rename from examples/image-telephone/application.pyrename to examples/image_telephone/application.pydiff --git a/examples/image-telephone/telephone_graph.png b/examples/image_telephone/telephone_graph.pngsimilarity index 100%rename from examples/image-telephone/telephone_graph.pngrename to examples/image_telephone/telephone_graph.png