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
Adds docstrings + clarifies streaming example
elijahbenizzy6507b38310d1
diff --git a/burr/core/action.py b/burr/core/action.pyindex 01faf56d..7014254e 100644--- a/burr/core/action.py+++ b/burr/core/action.py@@ -743,7 +743,7 @@ class AsyncStreamingResultContainer(typing.AsyncIterator[dict]):self._callback_realized = Falseasync def __anext__(self):- # TODO -- ensure this works+ """Moves to the next state in the streaming result"""if self._result is not None:# we're done, and we've run through itraise StopAsyncIteration@@ -754,6 +754,10 @@ class AsyncStreamingResultContainer(typing.AsyncIterator[dict]):return resultdef __aiter__(self):+ """Gives the iterator. Just calls anext, assigning the result in the finally block.+ Note this may not be perfect due to the complexity of callbacks for async generators,+ but it works in most cases."""+async def gen_fn():try:while True:@@ -780,6 +784,8 @@ class AsyncStreamingResultContainer(typing.AsyncIterator[dict]):@staticmethoddef pass_through(results: dict, final_state: State) -> "AsyncStreamingResultContainer":+ """Creates a streaming result container that just passes through the given results.+ This is not a public facing API."""async def just_results() -> AsyncGeneratorReturnType:yield results, final_statediff --git a/burr/core/application.py b/burr/core/application.pyindex 36ee7fdc..ffc6ca63 100644--- a/burr/core/application.py+++ b/burr/core/application.py@@ -230,11 +230,21 @@ def _run_single_step_action(def _run_single_step_streaming_action(action: SingleStepStreamingAction, state: State, inputs: Optional[Dict[str, Any]]) -> Generator[Tuple[dict, Optional[State]], None, None]:+ """Runs a single step streaming action. This API is internal-facing.+ This normalizes + validates the output."""action.validate_inputs(inputs)generator = action.stream_run_and_update(state, **inputs)result = Nonestate_update = None- for result, state_update in generator:+ for item in generator:+ if not isinstance(item, tuple):+ # TODO -- consider adding support for just returning a result.+ raise ValueError(+ f"Action {action.name} must yield a tuple of (result, state_update). "+ f"For all non-final results (intermediate),"+ f"the state update must be None"+ )+ result, state_update = itemif state_update is None:yield result, Noneif state_update is None:@@ -250,6 +260,7 @@ def _run_single_step_streaming_action(async def _arun_single_step_streaming_action(action: SingleStepStreamingAction, state: State, inputs: Optional[Dict[str, Any]]) -> AsyncGenerator[Tuple[dict, Optional[State]], None]:+ """Runs a single step streaming action in async. See the synchronous version for more details."""action.validate_inputs(inputs)generator = action.stream_run_and_update(state, **inputs)result = None@@ -279,6 +290,13 @@ async def _arun_single_step_streaming_action(def _run_multi_step_streaming_action(action: StreamingAction, state: State, inputs: Optional[Dict[str, Any]]) -> Generator[Tuple[dict, Optional[State]], None, None]:+ """Runs a multi-step streaming action. E.G. one with a run/reduce step.+ This API is internal-facing. Note that this converts the shape of a+ multi-step streaming action to yielding the results of the run step+ as well as the state update, which is None for all the finaly ones.++ This peeks ahead by one so we know when this is done (and when to validate).+ """action.validate_inputs(inputs)generator = action.stream_run(state, **inputs)result = None@@ -290,7 +308,6 @@ def _run_multi_step_streaming_action(result = itemif next_result is not None:yield next_result, None- # yield item, Nonestate_update = _run_reducer(action, state, result, action.name)_validate_result(result, action.name)_validate_reducer_writes(action, state_update, action.name)@@ -300,6 +317,7 @@ def _run_multi_step_streaming_action(async def _arun_multi_step_streaming_action(action: AsyncStreamingAction, state: State, inputs: Optional[Dict[str, Any]]) -> AsyncGenerator[Tuple[dict, Optional[State]], None]:+ """Runs a multi-step streaming action in async. See the synchronous version for more details."""action.validate_inputs(inputs)generator = action.stream_run(state, **inputs)result = Nonediff --git a/examples/streaming-overview/async_application.py b/examples/streaming-overview/async_application.pyindex 62e01a65..283bdef6 100644--- a/examples/streaming-overview/async_application.py+++ b/examples/streaming-overview/async_application.py@@ -182,23 +182,24 @@ TERMINAL_ACTIONS = []-async def it(app):+async def run(app):+ """Runs the application. Queries the input for prompt"""action, result = await app.astream_result(- halt_after=TERMINAL_ACTIONS, inputs={"prompt": "What are the first 100 prime numbers?"}+ halt_after=TERMINAL_ACTIONS, inputs={"prompt": input("Please enter a prompt: ")})async for item in result:- print(item["response"]["content"], end="")+ print(item["response"]["content"], end="\n")result, state = await result.get()print(result["response"]["content"])async def main():app = application()- await it(app)+ app.visualize(+ output_file_path="statemachine", include_conditions=False, view=True, format="png"+ )+ await run(app)if __name__ == "__main__":- # app.visualize(- # output_file_path="statemachine", include_conditions=False, view=True, format="png"- # )asyncio.run(main())