Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.
Python aiburrchatbot-frameworkdagsgenerative-aigraphshacktoberfestllmopsllmsmlopspersistent-data-structurestate-machinestate-managementvisibility
Fixes up email assistant example
elijahbenizzya7434e848e51
diff --git a/burr/tracking/server/backend.py b/burr/tracking/server/backend.pyindex 384bd095..1dcdbec1 100644--- a/burr/tracking/server/backend.py+++ b/burr/tracking/server/backend.py@@ -114,7 +114,8 @@ class LocalBackend(BackendBase):) -> Sequence[ApplicationSummary]:project_filepath = os.path.join(self.path, project_id)if not os.path.exists(project_filepath):- raise fastapi.HTTPException(status_code=404, detail=f"Project: {project_id} not found")+ return []+ # raise fastapi.HTTPException(status_code=404, detail=f"Project: {project_id} not found")out = []for entry in await aiofilesos.listdir(project_filepath):if entry.startswith("."):diff --git a/burr/tracking/server/examples/email_assistant.py b/burr/tracking/server/examples/email_assistant.pynew file mode 100644index 00000000..2d06320b--- /dev/null+++ b/burr/tracking/server/examples/email_assistant.py@@ -0,0 +1,130 @@+import functools+import importlib+from typing import Any, Dict, List, Literal, Optional++import pydantic+from fastapi import APIRouter, FastAPI++from burr.core import Application++email_assistant_application = importlib.import_module(+ "burr.examples.email-assistant.application"+) # noqa: F401++app = FastAPI()+router = APIRouter()+++# we want to render this after every response+class EmailAssistantState(pydantic.BaseModel):+ app_id: str+ email_to_respond: Optional[str]+ response_instructions: Optional[str]+ questions: Optional[List[str]]+ answers: Optional[List[str]]+ drafts: List[str]+ feedback_history: List[str]+ final_draft: Optional[str]+ # This stores the next step, which tells the frontend which ones to call+ next_step: Literal["process_input", "clarify_instructions", "process_feedback", None]++ @staticmethod+ def from_app(app: Application):+ state = app.state+ next_action = app.get_next_action()+ # TODO -- consolidate with the above++ if next_action is not None and next_action.name not in (+ "clarify_instructions",+ "process_feedback",+ "process_input",+ ):+ # quick hack -- this just means we're done if its an error+ # TODO -- add recovery+ next_action = None+ return EmailAssistantState(+ app_id=app.uid,+ email_to_respond=state.get("incoming_email"),+ response_instructions=state.get("response_instructions"),+ questions=state.get("clarification_questions"),+ answers=state.get("clarification_answers"),+ drafts=state.get("draft_history", []),+ feedback_history=state.get("feedback_history", []),+ final_draft=state.get("final_draft"),+ next_step=next_action.name if next_action is not None else None,+ )++[email protected]_cache(maxsize=128)+def _get_application(project_id: str, app_id: str) -> Application:+ app = email_assistant_application.application(app_id=app_id, project=project_id)+ return app+++def _run_through(project_id: str, app_id: [str], inputs: Dict[str, Any]) -> EmailAssistantState:+ if app_id == "create_new": # quick hack to allow for null+ app_id = None+ email_assistant_app = _get_application(project_id, app_id)+ email_assistant_app.run( # Using this as a side-effect, we'll just get the state aft+ halt_before=["clarify_instructions", "process_feedback"],+ halt_after=["final_result"],+ inputs=inputs,+ )+ return EmailAssistantState.from_app(email_assistant_app)+++class DraftInit(pydantic.BaseModel):+ email_to_respond: str+ response_instructions: str++[email protected]("/create_new/{project_id}/{app_id}")+def create_new_application(project_id: str, app_id: str) -> str:+ app = _get_application(project_id, app_id)+ return app.uid++[email protected]("/create/{project_id}/{app_id}")+def initialize_draft(project_id: str, app_id: str, draft_data: DraftInit) -> EmailAssistantState:+ return _run_through(+ project_id,+ app_id,+ dict(+ email_to_respond=draft_data.email_to_respond,+ response_instructions=draft_data.response_instructions,+ ),+ )+++class QuestionAnswers(pydantic.BaseModel):+ answers: List[str]++[email protected]("/answer_questions/{project_id}/{app_id}")+def answer_questions(+ project_id: str, app_id: str, question_answers: QuestionAnswers+) -> EmailAssistantState:+ return _run_through(project_id, app_id, dict(clarification_inputs=question_answers.answers))+++class Feedback(pydantic.BaseModel):+ feedback: str++[email protected]("/provide_feedback/{project_id}/{app_id}")+def provide_feedback(project_id: str, app_id: str, feedback: Feedback) -> EmailAssistantState:+ return _run_through(project_id, app_id, dict(feedback=feedback.feedback))++[email protected]("/state/{project_id}/{app_id}")+def get_state(project_id: str, app_id: str) -> EmailAssistantState:+ email_assistant_app = _get_application(project_id, app_id)+ return EmailAssistantState.from_app(email_assistant_app)+++if __name__ == "__main__":+ import uvicorn++ app.include_router(router, prefix="/")++ uvicorn.run(app, host="localhost", port=7242)diff --git a/burr/tracking/server/run.py b/burr/tracking/server/run.pyindex 7379f22c..f239ae3a 100644--- a/burr/tracking/server/run.py+++ b/burr/tracking/server/run.py@@ -3,7 +3,7 @@ from importlib.resources import filesfrom typing import Sequencefrom burr.integrations.base import require_plugin-from burr.tracking.server.examples import chatbot+from burr.tracking.server.examples import chatbot, email_assistanttry:import uvicorn@@ -79,6 +79,8 @@ async def ready() -> bool:# Examples -- todo -- put them behind `if` statementsapp.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")if SERVE_STATIC:diff --git a/examples/email-assistant/application.py b/examples/email-assistant/application.pyindex 8d6fd6c2..024f0021 100644--- a/examples/email-assistant/application.py+++ b/examples/email-assistant/application.py@@ -53,7 +53,7 @@ def determine_clarifications(state: State) -> Tuple[dict, State]:],)content = result.choices[0].message.content- all_questions = content.split("\n") if content else ""+ all_questions = content.split("\n") if content else []return {"clarification_questions": all_questions}, state.update(clarification_questions=all_questions)@@ -62,7 +62,7 @@ def determine_clarifications(state: State) -> Tuple[dict, State]:@action(reads=["clarification_questions"], writes=["clarification_answers"])def clarify_instructions(state: State, clarification_inputs: list[str]) -> Tuple[dict, State]:"""Clarifies the response instructions if needed."""- clarification_answers = dict(zip(state["clarification_questions"], clarification_inputs))+ clarification_answers = list(clarification_inputs)return {"clarification_answers": clarification_answers}, state.update(clarification_answers=clarification_answers)@@ -73,6 +73,7 @@ def clarify_instructions(state: State, clarification_inputs: list[str]) -> Tuple"incoming_email","response_instructions","clarification_answers",+ "clarification_questions","draft_history","feedback",],@@ -86,7 +87,12 @@ def formulate_draft(state: State) -> Tuple[dict, State]:client = _get_openai_client()# TODO -- use instructor to get a pydantic modelclarification_answers_formatted_q_a = "\n".join(- [f"Q: {q}\nA: {a}" for q, a in state["clarification_answers"].items()]+ [+ f"Q: {q}\nA: {a}"+ for q, a in zip(+ state["clarification_questions"], state.get("clarification_answers", [])+ )+ ])instructions = [f"The email you are to respond to is: {incoming_email}.",@@ -120,11 +126,11 @@ def formulate_draft(state: State) -> Tuple[dict, State]:)-@action(reads=[], writes=["feedback"])+@action(reads=[], writes=["feedback", "feedback_history"])def process_feedback(state: State, feedback: str) -> Tuple[dict, State]:"""Processes feedback from user and updates state with the feedback."""result = {"feedback": feedback}- return result, state.update(**result)+ return result, state.update(feedback=feedback).append(feedback_history=feedback)@action(reads=["current_draft", "feedback"], writes=["final_draft"])diff --git a/telemetry/ui/src/App.tsx b/telemetry/ui/src/App.tsxindex 983f5813..a9f9e9aa 100644--- a/telemetry/ui/src/App.tsx+++ b/telemetry/ui/src/App.tsx@@ -7,6 +7,7 @@ import { QueryClient, QueryClientProvider } from 'react-query';import { AppContainer } from './components/nav/appcontainer';import { ChatbotWithTelemetry } from './examples/Chatbot';import { Counter } from './examples/Counter';+import { EmailAssistantWithTelemetry } from './examples/EmailAssistant';/*** Basic application. We have an AppContainer -- this has a breadcrumb and a sidebar.@@ -35,6 +36,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/email-assistant" element={<EmailAssistantWithTelemetry />} /><Route path="*" element={<Navigate to="/projects" />} /></Routes></AppContainer>diff --git a/telemetry/ui/src/api/index.ts b/telemetry/ui/src/api/index.tsindex e696a7c9..62e09c82 100644--- a/telemetry/ui/src/api/index.ts+++ b/telemetry/ui/src/api/index.ts@@ -14,10 +14,14 @@ export type { ApplicationSummary } from './models/ApplicationSummary';export type { BeginEntryModel } from './models/BeginEntryModel';export type { BeginSpanModel } from './models/BeginSpanModel';export { ChatItem } from './models/ChatItem';+export type { DraftInit } from './models/DraftInit';+export { EmailAssistantState } from './models/EmailAssistantState';export type { EndEntryModel } from './models/EndEntryModel';export type { EndSpanModel } from './models/EndSpanModel';+export type { Feedback } from './models/Feedback';export type { HTTPValidationError } from './models/HTTPValidationError';export type { Project } from './models/Project';+export type { QuestionAnswers } from './models/QuestionAnswers';export type { Span } from './models/Span';export type { Step } from './models/Step';export type { TransitionModel } from './models/TransitionModel';diff --git a/telemetry/ui/src/api/models/DraftInit.ts b/telemetry/ui/src/api/models/DraftInit.tsnew file mode 100644index 00000000..f00da936--- /dev/null+++ b/telemetry/ui/src/api/models/DraftInit.ts@@ -0,0 +1,8 @@+/* generated using openapi-typescript-codegen -- do no edit */+/* istanbul ignore file */+/* tslint:disable */+/* eslint-disable */+export type DraftInit = {+ email_to_respond: string;+ response_instructions: string;+};diff --git a/telemetry/ui/src/api/models/EmailAssistantState.ts b/telemetry/ui/src/api/models/EmailAssistantState.tsnew file mode 100644index 00000000..4a2ed93b--- /dev/null+++ b/telemetry/ui/src/api/models/EmailAssistantState.ts@@ -0,0 +1,22 @@+/* generated using openapi-typescript-codegen -- do no edit */+/* istanbul ignore file */+/* tslint:disable */+/* eslint-disable */+export type EmailAssistantState = {+ app_id: string;+ email_to_respond: string | null;+ response_instructions: string | null;+ questions: Array<string> | null;+ answers: Array<string> | null;+ drafts: Array<string>;+ feedback_history: Array<string>;+ final_draft: string | null;+ next_step: EmailAssistantState.next_step;+};+export namespace EmailAssistantState {+ export enum next_step {+ PROCESS_INPUT = 'process_input',+ CLARIFY_INSTRUCTIONS = 'clarify_instructions',+ PROCESS_FEEDBACK = 'process_feedback'+ }+}diff --git a/telemetry/ui/src/api/models/QuestionAnswers.ts b/telemetry/ui/src/api/models/QuestionAnswers.tsnew file mode 100644index 00000000..2cb13d7d--- /dev/null+++ b/telemetry/ui/src/api/models/QuestionAnswers.ts@@ -0,0 +1,7 @@+/* generated using openapi-typescript-codegen -- do no edit */+/* istanbul ignore file */+/* tslint:disable */+/* eslint-disable */+export type QuestionAnswers = {+ answers: Array<string>;+};diff --git a/telemetry/ui/src/api/services/DefaultService.ts b/telemetry/ui/src/api/services/DefaultService.tsindex 2cb1be82..9b931000 100644--- a/telemetry/ui/src/api/services/DefaultService.ts+++ b/telemetry/ui/src/api/services/DefaultService.ts@@ -5,7 +5,11 @@import type { ApplicationLogs } from '../models/ApplicationLogs';import type { ApplicationSummary } from '../models/ApplicationSummary';import type { ChatItem } from '../models/ChatItem';+import type { DraftInit } from '../models/DraftInit';+import type { EmailAssistantState } from '../models/EmailAssistantState';+import type { Feedback } from '../models/Feedback';import type { Project } from '../models/Project';+import type { QuestionAnswers } from '../models/QuestionAnswers';import type { CancelablePromise } from '../core/CancelablePromise';import { OpenAPI } from '../core/OpenAPI';import { request as __request } from '../core/request';@@ -182,6 +186,110 @@ export class DefaultService {}});}+ /**+ * Initialize Draft+ * @param projectId+ * @param appId+ * @param requestBody+ * @returns EmailAssistantState Successful Response+ * @throws ApiError+ */+ public static initializeDraftApiV0EmailAssistantCreateProjectIdAppIdPost(+ projectId: string,+ appId: string,+ requestBody: DraftInit+ ): CancelablePromise<EmailAssistantState> {+ return __request(OpenAPI, {+ method: 'POST',+ url: '/api/v0/email_assistant/create/{project_id}/{app_id}',+ path: {+ project_id: projectId,+ app_id: appId+ },+ body: requestBody,+ mediaType: 'application/json',+ errors: {+ 422: `Validation Error`+ }+ });+ }+ /**+ * Answer Questions+ * @param projectId+ * @param appId+ * @param requestBody+ * @returns EmailAssistantState Successful Response+ * @throws ApiError+ */+ public static answerQuestionsApiV0EmailAssistantAnswerQuestionsProjectIdAppIdPost(+ projectId: string,+ appId: string,+ requestBody: QuestionAnswers+ ): CancelablePromise<EmailAssistantState> {+ return __request(OpenAPI, {+ method: 'POST',+ url: '/api/v0/email_assistant/answer_questions/{project_id}/{app_id}',+ path: {+ project_id: projectId,+ app_id: appId+ },+ body: requestBody,+ mediaType: 'application/json',+ errors: {+ 422: `Validation Error`+ }+ });+ }+ /**+ * Provide Feedback+ * @param projectId+ * @param appId+ * @param requestBody+ * @returns EmailAssistantState Successful Response+ * @throws ApiError+ */+ public static provideFeedbackApiV0EmailAssistantProvideFeedbackProjectIdAppIdPost(+ projectId: string,+ appId: string,+ requestBody: Feedback+ ): CancelablePromise<EmailAssistantState> {+ return __request(OpenAPI, {+ method: 'POST',+ url: '/api/v0/email_assistant/provide_feedback/{project_id}/{app_id}',+ path: {+ project_id: projectId,+ app_id: appId+ },+ body: requestBody,+ mediaType: 'application/json',+ errors: {+ 422: `Validation Error`+ }+ });+ }+ /**+ * Get State+ * @param projectId+ * @param appId+ * @returns EmailAssistantState Successful Response+ * @throws ApiError+ */+ public static getStateApiV0EmailAssistantStateProjectIdAppIdGet(+ projectId: string,+ appId: string+ ): CancelablePromise<EmailAssistantState> {+ return __request(OpenAPI, {+ method: 'GET',+ url: '/api/v0/email_assistant/state/{project_id}/{app_id}',+ path: {+ project_id: projectId,+ app_id: appId+ },+ errors: {+ 422: `Validation Error`+ }+ });+ }/*** React App* Quick trick to server the react appdiff --git a/telemetry/ui/src/components/common/input.tsx b/telemetry/ui/src/components/common/input.tsxnew file mode 100644index 00000000..2568dbd2--- /dev/null+++ b/telemetry/ui/src/components/common/input.tsx@@ -0,0 +1,82 @@+import { Input as HeadlessInput, type InputProps as HeadlessInputProps } from '@headlessui/react'+import { clsx } from 'clsx'+import { forwardRef } from 'react'++const dateTypes = ['date', 'datetime-local', 'month', 'time', 'week']+type DateType = (typeof dateTypes)[number]++export const Input = forwardRef<+ HTMLInputElement,+ { type?: 'email' | 'number' | 'password' | 'search' | 'tel' | 'text' | 'url' | DateType } & HeadlessInputProps+>(function Input({ className, ...props }, ref) {+ return (+ <span+ data-slot="control"+ className={clsx([+ className,++ // Basic layout+ 'relative block w-full',++ // Background color + shadow applied to inset pseudo element, so shadow blends with border in light mode+ 'before:absolute before:inset-px before:rounded-[calc(theme(borderRadius.lg)-1px)] before:bg-white before:shadow',++ // Background color is moved to control and shadow is removed in dark mode so hide `before` pseudo+ 'dark:before:hidden',++ // Focus ring+ 'after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-inset after:ring-transparent sm:after:focus-within:ring-2 sm:after:focus-within:ring-blue-500',++ // Disabled state+ 'has-[[data-disabled]]:opacity-50 before:has-[[data-disabled]]:bg-zinc-950/5 before:has-[[data-disabled]]:shadow-none',++ // Invalid state+ 'before:has-[[data-invalid]]:shadow-red-500/10',+ ])}+ >+ <HeadlessInput+ ref={ref}+ className={clsx([+ // Date classes+ props.type &&+ dateTypes.includes(props.type) && [+ '[&::-webkit-datetime-edit-fields-wrapper]:p-0',+ '[&::-webkit-date-and-time-value]:min-h-[1.5em]',+ '[&::-webkit-datetime-edit]:inline-flex',+ '[&::-webkit-datetime-edit]:p-0',+ '[&::-webkit-datetime-edit-year-field]:p-0',+ '[&::-webkit-datetime-edit-month-field]:p-0',+ '[&::-webkit-datetime-edit-day-field]:p-0',+ '[&::-webkit-datetime-edit-hour-field]:p-0',+ '[&::-webkit-datetime-edit-minute-field]:p-0',+ '[&::-webkit-datetime-edit-second-field]:p-0',+ '[&::-webkit-datetime-edit-millisecond-field]:p-0',+ '[&::-webkit-datetime-edit-meridiem-field]:p-0',+ ],++ // Basic layout+ 'relative block w-full appearance-none rounded-lg px-[calc(theme(spacing[3.5])-1px)] py-[calc(theme(spacing[2.5])-1px)] sm:px-[calc(theme(spacing[3])-1px)] sm:py-[calc(theme(spacing[1.5])-1px)]',++ // Typography+ 'text-base/6 text-zinc-950 placeholder:text-zinc-500 sm:text-sm/6 dark:text-white',++ // Border+ 'border border-zinc-950/10 data-[hover]:border-zinc-950/20 dark:border-white/10 dark:data-[hover]:border-white/20',++ // Background color+ 'bg-transparent dark:bg-white/5',++ // Hide default focus styles+ 'focus:outline-none',++ // Invalid state+ 'data-[invalid]:border-red-500 data-[invalid]:data-[hover]:border-red-500 data-[invalid]:dark:border-red-500 data-[invalid]:data-[hover]:dark:border-red-500',++ // Disabled state+ 'data-[disabled]:border-zinc-950/20 dark:data-[hover]:data-[disabled]:border-white/15 data-[disabled]:dark:border-white/15 data-[disabled]:dark:bg-white/[2.5%]',+ ])}+ {...props}+ />+ </span>+ )+})diff --git a/telemetry/ui/src/components/common/text.tsx b/telemetry/ui/src/components/common/text.tsxnew file mode 100644index 00000000..099919c3--- /dev/null+++ b/telemetry/ui/src/components/common/text.tsx@@ -0,0 +1,40 @@+import { clsx } from 'clsx'+import { Link } from './link'++export function Text({ className, ...props }: React.ComponentPropsWithoutRef<'p'>) {+ return (+ <p+ {...props}+ data-slot="text"+ className={clsx(className, 'text-base/6 text-zinc-500 sm:text-sm/6 dark:text-zinc-400')}+ />+ )+}++export function TextLink({ className, ...props }: React.ComponentPropsWithoutRef<typeof Link>) {+ return (+ <Link+ {...props}+ className={clsx(+ className,+ 'text-zinc-950 underline decoration-zinc-950/50 data-[hover]:decoration-zinc-950 dark:text-white dark:decoration-white/50 dark:data-[hover]:decoration-white'+ )}+ />+ )+}++export function Strong({ className, ...props }: React.ComponentPropsWithoutRef<'strong'>) {+ return <strong {...props} className={clsx(className, 'font-medium text-zinc-950 dark:text-white')} />+}++export function Code({ className, ...props }: React.ComponentPropsWithoutRef<'code'>) {+ return (+ <code+ {...props}+ className={clsx(+ className,+ 'rounded border border-zinc-950/10 bg-zinc-950/[2.5%] px-0.5 text-sm font-medium text-zinc-950 sm:text-[0.8125rem] dark:border-white/20 dark:bg-white/5 dark:text-white'+ )}+ />+ )+}diff --git a/telemetry/ui/src/components/common/textarea.tsx b/telemetry/ui/src/components/common/textarea.tsxnew file mode 100644index 00000000..df05b4a6--- /dev/null+++ b/telemetry/ui/src/components/common/textarea.tsx@@ -0,0 +1,61 @@+import { Textarea as HeadlessTextarea, type TextareaProps as HeadlessTextareaProps } from '@headlessui/react'+import { clsx } from 'clsx'+import { forwardRef } from 'react'++export const Textarea = forwardRef<HTMLTextAreaElement, { resizable?: boolean } & HeadlessTextareaProps>(+ function Textarea({ className, resizable = true, ...props }, ref) {+ return (+ <span+ data-slot="control"+ className={clsx([+ className,++ // Basic layout+ 'relative block w-full',++ // Background color + shadow applied to inset pseudo element, so shadow blends with border in light mode+ 'before:absolute before:inset-px before:rounded-[calc(theme(borderRadius.lg)-1px)] before:bg-white before:shadow',++ // Background color is moved to control and shadow is removed in dark mode so hide `before` pseudo+ 'dark:before:hidden',++ // Focus ring+ 'after:pointer-events-none after:absolute after:inset-0 after:rounded-lg after:ring-inset after:ring-transparent sm:after:focus-within:ring-2 sm:after:focus-within:ring-blue-500',++ // Disabled state+ 'has-[[data-disabled]]:opacity-50 before:has-[[data-disabled]]:bg-zinc-950/5 before:has-[[data-disabled]]:shadow-none',+ ])}+ >+ <HeadlessTextarea+ ref={ref}+ className={clsx([+ // Basic layout+ 'relative block h-full w-full appearance-none rounded-lg px-[calc(theme(spacing[3.5])-1px)] py-[calc(theme(spacing[2.5])-1px)] sm:px-[calc(theme(spacing.3)-1px)] sm:py-[calc(theme(spacing[1.5])-1px)]',++ // Typography+ 'text-base/6 text-zinc-950 placeholder:text-zinc-500 sm:text-sm/6 dark:text-white',++ // Border+ 'border border-zinc-950/10 data-[hover]:border-zinc-950/20 dark:border-white/10 dark:data-[hover]:border-white/20',++ // Background color+ 'bg-transparent dark:bg-white/5',++ // Hide default focus styles+ 'focus:outline-none',++ // Invalid state+ 'data-[invalid]:border-red-500 data-[invalid]:data-[hover]:border-red-500 data-[invalid]:dark:border-red-600 data-[invalid]:data-[hover]:dark:border-red-600',++ // Disabled state+ 'disabled:border-zinc-950/20 disabled:dark:border-white/15 disabled:dark:bg-white/[2.5%] dark:data-[hover]:disabled:border-white/15',++ // Resizable+ resizable ? 'resize-y' : 'resize-none',+ ])}+ {...props}+ />+ </span>+ )+ }+)diff --git a/telemetry/ui/src/components/nav/appcontainer.tsx b/telemetry/ui/src/components/nav/appcontainer.tsxindex 6dac8944..6385c6ea 100644--- a/telemetry/ui/src/components/nav/appcontainer.tsx+++ b/telemetry/ui/src/components/nav/appcontainer.tsx@@ -74,22 +74,29 @@ export const AppContainer = (props: { children: React.ReactNode }) => {icon: Square2StackIcon,linkType: 'internal'},+ {+ name: 'Examples',+ href: 'https://github.com/DAGWorks-Inc/burr/tree/main/examples',+ icon: FolderIcon,+ linkType: 'external'+ },{name: 'Demos',href: '/demos',icon: ListBulletIcon,linkType: 'internal',children: [- // { name: 'counter', href: '/demos/counter', current: false, linkType: 'internal' },- { name: 'chatbot', href: '/demos/chatbot', current: false, linkType: 'internal' }+ { name: 'counter', href: '/demos/counter', current: false, linkType: 'internal' },+ { name: 'chatbot', href: '/demos/chatbot', current: false, linkType: 'internal' },+ {+ name: 'email-assistant',+ href: '/demos/email-assistant',+ current: false,+ linkType: 'internal'+ }]},- {- name: 'Examples',- href: 'https://github.com/DAGWorks-Inc/burr/tree/main/examples',- icon: FolderIcon,- linkType: 'external'- },+{name: 'Develop',href: 'https://github.com/dagworks-inc/burr',@@ -184,10 +191,6 @@ export const AppContainer = (props: { children: React.ReactNode }) => {<li key={item.name}><Linkto={item.href}- // target={item.linkType === 'external' ? '_blank' : undefined}- // rel={- // item.linkType === 'external' ? 'noopener noreferrer' : undefined- // }className={classNames(isCurrent(item.href, item.linkType)? 'bg-gray-50 text-dwdarkblue'diff --git a/telemetry/ui/src/examples/AppSelector.tsx b/telemetry/ui/src/examples/AppSelector.tsxdeleted file mode 100644index 84118e3c..00000000--- a/telemetry/ui/src/examples/AppSelector.tsx+++ /dev/null@@ -1,96 +0,0 @@-import { useQuery, useMutation } from 'react-query';-import { ApplicationSummary, DefaultService } from '../api';-import AsyncCreatableSelect from 'react-select/async-creatable';-import { DateTimeDisplay } from '../components/common/dates';--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 AppSelector = (props: {- projectId: string;- setApp: (app: ApplicationSummary) => void;- currentApp: ApplicationSummary | undefined;-}) => {- 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 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="Select a conversation to view telemetry and interact or create a new one by typing..."- cacheOptions- defaultOptions={options}- onCreateOption={(inputValue) => {- createAndUpdateMutation.mutate(inputValue);- }}- value={options.find((option) => option.value === props.currentApp?.app_id) || null}- // options={options}- // isLoading={isLoading || isRefetching || createAndUpdateMutation.isLoading}- onChange={(choice) => {- const app = dataOrEmpty.find((app) => app.app_id === choice?.value);- if (app) {- setApp(app);- }- }}- // onCreateOption={(inputValue) => {- // setApp({- // app_id: inputValue,- // first_written: new Date().toISOString(),- // last_written: new Date().toISOString(),- // num_steps: 0,- // tags: {}- // });- // createAndUpdateMutation.mutate(inputValue);- // }}- // onCreateOption={(inputValue) => {- // const newApp: ApplicationSummary = {- // app_id: inputValue,- // first_written: new Date().toISOString(),- // last_written: new Date().toISOString(),- // num_steps: 0,- // tags: {}- // };- // setApp(newApp);- // refetch().then(() => {- // setApp(newApp);- // });- // }}- />- );-};diff --git a/telemetry/ui/src/examples/Chatbot.tsx b/telemetry/ui/src/examples/Chatbot.tsxindex 8fe59f65..e5e8d86e 100644--- a/telemetry/ui/src/examples/Chatbot.tsx+++ b/telemetry/ui/src/examples/Chatbot.tsx@@ -3,13 +3,14 @@ import { classNames } from '../utils/tailwind';import { Button } from '../components/common/button';import { TwoColumnLayout } from '../components/common/layout';import { MiniTelemetry } from './MiniTelemetry';-import { AppSelector } from './AppSelector';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';type Role = 'assistant' | 'user';@@ -218,17 +219,87 @@ export const TelemetryWithSelector = (props: {return (<div className="w-full h-[90%]"><div className="w-full">- <AppSelector+ <ChatbotAppSelectorprojectId={props.projectId}setApp={props.setCurrentApp}currentApp={props.currentApp}- ></AppSelector>+ 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);diff --git a/telemetry/ui/src/examples/EmailAssistant.tsx b/telemetry/ui/src/examples/EmailAssistant.tsxnew file mode 100644index 00000000..ea04928e--- /dev/null+++ b/telemetry/ui/src/examples/EmailAssistant.tsx@@ -0,0 +1,444 @@+import { TwoColumnLayout } from '../components/common/layout';+import { MiniTelemetry } from './MiniTelemetry';+import {+ ApplicationSummary,+ DefaultService,+ DraftInit,+ EmailAssistantState,+ Feedback,+ QuestionAnswers+} from '../api';+import { useEffect, useState } from 'react';+import { useMutation, useQuery } from 'react-query';+import { Loading } from '../components/common/loading';+import { Field, Label } from '../components/common/fieldset';+import { Textarea } from '../components/common/textarea';+import { Input } from '../components/common/input';+import { Text } from '../components/common/text';+import { Button } from '../components/common/button';+import { DateTimeDisplay } from '../components/common/dates';+import AsyncCreatableSelect from 'react-select/async-creatable';++export const InitialDraftView = (props: {+ submitInitial: (initial: DraftInit) => void;+ isLoading: boolean;+ responseInstructions: string | null;+ emailToRespond: string | null;+}) => {+ const [userProvidedEmailToRespond, setUserProvidedEmailToRespond] = useState<string>(+ props.emailToRespond || ''+ );+ const [userProvidedResponseInstructions, setUserProvidedResponseInstructions] = useState<string>(+ props.responseInstructions || ''+ );+ const editMode = props.emailToRespond === null;++ return (+ <div className="w-full flex flex-col gap-2">+ <Field>+ <Label>Email to respond to</Label>+ <Textarea+ name="email_to_respond"+ value={userProvidedEmailToRespond}+ onChange={(e) => {+ setUserProvidedEmailToRespond(e.target.value);+ }}+ disabled={!editMode}+ />+ </Field>+ <Field>+ <Label>Response Instructions</Label>+ <Input+ name="response_instructions"+ value={userProvidedResponseInstructions}+ onChange={(e) => {+ setUserProvidedResponseInstructions(e.target.value);+ }}+ disabled={!editMode}+ />+ </Field>+ {editMode && (+ <Button+ color="white"+ className="cursor-pointer w-full"+ disabled={props.isLoading}+ onClick={() =>+ props.submitInitial({+ email_to_respond: userProvidedEmailToRespond,+ response_instructions: userProvidedResponseInstructions+ })+ }+ >+ {'Submit'}+ </Button>+ )}+ </div>+ );+};++export const SubmitAnswersView = (props: {+ state: EmailAssistantState;+ submitAnswers: (questions: QuestionAnswers) => void;+ questions: string[] | null;+ answers: string[] | null;+ isLoading: boolean;+}) => {+ const questions = props.state.questions || [];+ const [answers, setAnswers] = useState<string[]>(props.answers || questions.map(() => ''));+ const editMode = props.isLoading || props.answers === null;+ return (+ <div className="w-full flex flex-col gap-2">+ <div className="flex flex-col gap-2">+ {(props.state.questions || []).map((question, index) => {+ return (+ <Field key={index}>+ <Label>{question}</Label>+ <Input+ disabled={!editMode}+ value={answers[index]}+ onChange={(e) => {+ const newAnswers = [...answers];+ newAnswers[index] = e.target.value;+ setAnswers(newAnswers);+ }}+ />+ </Field>+ );+ })}+ </div>+ {editMode && (+ <Button+ color="white"+ className="cursor-pointer w-full"+ disabled={props.isLoading}+ onClick={() => props.submitAnswers({ answers: answers })}+ >+ {'Submit'}+ </Button>+ )}+ </div>+ );+};++export const SubmitFeedbackView = (props: {+ state: EmailAssistantState;+ submitFeedback: (feedbacks: Feedback) => void;+ drafts: string[] | null;+ feedbacks: string[] | null;+ isLoading: boolean;+}) => {+ const editMode = props.feedbacks === null || props.feedbacks.length !== props.drafts?.length; // if its not equal we are one step behind+ const [feedback, setFeedback] = useState<string>(props.feedbacks?.[-1] || '');+ return (+ <div className="w-full flex flex-col gap-2">+ <Field>+ <Label className="text-lg font-bold text-gray-600">Drafts</Label>+ </Field>+ <div className="flex flex-col gap-2">+ {(props.drafts || []).map((draft, index) => {+ const providedFeedback = props.feedbacks?.[index];+ return (+ <>+ <Text>+ <pre className="whitespace-pre-wrap text-xs" key={index}>+ {draft}+ </pre>+ </Text>+ <h3 className="text-sm font-semibold text-gray-600"></h3>+ <Input+ disabled={!editMode || props.isLoading || index !== (props.drafts || []).length - 1}+ placeholder="Provide feedback here..."+ value={providedFeedback || feedback}+ onChange={(e) => {+ setFeedback(e.target.value);+ }}+ />+ </>+ );+ })}+ {editMode && (+ <div className="flex flex-row gap-1">+ <Button+ color="white"+ className="cursor-pointer w-full"+ disabled={props.isLoading}+ onClick={() => {+ props.submitFeedback({ feedback: feedback }), setFeedback('');+ }}+ >+ {'Submit Feedback'}+ </Button>+ <Button+ color="white"+ className="cursor-pointer w-full"+ disabled={props.isLoading}+ onClick={() => props.submitFeedback({ feedback: '' })}+ >+ {'Looks good!'}+ </Button>+ </div>+ )}+ </div>+ </div>+ );+};++export const EmailAssistant = (props: { projectId: string; appId: string | undefined }) => {+ // starts off as null+ const [emailAssistantState, setEmailAssistantState] = useState<EmailAssistantState | null>(null);++ useEffect(() => {+ if (props.appId !== undefined) {+ // TODO -- handle errors+ DefaultService.getStateApiV0EmailAssistantStateProjectIdAppIdGet(props.projectId, props.appId)+ .then((data) => {+ setEmailAssistantState(data); // we want to initialize the chat history+ })+ .catch((e) => {+ // eslint-disable-next-line+ console.error(e); // TODO -- handle errors+ });+ }+ }, [props.appId, props.projectId]); // This will only get called when the appID or projectID changes, which will be at the beginning++ const { isLoading: isGetInitialStateLoading } = useQuery(+ // TODO -- handle errors+ ['emailAssistant', props.projectId, props.appId],+ () =>+ DefaultService.getStateApiV0EmailAssistantStateProjectIdAppIdGet(+ props.projectId,+ props.appId || '' // TODO -- find a cleaner way of doing a skip-token like thing here+ // This is skipped if the appId is undefined so this is just to make the type-checker happy+ ),+ {+ enabled: props.appId !== undefined,+ onSuccess: (data) => {+ setEmailAssistantState(data); // when its succesful we want to set the displayed chat history+ }+ }+ );++ const submitInitialMutation = useMutation(+ (draftData: DraftInit) =>+ DefaultService.initializeDraftApiV0EmailAssistantCreateProjectIdAppIdPost(+ props.projectId,+ props.appId || 'create_new',+ draftData+ ),+ {+ onSuccess: (data) => {+ setEmailAssistantState(data);+ }+ }+ );++ const submitAnswersMutation = useMutation(+ (answers: QuestionAnswers) =>+ DefaultService.answerQuestionsApiV0EmailAssistantAnswerQuestionsProjectIdAppIdPost(+ props.projectId,+ props.appId || '',+ answers+ ),+ {+ onSuccess: (data) => {+ setEmailAssistantState(data);+ }+ }+ );+ const submitFeedbackMutation = useMutation(+ (feedbacks: Feedback) =>+ DefaultService.provideFeedbackApiV0EmailAssistantProvideFeedbackProjectIdAppIdPost(+ props.projectId,+ props.appId || '',+ feedbacks+ ),+ {+ onSuccess: (data) => {+ setEmailAssistantState(data);+ }+ }+ );++ const isLoading = isGetInitialStateLoading;+ const anyMutationLoading =+ submitInitialMutation.isLoading ||+ submitAnswersMutation.isLoading ||+ submitFeedbackMutation.isLoading;++ if (isLoading) {+ return <Loading />;+ }+ const displayInstructions = emailAssistantState === null;+ const displayInitialDraft = emailAssistantState !== null;+ const displaySubmitAnswers =+ displayInitialDraft && emailAssistantState.next_step !== 'process_input';+ const displaySubmitFeedback =+ displaySubmitAnswers && emailAssistantState.next_step !== 'clarify_instructions';+ const displayFinalDraft = displaySubmitFeedback && emailAssistantState.next_step === null;+ return (+ <div className="px-4 bg-white w-full flex flex-col h-full gap-5 overflow-y-scroll">+ <h1 className="text-2xl font-bold text-gray-600">{'Learn Burr '}</h1>+ <h2 className="text-lg font-normal text-gray-500 flex flex-row">+ The email assistant below is implemented using Burr. Copy/paste the email you want to+ respond to and provide directions, it will ask you questions, generate a response, and+ adjust for your feedback.+ </h2>+ <div className="flex flex-col">+ {displayInstructions && (+ <p className="text-lg font-normal text-gray-500">+ Please click 'create new' on the right to get started!+ </p>+ )}+ {displayInitialDraft && (+ <InitialDraftView+ isLoading={anyMutationLoading}+ submitInitial={(initial) => {+ submitInitialMutation.mutate(initial);+ }}+ responseInstructions={emailAssistantState?.response_instructions}+ emailToRespond={emailAssistantState?.email_to_respond}+ />+ )}+ </div>+ {displaySubmitAnswers && (+ <SubmitAnswersView+ state={emailAssistantState}+ submitAnswers={(answers) => {+ submitAnswersMutation.mutate(answers);+ }}+ questions={emailAssistantState.questions}+ answers={emailAssistantState.answers}+ isLoading={anyMutationLoading}+ />+ )}+ {displaySubmitFeedback && (+ <SubmitFeedbackView+ state={emailAssistantState}+ submitFeedback={(feedbacks) => {+ submitFeedbackMutation.mutate(feedbacks);+ }}+ drafts={emailAssistantState.drafts}+ feedbacks={emailAssistantState.feedback_history}+ isLoading={anyMutationLoading}+ />+ )}+ {displayFinalDraft && (+ <div className="flex flex-col gap-2">+ <h2 className="text-lg font-bold text-gray-600">Final Draft</h2>+ <Text>+ <pre className="whitespace-pre-wrap text-xs">+ {emailAssistantState.drafts?.[emailAssistantState.drafts.length - 1]}+ </pre>+ </Text>+ </div>+ )}+ </div>+ );+};++export const TelemetryWithSelector = (props: {+ projectId: string;+ currentApp: ApplicationSummary | undefined;+ setCurrentApp: (app: ApplicationSummary) => void;+}) => {+ return (+ <div className="w-full h-[90%]">+ <div className="w-full">+ <EmailAssistantAppSelector+ projectId={props.projectId}+ setApp={props.setCurrentApp}+ currentApp={props.currentApp}+ placeholder={'Select a conversation or create a new one by typing...'}+ ></EmailAssistantAppSelector>+ </div>+ <MiniTelemetry projectId={props.projectId} appId={props.currentApp?.app_id}></MiniTelemetry>+ </div>+ );+};++const EmailAssistantLabel = (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 EmailAssistantAppSelector = (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: <EmailAssistantLabel 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 EmailAssistantWithTelemetry = () => {+ const currentProject = 'demo:email-assistant';+ const [currentApp, setCurrentApp] = useState<ApplicationSummary | undefined>(undefined);++ return (+ <TwoColumnLayout+ firstItem={<EmailAssistant projectId={currentProject} appId={currentApp?.app_id} />}+ secondItem={+ <TelemetryWithSelector+ projectId={currentProject}+ currentApp={currentApp}+ setCurrentApp={setCurrentApp}+ />+ }+ mode={'third'}+ ></TwoColumnLayout>+ );+};