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 tracker to log spans
elijahbenizzya948fd528a68
diff --git a/burr/core/application.py b/burr/core/application.pyindex 57a8c490..5fc28392 100644--- a/burr/core/application.py+++ b/burr/core/application.py@@ -263,7 +263,11 @@ class Application:inputs = self._process_inputs(inputs, next_action)if _run_hooks:self._adapter_set.call_all_lifecycle_hooks_sync(- "pre_run_step", action=next_action, state=self._state, inputs=inputs+ "pre_run_step",+ action=next_action,+ state=self._state,+ inputs=inputs,+ sequence_id=self.sequence_id,)exc = Noneresult = None@@ -288,6 +292,7 @@ class Application:action=next_action,state=new_state,result=result,+ sequence_id=self.sequence_id,exception=exc,)return next_action, result, new_state@@ -343,7 +348,11 @@ class Application:inputs = {}inputs = self._process_inputs(inputs, next_action)await self._adapter_set.call_all_lifecycle_hooks_sync_and_async(- "pre_run_step", action=next_action, state=self._state, inputs=inputs+ "pre_run_step",+ action=next_action,+ state=self._state,+ inputs=inputs,+ sequence_id=self.sequence_id,)exc = Noneresult = None@@ -373,7 +382,12 @@ class Application:raise efinally:await self._adapter_set.call_all_lifecycle_hooks_sync_and_async(- "post_run_step", action=next_action, state=new_state, result=result, exception=exc+ "post_run_step",+ action=next_action,+ state=new_state,+ result=result,+ sequence_id=self.sequence_id,+ exception=exc,)# we want to increment regardless of failureself._increment_sequence_id()@@ -619,6 +633,9 @@ class Application:)digraph.node(action.name, label=label, shape="box", style="rounded")for input_ in action.inputs:+ if input_.startswith("__"):+ # These are internally injected by the framework+ continueinput_name = f"input__{input_}"digraph.node(input_name, shape="oval", style="dashed", label=f"input: {input_}")digraph.edge(input_name, action.name)diff --git a/burr/lifecycle/base.py b/burr/lifecycle/base.pyindex da158596..9a68474b 100644--- a/burr/lifecycle/base.py+++ b/burr/lifecycle/base.py@@ -15,13 +15,20 @@ class PreRunStepHook(abc.ABC):@abc.abstractmethoddef pre_run_step(- self, *, state: "State", action: "Action", inputs: Dict[str, Any], **future_kwargs: Any+ self,+ *,+ state: "State",+ action: "Action",+ inputs: Dict[str, Any],+ sequence_id: int,+ **future_kwargs: Any,):"""Run before a step is executed.:param state: State prior to step execution:param action: Action to be executed:param inputs: Inputs to the action+ :param sequence_id: Sequence ID of the action:param future_kwargs: Future keyword arguments"""pass@@ -33,13 +40,20 @@ class PreRunStepHookAsync(abc.ABC):@abc.abstractmethodasync def pre_run_step(- self, *, state: "State", action: "Action", inputs: Dict[str, Any], **future_kwargs: Any+ self,+ *,+ state: "State",+ action: "Action",+ inputs: Dict[str, Any],+ sequence_id: int,+ **future_kwargs: Any,):"""Async run before a step is executed.:param state: State prior to step execution:param action: Action to be executed:param inputs: Inputs to the action+ :param sequence_id: Sequence ID of the action:param future_kwargs: Future keyword arguments"""pass@@ -56,6 +70,7 @@ class PostRunStepHook(abc.ABC):state: "State",action: "Action",result: Optional[Dict[str, Any]],+ sequence_id: int,exception: Exception,**future_kwargs: Any,):@@ -64,6 +79,7 @@ class PostRunStepHook(abc.ABC)::param state: State after step execution:param action: Action that was executed:param result: Result of the action+ :param sequence_id: Sequence ID of the action:param exception: Exception that was raised:param future_kwargs: Future keyword arguments"""@@ -81,6 +97,7 @@ class PostRunStepHookAsync(abc.ABC):state: "State",action: "Action",result: Optional[dict],+ sequence_id: int,exception: Exception,**future_kwargs: Any,):@@ -89,6 +106,7 @@ class PostRunStepHookAsync(abc.ABC)::param state: State after step execution:param action: Action that was executed:param result: Result of the action+ :param sequence_id: Sequence ID of the action:param exception: Exception that was raised:param future_kwargs: Future keyword arguments"""diff --git a/burr/tracking/client.py b/burr/tracking/client.pyindex 05dc05c4..bfbf9209 100644--- a/burr/tracking/client.py+++ b/burr/tracking/client.py@@ -9,8 +9,15 @@ from typing import Any, Dict, Optionalfrom burr.core import Action, ApplicationGraph, Statefrom burr.integrations.base import require_pluginfrom burr.lifecycle import PostRunStepHook, PreRunStepHook-from burr.lifecycle.base import PostApplicationCreateHook-from burr.tracking.common.models import ApplicationModel, BeginEntryModel, EndEntryModel+from burr.lifecycle.base import PostApplicationCreateHook, PostEndSpanHook, PreStartSpanHook+from burr.tracking.common.models import (+ ApplicationModel,+ BeginEntryModel,+ BeginSpanModel,+ EndEntryModel,+ EndSpanModel,+)+from burr.visibility import ActionSpanlogger = logging.getLogger(__name__)@@ -30,7 +37,13 @@ def _format_exception(exception: Exception) -> Optional[str]:return "".join(traceback.format_exception(type(exception), exception, exception.__traceback__))-class LocalTrackingClient(PostApplicationCreateHook, PreRunStepHook, PostRunStepHook):+class LocalTrackingClient(+ PostApplicationCreateHook,+ PreRunStepHook,+ PostRunStepHook,+ PreStartSpanHook,+ PostEndSpanHook,+):"""Tracker to track locally -- goes along with the Burr UI. Writesdown the following:#. The whole application + debugging information (e.g. source code) to a file@@ -152,21 +165,27 @@ class LocalTrackingClient(PostApplicationCreateHook, PreRunStepHook, PostRunStepself.f.flush()def pre_run_step(- self, *, state: State, action: Action, inputs: Dict[str, Any], **future_kwargs: Any+ self,+ state: State,+ action: Action,+ inputs: Dict[str, Any],+ sequence_id: int,+ **future_kwargs: Any,):pre_run_entry = BeginEntryModel(start_time=datetime.datetime.now(),action=action.name,inputs=inputs,+ sequence_id=sequence_id,)self._append_write_line(pre_run_entry)def post_run_step(self,- *,state: State,action: Action,result: Optional[dict],+ sequence_id: int,exception: Exception,**future_kwargs: Any,):@@ -174,11 +193,47 @@ class LocalTrackingClient(PostApplicationCreateHook, PreRunStepHook, PostRunStepend_time=datetime.datetime.now(),action=action.name,result=result,+ sequence_id=sequence_id,exception=_format_exception(exception),state=state.get_all(),)self._append_write_line(post_run_entry)+ def pre_start_span(+ self,+ *,+ action: str,+ sequence_id: int,+ span: ActionSpan,+ span_dependencies: list[str],+ **future_kwargs: Any,+ ):+ being_span_model = BeginSpanModel(+ start_time=datetime.datetime.now(),+ action_sequence_id=sequence_id,+ span_id=span.uid,+ parent_span_id=span.parent.uid if span.parent else None,+ span_dependencies=span_dependencies,+ span_name=span.name,+ )+ self._append_write_line(being_span_model)++ def post_end_span(+ self,+ *,+ action: str,+ sequence_id: int,+ span: ActionSpan,+ span_dependencies: list[str],+ **future_kwargs: Any,+ ):+ end_span_model = EndSpanModel(+ end_time=datetime.datetime.now(),+ action_sequence_id=sequence_id,+ span_id=span.uid,+ )+ self._append_write_line(end_span_model)+def __del__(self):self.f.close()diff --git a/burr/tracking/common/models.py b/burr/tracking/common/models.pyindex 75f8f85b..a2260293 100644--- a/burr/tracking/common/models.py+++ b/burr/tracking/common/models.py@@ -99,6 +99,7 @@ class BeginEntryModel(IdentifyingModel):start_time: datetime.datetimeaction: strinputs: Dict[str, Any]+ sequence_id: inttype: str = "begin_entry"@field_serializer("inputs")@@ -126,6 +127,7 @@ class EndEntryModel(IdentifyingModel):result: Optional[dict]exception: Optional[str]state: Dict[str, Any] # TODO -- consider logging updates to the state so we can recreate+ sequence_id: inttype: str = "end_entry"@field_serializer("result")@@ -135,3 +137,24 @@ class EndEntryModel(IdentifyingModel):@field_serializer("state")def serialize_state(self, state):return _serialize_object(state)+++class BeginSpanModel(IdentifyingModel):+ """Pydantic model that represents an entry for the beginning of a span"""++ start_time: datetime.datetime+ action_sequence_id: int+ span_id: str # unique among the application+ span_name: str+ parent_span_id: Optional[str]+ span_dependencies: list[str]+ type: str = "begin_span"+++class EndSpanModel(IdentifyingModel):+ """Pydantic model that represents an entry for the end of a span"""++ end_time: datetime.datetime+ action_sequence_id: int+ span_id: str # unique among the application+ type: str = "end_span"diff --git a/burr/visibility/tracing.py b/burr/visibility/tracing.pyindex 0c21ff2d..84bba3ba 100644--- a/burr/visibility/tracing.py+++ b/burr/visibility/tracing.py@@ -129,7 +129,7 @@ class ActionSpanTracer(AbstractContextManager, AbstractAsyncContextManager):action=self.action,span=context,span_dependencies=self.span_dependencies,- action_sequence_id=self.action_sequence_id,+ sequence_id=self.action_sequence_id,)async def _async_hooks_enter(self, context: ActionSpan):@@ -138,7 +138,7 @@ class ActionSpanTracer(AbstractContextManager, AbstractAsyncContextManager):action=self.action,span=context,span_dependencies=self.span_dependencies,- action_sequence_id=self.action_sequence_id,+ sequence_id=self.action_sequence_id,)async def _async_hooks_exit(self, context: ActionSpan):@@ -147,7 +147,7 @@ class ActionSpanTracer(AbstractContextManager, AbstractAsyncContextManager):action=self.action,span=context,span_dependencies=self.span_dependencies,- action_sequence_id=self.action_sequence_id,+ sequence_id=self.action_sequence_id,)def _enter(self):@@ -177,6 +177,7 @@ class ActionSpanTracer(AbstractContextManager, AbstractAsyncContextManager):action=self.action,span=context,span_dependencies=self.span_dependencies,+ sequence_id=self.action_sequence_id,)def __enter__(self):@@ -264,6 +265,8 @@ class TracerFactory:) -> ActionSpanTracer:if self.context_var.get() is None:self.top_level_span_count += 1+ if span_dependencies is None:+ span_dependencies = []return ActionSpanTracer(action=self.action,action_sequence_id=self.action_sequence_id,diff --git a/examples/gpt/application.py b/examples/gpt/application.pyindex 9dc60d82..b35d62a0 100644--- a/examples/gpt/application.py+++ b/examples/gpt/application.py@@ -8,6 +8,7 @@ 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+from burr.visibility import TracerFactoryMODES = {"answer_question": "text",@@ -18,16 +19,18 @@ MODES = {@action(reads=[], writes=["chat_history", "prompt"])-def process_prompt(state: State, prompt: str) -> Tuple[dict, State]:- result = {"chat_item": {"role": "user", "content": prompt, "type": "text"}}+def process_prompt(state: State, prompt: str, __tracer: TracerFactory) -> Tuple[dict, State]:+ with __tracer("process_prompt"):+ 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)@action(reads=["prompt"], writes=["safe"])-def check_safety(state: State) -> Tuple[dict, State]:- result = {"safe": "unsafe" not in state["prompt"]} # quick hack to demonstrate+def check_safety(state: State, __tracer: TracerFactory) -> Tuple[dict, State]:+ with __tracer("check_safety"):+ result = {"safe": "unsafe" not in state["prompt"]} # quick hack to demonstratereturn result, state.update(safe=result["safe"])@@ -36,28 +39,33 @@ def _get_openai_client():@action(reads=["prompt"], writes=["mode"])-def choose_mode(state: State) -> Tuple[dict, 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)}. "- "Please respond with *only* a single word representing the mode that most accurately "- "corresponds to the prompt. Fr instance, if the prompt is 'draw a picture of a cat', "- "the mode would be 'generate_image'. If the prompt is 'what is the capital of France', the mode would be 'answer_question'."- "If none of these modes apply, please respond with 'unknown'."- )-- result = _get_openai_client().chat.completions.create(- model="gpt-4",- messages=[- {"role": "system", "content": "You are a helpful assistant"},- {"role": "user", "content": prompt},- ],- )- content = result.choices[0].message.content- mode = content.lower()- if mode not in MODES:- mode = "unknown"- result = {"mode": mode}+def choose_mode(state: State, __tracer: TracerFactory) -> Tuple[dict, State]:+ with __tracer("generate_prompt"):+ 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)}. "+ "Please respond with *only* a single word representing the mode that most accurately "+ "corresponds to the prompt. Fr instance, if the prompt is 'draw a picture of a cat', "+ "the mode would be 'generate_image'. If the prompt is 'what is the capital of France', the mode would be 'answer_question'."+ "If none of these modes apply, please respond with 'unknown'."+ )+ with __tracer("query_openai", span_dependencies=["generate_prompt"]):+ with __tracer("create_openai_client"):+ client = _get_openai_client()+ with __tracer("query_openai"):+ result = client.chat.completions.create(+ model="gpt-4",+ messages=[+ {"role": "system", "content": "You are a helpful assistant"},+ {"role": "user", "content": prompt},+ ],+ )+ with __tracer("process_openai_response", span_dependencies=["query_openai"]):+ content = result.choices[0].message.content+ mode = content.lower()+ if mode not in MODES:+ mode = "unknown"+ result = {"mode": mode}return result, state.update(**result)@@ -75,50 +83,70 @@ def prompt_for_more(state: State) -> Tuple[dict, State]:@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"+ state: State,+ prepend_prompt: str,+ __tracer: TracerFactory,+ model: str = "gpt-3.5-turbo",) -> Tuple[dict, State]:- chat_history = state["chat_history"].copy()- chat_history[-1]["content"] = f"{prepend_prompt}: {chat_history[-1]['content']}"- chat_history_api_format = [- {- "role": chat["role"],- "content": chat["content"],+ with __tracer("process_chat_history"):+ chat_history = state["chat_history"].copy()+ chat_history[-1]["content"] = f"{prepend_prompt}: {chat_history[-1]['content']}"+ chat_history_api_format = [+ {+ "role": chat["role"],+ "content": chat["content"],+ }+ for chat in chat_history+ ]+ with __tracer("query_openai", span_dependencies=["change_chat_history"]):+ with __tracer("create_openai_client"):+ client = _get_openai_client()+ with __tracer("query_openai", span_dependencies=["create_openai_client"]):+ result = client.chat.completions.create(+ model=model,+ messages=chat_history_api_format,+ )+ with __tracer("process_openai_response", span_dependencies=["query_openai"]):+ response = result.choices[0].message.content+ result = {+ "response": {"content": response, "type": MODES[state["mode"]], "role": "assistant"}}- for chat in chat_history- ]- client = _get_openai_client()- result = client.chat.completions.create(- model=model,- messages=chat_history_api_format,- )- response = result.choices[0].message.content- result = {"response": {"content": response, "type": MODES[state["mode"]], "role": "assistant"}}return result, state.update(**result)@action(reads=["prompt", "chat_history", "mode"], writes=["response"])-def image_response(state: State, model: str = "dall-e-2") -> Tuple[dict, State]:- client = _get_openai_client()- result = client.images.generate(- model=model, prompt=state["prompt"], size="1024x1024", quality="standard", n=1- )- response = result.data[0].url- result = {"response": {"content": response, "type": MODES[state["mode"]], "role": "assistant"}}+def image_response(+ state: State, __tracer: TracerFactory, model: str = "dall-e-2"+) -> Tuple[dict, State]:+ with __tracer("create_openai_client"):+ client = _get_openai_client()+ with __tracer("query_openai_image", span_dependencies=["create_openai_client"]):+ result = client.images.generate(+ model=model, prompt=state["prompt"], size="1024x1024", quality="standard", n=1+ )+ response = result.data[0].url+ with __tracer("process_openai_response", span_dependencies=["query_openai_image"]):+ result = {+ "response": {"content": response, "type": MODES[state["mode"]], "role": "assistant"}+ }return result, state.update(**result)@action(reads=["response", "safe", "mode"], writes=["chat_history"])-def response(state: State) -> Tuple[dict, State]:- if not state["safe"]:- result = {- "chat_item": {- "role": "assistant",- "content": "I'm sorry, I can't respond to that.",- "type": "text",- }- }- else:- result = {"chat_item": state["response"]}+def response(state: State, __tracer: TracerFactory) -> Tuple[dict, State]:+ with __tracer("process_response"):+ if not state["safe"]:+ with __tracer("unsafe"):+ result = {+ "chat_item": {+ "role": "assistant",+ "content": "I'm sorry, I can't respond to that.",+ "type": "text",+ }+ }+ else:+ with __tracer("safe"):+ result = {"chat_item": state["response"]}return result, state.append(chat_history=result["chat_item"])diff --git a/tests/tracking/test_local_tracking_client.py b/tests/tracking/test_local_tracking_client.pyindex adfe40bf..e7ce8ee5 100644--- a/tests/tracking/test_local_tracking_client.py+++ b/tests/tracking/test_local_tracking_client.py@@ -8,12 +8,20 @@ import pytestimport burrfrom burr.core import Result, State, action, default, exprfrom burr.tracking import LocalTrackingClient-from burr.tracking.common.models import ApplicationModel, BeginEntryModel, EndEntryModel+from burr.tracking.common.models import (+ ApplicationModel,+ BeginEntryModel,+ BeginSpanModel,+ EndEntryModel,+ EndSpanModel,+)+from burr.visibility import TracerFactory@action(reads=["counter", "break_at"], writes=["counter"])-def counter(state: State) -> Tuple[dict, State]:- result = {"counter": state["counter"] + 1}+def counter(state: State, __tracer: TracerFactory) -> Tuple[dict, State]:+ with __tracer("increment"):+ result = {"counter": state["counter"] + 1}if state["break_at"] == result["counter"]:raise ValueError("Broken")return result, state.update(**result)@@ -58,13 +66,23 @@ def test_application_tracks_end_to_end(tmpdir: str):assert app_model.actions[0].name == "counter"assert app_model.actions[1].name == "result"pre_run = [- BeginEntryModel.parse_obj(line) for line in log_contents if line["type"] == "begin_entry"+ BeginEntryModel.model_validate(line)+ for line in log_contents+ if line["type"] == "begin_entry"]post_run = [- EndEntryModel.parse_obj(line) for line in log_contents if line["type"] == "end_entry"+ EndEntryModel.model_validate(line) for line in log_contents if line["type"] == "end_entry"+ ]+ span_start_model = [+ BeginSpanModel.model_validate(line) for line in log_contents if line["type"] == "begin_span"+ ]+ span_end_model = [+ EndSpanModel.model_validate(line) for line in log_contents if line["type"] == "end_span"]assert len(pre_run) == 3assert len(post_run) == 3+ assert len(span_start_model) == 2 # two custom-defined spans+ assert len(span_end_model) == 2 # dittoassert not any(item.exception for item in post_run)@@ -86,15 +104,17 @@ def test_application_tracks_end_to_end_broken(tmpdir: str):with open(graph_output) as f:graph_contents = json.load(f)assert graph_contents["type"] == "application"- app_model = ApplicationModel.parse_obj(graph_contents)+ app_model = ApplicationModel.model_validate(graph_contents)assert app_model.entrypoint == "counter"assert app_model.actions[0].name == "counter"assert app_model.actions[1].name == "result"pre_run = [- BeginEntryModel.parse_obj(line) for line in log_contents if line["type"] == "begin_entry"+ BeginEntryModel.model_validate(line)+ for line in log_contents+ if line["type"] == "begin_entry"]post_run = [- EndEntryModel.parse_obj(line) for line in log_contents if line["type"] == "end_entry"+ EndEntryModel.model_validate(line) for line in log_contents if line["type"] == "end_entry"]assert len(pre_run) == 2assert len(post_run) == 2