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
Updates some examples + docs to use new API
elijahbenizzyd637a9600023
diff --git a/examples/email-assistant/application.py b/examples/email-assistant/application.pyindex 9b5caaf3..14b429bd 100644--- a/examples/email-assistant/application.py+++ b/examples/email-assistant/application.py@@ -15,22 +15,20 @@ def _get_openai_client():@action(reads=[], writes=["incoming_email", "response_instructions"])-def process_input(- state: State, email_to_respond: str, response_instructions: str-) -> Tuple[dict, State]:+def process_input(state: State, email_to_respond: str, response_instructions: str) -> State:"""Processes input from user and updates state with the input."""result = {"incoming_email": email_to_respond, "response_instructions": response_instructions}- return result, state.update(**result)+ return state.update(**result)@action(reads=[], writes=["has_openai_key"])-def check_openai_key(state: State) -> Tuple[dict, State]:+def check_openai_key(state: State) -> State:result = {"has_openai_key": "OPENAI_API_KEY" in os.environ}- return result, state.update(**result)+ return state.update(**result)@action(reads=["response_instructions", "incoming_email"], writes=["clarification_questions"])-def determine_clarifications(state: State) -> Tuple[dict, State]:+def determine_clarifications(state: State) -> State:"""Determines if the response instructions require clarification."""# TODO -- query an LLM to determine if the response instructions are clear, or if it needs more informationincoming_email = state["incoming_email"]@@ -61,18 +59,14 @@ def determine_clarifications(state: State) -> Tuple[dict, State]:)content = result.choices[0].message.contentall_questions = content.split("\n") if content else []- return {"clarification_questions": all_questions}, state.update(- clarification_questions=all_questions- )+ return state.update(clarification_questions=all_questions)@action(reads=["clarification_questions"], writes=["clarification_answers"])-def clarify_instructions(state: State, clarification_inputs: list[str]) -> Tuple[dict, State]:+def clarify_instructions(state: State, clarification_inputs: list[str]) -> State:"""Clarifies the response instructions if needed."""clarification_answers = list(clarification_inputs)- return {"clarification_answers": clarification_answers}, state.update(- clarification_answers=clarification_answers- )+ return state.update(clarification_answers=clarification_answers)@action(@@ -128,6 +122,7 @@ def formulate_draft(state: State) -> Tuple[dict, State]:],)content = result.choices[0].message.content+ # returning some intermediate results for debugging as wellreturn {"prompt": prompt, "current_draft": content}, state.update(current_draft=content).append(draft_history=content)diff --git a/examples/hello-world-counter/application.py b/examples/hello-world-counter/application.pyindex 3cba6d26..d160dd83 100644--- a/examples/hello-world-counter/application.py+++ b/examples/hello-world-counter/application.py@@ -1,5 +1,5 @@import logging-from typing import List, Optional, Tuple+from typing import List, Optionalimport burr.corefrom burr.core import Application, Result, State, default, expr@@ -11,10 +11,10 @@ logger = logging.getLogger(__name__)@action(reads=["counter"], writes=["counter"])-def counter(state: State) -> Tuple[dict, State]:+def counter(state: State) -> State:result = {"counter": state["counter"] + 1}print(f"counted to {result['counter']}")- return result, state.update(**result)+ return state.update(**result)def application(diff --git a/examples/multi-modal-chatbot/application.py b/examples/multi-modal-chatbot/application.pyindex aa5914c9..d037a41c 100644--- a/examples/multi-modal-chatbot/application.py+++ b/examples/multi-modal-chatbot/application.py@@ -1,6 +1,6 @@import copyimport os-from typing import List, Optional, Tuple+from typing import List, Optionalimport openai@@ -18,23 +18,25 @@ MODES = {@action(reads=[], writes=["chat_history", "prompt"])-def process_prompt(state: State, prompt: str) -> Tuple[dict, State]:+def process_prompt(state: State, prompt: str):result = {"chat_item": {"role": "user", "content": prompt, "type": "text"}}- return result, state.wipe(keep=["prompt", "chat_history"]).append(- chat_history=result["chat_item"]- ).update(prompt=prompt)+ return (+ state.wipe(keep=["prompt", "chat_history"])+ .append(chat_history=result["chat_item"])+ .update(prompt=prompt)+ )@action(reads=[], writes=["has_openai_key"])-def check_openai_key(state: State) -> Tuple[dict, State]:+def check_openai_key(state: State):result = {"has_openai_key": "OPENAI_API_KEY" in os.environ}- return result, state.update(**result)+ return state.update(**result)@action(reads=["prompt"], writes=["safe"])-def check_safety(state: State) -> Tuple[dict, State]:+def check_safety(state: State):result = {"safe": "unsafe" not in state["prompt"]} # quick hack to demonstrate- return result, state.update(safe=result["safe"])+ return state.update(safe=result["safe"])def _get_openai_client():@@ -42,7 +44,7 @@ def _get_openai_client():@action(reads=["prompt"], writes=["mode"])-def choose_mode(state: State) -> Tuple[dict, State]:+def choose_mode(state: State):prompt = (f"You are a chatbot. You've been prompted this: {state['prompt']}. "f"You have the capability of responding in the following modes: {', '.join(MODES)}. "@@ -64,11 +66,11 @@ def choose_mode(state: State) -> Tuple[dict, State]:if mode not in MODES:mode = "unknown"result = {"mode": mode}- return result, state.update(**result)+ return state.update(**result)@action(reads=["prompt", "chat_history"], writes=["response"])-def prompt_for_more(state: State) -> Tuple[dict, State]:+def prompt_for_more(state: State):result = {"response": {"content": "None of the response modes I support apply to your question. Please clarify?",@@ -76,13 +78,13 @@ def prompt_for_more(state: State) -> Tuple[dict, State]:"role": "assistant",}}- return result, state.update(**result)+ return state.update(**result)@action(reads=["prompt", "chat_history", "mode"], writes=["response"])def chat_response(state: State, prepend_prompt: str, display_type: str = "text", model: str = "gpt-3.5-turbo"-) -> Tuple[dict, State]:+):chat_history = copy.deepcopy(state["chat_history"])chat_history[-1]["content"] = f"{prepend_prompt}: {chat_history[-1]['content']}"chat_history_api_format = [@@ -99,11 +101,11 @@ def chat_response()response = result.choices[0].message.contentresult = {"response": {"content": response, "type": MODES[state["mode"]], "role": "assistant"}}- return result, state.update(**result)+ return state.update(**result)@action(reads=["prompt", "chat_history", "mode"], writes=["response"])-def image_response(state: State, model: str = "dall-e-2") -> Tuple[dict, State]:+def image_response(state: State, model: str = "dall-e-2"):"""Generates an image response to the prompt. Optional save function to save the image to a URL."""client = _get_openai_client()result = client.images.generate(@@ -111,11 +113,11 @@ def image_response(state: State, model: str = "dall-e-2") -> Tuple[dict, State]:)response = result.data[0].urlresult = {"response": {"content": response, "type": MODES[state["mode"]], "role": "assistant"}}- return result, state.update(**result)+ return state.update(**result)@action(reads=["response", "mode", "safe", "has_openai_key"], writes=["chat_history"])-def response(state: State) -> Tuple[dict, State]:+def response(state: State):if not state["has_openai_key"]:result = {"chat_item": {@@ -137,7 +139,7 @@ def response(state: State) -> Tuple[dict, State]:}else:result = {"chat_item": state["response"]}- return result, state.append(chat_history=result["chat_item"])+ return state.append(chat_history=result["chat_item"])def base_application(@@ -212,4 +214,4 @@ if __name__ == "__main__":app.visualize(output_file_path="statemachine", include_conditions=False, view=True, format="png")- app.run(halt_after=["response"])+ print(app.run(halt_after=["response"], inputs={"prompt": "Who was Aaron Burr, sir?"}))diff --git a/examples/multi-modal-chatbot/statemachine.png b/examples/multi-modal-chatbot/statemachine.pngindex dafd2171..116f45b4 100644Binary files a/examples/multi-modal-chatbot/statemachine.png and b/examples/multi-modal-chatbot/statemachine.png differdiff --git a/tests/core/test_application.py b/tests/core/test_application.pyindex aa0e523b..e55dd0b4 100644--- a/tests/core/test_application.py+++ b/tests/core/test_application.py@@ -2194,8 +2194,8 @@ def test_application_builder_assigns_correct_actions_with_dual_api():result_action = Result("count")@action(reads=[], writes=[])- def test_action(state: State) -> Tuple[State, Dict[str, Any]]:- return state, {}+ def test_action(state: State) -> State:+ return stateapp = (ApplicationBuilder()@@ -2214,8 +2214,8 @@ def test__validate_halt_conditions():result_action = Result("count")@action(reads=[], writes=[])- def test_action(state: State) -> Tuple[State, Dict[str, Any]]:- return state, {}+ def test_action(state: State) -> State:+ return stateapp = (ApplicationBuilder()@@ -2375,11 +2375,9 @@ def test_application_passes_context_when_declared():context_list = []@action(reads=["count"], writes=["count"])- def context_counter(- state: State, __context: ApplicationContext- ) -> Tuple[Dict[str, Any], State]:+ def context_counter(state: State, __context: ApplicationContext) -> State:context_list.append(__context)- return {}, state.update(count=state["count"] + 1)+ return state.update(count=state["count"] + 1)result_action = Result("count")app = (@@ -2408,11 +2406,9 @@ def test_optional_context_in_dependency_factories():context_list = []@action(reads=["count"], writes=["count"])- def context_counter(- state: State, __context: ApplicationContext = None- ) -> Tuple[Dict[str, Any], State]:+ def context_counter(state: State, __context: ApplicationContext = None) -> State:context_list.append(__context)- return {}, state.update(count=state["count"] + 1)+ return state.update(count=state["count"] + 1)result_action = Result("count")app = (