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 other examples (less validated) t
elijahbenizzy85706acc0172
diff --git a/examples/other-examples/cowsay/README.md b/examples/other-examples/cowsay/README.mdnew file mode 100644index 00000000..2fe0194e--- /dev/null+++ b/examples/other-examples/cowsay/README.md@@ -0,0 +1,28 @@+# Cowsay++This is an example of a simple infinite state machine.++We have three files:++- [application.py](application.py) -- This contains a mainline to run the cowsay app as well as a function to export the app (for later use)+- [requirements.txt](requirements.txt) -- Just the requirements. All this needs is Burr/Streamlit/cowsay+- [streamlit_app.py](streamlit_app.py) -- This contains a simple Streamlit app to interact with the cow++To run just the application, you can run:++```bash+python application.py+```++Note this is an infinte state machine, so this will run forever! Thus remember to ctrl-c eventually.+To run the streamlit app, you can run:++```bash+streamlit run streamlit_app.py+```++This allows you to press a button and see the cow say something (or see it decide not to speak).++This will open a chrome window and print out the URL. The state machine this encapsulates takes the following form:++diff --git a/examples/other-examples/cowsay/application.py b/examples/other-examples/cowsay/application.pynew file mode 100644index 00000000..c2bc2bd5--- /dev/null+++ b/examples/other-examples/cowsay/application.py@@ -0,0 +1,76 @@+import random+import time+from typing import Tuple++import cowsay++from burr.core import Action, Application, ApplicationBuilder, State, default, expr+from burr.core.action import action+from burr.lifecycle import PostRunStepHook+++class PrintWhatTheCowSaid(PostRunStepHook):+ def post_run_step(self, *, state: "State", action: "Action", **future_kwargs):+ if action.name != "cow_should_say" and state["cow_said"] is not None:+ print(state["cow_said"])+++class CowCantSpeakFast(PostRunStepHook):+ def __init__(self, sleep_time: float):+ super(PostRunStepHook, self).__init__()+ self.sleep_time = sleep_time++ def post_run_step(self, *, state: "State", action: "Action", **future_kwargs):+ if action.name != "cow_should_say": # no need to print if we're not saying anything+ time.sleep(self.sleep_time)+++@action(reads=[], writes=["cow_said"])+def cow_said(state: State, say_what: list[str]) -> Tuple[dict, State]:+ said = random.choice(say_what)+ result = {"cow_said": cowsay.get_output_string("cow", said) if say_what is not None else None}+ return result, state.update(**result)+++@action(reads=[], writes=["cow_should_speak"])+def cow_should_speak(state: State) -> Tuple[dict, State]:+ result = {"cow_should_speak": random.randint(0, 3) == 0}+ return result, state.update(**result)+++def application(in_terminal: bool = False) -> Application:+ hooks = (+ [+ PrintWhatTheCowSaid(),+ CowCantSpeakFast(sleep_time=2.0),+ ]+ if in_terminal+ else []+ )+ return (+ ApplicationBuilder()+ .with_state(cow_said=None)+ .with_actions(+ say_nothing=cow_said.bind(say_what=None),+ say_hello=cow_said.bind(+ say_what=["Hello world!", "What's up?", "Are you Aaron Burr, sir?"]+ ),+ cow_should_speak=cow_should_speak,+ )+ .with_transitions(+ ("cow_should_speak", "say_hello", expr("cow_should_speak")),+ ("say_hello", "cow_should_speak", default),+ ("cow_should_speak", "say_nothing", expr("not cow_should_speak")),+ ("say_nothing", "cow_should_speak", default),+ )+ .with_entrypoint("cow_should_speak")+ .with_hooks(*hooks)+ .build()+ )+++if __name__ == "__main__":+ app = application(in_terminal=True)+ app.visualize(output_file_path="digraph", include_conditions=True, view=True, format="png")+ while True:+ action, result, state = app.step()diff --git a/examples/other-examples/cowsay/digraph b/examples/other-examples/cowsay/digraphnew file mode 100644index 00000000..e4be488b--- /dev/null+++ b/examples/other-examples/cowsay/digraph@@ -0,0 +1,10 @@+digraph {+ graph [compound=false concentrate=false rankdir=TB ranksep=0.4]+ say_nothing [label=say_nothing shape=box style=rounded]+ say_hello [label=say_hello shape=box style=rounded]+ cow_should_speak [label=cow_should_speak shape=box style=rounded]+ cow_should_speak -> say_hello [label=cow_should_speak style=dashed]+ say_hello -> cow_should_speak [style=solid]+ cow_should_speak -> say_nothing [label="not cow_should_speak" style=dashed]+ say_nothing -> cow_should_speak [style=solid]+}diff --git a/examples/other-examples/cowsay/digraph.png b/examples/other-examples/cowsay/digraph.pngnew file mode 100644index 00000000..5418c954Binary files /dev/null and b/examples/other-examples/cowsay/digraph.png differdiff --git a/examples/other-examples/cowsay/notebook.ipynb b/examples/other-examples/cowsay/notebook.ipynbnew file mode 100644index 00000000..3f4e8b26--- /dev/null+++ b/examples/other-examples/cowsay/notebook.ipynb@@ -0,0 +1,313 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": 1,+ "id": "initial_id",+ "metadata": {+ "collapsed": true,+ "ExecuteTime": {+ "end_time": "2024-03-27T00:12:50.561804Z",+ "start_time": "2024-03-27T00:12:50.531039Z"+ }+ },+ "outputs": [],+ "source": [+ "import random\n",+ "import time\n",+ "from typing import Tuple\n",+ "\n",+ "import cowsay\n",+ "\n",+ "from burr.core import Action, Application, ApplicationBuilder, State, default, expr\n",+ "from burr.core.action import action\n",+ "from burr.lifecycle import PostRunStepHook"+ ]+ },+ {+ "cell_type": "code",+ "outputs": [],+ "source": [+ "# create some hooks!\n",+ "class PrintWhatTheCowSaid(PostRunStepHook):\n",+ " def post_run_step(self, *, state: \"State\", action: \"Action\", **future_kwargs):\n",+ " if action.name != \"cow_should_say\" and state[\"cow_said\"] is not None:\n",+ " print(state[\"cow_said\"])\n",+ "\n",+ "\n",+ "class CowCantSpeakFast(PostRunStepHook):\n",+ " def __init__(self, sleep_time: float):\n",+ " super(PostRunStepHook, self).__init__()\n",+ " self.sleep_time = sleep_time\n",+ "\n",+ " def post_run_step(self, *, state: \"State\", action: \"Action\", **future_kwargs):\n",+ " if action.name != \"cow_should_say\": # no need to print if we're not saying anything\n",+ " time.sleep(self.sleep_time)"+ ],+ "metadata": {+ "collapsed": false,+ "ExecuteTime": {+ "end_time": "2024-03-27T00:13:03.529875Z",+ "start_time": "2024-03-27T00:13:03.524449Z"+ }+ },+ "id": "9f5b9bfc78851a59",+ "execution_count": 3+ },+ {+ "cell_type": "code",+ "outputs": [],+ "source": [+ "# instantiate actions\n",+ "@action(reads=[], writes=[\"cow_said\"])\n",+ "def cow_said(state: State, say_what: list[str]) -> Tuple[dict, State]:\n",+ " said = random.choice(say_what)\n",+ " result = {\"cow_said\": cowsay.get_output_string(\"cow\", said) if say_what is not None else None}\n",+ " return result, state.update(**result)\n",+ "\n",+ "\n",+ "@action(reads=[], writes=[\"cow_should_speak\"])\n",+ "def cow_should_speak(state: State) -> Tuple[dict, State]:\n",+ " result = {\"cow_should_speak\": random.randint(0, 3) == 0}\n",+ " return result, state.update(**result)\n"+ ],+ "metadata": {+ "collapsed": false,+ "ExecuteTime": {+ "end_time": "2024-03-27T00:13:12.756137Z",+ "start_time": "2024-03-27T00:13:12.750764Z"+ }+ },+ "id": "5b29e9de2ca536b9",+ "execution_count": 4+ },+ {+ "cell_type": "code",+ "outputs": [],+ "source": [+ "# build application\n",+ "hooks = [\n",+ " PrintWhatTheCowSaid(),\n",+ " CowCantSpeakFast(sleep_time=2.0),\n",+ "]\n",+ " \n",+ "app = (ApplicationBuilder()\n",+ " .with_state(cow_said=None)\n",+ " .with_actions(\n",+ " say_nothing=cow_said.bind(say_what=None),\n",+ " say_hello=cow_said.bind(\n",+ " say_what=[\"Hello world!\", \"What's up?\", \"Are you Aaron Burr, sir?\"]\n",+ " ),\n",+ " cow_should_speak=cow_should_speak,\n",+ " )\n",+ " .with_transitions(\n",+ " (\"cow_should_speak\", \"say_hello\", expr(\"cow_should_speak\")),\n",+ " (\"say_hello\", \"cow_should_speak\", default),\n",+ " (\"cow_should_speak\", \"say_nothing\", expr(\"not cow_should_speak\")),\n",+ " (\"say_nothing\", \"cow_should_speak\", default),\n",+ " )\n",+ " .with_entrypoint(\"cow_should_speak\")\n",+ " .with_hooks(*hooks)\n",+ " .build()\n",+ ")"+ ],+ "metadata": {+ "collapsed": false,+ "ExecuteTime": {+ "end_time": "2024-03-27T00:14:10.836543Z",+ "start_time": "2024-03-27T00:14:10.829258Z"+ }+ },+ "id": "271b868317fbbdf4",+ "execution_count": 5+ },+ {+ "cell_type": "code",+ "outputs": [+ {+ "data": {+ "image/svg+xml": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<!-- Generated by graphviz version 9.0.0 (20230911.1827)\n -->\n<!-- Pages: 1 -->\n<svg width=\"192pt\" height=\"209pt\"\n viewBox=\"0.00 0.00 192.02 209.00\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n<g id=\"graph0\" class=\"graph\" transform=\"scale(1 1) rotate(0) translate(4 205)\">\n<polygon fill=\"white\" stroke=\"none\" points=\"-4,4 -4,-205 188.02,-205 188.02,4 -4,4\"/>\n<!-- say_nothing -->\n<g id=\"node1\" class=\"node\">\n<title>say_nothing</title>\n<path fill=\"none\" stroke=\"black\" d=\"M89.27,-201C89.27,-201 31.27,-201 31.27,-201 25.27,-201 19.27,-195 19.27,-189 19.27,-189 19.27,-177 19.27,-177 19.27,-171 25.27,-165 31.27,-165 31.27,-165 89.27,-165 89.27,-165 95.27,-165 101.27,-171 101.27,-177 101.27,-177 101.27,-189 101.27,-189 101.27,-195 95.27,-201 89.27,-201\"/>\n<text text-anchor=\"middle\" x=\"60.27\" y=\"-177.95\" font-family=\"Times,serif\" font-size=\"14.00\">say_nothing</text>\n</g>\n<!-- cow_should_speak -->\n<g id=\"node3\" class=\"node\">\n<title>cow_should_speak</title>\n<path fill=\"none\" stroke=\"black\" d=\"M107.65,-118.5C107.65,-118.5 12.9,-118.5 12.9,-118.5 6.9,-118.5 0.9,-112.5 0.9,-106.5 0.9,-106.5 0.9,-94.5 0.9,-94.5 0.9,-88.5 6.9,-82.5 12.9,-82.5 12.9,-82.5 107.65,-82.5 107.65,-82.5 113.65,-82.5 119.65,-88.5 119.65,-94.5 119.65,-94.5 119.65,-106.5 119.65,-106.5 119.65,-112.5 113.65,-118.5 107.65,-118.5\"/>\n<text text-anchor=\"middle\" x=\"60.27\" y=\"-95.45\" font-family=\"Times,serif\" font-size=\"14.00\">cow_should_speak</text>\n</g>\n<!-- say_nothing->cow_should_speak -->\n<g id=\"edge4\" class=\"edge\">\n<title>say_nothing->cow_should_speak</title>\n<path fill=\"none\" stroke=\"black\" d=\"M58.99,-164.74C58.7,-159.97 58.42,-154.78 58.27,-150 58.04,-142.67 58.04,-140.83 58.27,-133.5 58.31,-132.3 58.35,-131.08 58.41,-129.85\"/>\n<polygon fill=\"black\" stroke=\"black\" points=\"61.88,-130.45 58.91,-120.27 54.89,-130.07 61.88,-130.45\"/>\n</g>\n<!-- say_hello -->\n<g id=\"node2\" class=\"node\">\n<title>say_hello</title>\n<path fill=\"none\" stroke=\"black\" d=\"M82.15,-36C82.15,-36 38.4,-36 38.4,-36 32.4,-36 26.4,-30 26.4,-24 26.4,-24 26.4,-12 26.4,-12 26.4,-6 32.4,0 38.4,0 38.4,0 82.15,0 82.15,0 88.15,0 94.15,-6 94.15,-12 94.15,-12 94.15,-24 94.15,-24 94.15,-30 88.15,-36 82.15,-36\"/>\n<text text-anchor=\"middle\" x=\"60.27\" y=\"-12.95\" font-family=\"Times,serif\" font-size=\"14.00\">say_hello</text>\n</g>\n<!-- say_hello->cow_should_speak -->\n<g id=\"edge2\" class=\"edge\">\n<title>say_hello->cow_should_speak</title>\n<path fill=\"none\" stroke=\"black\" d=\"M93.05,-36.42C97.97,-40.53 102.37,-45.38 105.27,-51 108.63,-57.52 108.63,-60.98 105.27,-67.5 104.09,-69.78 102.67,-71.94 101.06,-73.97\"/>\n<polygon fill=\"black\" stroke=\"black\" points=\"98.65,-71.43 94.11,-81 103.63,-76.35 98.65,-71.43\"/>\n</g>\n<!-- cow_should_speak->say_nothing -->\n<g id=\"edge3\" class=\"edge\">\n<title>cow_should_speak->say_nothing</title>\n<path fill=\"none\" stroke=\"black\" stroke-dasharray=\"5,2\" d=\"M60.27,-118.93C60.27,-128.95 60.27,-141.78 60.27,-153.25\"/>\n<polygon fill=\"black\" stroke=\"black\" points=\"56.77,-153.02 60.27,-163.02 63.77,-153.02 56.77,-153.02\"/>\n<text text-anchor=\"middle\" x=\"122.15\" y=\"-136.7\" font-family=\"Times,serif\" font-size=\"14.00\">not cow_should_speak</text>\n</g>\n<!-- cow_should_speak->say_hello -->\n<g id=\"edge1\" class=\"edge\">\n<title>cow_should_speak->say_hello</title>\n<path fill=\"none\" stroke=\"black\" stroke-dasharray=\"5,2\" d=\"M16.41,-82.17C10.87,-78.17 5.95,-73.33 2.52,-67.5 -4.42,-55.72 3.91,-45.49 16.2,-37.49\"/>\n<polygon fill=\"black\" stroke=\"black\" points=\"17.9,-40.55 24.87,-32.57 14.44,-34.46 17.9,-40.55\"/>\n<text text-anchor=\"middle\" x=\"54.65\" y=\"-54.2\" font-family=\"Times,serif\" font-size=\"14.00\">cow_should_speak</text>\n</g>\n</g>\n</svg>\n",+ "text/plain": "<graphviz.graphs.Digraph at 0x1107a98a0>"+ },+ "execution_count": 6,+ "metadata": {},+ "output_type": "execute_result"+ }+ ],+ "source": [+ "app.visualize(include_conditions=True)"+ ],+ "metadata": {+ "collapsed": false,+ "ExecuteTime": {+ "end_time": "2024-03-27T00:14:29.829383Z",+ "start_time": "2024-03-27T00:14:29.511355Z"+ }+ },+ "id": "794bc0abda9e48ad",+ "execution_count": 6+ },+ {+ "cell_type": "code",+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ " ____________\n",+ "| Hello world! |\n",+ " ============\n",+ " \\\n",+ " \\\n",+ " ^__^\n",+ " (oo)\\_______\n",+ " (__)\\ )\\/\\\n",+ " ||----w |\n",+ " || ||\n",+ " ____________\n",+ "| Hello world! |\n",+ " ============\n",+ " \\\n",+ " \\\n",+ " ^__^\n",+ " (oo)\\_______\n",+ " (__)\\ )\\/\\\n",+ " ||----w |\n",+ " || ||\n",+ " ____________\n",+ "| Hello world! |\n",+ " ============\n",+ " \\\n",+ " \\\n",+ " ^__^\n",+ " (oo)\\_______\n",+ " (__)\\ )\\/\\\n",+ " ||----w |\n",+ " || ||\n",+ " ____________\n",+ "| Hello world! |\n",+ " ============\n",+ " \\\n",+ " \\\n",+ " ^__^\n",+ " (oo)\\_______\n",+ " (__)\\ )\\/\\\n",+ " ||----w |\n",+ " || ||\n"+ ]+ }+ ],+ "source": [+ "# run things!\n",+ "for i in range(0, 4):\n",+ " # step through 4 times\n",+ " a_obj, result, state = app.step()"+ ],+ "metadata": {+ "collapsed": false,+ "ExecuteTime": {+ "end_time": "2024-03-27T00:16:40.234406Z",+ "start_time": "2024-03-27T00:16:32.211734Z"+ }+ },+ "id": "2facfb753233cd7d",+ "execution_count": 11+ },+ {+ "cell_type": "code",+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ " ________________________\n",+ "| Are you Aaron Burr, sir? |\n",+ " ========================\n",+ " \\\n",+ " \\\n",+ " ^__^\n",+ " (oo)\\_______\n",+ " (__)\\ )\\/\\\n",+ " ||----w |\n",+ " || ||\n",+ " ________________________\n",+ "| Are you Aaron Burr, sir? |\n",+ " ========================\n",+ " \\\n",+ " \\\n",+ " ^__^\n",+ " (oo)\\_______\n",+ " (__)\\ )\\/\\\n",+ " ||----w |\n",+ " || ||\n",+ " ____________\n",+ "| Hello world! |\n",+ " ============\n",+ " \\\n",+ " \\\n",+ " ^__^\n",+ " (oo)\\_______\n",+ " (__)\\ )\\/\\\n",+ " ||----w |\n",+ " || ||\n",+ " ____________\n",+ "| Hello world! |\n",+ " ============\n",+ " \\\n",+ " \\\n",+ " ^__^\n",+ " (oo)\\_______\n",+ " (__)\\ )\\/\\\n",+ " ||----w |\n",+ " || ||\n"+ ]+ }+ ],+ "source": [+ "# Run some more\n",+ "for i in range(0, 4):\n",+ " # step through 4 times\n",+ " a_obj, result, state = app.step()"+ ],+ "metadata": {+ "collapsed": false,+ "ExecuteTime": {+ "end_time": "2024-03-27T00:17:18.640978Z",+ "start_time": "2024-03-27T00:17:10.619878Z"+ }+ },+ "id": "fed65721e7cc457a",+ "execution_count": 16+ },+ {+ "cell_type": "code",+ "outputs": [],+ "source": [],+ "metadata": {+ "collapsed": false+ },+ "id": "19095ae96e98fd83"+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 2+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython2",+ "version": "2.7.6"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}diff --git a/examples/other-examples/cowsay/requirements.txt b/examples/other-examples/cowsay/requirements.txtnew file mode 100644index 00000000..ee7475ae--- /dev/null+++ b/examples/other-examples/cowsay/requirements.txt@@ -0,0 +1,2 @@+burr[streamlit,graphviz]+cowsaydiff --git a/examples/other-examples/cowsay/streamlit_app.py b/examples/other-examples/cowsay/streamlit_app.pynew file mode 100644index 00000000..8db01336--- /dev/null+++ b/examples/other-examples/cowsay/streamlit_app.py@@ -0,0 +1,69 @@+import application as cowsay_application+import streamlit as st++from burr.integrations.streamlit import (+ AppState,+ Record,+ get_state,+ render_explorer,+ set_slider_to_current,+ update_state,+)+++def cow_say_view(app_state: AppState):+ application = app_state.app+ button = st.button("Cow say?", use_container_width=True)+ if button:+ step_output = application.step()+ action, result, state = step_output+ app_state.history.append(Record(state.get_all(), action.name, result))+ set_slider_to_current()+++def render_cow_said(record: Record):+ cow_said = record.state.get("cow_said")+ cow_should_speak = record.state.get("cow_should_speak")+ with st.chat_message("cow", avatar="🐮" if cow_should_speak and cow_said else "💭"):+ grey = "#A9A9A9"+ if record.action == "cow_should_say":+ if cow_should_speak:+ st.markdown(+ f"<p style='color: {grey};'>Cow will not speak.</p>", unsafe_allow_html=True+ )+ else:+ st.markdown(+ f"<p style='color: {grey};'>Cow will not speak.</p>", unsafe_allow_html=True+ )+ else:+ if cow_said is None:+ st.markdown(f"<p style='color: {grey};'>...</p>", unsafe_allow_html=True)+ if cow_said is not None:+ st.code(cow_said, language="plaintext")+++def retrieve_state():+ if "burr_state" not in st.session_state:+ state = AppState.from_empty(app=cowsay_application.application())+ else:+ state = get_state()+ return state+++def main():+ st.set_page_config(layout="wide")+ st.title("Talking cows with Burr")+ app_state = retrieve_state() # retrieve first so we can use for the ret of the step+ columns = st.columns(2)+ with columns[0]:+ cow_say_view(app_state)+ with st.container(height=800):+ for item in app_state.history:+ render_cow_said(item)+ with columns[1]:+ render_explorer(app_state)+ update_state(app_state) # update so the next iteration knows what to do+++if __name__ == "__main__":+ main()diff --git a/examples/other-examples/image-telephone/README.md b/examples/other-examples/image-telephone/README.mdnew file mode 100644index 00000000..23864316--- /dev/null+++ b/examples/other-examples/image-telephone/README.md@@ -0,0 +1,24 @@+# Image Telephone++This example demonstrates how to play telephone with DALL-E and ChatGPT.++You provide an initial image to ChatGPT, which then generates a caption. The caption+is saved to state. That caption is then provided to DALL-E, which generates an image, which is saved to state.+You then provide that image to ChatGPT, and so on.++Right now the teriminal state is set to 2, so the game will end after 2 iterations:++++## Modifying the game+There are two levels you can modify:++1. The high-level orchestration and state management+2. What each action actually does.++For the high-level orchestration you can add more nodes, change conditions, etc.++For the low-level actions, you can change the prompt, the template, etc. too. To do so see the+documentation for the Hamilton dataflows that are used: [captioning](https://hub.dagworks.io/docs/Users/elijahbenizzy/caption_images/) and+[generating image](https://hub.dagworks.io/docs/Users/elijahbenizzy/generate_images/). You can easily modify the prompt and+template by overriding values, or by copying the code and modifying it yourself in 2 minutes - see instructions on the [hub](https://hub.dagworks.io/).diff --git a/examples/other-examples/image-telephone/application.py b/examples/other-examples/image-telephone/application.pynew file mode 100644index 00000000..599d2400--- /dev/null+++ b/examples/other-examples/image-telephone/application.py@@ -0,0 +1,156 @@+from typing import Tuple++from hamilton import dataflows, driver++from burr.core import Action, ApplicationBuilder, State, default, expr+from burr.core.action import action+from burr.integrations import hamilton+from burr.lifecycle import PostRunStepHook++caption_images = dataflows.import_module("caption_images", "elijahbenizzy")+generate_images = dataflows.import_module("generate_images", "elijahbenizzy")+++caption_image_driver = driver.Builder().with_config({}).with_modules(caption_images).build()++generate_image_driver = driver.Builder().with_config({}).with_modules(generate_images).build()+++class PrintStepHook(PostRunStepHook):+ 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=["current_image_location"],+ writes=["current_image_caption", "image_location_history"],+)+def image_caption(state: State) -> Tuple[dict, State]:+ current_image = state["current_image_location"]+ result = caption_image_driver.execute(+ ["generated_caption"], inputs={"image_url": current_image}+ )+ updates = {+ "current_image_caption": result["generated_caption"],+ }+ return result, state.update(**updates).append(image_location_history=current_image)+++# procedural way to do this+@action(+ reads=["current_image_caption"],+ writes=["current_image_location", "image_caption_history"],+)+def image_generation(state: State) -> Tuple[dict, State]:+ current_caption = state["current_image_caption"]+ result = generate_image_driver.execute(+ ["generated_image"], inputs={"image_generation_prompt": current_caption}+ )+ updates = {+ "current_image_location": result["generated_image"],+ }+ return result, state.update(**updates).append(image_caption_history=current_caption)+++@action(reads=[], writes=[])+def terminal_step(state: State) -> Tuple[dict, State]:+ return {}, state+++def regular_action_main():+ """This shows how one might define functions to be nodes."""+ app = (+ ApplicationBuilder()+ .with_state(+ current_image_location="telephone_graph.png",+ current_image_caption="",+ image_location_history=[],+ image_caption_history=[],+ )+ .with_actions(+ caption=image_caption,+ image=image_generation,+ terminal=terminal_step,+ )+ .with_transitions(+ ("caption", "image", default),+ ("image", "terminal", expr("len(image_caption_history) == 2")),+ ("image", "caption", default),+ )+ .with_entrypoint("caption")+ .with_hooks(PrintStepHook())+ .with_tracker(project="image-telephone")+ .build()+ )+ return app+++def hamilton_action_main():+ """This shows how to use the Hamilton syntactic wrapper for the nodes."""++ _caption = hamilton.Hamilton(+ inputs={"image_url": hamilton.from_state("current_image_location")},+ outputs={+ "generated_caption": hamilton.update_state("current_image_caption"),+ "image_url": hamilton.append_state("image_location_history"),+ },+ driver=caption_image_driver,+ )+ _image = hamilton.Hamilton(+ inputs={"image_generation_prompt": hamilton.from_state("current_image_caption")},+ outputs={+ "generated_image": hamilton.update_state("current_image_location"),+ "image_generation_prompt": hamilton.append_state("image_caption_history"),+ },+ driver=generate_image_driver,+ )+ app = (+ ApplicationBuilder()+ .with_state(+ current_image_location="telephone_graph.png",+ current_image_caption="",+ image_location_history=[],+ image_caption_history=[],+ )+ .with_actions(+ caption=_caption,+ image=_image,+ terminal=terminal_step,+ )+ .with_transitions(+ ("caption", "image", default),+ ("image", "terminal", expr("len(image_caption_history) == 2")),+ ("image", "caption", default),+ )+ .with_entrypoint("caption")+ .with_hooks(PrintStepHook())+ .with_tracker(project="image-telephone")+ .build()+ )+ return app+++if __name__ == "__main__":+ import random++ coin_flip = random.choice([True, False])+ if coin_flip:+ app = hamilton_action_main()+ else:+ app = regular_action_main()+ app.visualize(+ output_file_path="telephone_graph", include_conditions=True, view=True, format="png"+ )+ if coin_flip:+ app.run(halt_after=["terminal"])+ else:+ # alternate way to run:+ while True:+ action, result, state = app.step()+ print("action=====\n", action)+ print("result=====\n", result)+ print("state======\n", state)+ if action.name == "terminal":+ breakdiff --git a/examples/other-examples/image-telephone/telephone_graph.png b/examples/other-examples/image-telephone/telephone_graph.pngnew file mode 100644index 00000000..eacaa87cBinary files /dev/null and b/examples/other-examples/image-telephone/telephone_graph.png differ