Skip to content

armgit / burr

Public Imported from GitHub
0

Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.

Makes multi-modal-chatbot compliant

elijahbenizzy5e446f2539ed
diff --git a/examples/multi-modal-chatbot/Digraph.gv b/examples/multi-modal-chatbot/Digraph.gv
deleted file mode 100644
index 71128c8b..00000000
--- a/examples/multi-modal-chatbot/Digraph.gv
+++ /dev/null
@@ -1,28 +0,0 @@
-digraph {
- graph [compound=false concentrate=false rankdir=TB ranksep=0.4]
- prompt [label=prompt shape=box style=rounded]
- input__prompt [label="input: prompt" shape=oval style=dashed]
- input__prompt -> prompt
- check_openai_key [label=check_openai_key shape=box style=rounded]
- check_safety [label=check_safety shape=box style=rounded]
- decide_mode [label=decide_mode shape=box style=rounded]
- generate_image [label=generate_image shape=box style=rounded]
- generate_code [label=generate_code shape=box style=rounded]
- answer_question [label=answer_question shape=box style=rounded]
- prompt_for_more [label=prompt_for_more shape=box style=rounded]
- response [label=response shape=box style=rounded]
- prompt -> check_openai_key [style=solid]
- check_openai_key -> check_safety [style=dashed]
- check_openai_key -> response [style=solid]
- check_safety -> decide_mode [style=dashed]
- check_safety -> response [style=solid]
- decide_mode -> generate_image [style=dashed]
- decide_mode -> generate_code [style=dashed]
- decide_mode -> answer_question [style=dashed]
- decide_mode -> prompt_for_more [style=solid]
- generate_image -> response [style=solid]
- answer_question -> response [style=solid]
- generate_code -> response [style=solid]
- prompt_for_more -> response [style=solid]
- response -> prompt [style=solid]
-}
diff --git a/examples/multi-modal-chatbot/Digraph.gv.pdf b/examples/multi-modal-chatbot/Digraph.gv.pdf
deleted file mode 100644
index 91eb4aba..00000000
Binary files a/examples/multi-modal-chatbot/Digraph.gv.pdf and /dev/null differ
diff --git a/examples/multi-modal-chatbot/__init__.py b/examples/multi-modal-chatbot/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/examples/multi-modal-chatbot/application.py b/examples/multi-modal-chatbot/application.py
index 38ad8281..86d175dd 100644
--- a/examples/multi-modal-chatbot/application.py
+++ b/examples/multi-modal-chatbot/application.py
@@ -3,11 +3,9 @@ import os
from typing import List, Optional, Tuple
import openai
-from hamilton import driver
from burr.core import Application, ApplicationBuilder, State, default, when
from burr.core.action import action
-from burr.integrations.hamilton import Hamilton, append_state, from_state, update_state
from burr.lifecycle import LifecycleAdapter
from burr.tracking import LocalTrackingClient
@@ -200,90 +198,15 @@ def base_application(
)
-def hamilton_application(
- hooks: List[LifecycleAdapter], app_id: str, storage_dir: str, project_id: str
-):
- import dag
-
- dr = driver.Driver({"provider": "openai"}, dag) # TODO -- add modules
- Hamilton.set_driver(dr)
- application = (
- ApplicationBuilder()
- .with_state(chat_history=[], prompt="Draw an image of a turtle saying 'hello, world'")
- .with_entrypoint("prompt")
- .with_state(chat_history=[])
- .with_actions(
- prompt=Hamilton(
- inputs={"prompt": from_state("prompt")},
- outputs={"processed_prompt": append_state("chat_history")},
- ),
- check_safety=Hamilton(
- inputs={"prompt": from_state("prompt")},
- outputs={"safe": update_state("safe")},
- ),
- decide_mode=Hamilton(
- inputs={"prompt": from_state("prompt")},
- outputs={"mode": update_state("mode")},
- ),
- generate_image=Hamilton(
- inputs={"prompt": from_state("prompt")},
- outputs={"generated_image": update_state("response")},
- ),
- generate_code=Hamilton( # TODO -- implement
- inputs={"chat_history": from_state("chat_history")},
- outputs={"generated_code": update_state("response")},
- ),
- answer_question=Hamilton( # TODO -- implement
- inputs={"chat_history": from_state("chat_history")},
- outputs={"answered_question": update_state("response")},
- ),
- prompt_for_more=Hamilton(
- inputs={},
- outputs={"prompt_for_more": update_state("response")},
- ),
- response=Hamilton(
- inputs={
- "response": from_state("response"),
- "safe": from_state("safe"),
- "mode": from_state("mode"),
- },
- outputs={"processed_response": append_state("chat_history")},
- ),
- )
- .with_transitions(
- ("prompt", "check_safety", default),
- ("check_safety", "decide_mode", when(safe=True)),
- ("check_safety", "response", default),
- ("decide_mode", "generate_image", when(mode="generate_image")),
- ("decide_mode", "generate_code", when(mode="generate_code")),
- ("decide_mode", "answer_question", when(mode="answer_question")),
- ("decide_mode", "prompt_for_more", default),
- (
- ["generate_image", "answer_question", "generate_code", "prompt_for_more"],
- "response",
- ),
- ("response", "prompt", default),
- )
- .with_hooks(*hooks)
- .with_identifiers(app_id=app_id)
- .with_tracker("local", project=project_id, params={"storage_dir": storage_dir})
- .build()
- )
- return application
-
-
def application(
- use_hamilton: bool,
app_id: Optional[str] = None,
project_id: str = "demo:chatbot",
storage_dir: Optional[str] = "~/.burr",
hooks: Optional[List[LifecycleAdapter]] = None,
) -> Application:
- if use_hamilton:
- return hamilton_application(hooks, app_id, storage_dir, project_id=project_id)
return base_application(hooks, app_id, storage_dir, project_id=project_id)
if __name__ == "__main__":
- app = application(use_hamilton=False)
+ app = application()
app.visualize(output_file_path="digraph", include_conditions=False, view=True, format="png")
diff --git a/examples/multi-modal-chatbot/application_with_traces.py b/examples/multi-modal-chatbot/application_with_traces.py
deleted file mode 100644
index 2c39b54b..00000000
--- a/examples/multi-modal-chatbot/application_with_traces.py
+++ /dev/null
@@ -1,209 +0,0 @@
-from typing import List, Optional, Tuple
-
-import openai
-
-from burr.core import Application, ApplicationBuilder, State, default, when
-from burr.core.action import action
-from burr.lifecycle import LifecycleAdapter
-from burr.visibility import TracerFactory
-
-MODES = {
- "answer_question": "text",
- "generate_image": "image",
- "generate_code": "code",
- "unknown": "text",
-}
-
-
-@action(reads=[], writes=["chat_history", "prompt"])
-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, __tracer: TracerFactory) -> Tuple[dict, State]:
- with __tracer("check_safety"):
- result = {"safe": "unsafe" not in state["prompt"]} # quick hack to demonstrate
- return result, state.update(safe=result["safe"])
-
-
-def _get_openai_client():
- return openai.Client()
-
-
-@action(reads=["prompt"], writes=["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)
-
-
-@action(reads=["prompt", "chat_history"], writes=["response"])
-def prompt_for_more(state: State) -> Tuple[dict, State]:
- result = {
- "response": {
- "content": "None of the response modes I support apply to your question. Please clarify?",
- "type": "text",
- "role": "assistant",
- }
- }
- return result, state.update(**result)
-
-
-@action(reads=["prompt", "chat_history", "mode"], writes=["response"])
-def chat_response(
- state: State,
- prepend_prompt: str,
- __tracer: TracerFactory,
- model: str = "gpt-3.5-turbo",
-) -> Tuple[dict, State]:
- 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"}
- }
- return result, state.update(**result)
-
-
-@action(reads=["prompt", "chat_history", "mode"], writes=["response"])
-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, __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"])
-
-
-# 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], app_id: str, storage_dir: str):
- if hooks is None:
- hooks = []
- return (
- ApplicationBuilder()
- .with_actions(
- prompt=process_prompt,
- check_safety=check_safety,
- decide_mode=choose_mode,
- generate_image=image_response,
- generate_code=chat_response.bind(
- prepend_prompt="Please respond with *only* code and no other text (at all) to the following:",
- ),
- answer_question=chat_response.bind(
- prepend_prompt="Please answer the following question:",
- ),
- prompt_for_more=prompt_for_more,
- response=response,
- )
- .with_entrypoint("prompt")
- .with_state(chat_history=[])
- .with_transitions(
- ("prompt", "check_safety", default),
- ("check_safety", "decide_mode", when(safe=True)),
- ("check_safety", "response", default),
- ("decide_mode", "generate_image", when(mode="generate_image")),
- ("decide_mode", "generate_code", when(mode="generate_code")),
- ("decide_mode", "answer_question", when(mode="answer_question")),
- ("decide_mode", "prompt_for_more", default),
- (
- ["generate_image", "answer_question", "generate_code", "prompt_for_more"],
- "response",
- ),
- ("response", "prompt", default),
- )
- .with_hooks(*hooks)
- .with_tracker(project="demo:tracing", params={"storage_dir": storage_dir})
- .with_identifiers(app_id=app_id)
- .build()
- )
-
-
-def application(
- app_id: Optional[str] = None,
- storage_dir: Optional[str] = "~/.burr",
- hooks: Optional[List[LifecycleAdapter]] = None,
-) -> Application:
- return base_application(hooks, app_id, storage_dir)
-
-
-if __name__ == "__main__":
- app = application()
- app.visualize(output_file_path="digraph", include_conditions=False, view=True, format="png")
diff --git a/examples/multi-modal-chatbot/dag.py b/examples/multi-modal-chatbot/dag.py
deleted file mode 100644
index ce8ef9e4..00000000
--- a/examples/multi-modal-chatbot/dag.py
+++ /dev/null
@@ -1,156 +0,0 @@
-import copy
-from typing import Dict, Optional, TypedDict
-
-import openai
-from hamilton.function_modifiers import config
-
-ChatContents = TypedDict("ChatContents", {"role": str, "content": str, "type": str})
-
-
-def processed_prompt(prompt: str) -> dict:
- return {"role": "user", "content": prompt, "type": "text"}
-
-
[email protected](provider="openai")
-def client() -> openai.Client:
- return openai.Client()
-
-
-def text_model() -> str:
- return "gpt-3.5-turbo"
-
-
-def image_model() -> str:
- return "dall-e-2"
-
-
-def safe(prompt: str) -> bool:
- if "unsafe" in prompt:
- return False
- return True
-
-
-def modes() -> Dict[str, str]:
- return {
- "answer_question": "text",
- "generate_image": "image",
- "generate_code": "code",
- "unknown": "text",
- }
-
-
-def find_mode_prompt(prompt: str, modes: Dict[str, str]) -> str:
- return (
- f"You are a chatbot. You've been prompted this: {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'."
- )
-
-
-def suggested_mode(find_mode_prompt: str, client: openai.Client, text_model: str) -> str:
- result = client.chat.completions.create(
- model=text_model,
- messages=[
- {"role": "system", "content": "You are a helpful assistant"},
- {"role": "user", "content": find_mode_prompt},
- ],
- )
- content = result.choices[0].message.content
- return content
-
-
-def mode(suggested_mode: str, modes: Dict[str, str]) -> str:
- # TODO -- use instructor!
- print(f"Mode: {suggested_mode}")
- lowercase = suggested_mode.lower()
- if lowercase not in modes:
- return "unknown" # default to unknown
- return lowercase
-
-
-def generated_text(chat_history: list[dict], text_model: str, client: openai.Client) -> str:
- chat_history_api_format = [
- {
- "role": chat["role"],
- "content": chat["content"],
- }
- for i, chat in enumerate(chat_history)
- ]
- result = client.chat.completions.create(
- model=text_model,
- messages=chat_history_api_format,
- )
- return result.choices[0].message.content
-
-
-# def generated_text_error(generated_text) -> dict:
-# ...
-
-
-def generated_image(prompt: str, image_model: str, client: openai.Client) -> str:
- result = client.images.generate(
- model=image_model, prompt=prompt, size="1024x1024", quality="standard", n=1
- )
- return result.data[0].url
-
-
-def answered_question(chat_history: list[dict], text_model: str, client: openai.Client) -> str:
- chat_history = copy.deepcopy(chat_history)
- chat_history[-1][
- "content"
- ] = f"Please answer the following question: {chat_history[-1]['content']}"
-
- chat_history_api_format = [
- {
- "role": chat["role"],
- "content": chat["content"],
- }
- for i, chat in enumerate(chat_history)
- ]
- response = client.chat.completions.create(
- model=text_model,
- messages=chat_history_api_format,
- )
- return response.choices[0].message.content
-
-
-def generated_code(chat_history: list[dict], text_model: str, client: openai.Client) -> str:
- chat_history = copy.deepcopy(chat_history)
- chat_history[-1][
- "content"
- ] = f"Please respond to the following with *only* code: {chat_history[-1]['content']}"
-
- chat_history_api_format = [
- {
- "role": chat["role"],
- "content": chat["content"],
- }
- for i, chat in enumerate(chat_history)
- ]
- response = client.chat.completions.create(
- model=text_model,
- messages=chat_history_api_format,
- )
- return response.choices[0].message.content
-
-
-def prompt_for_more(modes: Dict[str, str]) -> str:
- return (
- f"I can't find a mode that applies to your input. Can you"
- f" please clarify? I support: {', '.join(modes)}."
- )
-
-
-def processed_response(
- response: Optional[str], mode: str, modes: Dict[str, str], safe: bool
-) -> ChatContents:
- if not safe:
- return {"role": "assistant", "content": "I'm sorry, I can't do that.", "type": "text"}
- return {"role": "assistant", "type": modes[mode], "content": response}
-
-
-def processed_error(error: str) -> dict:
- return {"role": "assistant", "error": error, "type": "text"}
diff --git a/examples/multi-modal-chatbot/digraph b/examples/multi-modal-chatbot/digraph
deleted file mode 100644
index ea35f895..00000000
--- a/examples/multi-modal-chatbot/digraph
+++ /dev/null
@@ -1,25 +0,0 @@
-digraph {
- graph [compound=false concentrate=false rankdir=TB ranksep=0.4]
- prompt [label=prompt shape=box style=rounded]
- input__prompt [label="input: prompt" shape=oval style=dashed]
- input__prompt -> prompt
- check_safety [label=check_safety shape=box style=rounded]
- decide_mode [label=decide_mode shape=box style=rounded]
- generate_image [label=generate_image shape=box style=rounded]
- generate_code [label=generate_code shape=box style=rounded]
- answer_question [label=answer_question shape=box style=rounded]
- prompt_for_more [label=prompt_for_more shape=box style=rounded]
- response [label=response shape=box style=rounded]
- prompt -> check_safety [style=solid]
- check_safety -> decide_mode [style=dashed]
- check_safety -> response [style=solid]
- decide_mode -> generate_image [style=dashed]
- decide_mode -> generate_code [style=dashed]
- decide_mode -> answer_question [style=dashed]
- decide_mode -> prompt_for_more [style=solid]
- generate_image -> response [style=solid]
- answer_question -> response [style=solid]
- generate_code -> response [style=solid]
- prompt_for_more -> response [style=solid]
- response -> prompt [style=solid]
-}
diff --git a/examples/multi-modal-chatbot/gpt.png b/examples/multi-modal-chatbot/gpt.png
deleted file mode 100644
index 25676e1f..00000000
Binary files a/examples/multi-modal-chatbot/gpt.png and /dev/null differ
diff --git a/examples/multi-modal-chatbot/notebook.ipynb b/examples/multi-modal-chatbot/notebook.ipynb
new file mode 100644
index 00000000..c89cf9e2
--- /dev/null
+++ b/examples/multi-modal-chatbot/notebook.ipynb
@@ -0,0 +1,98 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "0ebb856d-fdb0-412c-8eaf-27af91a35ce3",
+ "metadata": {},
+ "source": [
+ "# Simple Multi-Modal chatbot\n",
+ "\n",
+ "This runs through an example of a multi-modal chatbot. Follow in the [application.py] file for specific implementation."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "89b22472-8074-4adb-9d19-fcbaf8cd94c2",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from application import application as multi_modal_chatbot"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "84068205-605f-45c8-9b2e-5a3f787d598a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "app = multi_modal_chatbot()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0b21d035-ec45-4606-b3d7-e4dfd0266a47",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "app.visualize(include_conditions=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "923beb31-3abf-4511-9f86-007a46734f21",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "action, result, state = app.run(halt_after=[\"response\"], inputs={\"prompt\" : \"please draw a turtle\"})\n",
+ "print(result)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "de4ca6ad-2eeb-4ba5-8bad-df807546c848",
+ "metadata": {},
+ "source": [
+ "# Viewing in UI\n",
+ "\n",
+ "The following cell gives you a link to the prior run in the UI. If you have not yet, run `burr` in your terminal to start the local tracking server."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "84e812d2-9a40-4bcb-a031-4e3ab7d4ca1c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from IPython.display import Markdown\n",
+ "url = f\"[Link to UI](http://localhost:7241/project/demo:chatbot/{app.uid})\"\n",
+ "Markdown(url)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.11.6"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/examples/multi-modal-chatbot/simple_streamlit_app.py b/examples/multi-modal-chatbot/simple_streamlit_app.py
index 1a221fb4..0a8be42d 100644
--- a/examples/multi-modal-chatbot/simple_streamlit_app.py
+++ b/examples/multi-modal-chatbot/simple_streamlit_app.py
@@ -22,7 +22,7 @@ def render_chat_message(chat_item: dict):
def initialize_app() -> burr.core.Application:
if "burr_app" not in st.session_state:
st.session_state.burr_app = chatbot_application.application(
- use_hamilton=False, app_id=f"chat:{str(uuid.uuid4())[0:6]}"
+ app_id=f"chat:{str(uuid.uuid4())[0:6]}"
)
return st.session_state.burr_app
diff --git a/examples/multi-modal-chatbot/digraph.png b/examples/multi-modal-chatbot/statemachine.png
similarity index 100%
rename from examples/multi-modal-chatbot/digraph.png
rename to examples/multi-modal-chatbot/statemachine.png
diff --git a/examples/multi-modal-chatbot/streamlit_app.py b/examples/multi-modal-chatbot/streamlit_app.py
index 847f043b..13fad0df 100644
--- a/examples/multi-modal-chatbot/streamlit_app.py
+++ b/examples/multi-modal-chatbot/streamlit_app.py
@@ -42,9 +42,7 @@ def retrieve_state():
# TODO --enable usage of hamilton. Currently its not wiring in inputs
# But it should be easy enough
state = AppState.from_empty(
- app=chatbot_application.application(
- use_hamilton=False,
- ),
+ app=chatbot_application.application(),
)
else:
state = get_state()