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.

Streaming example

elijahbenizzybf7d5b400c9e
diff --git a/burr/core/action.py b/burr/core/action.py
index e2743483..73a57252 100644
--- a/burr/core/action.py
+++ b/burr/core/action.py
@@ -1013,10 +1013,10 @@ class FunctionRepresentingAction(Protocol[C]):
def copy_func(f: types.FunctionType) -> types.FunctionType:
"""Copies a function. This is used internally to bind parameters to a function
- so we don't accidentally overwrite them
+ so we don't accidentally overwrite them.
- :param f:
- :return:
+ :param f: Function to copy
+ :return: The copied function
"""
fn = types.FunctionType(f.__code__, f.__globals__, f.__name__, f.__defaults__, f.__closure__)
fn.__dict__.update(f.__dict__)
diff --git a/burr/tracking/server/run.py b/burr/tracking/server/run.py
index 9f318a11..be99070a 100644
--- a/burr/tracking/server/run.py
+++ b/burr/tracking/server/run.py
@@ -18,6 +18,7 @@ try:
# dynamic importing due to the dashes (which make reading the examples on github easier)
email_assistant = importlib.import_module("burr.examples.email-assistant.server")
chatbot = importlib.import_module("burr.examples.multi-modal-chatbot.server")
+ streaming_chatbot = importlib.import_module("burr.examples.streaming-fastapi.server")
except ImportError as e:
require_plugin(
@@ -97,7 +98,7 @@ async def version() -> dict:
# Examples -- todo -- put them behind `if` statements
app.include_router(chatbot.router, prefix="/api/v0/chatbot")
app.include_router(email_assistant.router, prefix="/api/v0/email_assistant")
-# email_assistant.register(app, "/api/v0/email_assistant")
+app.include_router(streaming_chatbot.router, prefix="/api/v0/streaming_chatbot")
if SERVE_STATIC:
diff --git a/examples/streaming-fastapi/README.md b/examples/streaming-fastapi/README.md
new file mode 100644
index 00000000..32bddafc
--- /dev/null
+++ b/examples/streaming-fastapi/README.md
@@ -0,0 +1,214 @@
+# Streaming in FastAPI
+
+This example demonstrates how to stream data from Burr's streaming mode through FastAPI.
+
+This is gone over in more detail in our blog post (coming soon). This README will go over the main code + roles and how to run the example.
+
+This uses Server Sent Events (SSE) to stream data from FastAPI to the frontend. This also uses Async Generators to ensure optimal performance.
+
+## Example
+
+The application we created will be a simple chatbot proxy. It has a few diffrent modes -- it can either decide a prompt is "unsafe" (in this case meaning that it has the word "unsafe" in it, but this would typically go to specific model),
+or do one of the following:
+
+1. Generate code
+2. Answer a question
+3. Generate a poem
+4. Prompt for more
+
+It will use an LLM to decide which to do. It streams back text using async streaming in Burr. Read more about how that is implemented [here](https://burr.dagworks.io/concepts/streaming-actions/).
+
+Note that, even though not every response is streaming (E.G. unsafe response, which is hardcoded), they are modeled as streaming to make interaction with the app simpler.
+
+The app looks like this:
+
+![application graph](statemachine.png)
+
+## Running the example
+
+You will need an API key from Open AI to run this.
+
+You'll first have to have `burr[start]` installed. You can then view this demo in your app by running Burr:
+
+```bash
+burr
+```
+
+This will open a browser on [http://localhost:7241](http://localhost:7241)
+
+Navigate to the [streaming example](http://localhost:7241/demos/streaming-chatbot).
+
+## Streaming in Burr
+
+Read more [here](https://burr.dagworks.io/concepts/streaming-actions/)
+To use streaming in Burr, you write your actions as a generator. If you're using the function-based API (as we do in this example),
+the function should yield a tuple, consisting of:
+1. The result (intermediate or final)
+2. The updated (`None` if intermediate, present if final)
+
+(2) will always be the last yield, and indicate that the streaming action is complete. Take, for example, the
+"unsafe" response, meaning that the LLM has determined that it cannot respond. This is a simple example -- just to illustrate streaming:
+
+This sleeps to make a point (and make the demo more fun/give the appearance of the app "thinking") -- in reality you really would not want to do this.
+
+```python
+@streaming_action(reads=["prompt", "chat_history"], writes=["response"])
+async def unsafe_response(state: State) -> Tuple[dict, State]:
+ result = {
+ "response": {
+ "content": "I am afraid I can't respond to that...",
+ "type": "text",
+ "role": "assistant",
+ }
+ }
+ for word in result["response"]["content"].split():
+ await asyncio.sleep(0.1)
+ yield {"delta": word + " "}, None
+ yield result, state.update(**result).append(chat_history=result["response"])
+```
+
+This is an async generator that yields just the delta until it gets to the end. This can easily proxy from another service (openAI for example),
+or do some other async operation.
+
+When you call the action, you will get back a `AsyncStreamingResponseContainer` object. This is *also* an async generator!
+
+```python
+action, streaming_container = await app.astream_result(
+ halt_after=TERMINAL_ACTIONS, inputs={"prompt": "Please generate a limerick about Alexander Hamilton and Aaron Burr"}
+)
+
+async for item in streaming_container:
+ print(item['delta'], end="")
+```
+
+This will stream the results out.
+
+## Connecting to FastAPI
+
+To connect to FastAPI, we need to do the following:
+
+1. Instantiate a Burr Application in FastAPI
+2. Create a route that will stream the data to the frontend, which is *also* an async generator.
+3. Bridge the two together
+
+In [server.py](server.py), we have a helpful `_get_application` function that will get or create an application for us.
+We can then call a chat_response function that looks like this:
+
+```python
[email protected]("/response/{project_id}/{app_id}", response_class=StreamingResponse)
+async def chat_response(project_id: str, app_id: str, prompt: PromptInput) -> StreamingResponse:
+ burr_app = _get_application(project_id, app_id)
+ chat_history = burr_app.state.get("chat_history", [])
+ action, streaming_container = await burr_app.astream_result(
+ halt_after=chat_application.TERMINAL_ACTIONS, inputs=dict(prompt=prompt.prompt)
+ )
+
+ async def sse_generator():
+ yield f"data: {json.dumps({'type': 'chat_history', 'value': chat_history})}\n\n"
+
+ async for item in streaming_container:
+ yield f"data: {json.dumps({'type': 'delta', 'value': item['delta']})} \n\n"
+
+ return StreamingResponse(sse_generator())
+```
+
+Note this returns a [StreamingResponse](https://fastapi.tiangolo.com/advanced/custom-response/#streamingresponse)
+and does some fancy stuff with the SSE API. Particularly:
+1. It returns the initial state, so the UI can update to the latest (not strictly necessary, but nice to have for rendering)
+2. It streams the deltas as they come in
+3. It returns the data in the format: "data: ...\n\n" as this is standard for SSE
+
+And it's as simple as that! You can now stream data from Burr to FastAPI.
+
+## Streaming in Typescript/React
+
+This part can get a little messy with state management/chat history, but here's the basics of it. There are multiple approaches
+to managing SSE in React, but we will be using the very bare-bones `fetch` and `getReaders()` API.
+
+The following code is the `submitPrompt` function that will send the prompt and modify the state. This gets called when the
+user submits a prompt (E.G. on the `onClick` of a button).
+
+It relies on the state variables:
+
+- `currentPrompt`/`setCurrentPrompt` - the current prompt
+- `chatHistory`/`setChatHistory` - the chat history
+
+This also assumes the server is a post request with the prompt in the URL (putting it in the body is probably better...)
+
+### Fetch the result (POST)
+
+First we'll fetch the result with a post request to match the endpoint above. We will also get a reader object
+to help us iterate through the inputs:
+
+```typescript
+const response = await fetch(
+ `/api/v0/streaming_chatbot/response/${props.projectId}/${props.appId}`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ prompt: currentPrompt })
+ }
+ );
+const reader = response.body?.getReader();
+```
+
+Then we'll run through the reader object and parse the data, modifying the state as we go:
+
+```typescript
+if (reader) {
+ const decoder = new TextDecoder('utf-8');
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ const result = await reader.read();
+ if (result.done) {
+ break;
+ }
+ const message = decoder.decode(result.value, { stream: true });
+ message
+ .split('data: ')
+ .slice(1)
+ .forEach((item) => {
+ const event: Event = JSON.parse(item);
+ if (event.type === 'chat_history') {
+ const chatMessageEvent = event as ChatHistoryEvent;
+ setDisplayedChatHistory(chatMessageEvent.value);
+ }
+ if (event.type === 'delta') {
+ const chatMessageEvent = event as ChatMessageEvent;
+ chatResponse += chatMessageEvent.value;
+ setCurrentResponse(chatResponse);
+ }
+ });
+ }
+ setDisplayedChatHistory((chatHistory) => [
+ ...chatHistory,
+ {
+ role: ChatItem.role.USER,
+ content: currentPrompt,
+ type: ChatItem.type.TEXT
+ },
+ {
+ role: ChatItem.role.ASSISTANT,
+ content: chatResponse,
+ type: ChatItem.type.TEXT
+ }
+ ]);
+ setCurrentPrompt('');
+ setCurrentResponse('');
+ setIsChatWaiting(false);
+}
+```
+In the above we:
+1. Check if the reader is present (it is likely worth adding more error-correcting here)
+2. Break if the reader is done
+3. Decode the message
+4. Parse the message
+ a. If it is a chat history event, update the chat history
+ b. If it is a delta event, update the chat response
+5. Update the chat history with the new prompt and response
+6. Reset the variables so we don't render them twice
+
+While the logic of updating state is bespoke to how we do it here, looping through the reader and parsing the data
+is a common, highly generatizable operation.
+
+Note there are multiple ways of doing this -- this was just the simplest.
diff --git a/examples/streaming-fastapi/__init__.py b/examples/streaming-fastapi/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/examples/streaming-fastapi/application.py b/examples/streaming-fastapi/application.py
new file mode 100644
index 00000000..8e90df8e
--- /dev/null
+++ b/examples/streaming-fastapi/application.py
@@ -0,0 +1,192 @@
+import asyncio
+import copy
+from typing import AsyncGenerator, Optional, Tuple
+
+import openai
+
+from burr.core import ApplicationBuilder, State, default, when
+from burr.core.action import action, streaming_action
+from burr.core.graph import GraphBuilder
+
+MODES = [
+ "answer_question",
+ "generate_poem",
+ "generate_code",
+ "unknown",
+]
+
+
+@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"}}
+ 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
+ return result, state.update(safe=result["safe"])
+
+
+def _get_openai_client():
+ return openai.AsyncOpenAI()
+
+
+@action(reads=["prompt"], writes=["mode"])
+async 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 'write a poem about Alexander Hamilton and Aaron Burr', "
+ "the mode would be 'generate_poem'. If the prompt is 'what is the capital of France', the mode would be 'answer_question'."
+ "And so on, for every mode. If none of these modes apply, please respond with 'unknown'."
+ )
+
+ result = await _get_openai_client().chat.completions.create(
+ model="gpt-4o",
+ 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}
+ return result, state.update(**result)
+
+
+@streaming_action(reads=["prompt", "chat_history"], writes=["response"])
+async def prompt_for_more(state: State) -> AsyncGenerator[Tuple[dict, Optional[State]], None]:
+ """Not streaming, as we have the result immediately."""
+ result = {
+ "response": {
+ "content": "None of the response modes I support apply to your question. Please clarify?",
+ "type": "text",
+ "role": "assistant",
+ }
+ }
+ for word in result["response"]["content"].split():
+ await asyncio.sleep(0.1)
+ yield {"delta": word + " "}, None
+ yield result, state.update(**result).append(chat_history=result["response"])
+
+
+@streaming_action(reads=["prompt", "chat_history", "mode"], writes=["response"])
+async def chat_response(
+ state: State, prepend_prompt: str, model: str = "gpt-3.5-turbo"
+) -> AsyncGenerator[Tuple[dict, Optional[State]], None]:
+ """Streaming action, as we don't have the result immediately. This makes it more interactive"""
+ chat_history = copy.deepcopy(state["chat_history"])
+ 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
+ ]
+ client = _get_openai_client()
+ result = await client.chat.completions.create(
+ model=model, messages=chat_history_api_format, stream=True
+ )
+ buffer = []
+ async for chunk in result:
+ chunk_str = chunk.choices[0].delta.content
+ if chunk_str is None:
+ continue
+ buffer.append(chunk_str)
+ yield {
+ "delta": chunk_str,
+ }, None
+
+ result = {
+ "response": {"content": "".join(buffer), "type": "text", "role": "assistant"},
+ "modified_chat_history": chat_history,
+ }
+ yield result, state.update(**result).append(chat_history=result["response"])
+
+
+@streaming_action(reads=["prompt", "chat_history"], writes=["response"])
+async def unsafe_response(state: State) -> Tuple[dict, State]:
+ result = {
+ "response": {
+ "content": "I am afraid I can't respond to that...",
+ "type": "text",
+ "role": "assistant",
+ }
+ }
+ for word in result["response"]["content"].split():
+ await asyncio.sleep(0.1)
+ yield {"delta": word + " "}, None
+ yield result, state.update(**result).append(chat_history=result["response"])
+
+
+graph = (
+ GraphBuilder()
+ .with_actions(
+ prompt=process_prompt,
+ check_safety=check_safety,
+ unsafe_response=unsafe_response,
+ decide_mode=choose_mode,
+ 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",
+ ),
+ generate_poem=chat_response.bind(
+ prepend_prompt="Please generate a poem based on the following prompt",
+ ),
+ prompt_for_more=prompt_for_more,
+ )
+ .with_transitions(
+ ("prompt", "check_safety", default),
+ ("check_safety", "decide_mode", when(safe=True)),
+ ("check_safety", "unsafe_response", default),
+ ("decide_mode", "generate_code", when(mode="generate_code")),
+ ("decide_mode", "answer_question", when(mode="answer_question")),
+ ("decide_mode", "generate_poem", when(mode="generate_poem")),
+ ("decide_mode", "prompt_for_more", default),
+ (
+ [
+ "answer_question",
+ "generate_poem",
+ "generate_code",
+ "prompt_for_more",
+ "unsafe_response",
+ ],
+ "prompt",
+ ),
+ )
+ .build()
+)
+
+
+def application(app_id: Optional[str] = None):
+ return (
+ ApplicationBuilder()
+ .with_entrypoint("prompt")
+ .with_state(chat_history=[])
+ .with_graph(graph)
+ .with_tracker(project="demo_chatbot_streaming")
+ .with_identifiers(app_id=app_id)
+ .build()
+ )
+
+
+# TODO -- replace these with action tags when we have the availability
+TERMINAL_ACTIONS = [
+ "answer_question",
+ "generate_code",
+ "prompt_for_more",
+ "unsafe_response",
+ "generate_poem",
+]
+if __name__ == "__main__":
+ app = application()
+ app.visualize(output_file_path="statemachine", include_conditions=True, view=True, format="png")
diff --git a/examples/streaming-fastapi/notebook.ipynb b/examples/streaming-fastapi/notebook.ipynb
new file mode 100644
index 00000000..5bb50255
--- /dev/null
+++ b/examples/streaming-fastapi/notebook.ipynb
@@ -0,0 +1,336 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1ce738e6-14b4-4892-9f2d-a1db94cfb29a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "!pip install burr[start]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2118a2f4-d969-4771-81d3-156b432d1dc8",
+ "metadata": {},
+ "source": [
+ "# Streaming applications\n",
+ "\n",
+ "This shows how one goes about working with a streaming response with Burr, using FastAPI.\n",
+ "The code for implementation is in [application.py](application.py).\n",
+ "\n",
+ "This notebook only shows the streaming side. To check out FastAPI in Burr, check out\n",
+ "- The [Burr code](./application.py) -- imported and used here\n",
+ "- The [backend FastAPI server](./server.py) for the streaming output using SSE\n",
+ "- The [frontend typescript code](https://github.com/dagworks-inc/burr/blob/main/telemetry/ui/src/examples/StreamingChatbot.tsx) that renders and interacts with the stream\n",
+ "\n",
+ "You can view this demo in your app by running Burr:\n",
+ "\n",
+ "```bash\n",
+ "burr \n",
+ "```\n",
+ "\n",
+ "This will open a browser on [http://localhost:7241](http://localhost:7241)\n",
+ "\n",
+ "Then navigate to the [streaming example](http://localhost:7241/demos/streaming-chatbot)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "5b53de32-86af-475f-8976-e88a08986e34",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from application import application as streaming_application\n",
+ "from application import TERMINAL_ACTIONS\n",
+ "import pprint"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "675a4245-816f-4d43-b412-307aee83db8e",
+ "metadata": {},
+ "source": [
+ "# The application\n",
+ "\n",
+ "The application we created will be a simple chatbot proxy. It has a few diffrent modes -- it can either decide a prompt is \"unsafe\" (in this case meaning that it has the word \"unsafe\" in it, but this would typically go to specific model),\n",
+ "or do one of the following:\n",
+ "\n",
+ "1. Generate code\n",
+ "2. Answer a question\n",
+ "3. Generate a poem\n",
+ "4. Prompt for more\n",
+ "\n",
+ "It will use an LLM to decide which to do. It streams back text using async streaming in Burr. Read more about how that is implemented [here](https://burr.dagworks.io/concepts/streaming-actions/).\n",
+ "\n",
+ "Note that, even though not every response is streaming (E.G. unsafe response, which is hardcoded), they are modeled as streaming to make interaction with the app simpler."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "81799877-8f0f-4572-9a96-f6ce6c430d9a",
+ "metadata": {},
+ "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 8.1.0 (20230707.0739)\n",
+ " -->\n",
+ "<!-- Pages: 1 -->\n",
+ "<svg width=\"553pt\" height=\"304pt\"\n",
+ " viewBox=\"0.00 0.00 552.78 304.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 300)\">\n",
+ "<polygon fill=\"white\" stroke=\"none\" points=\"-4,4 -4,-300 548.78,-300 548.78,4 -4,4\"/>\n",
+ "<!-- prompt -->\n",
+ "<g id=\"node1\" class=\"node\">\n",
+ "<title>prompt</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M164.91,-231C164.91,-231 133.16,-231 133.16,-231 127.16,-231 121.16,-225 121.16,-219 121.16,-219 121.16,-207 121.16,-207 121.16,-201 127.16,-195 133.16,-195 133.16,-195 164.91,-195 164.91,-195 170.91,-195 176.91,-201 176.91,-207 176.91,-207 176.91,-219 176.91,-219 176.91,-225 170.91,-231 164.91,-231\"/>\n",
+ "<text text-anchor=\"middle\" x=\"149.03\" y=\"-207.95\" font-family=\"Times,serif\" font-size=\"14.00\">prompt</text>\n",
+ "</g>\n",
+ "<!-- check_safety -->\n",
+ "<g id=\"node3\" class=\"node\">\n",
+ "<title>check_safety</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M216.28,-166C216.28,-166 153.78,-166 153.78,-166 147.78,-166 141.78,-160 141.78,-154 141.78,-154 141.78,-142 141.78,-142 141.78,-136 147.78,-130 153.78,-130 153.78,-130 216.28,-130 216.28,-130 222.28,-130 228.28,-136 228.28,-142 228.28,-142 228.28,-154 228.28,-154 228.28,-160 222.28,-166 216.28,-166\"/>\n",
+ "<text text-anchor=\"middle\" x=\"185.03\" y=\"-142.95\" font-family=\"Times,serif\" font-size=\"14.00\">check_safety</text>\n",
+ "</g>\n",
+ "<!-- prompt&#45;&gt;check_safety -->\n",
+ "<g id=\"edge5\" class=\"edge\">\n",
+ "<title>prompt&#45;&gt;check_safety</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M158.87,-194.78C162.28,-188.81 166.19,-181.97 169.93,-175.43\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"173.28,-177.61 175.21,-167.19 167.21,-174.14 173.28,-177.61\"/>\n",
+ "</g>\n",
+ "<!-- input__prompt -->\n",
+ "<g id=\"node2\" class=\"node\">\n",
+ "<title>input__prompt</title>\n",
+ "<ellipse fill=\"none\" stroke=\"black\" stroke-dasharray=\"5,2\" cx=\"149.03\" cy=\"-278\" rx=\"62.1\" ry=\"18\"/>\n",
+ "<text text-anchor=\"middle\" x=\"149.03\" y=\"-272.95\" font-family=\"Times,serif\" font-size=\"14.00\">input: prompt</text>\n",
+ "</g>\n",
+ "<!-- input__prompt&#45;&gt;prompt -->\n",
+ "<g id=\"edge1\" class=\"edge\">\n",
+ "<title>input__prompt&#45;&gt;prompt</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M149.03,-259.78C149.03,-254.23 149.03,-247.92 149.03,-241.8\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"152.53,-242.19 149.03,-232.19 145.53,-242.19 152.53,-242.19\"/>\n",
+ "</g>\n",
+ "<!-- unsafe_response -->\n",
+ "<g id=\"node4\" class=\"node\">\n",
+ "<title>unsafe_response</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M154.66,-101C154.66,-101 73.41,-101 73.41,-101 67.41,-101 61.41,-95 61.41,-89 61.41,-89 61.41,-77 61.41,-77 61.41,-71 67.41,-65 73.41,-65 73.41,-65 154.66,-65 154.66,-65 160.66,-65 166.66,-71 166.66,-77 166.66,-77 166.66,-89 166.66,-89 166.66,-95 160.66,-101 154.66,-101\"/>\n",
+ "<text text-anchor=\"middle\" x=\"114.03\" y=\"-77.95\" font-family=\"Times,serif\" font-size=\"14.00\">unsafe_response</text>\n",
+ "</g>\n",
+ "<!-- check_safety&#45;&gt;unsafe_response -->\n",
+ "<g id=\"edge7\" class=\"edge\">\n",
+ "<title>check_safety&#45;&gt;unsafe_response</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M165.63,-129.78C158.2,-123.19 149.56,-115.53 141.51,-108.39\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"144.21,-106.21 134.41,-102.19 139.57,-111.45 144.21,-106.21\"/>\n",
+ "</g>\n",
+ "<!-- decide_mode -->\n",
+ "<g id=\"node5\" class=\"node\">\n",
+ "<title>decide_mode</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M396.41,-101C396.41,-101 331.66,-101 331.66,-101 325.66,-101 319.66,-95 319.66,-89 319.66,-89 319.66,-77 319.66,-77 319.66,-71 325.66,-65 331.66,-65 331.66,-65 396.41,-65 396.41,-65 402.41,-65 408.41,-71 408.41,-77 408.41,-77 408.41,-89 408.41,-89 408.41,-95 402.41,-101 396.41,-101\"/>\n",
+ "<text text-anchor=\"middle\" x=\"364.03\" y=\"-77.95\" font-family=\"Times,serif\" font-size=\"14.00\">decide_mode</text>\n",
+ "</g>\n",
+ "<!-- check_safety&#45;&gt;decide_mode -->\n",
+ "<g id=\"edge6\" class=\"edge\">\n",
+ "<title>check_safety&#45;&gt;decide_mode</title>\n",
+ "<path fill=\"none\" stroke=\"black\" stroke-dasharray=\"5,2\" d=\"M228.36,-131.75C252.66,-123.2 283.21,-112.45 309.16,-103.31\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"309.96,-106.39 318.23,-99.77 307.64,-99.79 309.96,-106.39\"/>\n",
+ "</g>\n",
+ "<!-- unsafe_response&#45;&gt;prompt -->\n",
+ "<g id=\"edge16\" class=\"edge\">\n",
+ "<title>unsafe_response&#45;&gt;prompt</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M117.5,-101.42C120.96,-118.11 126.66,-143.96 133.03,-166 134.76,-171.99 136.82,-178.35 138.88,-184.36\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"135.89,-185.4 142.51,-193.67 142.49,-183.07 135.89,-185.4\"/>\n",
+ "</g>\n",
+ "<!-- generate_code -->\n",
+ "<g id=\"node6\" class=\"node\">\n",
+ "<title>generate_code</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M160.03,-36C160.03,-36 90.03,-36 90.03,-36 84.03,-36 78.03,-30 78.03,-24 78.03,-24 78.03,-12 78.03,-12 78.03,-6 84.03,0 90.03,0 90.03,0 160.03,0 160.03,0 166.03,0 172.03,-6 172.03,-12 172.03,-12 172.03,-24 172.03,-24 172.03,-30 166.03,-36 160.03,-36\"/>\n",
+ "<text text-anchor=\"middle\" x=\"125.03\" y=\"-12.95\" font-family=\"Times,serif\" font-size=\"14.00\">generate_code</text>\n",
+ "</g>\n",
+ "<!-- decide_mode&#45;&gt;generate_code -->\n",
+ "<g id=\"edge8\" class=\"edge\">\n",
+ "<title>decide_mode&#45;&gt;generate_code</title>\n",
+ "<path fill=\"none\" stroke=\"black\" stroke-dasharray=\"5,2\" d=\"M319.3,-67.34C316.51,-66.52 313.74,-65.73 311.03,-65 257.02,-50.35 240.12,-50.93 182.7,-36.32\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"183.88,-32.75 173.32,-33.63 182.12,-39.53 183.88,-32.75\"/>\n",
+ "</g>\n",
+ "<!-- answer_question -->\n",
+ "<g id=\"node8\" class=\"node\">\n",
+ "<title>answer_question</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M284.41,-36C284.41,-36 201.66,-36 201.66,-36 195.66,-36 189.66,-30 189.66,-24 189.66,-24 189.66,-12 189.66,-12 189.66,-6 195.66,0 201.66,0 201.66,0 284.41,0 284.41,0 290.41,0 296.41,-6 296.41,-12 296.41,-12 296.41,-24 296.41,-24 296.41,-30 290.41,-36 284.41,-36\"/>\n",
+ "<text text-anchor=\"middle\" x=\"243.03\" y=\"-12.95\" font-family=\"Times,serif\" font-size=\"14.00\">answer_question</text>\n",
+ "</g>\n",
+ "<!-- decide_mode&#45;&gt;answer_question -->\n",
+ "<g id=\"edge9\" class=\"edge\">\n",
+ "<title>decide_mode&#45;&gt;answer_question</title>\n",
+ "<path fill=\"none\" stroke=\"black\" stroke-dasharray=\"5,2\" d=\"M330.65,-64.62C316.76,-57.39 300.47,-48.91 285.73,-41.23\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"287.79,-37.84 277.31,-36.33 284.56,-44.05 287.79,-37.84\"/>\n",
+ "</g>\n",
+ "<!-- generate_poem -->\n",
+ "<g id=\"node9\" class=\"node\">\n",
+ "<title>generate_poem</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M401.66,-36C401.66,-36 326.41,-36 326.41,-36 320.41,-36 314.41,-30 314.41,-24 314.41,-24 314.41,-12 314.41,-12 314.41,-6 320.41,0 326.41,0 326.41,0 401.66,0 401.66,0 407.66,0 413.66,-6 413.66,-12 413.66,-12 413.66,-24 413.66,-24 413.66,-30 407.66,-36 401.66,-36\"/>\n",
+ "<text text-anchor=\"middle\" x=\"364.03\" y=\"-12.95\" font-family=\"Times,serif\" font-size=\"14.00\">generate_poem</text>\n",
+ "</g>\n",
+ "<!-- decide_mode&#45;&gt;generate_poem -->\n",
+ "<g id=\"edge10\" class=\"edge\">\n",
+ "<title>decide_mode&#45;&gt;generate_poem</title>\n",
+ "<path fill=\"none\" stroke=\"black\" stroke-dasharray=\"5,2\" d=\"M364.03,-64.78C364.03,-59.23 364.03,-52.92 364.03,-46.8\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"367.53,-47.19 364.03,-37.19 360.53,-47.19 367.53,-47.19\"/>\n",
+ "</g>\n",
+ "<!-- prompt_for_more -->\n",
+ "<g id=\"node10\" class=\"node\">\n",
+ "<title>prompt_for_more</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M532.78,-36C532.78,-36 443.28,-36 443.28,-36 437.28,-36 431.28,-30 431.28,-24 431.28,-24 431.28,-12 431.28,-12 431.28,-6 437.28,0 443.28,0 443.28,0 532.78,0 532.78,0 538.78,0 544.78,-6 544.78,-12 544.78,-12 544.78,-24 544.78,-24 544.78,-30 538.78,-36 532.78,-36\"/>\n",
+ "<text text-anchor=\"middle\" x=\"488.03\" y=\"-12.95\" font-family=\"Times,serif\" font-size=\"14.00\">prompt_for_more</text>\n",
+ "</g>\n",
+ "<!-- decide_mode&#45;&gt;prompt_for_more -->\n",
+ "<g id=\"edge11\" class=\"edge\">\n",
+ "<title>decide_mode&#45;&gt;prompt_for_more</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M398.24,-64.62C412.47,-57.39 429.17,-48.91 444.28,-41.23\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"445.6,-43.98 452.93,-36.33 442.43,-37.73 445.6,-43.98\"/>\n",
+ "</g>\n",
+ "<!-- generate_code&#45;&gt;prompt -->\n",
+ "<g id=\"edge14\" class=\"edge\">\n",
+ "<title>generate_code&#45;&gt;prompt</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M77.7,-27.27C55.95,-33.7 32.13,-45.04 19.03,-65 -5.59,-102.53 -6.88,-129.35 19.03,-166 39.52,-194.99 79.9,-205.83 110.24,-209.82\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"109.59,-213.38 119.91,-211 110.36,-206.42 109.59,-213.38\"/>\n",
+ "</g>\n",
+ "<!-- input__model -->\n",
+ "<g id=\"node7\" class=\"node\">\n",
+ "<title>input__model</title>\n",
+ "<ellipse fill=\"none\" stroke=\"black\" stroke-dasharray=\"5,2\" cx=\"243.03\" cy=\"-83\" rx=\"58.52\" ry=\"18\"/>\n",
+ "<text text-anchor=\"middle\" x=\"243.03\" y=\"-77.95\" font-family=\"Times,serif\" font-size=\"14.00\">input: model</text>\n",
+ "</g>\n",
+ "<!-- input__model&#45;&gt;generate_code -->\n",
+ "<g id=\"edge2\" class=\"edge\">\n",
+ "<title>input__model&#45;&gt;generate_code</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M214.77,-66.91C200.54,-59.31 183,-49.95 167.22,-41.52\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"169.13,-38.04 158.66,-36.42 165.83,-44.22 169.13,-38.04\"/>\n",
+ "</g>\n",
+ "<!-- input__model&#45;&gt;answer_question -->\n",
+ "<g id=\"edge3\" class=\"edge\">\n",
+ "<title>input__model&#45;&gt;answer_question</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M243.03,-64.78C243.03,-59.23 243.03,-52.92 243.03,-46.8\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"246.53,-47.19 243.03,-37.19 239.53,-47.19 246.53,-47.19\"/>\n",
+ "</g>\n",
+ "<!-- input__model&#45;&gt;generate_poem -->\n",
+ "<g id=\"edge4\" class=\"edge\">\n",
+ "<title>input__model&#45;&gt;generate_poem</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M272.01,-66.91C286.74,-59.24 304.93,-49.77 321.23,-41.28\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"322.32,-44.14 329.58,-36.42 319.09,-37.93 322.32,-44.14\"/>\n",
+ "</g>\n",
+ "<!-- answer_question&#45;&gt;prompt -->\n",
+ "<g id=\"edge12\" class=\"edge\">\n",
+ "<title>answer_question&#45;&gt;prompt</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M189.3,-33.9C186.51,-34.62 183.74,-35.32 181.03,-36 124.01,-50.22 88.75,-19.12 52.03,-65 19.18,-106.06 74.25,-158.3 113.94,-188.17\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"111.5,-191.45 121.63,-194.54 115.64,-185.81 111.5,-191.45\"/>\n",
+ "</g>\n",
+ "<!-- generate_poem&#45;&gt;prompt -->\n",
+ "<g id=\"edge13\" class=\"edge\">\n",
+ "<title>generate_poem&#45;&gt;prompt</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M392.62,-36.42C402.23,-43.91 411.82,-53.58 417.03,-65 423.67,-79.56 425.92,-87.7 417.03,-101 365.41,-178.26 248.97,-201.81 187.98,-208.94\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"187.83,-205.54 178.26,-210.09 188.58,-212.5 187.83,-205.54\"/>\n",
+ "</g>\n",
+ "<!-- prompt_for_more&#45;&gt;prompt -->\n",
+ "<g id=\"edge15\" class=\"edge\">\n",
+ "<title>prompt_for_more&#45;&gt;prompt</title>\n",
+ "<path fill=\"none\" stroke=\"black\" d=\"M481.02,-36.29C467.23,-67.87 433.39,-134.5 382.03,-166 321.38,-203.2 236.63,-211.15 187.83,-212.38\"/>\n",
+ "<polygon fill=\"black\" stroke=\"black\" points=\"188.05,-208.89 178.1,-212.56 188.16,-215.89 188.05,-208.89\"/>\n",
+ "</g>\n",
+ "</g>\n",
+ "</svg>\n"
+ ],
+ "text/plain": [
+ "<graphviz.graphs.Digraph at 0x121ae3490>"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "app = streaming_application()\n",
+ "app.visualize()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6f57c117-8951-4f98-86eb-ea1eac16347b",
+ "metadata": {},
+ "source": [
+ "# Calling the application\n",
+ "\n",
+ "With async streaming, we get back an `AsyncStreamingResultContainer`. This allows us to get partial results streaming in, while also allowing us to get the full result.\n",
+ "In the following case, we just "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "eeb23b59-e207-47b1-b500-b60d431396f8",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Alexander and Aaron, a duo renowned,\n",
+ "Their story in history forever bound,\n",
+ "In a duel they met,\n",
+ "A fate they couldn't forget,\n",
+ "A tragic end to a rivalry unsewn, unground.\n",
+ "\n",
+ "{'response': {'content': 'Alexander and Aaron, a duo renowned,\\n'\n",
+ " 'Their story in history forever bound,\\n'\n",
+ " 'In a duel they met,\\n'\n",
+ " \"A fate they couldn't forget,\\n\"\n",
+ " 'A tragic end to a rivalry unsewn, unground.',\n",
+ " 'role': 'assistant',\n",
+ " 'type': 'text'}}\n"
+ ]
+ }
+ ],
+ "source": [
+ "action, streaming_container = await app.astream_result(\n",
+ " halt_after=TERMINAL_ACTIONS, inputs={\"prompt\": \"Please generate a limerick about Alexander Hamilton and Aaron Burr\"}\n",
+ ")\n",
+ "# Stream results in\n",
+ "async for item in streaming_container:\n",
+ " print(item['delta'], end=\"\")\n",
+ "\n",
+ "# Or just get the final result\n",
+ "result, state = await streaming_container.get()\n",
+ "print(\"\\n\")\n",
+ "pprint.pprint(result)"
+ ]
+ }
+ ],
+ "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/streaming-fastapi/server.py b/examples/streaming-fastapi/server.py
new file mode 100644
index 00000000..51a1b15e
--- /dev/null
+++ b/examples/streaming-fastapi/server.py
@@ -0,0 +1,125 @@
+import functools
+import importlib
+import json
+from typing import List, Literal
+
+import pydantic
+from fastapi import APIRouter
+from starlette.responses import StreamingResponse
+
+from burr.core import Application, ApplicationBuilder
+from burr.tracking import LocalTrackingClient
+
+"""This file represents a simple chatbot API backed with Burr.
+We manage an application, write to it with post endpoints, and read with
+get/ endpoints.
+
+This demonstrates how you can build interactive web applications with Burr!
+"""
+# We're doing dynamic import cause this lives within examples/ (and that module has dashes)
+# navigate to the examples directory to read more about this!
+chat_application = importlib.import_module(
+ "burr.examples.streaming-fastapi.application"
+) # noqa: F401
+
+# the app is commented out as we include the router.
+# app = FastAPI()
+
+router = APIRouter()
+
+graph = chat_application.graph
+
+
+class ChatItem(pydantic.BaseModel):
+ """Pydantic model for a chat item. This is used to render the chat history."""
+
+ content: str
+ type: Literal["image", "text", "code", "error"]
+ role: Literal["user", "assistant"]
+
+
[email protected]_cache(maxsize=128)
+def _get_application(project_id: str, app_id: str) -> Application:
+ """Quick tool to get the application -- caches it"""
+ tracker = LocalTrackingClient(project=project_id, storage_dir="~/.burr")
+ return (
+ ApplicationBuilder()
+ .with_graph(graph)
+ # initializes from the tracking log if it does not already exist
+ .initialize_from(
+ tracker,
+ resume_at_next_action=False, # always resume from entrypoint in the case of failure
+ default_state={"chat_history": []},
+ default_entrypoint="prompt",
+ )
+ .with_tracker(tracker)
+ .with_identifiers(app_id=app_id)
+ .build()
+ )
+
+
+class PromptInput(pydantic.BaseModel):
+ prompt: str
+
+
[email protected]("/response/{project_id}/{app_id}", response_class=StreamingResponse)
+async def chat_response(project_id: str, app_id: str, prompt: PromptInput) -> StreamingResponse:
+ """Chat response endpoint. User passes in a prompt and the system returns the
+ full chat history, so its easier to render.
+
+ :param project_id: Project ID to run
+ :param app_id: Application ID to run
+ :param prompt: Prompt to send to the chatbot
+ :return:
+ """
+ burr_app = _get_application(project_id, app_id)
+ chat_history = burr_app.state.get("chat_history", [])
+ action, streaming_container = await burr_app.astream_result(
+ halt_after=chat_application.TERMINAL_ACTIONS, inputs=dict(prompt=prompt.prompt)
+ )
+
+ async def sse_generator():
+ """This is a generator that yields Server-Sent Events (SSE) to the client
+ It is necessary to yield them in a special format to ensure the client can
+ access them streaming. We type them (using our own simple typing system) then
+ parse on the client side. Unfortunately, typing these in FastAPI is not feasible."""
+ yield f"data: {json.dumps({'type': 'chat_history', 'value': chat_history})}\n\n"
+
+ async for item in streaming_container:
+ yield f"data: {json.dumps({'type': 'delta', 'value': item['delta']})} \n\n"
+
+ return StreamingResponse(sse_generator())
+
+
[email protected]("/history/{project_id}/{app_id}", response_model=List[ChatItem])
+def chat_history(project_id: str, app_id: str) -> List[ChatItem]:
+ """Endpoint to get chat history. Gets the application and returns the chat history from state.
+
+ :param project_id: Project ID
+ :param app_id: App ID.
+ :return: The list of chat items in the state
+ """
+ chat_app = _get_application(project_id, app_id)
+ state = chat_app.state
+ return state.get("chat_history", [])
+
+
[email protected]("/create/{project_id}/{app_id}", response_model=str)
+async def create_new_application(project_id: str, app_id: str) -> str:
+ """Endpoint to create a new application -- used by the FE when
+ the user types in a new App ID
+
+ :param project_id: Project ID
+ :param app_id: App ID
+ :return: The app ID
+ """
+ # side-effect of this persists it -- see the application function for details
+ _get_application(app_id=app_id, project_id=project_id)
+ return app_id # just return it for now
+
+
+# # comment this back in for a standalone chatbot API
+# import fastapi
+#
+# app = fastapi.FastAPI()
+# app.include_router(router, prefix="/api/v0/chatbot")
diff --git a/examples/streaming-fastapi/statemachine.png b/examples/streaming-fastapi/statemachine.png
new file mode 100644
index 00000000..ba5527a4
Binary files /dev/null and b/examples/streaming-fastapi/statemachine.png differ
diff --git a/examples/streaming-fastapi/streamlit_app.py b/examples/streaming-fastapi/streamlit_app.py
new file mode 100644
index 00000000..9b6bd50b
--- /dev/null
+++ b/examples/streaming-fastapi/streamlit_app.py
@@ -0,0 +1,55 @@
+import asyncio
+import uuid
+
+import application as chatbot_application
+import streamlit as st
+
+import burr.core
+from burr.core.action import AsyncStreamingResultContainer
+
+
+def render_chat_message(chat_item: dict):
+ content = chat_item["content"]
+ role = chat_item["role"]
+ with st.chat_message(role):
+ st.write(content)
+
+
+async def render_streaming_chat_message(stream: AsyncStreamingResultContainer):
+ buffer = ""
+ with st.chat_message("assistant"):
+ # This is very ugly as streamlit does not support async generators
+ # Thus we have to ignore the benefit of writing the delta and instead write *everything*
+ with st.empty():
+ async for item in stream:
+ buffer += item["delta"]
+ st.write(buffer)
+
+
+def initialize_app() -> burr.core.Application:
+ if "burr_app" not in st.session_state:
+ st.session_state.burr_app = chatbot_application.application(
+ app_id=f"chat_streaming:{str(uuid.uuid4())[0:6]}"
+ )
+ return st.session_state.burr_app
+
+
+async def main():
+ st.title("Streaming chatbot with Burr")
+ app = initialize_app()
+
+ prompt = st.chat_input("Ask me a question!", key="chat_input")
+ for chat_message in app.state.get("chat_history", []):
+ render_chat_message(chat_message)
+
+ if prompt:
+ render_chat_message({"role": "user", "content": prompt, "type": "text"})
+ with st.spinner(text="Waiting for response..."):
+ action, streaming_container = await app.astream_result(
+ halt_after=chatbot_application.TERMINAL_ACTIONS, inputs={"prompt": prompt}
+ )
+ await render_streaming_chat_message(streaming_container)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/telemetry/ui/package-lock.json b/telemetry/ui/package-lock.json
index 4a2bf7e2..65b10a90 100644
--- a/telemetry/ui/package-lock.json
+++ b/telemetry/ui/package-lock.json
@@ -10,6 +10,7 @@
"dependencies": {
"@headlessui/react": "^2.0.0-alpha.4",
"@heroicons/react": "^2.1.1",
+ "@microsoft/fetch-event-source": "^2.0.1",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
@@ -3496,6 +3497,11 @@
"resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.4.tgz",
"integrity": "sha512-Hcv+nVC0kZnQ3tD9GVu5xSMR4VVYOteQIr/hwFPVEvPdlXqgGEuRjiheChHgdM+JyqdgNcmzZOX/tnl0JOiI7A=="
},
+ "node_modules/@microsoft/fetch-event-source": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@microsoft/fetch-event-source/-/fetch-event-source-2.0.1.tgz",
+ "integrity": "sha512-W6CLUJ2eBMw3Rec70qrsEW0jOm/3twwJv21mrmj2yORiaVmVYGS4sSS5yUwvQc1ZlDLYGPnClVWmUUMagKNsfA=="
+ },
"node_modules/@nicolo-ribaudo/eslint-scope-5-internals": {
"version": "5.1.1-v1",
"resolved": "https://registry.npmjs.org/@nicolo-ribaudo/eslint-scope-5-internals/-/eslint-scope-5-internals-5.1.1-v1.tgz",
diff --git a/telemetry/ui/package.json b/telemetry/ui/package.json
index 4470de6a..0b361479 100644
--- a/telemetry/ui/package.json
+++ b/telemetry/ui/package.json
@@ -5,6 +5,7 @@
"dependencies": {
"@headlessui/react": "^2.0.0-alpha.4",
"@heroicons/react": "^2.1.1",
+ "@microsoft/fetch-event-source": "^2.0.1",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
diff --git a/telemetry/ui/src/App.tsx b/telemetry/ui/src/App.tsx
index a9f9e9aa..32d5ae00 100644
--- a/telemetry/ui/src/App.tsx
+++ b/telemetry/ui/src/App.tsx
@@ -8,6 +8,7 @@ import { AppContainer } from './components/nav/appcontainer';
import { ChatbotWithTelemetry } from './examples/Chatbot';
import { Counter } from './examples/Counter';
import { EmailAssistantWithTelemetry } from './examples/EmailAssistant';
+import { StreamingChatbotWithTelemetry } from './examples/StreamingChatbot';
/**
* Basic application. We have an AppContainer -- this has a breadcrumb and a sidebar.
@@ -36,6 +37,7 @@ const App = () => {
<Route path="/project/:projectId/:appId" element={<AppViewContainer />} />
<Route path="/demos/counter" element={<Counter />} />
<Route path="/demos/chatbot" element={<ChatbotWithTelemetry />} />
+ <Route path="/demos/streaming-chatbot" element={<StreamingChatbotWithTelemetry />} />
<Route path="/demos/email-assistant" element={<EmailAssistantWithTelemetry />} />
<Route path="*" element={<Navigate to="/projects" />} />
</Routes>
diff --git a/telemetry/ui/src/api/models/ChildApplicationModel.ts b/telemetry/ui/src/api/models/ChildApplicationModel.ts
index f98fc169..11206f37 100644
--- a/telemetry/ui/src/api/models/ChildApplicationModel.ts
+++ b/telemetry/ui/src/api/models/ChildApplicationModel.ts
@@ -12,7 +12,7 @@ export type ChildApplicationModel = {
child: PointerModel;
event_time: string;
event_type: ChildApplicationModel.event_type;
- sequence_id: number;
+ sequence_id: number | null;
};
export namespace ChildApplicationModel {
export enum event_type {
diff --git a/telemetry/ui/src/api/services/DefaultService.ts b/telemetry/ui/src/api/services/DefaultService.ts
index 447da977..4c58539f 100644
--- a/telemetry/ui/src/api/services/DefaultService.ts
+++ b/telemetry/ui/src/api/services/DefaultService.ts
@@ -96,6 +96,18 @@ export class DefaultService {
url: '/api/v0/ready'
});
}
+ /**
+ * Version
+ * Returns the burr version
+ * @returns any Successful Response
+ * @throws ApiError
+ */
+ public static versionApiV0VersionGet(): CancelablePromise<Record<string, any>> {
+ return __request(OpenAPI, {
+ method: 'GET',
+ url: '/api/v0/version'
+ });
+ }
/**
* Chat Response
* Chat response endpoint. User passes in a prompt and the system returns the
@@ -350,6 +362,98 @@ export class DefaultService {
url: '/api/v0/email_assistant/validate/{project_id}/{app_id}'
});
}
+ /**
+ * Chat Response
+ * Chat response endpoint. User passes in a prompt and the system returns the
+ * full chat history, so its easier to render.
+ *
+ * :param project_id: Project ID to run
+ * :param app_id: Application ID to run
+ * :param prompt: Prompt to send to the chatbot
+ * :return:
+ * @param projectId
+ * @param appId
+ * @param prompt
+ * @returns any Successful Response
+ * @throws ApiError
+ */
+ public static chatResponseApiV0StreamingChatbotResponseProjectIdAppIdPost(
+ projectId: string,
+ appId: string,
+ prompt: string
+ ): CancelablePromise<any> {
+ return __request(OpenAPI, {
+ method: 'POST',
+ url: '/api/v0/streaming_chatbot/response/{project_id}/{app_id}',
+ path: {
+ project_id: projectId,
+ app_id: appId
+ },
+ query: {
+ prompt: prompt
+ },
+ errors: {
+ 422: `Validation Error`
+ }
+ });
+ }
+ /**
+ * Chat History
+ * Endpoint to get chat history. Gets the application and returns the chat history from state.
+ *
+ * :param project_id: Project ID
+ * :param app_id: App ID.
+ * :return: The list of chat items in the state
+ * @param projectId
+ * @param appId
+ * @returns ChatItem Successful Response
+ * @throws ApiError
+ */
+ public static chatHistoryApiV0StreamingChatbotHistoryProjectIdAppIdGet(
+ projectId: string,
+ appId: string
+ ): CancelablePromise<Array<ChatItem>> {
+ return __request(OpenAPI, {
+ method: 'GET',
+ url: '/api/v0/streaming_chatbot/history/{project_id}/{app_id}',
+ path: {
+ project_id: projectId,
+ app_id: appId
+ },
+ errors: {
+ 422: `Validation Error`
+ }
+ });
+ }
+ /**
+ * Create New Application
+ * Endpoint to create a new application -- used by the FE when
+ * the user types in a new App ID
+ *
+ * :param project_id: Project ID
+ * :param app_id: App ID
+ * :return: The app ID
+ * @param projectId
+ * @param appId
+ * @returns string Successful Response
+ * @throws ApiError
+ */
+ public static createNewApplicationApiV0StreamingChatbotCreateProjectIdAppIdPost(
+ projectId: string,
+ appId: string
+ ): CancelablePromise<string> {
+ return __request(OpenAPI, {
+ method: 'POST',
+ url: '/api/v0/streaming_chatbot/create/{project_id}/{app_id}',
+ path: {
+ project_id: projectId,
+ app_id: appId
+ },
+ errors: {
+ 422: `Validation Error`
+ }
+ });
+ }
/**
* React App
* Quick trick to server the react app
diff --git a/telemetry/ui/src/components/nav/appcontainer.tsx b/telemetry/ui/src/components/nav/appcontainer.tsx
index 2d04e00c..70a4c817 100644
--- a/telemetry/ui/src/components/nav/appcontainer.tsx
+++ b/telemetry/ui/src/components/nav/appcontainer.tsx
@@ -93,6 +93,12 @@ export const AppContainer = (props: { children: React.ReactNode }) => {
href: '/demos/email-assistant',
current: false,
linkType: 'internal'
+ },
+ {
+ name: 'streaming-chatbot',
+ href: '/demos/streaming-chatbot',
+ current: false,
+ linkType: 'internal'
}
]
},
diff --git a/telemetry/ui/src/components/routes/app/StepList.tsx b/telemetry/ui/src/components/routes/app/StepList.tsx
index 53f9c8cd..a361765d 100644
--- a/telemetry/ui/src/components/routes/app/StepList.tsx
+++ b/telemetry/ui/src/components/routes/app/StepList.tsx
@@ -470,9 +470,9 @@ export const StepList = (props: {
const displaySpansCol = props.steps.some((step) => step.spans.length > 0);
const displayLinksCol = props.links.length > 0;
const linksBySequenceID = props.links.reduce((acc, child) => {
- const existing = acc.get(child.sequence_id) || [];
+ const existing = acc.get(child.sequence_id || -1) || [];
existing.push(child);
- acc.set(child.sequence_id, existing);
+ acc.set(child.sequence_id || -1, existing);
return acc;
}, new Map<number, ChildApplicationModel[]>());
return (
diff --git a/telemetry/ui/src/examples/Chatbot.tsx b/telemetry/ui/src/examples/Chatbot.tsx
index c66a0aeb..18e2edd5 100644
--- a/telemetry/ui/src/examples/Chatbot.tsx
+++ b/telemetry/ui/src/examples/Chatbot.tsx
@@ -2,15 +2,13 @@ import { ComputerDesktopIcon, UserIcon } from '@heroicons/react/24/outline';
import { classNames } from '../utils/tailwind';
import { Button } from '../components/common/button';
import { TwoColumnLayout } from '../components/common/layout';
-import { MiniTelemetry } from './MiniTelemetry';
import { ApplicationSummary, ChatItem, DefaultService } from '../api';
import { KeyboardEvent, useEffect, useState } from 'react';
import { useMutation, useQuery } from 'react-query';
import { Loading } from '../components/common/loading';
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
-import { DateTimeDisplay } from '../components/common/dates';
-import AsyncCreatableSelect from 'react-select/async-creatable';
+import { TelemetryWithSelector } from './Common';
type Role = 'assistant' | 'user';
@@ -211,95 +209,6 @@ export const Chatbot = (props: { projectId: string; appId: string | undefined })
);
};
-export const TelemetryWithSelector = (props: {
- projectId: string;
- currentApp: ApplicationSummary | undefined;
- setCurrentApp: (app: ApplicationSummary) => void;
-}) => {
- return (
- <div className="w-full h-[90%]">
- <div className="w-full">
- <ChatbotAppSelector
- projectId={props.projectId}
- setApp={props.setCurrentApp}
- currentApp={props.currentApp}
- placeholder={'Select a conversation or create a new one by typing...'}
- ></ChatbotAppSelector>
- </div>
- <MiniTelemetry projectId={props.projectId} appId={props.currentApp?.app_id}></MiniTelemetry>
- </div>
- );
-};
-
-const Label = (props: { application: ApplicationSummary }) => {
- return (
- <div className="flex flex-row gap-2 items-center justify-between">
- <div className="flex flex-row gap-2 items-center">
- <span className="text-gray-400 w-10">{props.application.num_steps}</span>
- <span>{props.application.app_id}</span>
- </div>
- <DateTimeDisplay date={props.application.first_written} mode="short" />
- </div>
- );
-};
-
-export const ChatbotAppSelector = (props: {
- projectId: string;
- setApp: (app: ApplicationSummary) => void;
- currentApp: ApplicationSummary | undefined;
- placeholder: string;
-}) => {
- const { projectId, setApp } = props;
- const { data, refetch } = useQuery(
- ['apps', projectId],
- () => DefaultService.getAppsApiV0ProjectIdAppsGet(projectId as string),
- { enabled: projectId !== undefined }
- );
- const createAndUpdateMutation = useMutation(
- (app_id: string) =>
- DefaultService.createNewApplicationApiV0ChatbotCreateProjectIdAppIdPost(projectId, app_id),
-
- {
- onSuccess: (appID) => {
- refetch().then((data) => {
- const appSummaries = data.data || [];
- const app = appSummaries.find((app) => app.app_id === appID);
- if (app) {
- setApp(app);
- }
- });
- }
- }
- );
- const appSetter = (appID: string) => createAndUpdateMutation.mutate(appID);
- const dataOrEmpty = Array.from(data || []);
- const options = dataOrEmpty
- .sort((a, b) => {
- return new Date(a.last_written) > new Date(b.last_written) ? -1 : 1;
- })
- .map((app) => {
- return {
- value: app.app_id,
- label: <Label application={app} />
- };
- });
- return (
- <AsyncCreatableSelect
- placeholder={props.placeholder}
- cacheOptions
- defaultOptions={options}
- onCreateOption={appSetter}
- value={options.find((option) => option.value === props.currentApp?.app_id) || null}
- onChange={(choice) => {
- const app = dataOrEmpty.find((app) => app.app_id === choice?.value);
- if (app) {
- setApp(app);
- }
- }}
- />
- );
-};
-
export const ChatbotWithTelemetry = () => {
const currentProject = 'demo_chatbot';
const [currentApp, setCurrentApp] = useState<ApplicationSummary | undefined>(undefined);
@@ -312,6 +221,7 @@ export const ChatbotWithTelemetry = () => {
projectId={currentProject}
currentApp={currentApp}
setCurrentApp={setCurrentApp}
+ createNewApp={DefaultService.createNewApplicationApiV0ChatbotCreateProjectIdAppIdPost}
/>
}
mode={'third'}
diff --git a/telemetry/ui/src/examples/Common.tsx b/telemetry/ui/src/examples/Common.tsx
new file mode 100644
index 00000000..de5f5874
--- /dev/null
+++ b/telemetry/ui/src/examples/Common.tsx
@@ -0,0 +1,106 @@
+import { useMutation, useQuery } from 'react-query';
+import { ApplicationSummary } from '../api/models/ApplicationSummary';
+import { DateTimeDisplay } from '../components/common/dates';
+import { MiniTelemetry } from './MiniTelemetry';
+import { DefaultService } from '../api';
+import AsyncCreatableSelect from 'react-select/async-creatable';
+
+type CreateNewApp = typeof DefaultService.createNewApplicationApiV0ChatbotCreateProjectIdAppIdPost;
+
+export const TelemetryWithSelector = (props: {
+ projectId: string;
+ currentApp: ApplicationSummary | undefined;
+ setCurrentApp: (app: ApplicationSummary) => void;
+ createNewApp: CreateNewApp;
+}) => {
+ return (
+ <div className="w-full h-[90%]">
+ <div className="w-full">
+ <ChatbotAppSelector
+ projectId={props.projectId}
+ setApp={props.setCurrentApp}
+ currentApp={props.currentApp}
+ placeholder={'Select a conversation or create a new one by typing...'}
+ createNewApp={props.createNewApp}
+ />
+ </div>
+ <MiniTelemetry projectId={props.projectId} appId={props.currentApp?.app_id}></MiniTelemetry>
+ </div>
+ );
+};
+
+const Label = (props: { application: ApplicationSummary }) => {
+ return (
+ <div className="flex flex-row gap-2 items-center justify-between">
+ <div className="flex flex-row gap-2 items-center">
+ <span className="text-gray-400 w-10">{props.application.num_steps}</span>
+ <span>{props.application.app_id}</span>
+ </div>
+ <DateTimeDisplay date={props.application.first_written} mode="short" />
+ </div>
+ );
+};
+
+export const ChatbotAppSelector = (props: {
+ projectId: string;
+ setApp: (app: ApplicationSummary) => void;
+ currentApp: ApplicationSummary | undefined;
+ placeholder: string;
+ createNewApp: CreateNewApp;
+}) => {
+ const { projectId, setApp } = props;
+ const { data, refetch } = useQuery(
+ ['apps', projectId],
+ () => DefaultService.getAppsApiV0ProjectIdAppsGet(projectId as string),
+ { enabled: projectId !== undefined }
+ );
+ const createAndUpdateMutation = useMutation(
+ (app_id: string) => props.createNewApp(projectId, app_id),
+ {
+ onSuccess: (appID) => {
+ refetch().then((data) => {
+ const appSummaries = data.data || [];
+ const app = appSummaries.find((app) => app.app_id === appID);
+ if (app) {
+ setApp(app);
+ }
+ });
+ }
+ }
+ );
+ const appSetter = (appID: string) => createAndUpdateMutation.mutate(appID);
+ const dataOrEmpty = Array.from(data || []);
+ const options = dataOrEmpty
+ .sort((a, b) => {
+ return new Date(a.last_written) > new Date(b.last_written) ? -1 : 1;
+ })
+ .map((app) => {
+ return {
+ value: app.app_id,
+ label: <Label application={app} />
+ };
+ });
+ return (
+ <AsyncCreatableSelect
+ placeholder={props.placeholder}
+ cacheOptions
+ defaultOptions={options}
+ options={options}
+ onCreateOption={appSetter}
+ value={options.find((option) => option.value === props.currentApp?.app_id) || null}
+ onChange={(choice) => {
+ const app = dataOrEmpty.find((app) => app.app_id === choice?.value);
+ if (app) {
+ setApp(app);
+ }
+ }}
+ loadOptions={(inputValue: string) => {
+ return Promise.resolve(
+ options.filter((option) => {
+ return option.value.startsWith(inputValue);
+ })
+ );
+ }}
+ />
+ );
+};
diff --git a/telemetry/ui/src/examples/StreamingChatbot.tsx b/telemetry/ui/src/examples/StreamingChatbot.tsx
new file mode 100644
index 00000000..bfb8c2b6
--- /dev/null
+++ b/telemetry/ui/src/examples/StreamingChatbot.tsx
@@ -0,0 +1,305 @@
+import { ComputerDesktopIcon, UserIcon } from '@heroicons/react/24/outline';
+import { classNames } from '../utils/tailwind';
+import { Button } from '../components/common/button';
+import { TwoColumnLayout } from '../components/common/layout';
+import { ApplicationSummary, ChatItem, DefaultService } from '../api';
+import { KeyboardEvent, useEffect, useState } from 'react';
+import { useQuery } from 'react-query';
+import { Loading } from '../components/common/loading';
+import Markdown from 'react-markdown';
+import remarkGfm from 'remark-gfm';
+import { TelemetryWithSelector } from './Common';
+
+type Role = 'assistant' | 'user';
+
+/**
+ * Simple chat history with instructions to start -- constant across everything.
+ */
+const DEFAULT_CHAT_HISTORY: ChatItem[] = [
+ {
+ role: ChatItem.role.ASSISTANT,
+ content:
+ 'πŸ“– Select a conversation from the list to get started! ' +
+ 'The left side of this is a simple chatbot. The right side is the same' +
+ ' Burr Telemetry app you can see if you click through the [chatbot demo](/projects/demo_chatbot) project. Note that images ' +
+ "will likely stop displaying after a while due to OpenAI's persistence policy. So generate some new ones! πŸ“–",
+ type: ChatItem.type.TEXT
+ },
+ {
+ role: ChatItem.role.ASSISTANT,
+ content:
+ ' \n\nπŸ’‘ This is meant to demonstrate the power of the Burr streaming capabilities! ' +
+ 'chat on the left while examining the internals of the chatbot on the right.πŸ’‘',
+ type: ChatItem.type.TEXT
+ }
+];
+
+/**
+ * Helper function to get the character based on the role -- this just selects how it renders
+ * @param role Role of the character
+ * @returns AI or You based on the role
+ */
+const getCharacter = (role: Role) => {
+ return role === 'assistant' ? 'AI' : 'You';
+};
+
+/**
+ * Component for the Icon based on the role
+ */
+const RoleIcon = (props: { role: Role }) => {
+ const Icon = props.role === 'assistant' ? ComputerDesktopIcon : UserIcon;
+ return (
+ <Icon className={classNames('text-gray-400', 'ml-auto h-6 w-6 shrink-0')} aria-hidden="true" />
+ );
+};
+
+// Constant so we can scroll to the latest
+const VIEW_END_ID = 'end-view';
+
+/**
+ * React component to render a chat message. Can handle markdown.
+ */
+const ChatMessage = (props: { message: ChatItem; id?: string }) => {
+ return (
+ <div className="flex gap-3 my-4 text-gray-600 text-sm flex-1 w-full" id={props.id}>
+ <span className="relative flex shrink-0">
+ <RoleIcon role={props.message.role} />
+ </span>
+ <div className="leading-relaxed w-full">
+ <span className="block font-bold text-gray-700">{getCharacter(props.message.role)} </span>
+ {props.message.type === ChatItem.type.TEXT ||
+ props.message.type === ChatItem.type.CODE ||
+ props.message.type === ChatItem.type.ERROR ? (
+ <Markdown
+ components={{
+ // Custom rendering for links
+ a: ({ ...props }) => <a className="text-dwlightblue hover:underline" {...props} />
+ }}
+ remarkPlugins={[remarkGfm]}
+ className={`whitespace-pre-wrap break-lines max-w-full ${props.message.type === ChatItem.type.ERROR ? 'bg-dwred/10' : ''} p-0.5`}
+ >
+ {props.message.content}
+ </Markdown>
+ ) : (
+ <></>
+ )}
+ </div>
+ </div>
+ );
+};
+
+/**
+ * Convenience function to scroll to the latest message in the chat.
+ * This just sets the div to scroll to the bottom and sets up an observer to keep it there.
+ */
+const scrollToLatest = () => {
+ const lastMessage = document.getElementById(VIEW_END_ID);
+ if (lastMessage) {
+ // Directly scroll to the bottom
+ lastMessage.scrollTop = lastMessage.scrollHeight;
+
+ // Setup an observer to auto-scroll on size changes
+ const observer = new ResizeObserver(() => {
+ lastMessage.scrollTop = lastMessage.scrollHeight;
+ });
+ observer.observe(lastMessage);
+
+ // Cleanup observer on component unmount or updates
+ return () => observer.disconnect();
+ }
+};
+
+// Types for the chatbot stream -- we can't use react-query/openapi as they don't support streaming
+// See
+type Event = {
+ type: 'delta' | 'chat_history';
+};
+
+type ChatMessageEvent = Event & {
+ value: string;
+};
+
+type ChatHistoryEvent = Event & {
+ value: ChatItem[];
+};
+
+/**
+ * Streaming chatbot component -- renders chat + fetches from API
+ */
+export const StreamingChatbot = (props: { projectId: string; appId: string | undefined }) => {
+ const [currentPrompt, setCurrentPrompt] = useState<string>('');
+ const [displayedChatHistory, setDisplayedChatHistory] = useState(DEFAULT_CHAT_HISTORY);
+ const [currentResponse, setCurrentResponse] = useState<string>('');
+ const [isChatWaiting, setIsChatWaiting] = useState<boolean>(false);
+
+ const { isLoading: isInitialLoading } = useQuery(
+ // TODO -- handle errors
+ ['chat', props.projectId, props.appId],
+ () =>
+ DefaultService.chatHistoryApiV0StreamingChatbotHistoryProjectIdAppIdGet(
+ props.projectId,
+ props.appId || '' // TODO -- find a cleaner way of doing a skip-token like thing here
+ ),
+ {
+ enabled: props.appId !== undefined,
+ onSuccess: (data) => {
+ setDisplayedChatHistory(data); // when its succesful we want to set the displayed chat history
+ },
+ onError: (error: Error) => {
+ setDisplayedChatHistory([
+ ...DEFAULT_CHAT_HISTORY,
+ {
+ content: `Unable to load from server: ${error.message}`,
+ role: ChatItem.role.ASSISTANT,
+ type: ChatItem.type.ERROR
+ }
+ ]);
+ }
+ }
+ );
+
+ const submitPrompt = async () => {
+ setCurrentResponse(''); // Reset it
+ setIsChatWaiting(true);
+ const response = await fetch(
+ `/api/v0/streaming_chatbot/response/${props.projectId}/${props.appId}`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ prompt: currentPrompt })
+ }
+ );
+ const reader = response.body?.getReader();
+ let chatResponse = '';
+ if (reader) {
+ const decoder = new TextDecoder('utf-8');
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ const result = await reader.read();
+ if (result.done) {
+ break;
+ }
+ const message = decoder.decode(result.value, { stream: true });
+ message
+ .split('data: ')
+ .slice(1)
+ .forEach((item) => {
+ const event: Event = JSON.parse(item);
+ if (event.type === 'chat_history') {
+ const chatMessageEvent = event as ChatHistoryEvent;
+ setDisplayedChatHistory(chatMessageEvent.value);
+ }
+ if (event.type === 'delta') {
+ const chatMessageEvent = event as ChatMessageEvent;
+ chatResponse += chatMessageEvent.value;
+ setCurrentResponse(chatResponse);
+ }
+ });
+ }
+ setDisplayedChatHistory((chatHistory) => [
+ ...chatHistory,
+ {
+ role: ChatItem.role.USER,
+ content: currentPrompt,
+ type: ChatItem.type.TEXT
+ },
+ {
+ role: ChatItem.role.ASSISTANT,
+ content: chatResponse,
+ type: ChatItem.type.TEXT
+ }
+ ]);
+ setCurrentPrompt('');
+ setCurrentResponse('');
+ setIsChatWaiting(false);
+ }
+ };
+
+ // Scroll to the latest message when the chat history changes
+ useEffect(() => {
+ scrollToLatest();
+ }, [displayedChatHistory, currentResponse, isChatWaiting]);
+
+ if (isInitialLoading) {
+ return <Loading />;
+ }
+ return (
+ <div className="mr-4 bg-white w-full flex flex-col h-full">
+ <h1 className="text-2xl font-bold px-4 text-gray-600">{'Learn Burr '}</h1>
+ <h2 className="text-lg font-normal px-4 text-gray-500 flex flex-row">
+ The chatbot below is implemented using Burr. Watch the Burr UI (on the right) change as you
+ chat...
+ </h2>
+ <div className="flex-1 overflow-y-auto p-4 hide-scrollbar" id={VIEW_END_ID}>
+ {displayedChatHistory.map((message, i) => (
+ <ChatMessage message={message} key={i} />
+ ))}
+ {isChatWaiting && (
+ <ChatMessage
+ message={{
+ role: ChatItem.role.USER,
+ content: currentPrompt,
+ type: ChatItem.type.TEXT
+ }}
+ />
+ )}
+ {isChatWaiting && (
+ <ChatMessage
+ message={{
+ content: currentResponse,
+ type: ChatItem.type.TEXT,
+ role: ChatItem.role.ASSISTANT
+ }}
+ />
+ )}
+ </div>
+ <div className="flex items-center pt-4 gap-2">
+ <input
+ className="flex h-10 w-full rounded-md border border-[#e5e7eb] px-3 py-2 text-sm placeholder-[#6b7280] focus:outline-none focus:ring-2 focus:ring-[#9ca3af] disabled:cursor-not-allowed disabled:opacity-50 text-[#030712] focus-visible:ring-offset-2"
+ placeholder="Ask me how tall the Eifel tower is!"
+ value={currentPrompt}
+ onChange={(e) => setCurrentPrompt(e.target.value)}
+ onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ submitPrompt();
+ }
+ }}
+ disabled={isChatWaiting || props.appId === undefined}
+ />
+ <Button
+ className="w-min cursor-pointer h-full"
+ color="dark"
+ disabled={isChatWaiting || props.appId === undefined}
+ onClick={() => {
+ submitPrompt();
+ }}
+ >
+ Send
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+export const StreamingChatbotWithTelemetry = () => {
+ const currentProject = 'demo_streaming_chatbot';
+ const [currentApp, setCurrentApp] = useState<ApplicationSummary | undefined>(undefined);
+
+ return (
+ <TwoColumnLayout
+ firstItem={<StreamingChatbot projectId={currentProject} appId={currentApp?.app_id} />}
+ secondItem={
+ <TelemetryWithSelector
+ projectId={currentProject}
+ currentApp={currentApp}
+ setCurrentApp={setCurrentApp}
+ createNewApp={
+ DefaultService.createNewApplicationApiV0StreamingChatbotCreateProjectIdAppIdPost
+ }
+ />
+ }
+ mode={'third'}
+ ></TwoColumnLayout>
+ );
+};