A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: support async callbacks in ui.chat (#2491)
Akshay Agrawal58864f896bce
diff --git a/examples/ai/chat/README.md b/examples/ai/chat/README.mdindex bc868ef282..518f3706f9 100644--- a/examples/ai/chat/README.md+++ b/examples/ai/chat/README.md@@ -13,6 +13,12 @@ stale, with the chatbot's response stored in the object's `value` attribute.You can use this to make notebooks that respond to the chatbot's responsein arbitrary ways. For example, you can make agentic notebooks!+Once you understand the basics, for a more interesting example, check out+[our notebook that lets you talk to any GitHub repo](../../third_party/sage/),+powered by Storia-AI/sage. This example demonstrates advanced usage+of `ui.chat`, using `langchain` to construct a RAG-powered chatbot, served by+an async generator callback function.+## Running examplesThe requirements of each notebook are serialized in them as a top-leveldiff --git a/examples/ai/chat/custom.py b/examples/ai/chat/custom.pyindex 69ce0090a4..e9516a3659 100644--- a/examples/ai/chat/custom.py+++ b/examples/ai/chat/custom.py@@ -1,3 +1,10 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "marimo",+# ]+# ///+import marimo__generated_with = "0.8.22"diff --git a/examples/ai/chat/openai.py b/examples/ai/chat/openai.pyindex acafb5db6a..8a590142a3 100644--- a/examples/ai/chat/openai.py+++ b/examples/ai/chat/openai.py@@ -7,7 +7,7 @@import marimo-__generated_with = "0.8.22"+__generated_with = "0.9.0"app = marimo.App(width="medium")@@ -17,7 +17,7 @@ def __():return (mo,)[email protected](hide_code=True)def __(mo):mo.md(r"""diff --git a/examples/third_party/sage/README.md b/examples/third_party/sage/README.mdnew file mode 100644index 0000000000..4ddab89d9e--- /dev/null+++ b/examples/third_party/sage/README.md@@ -0,0 +1,77 @@+# Sage: chat with any codebase 🤖💬++This example shows how to create a notebook that let's you+_chat with any codebase_, using [Sage](https://github.com/storia-ai/sage)+from Storia AI. It uses `mo.ui.chat` with a custom chat function that+implements a RAG-powered search over any GitHub repository of your choosing.+The result is a chatbot that you can use to incrementally explore a codebase+and even its associated GitHub issues.+++++## Running the chat notebook+++### Index a GitHub repo with sage++This notebook has its Python dependencies inlined in it, but you do need+to set up some non-Python dependencies before you can run it. To run locally,+follow these instructions. Get the full instructions at+[the sage repo](https://github.com/storia-ai/sage).+++```bash+docker rm -f marqo+docker pull marqoai/marqo:latest+docker run --name marqo -it -p 8882:8882 marqoai/marqo:latest+```++Then install [Ollama](https://github.com/ollama/ollama) and run++```bash+ollama pull llama3.1+```++Next, run++```+pipx install git+https://github.com/Storia-AI/sage.git@main+```++and choose a GitHub repo to index with (eg)++```bash+export GITHUB_REPO=marimo-team/marimo+```++Finally run++```+sage-index $GITHUB_REPO+```++### Run the marimo notebook!++Open the marimo notebook with++```bash+marimo edit --sandbox chat_with_github.py -- $GITHUB_REPO+```++and start chatting with your repo!++You can also deploy this notebook as a web app, with++```bash+marimo run --sandbox chat_with_github.py -- $GITHUB_REPO+```+++> [!TIP]+> The [`--sandbox` flag](https://docs.marimo.io/guides/editor_features/package_management.html) opens the notebook in an isolated virtual environment,+> automatically installing the notebook's dependencies 📦++You can also open the notebook without `uv`, with just `marimo edit+chat_with_github_repo.py`; however, you'll need to install the requirements+yourself.diff --git a/examples/third_party/sage/chat_with_github_repo.py b/examples/third_party/sage/chat_with_github_repo.pynew file mode 100644index 0000000000..93cd124613--- /dev/null+++ b/examples/third_party/sage/chat_with_github_repo.py@@ -0,0 +1,233 @@+# /// script+# requires-python = ">=3.10"+# dependencies = [+# "marimo >= 0.9.0",+# "sage @ git+https://github.com/Storia-AI/sage.git@28ce9537e4ec08deee6b9a4e3392866819e0edac",+# ]+# ///++import marimo++__generated_with = "0.9.0"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ return (mo,)+++def __(mo, sys):+ mo.md(f"# 🤖💬 {sys.argv[-1]} ")+ return++[email protected](hide_code=True)+def __(mo, sys):+ mo.md(+ f"""+ I'm a chatbot that can answer questions about the **{sys.argv[-1]}** GitHub repo. Ask me anything!+ """+ )+ return+++def __():+ import sys+ import logging++ import configargparse+ import gradio as gr+ import dotenv+ from langchain.chains import create_history_aware_retriever, create_retrieval_chain+ from langchain.chains.combine_documents import create_stuff_documents_chain+ from langchain.schema import AIMessage, HumanMessage+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder++ import sage.config as sage_config+ from sage.llm import build_llm_via_langchain+ from sage.retriever import build_retriever_from_args++ _ = dotenv.load_dotenv(dotenv.find_dotenv(usecwd=True))+ return (+ AIMessage,+ ChatPromptTemplate,+ HumanMessage,+ MessagesPlaceholder,+ build_llm_via_langchain,+ build_retriever_from_args,+ configargparse,+ create_history_aware_retriever,+ create_retrieval_chain,+ create_stuff_documents_chain,+ dotenv,+ gr,+ logging,+ sage_config,+ sys,+ )+++def __(+ ChatPromptTemplate,+ MessagesPlaceholder,+ build_llm_via_langchain,+ build_retriever_from_args,+ create_history_aware_retriever,+ create_retrieval_chain,+ create_stuff_documents_chain,+):+ def build_rag_chain(args):+ """Builds a RAG chain via LangChain."""+ llm = build_llm_via_langchain(args.llm_provider, args.llm_model)+ retriever = build_retriever_from_args(args)++ # Prompt to contextualize the latest query based on the chat history.+ contextualize_q_system_prompt = (+ "Given a chat history and the latest user question which might reference context in the chat history, "+ "formulate a standalone question which can be understood without the chat history. Do NOT answer the question, "+ "just reformulate it if needed and otherwise return it as is."+ )+ contextualize_q_prompt = ChatPromptTemplate.from_messages(+ [+ ("system", contextualize_q_system_prompt),+ MessagesPlaceholder("chat_history"),+ ("human", "{input}"),+ ]+ )+ contextualize_q_llm = llm.with_config(tags=["contextualize_q_llm"])+ history_aware_retriever = create_history_aware_retriever(+ contextualize_q_llm, retriever, contextualize_q_prompt+ )++ qa_system_prompt = (+ f"You are my coding buddy, helping me quickly understand a GitHub repository called {args.repo_id}."+ "Assume I am an advanced developer and answer my questions in the most succinct way possible."+ "\n\n"+ "Here are some snippets from the codebase."+ "\n\n"+ "{context}"+ )+ qa_prompt = ChatPromptTemplate.from_messages(+ [+ ("system", qa_system_prompt),+ MessagesPlaceholder("chat_history"),+ ("human", "{input}"),+ ]+ )++ question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)+ rag_chain = create_retrieval_chain(+ history_aware_retriever, question_answer_chain+ )+ return rag_chain+ return (build_rag_chain,)+++def __(configargparse, sage_config, sys):+ parser = configargparse.ArgParser(+ description="Batch-embeds a GitHub repository and its issues.",+ ignore_unknown_config_file_keys=True,+ prog="marimo edit chat.py --",+ )+ parser.add(+ "--share",+ default=False,+ help="Whether to make the gradio app publicly accessible.",+ )+ sage_config.add_config_args(parser)++ arg_validators = [+ sage_config.add_repo_args(parser),+ sage_config.add_embedding_args(parser),+ sage_config.add_vector_store_args(parser),+ sage_config.add_reranking_args(parser),+ sage_config.add_llm_args(parser),+ ]+ _argv = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else []+ args = parser.parse_args(_argv)+ for validator in arg_validators:+ validator(args)+ return arg_validators, args, parser, validator+++def __(args):+ args+ return+++def __(AIMessage, HumanMessage, args, build_rag_chain, logging, mo):+ rag_chain = build_rag_chain(args)+++ def source_md(file_path: str, url: str) -> str:+ """Formats a context source in Markdown."""+ return f"[{file_path}]({url})"+++ async def predict(messages):+ """Performs one RAG operation."""+ message = messages[-1].content+ history_langchain_format = []+ for msg in messages[:-1]:+ if msg.role == "user":+ history_langchain_format.append(HumanMessage(content=msg.content))+ elif msg.role == "assistant":+ history_langchain_format.append(AIMessage(content=msg.content))+ history_langchain_format.append(HumanMessage(content=message))++ query_rewrite = ""+ response = ""+ async for event in rag_chain.astream_events(+ {+ "input": message,+ "chat_history": history_langchain_format,+ },+ version="v1",+ ):+ if (+ event["name"] == "retrieve_documents"+ and "output" in event["data"]+ and event["data"]["output"] is not None+ ):+ sources = [+ (doc.metadata["file_path"], doc.metadata["url"])+ for doc in event["data"]["output"]+ ]+ # Deduplicate while preserving the order.+ sources = list(dict.fromkeys(sources))+ response += (+ "## Sources:\n"+ + "\n".join([source_md(s[0], s[1]) for s in sources])+ + "\n## Response:\n"+ )++ elif event["event"] == "on_chat_model_stream":+ chunk = event["data"]["chunk"].content++ if "contextualize_q_llm" in event["tags"]:+ query_rewrite += chunk+ else:+ # This is the actual response to the user query.+ if not response:+ logging.info(f"Query rewrite: {query_rewrite}")+ response += chunk+ yield mo.md(response)+ return predict, rag_chain, source_md+++def __(mo, predict):+ mo.ui.chat(predict, prompts=["What does this repo do?", "Give me some sample code"])+ return+++if __name__ == "__main__":+ app.run()diff --git a/examples/third_party/sage/chat_with_sage.png b/examples/third_party/sage/chat_with_sage.pngnew file mode 100644index 0000000000..5df811b7d9Binary files /dev/null and b/examples/third_party/sage/chat_with_sage.png differdiff --git a/examples/third_party/sage/continue_chatting_with_sage.png b/examples/third_party/sage/continue_chatting_with_sage.pngnew file mode 100644index 0000000000..00c9e2b551Binary files /dev/null and b/examples/third_party/sage/continue_chatting_with_sage.png differdiff --git a/marimo/_plugins/ui/_impl/chat/chat.py b/marimo/_plugins/ui/_impl/chat/chat.pyindex cfb4a18c3b..d489745831 100644--- a/marimo/_plugins/ui/_impl/chat/chat.py+++ b/marimo/_plugins/ui/_impl/chat/chat.py@@ -40,9 +40,9 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):**Example: Using a custom model.**Define a chatbot by implementing a function that takes a list of- `ChatMessage`s and a config object as input, and returns the chat response.- The response can be any object, including text, plots, or marimo UI- elements.+ `ChatMessage`s and optionally a config object as input, and returns the+ chat response. The response can be any object, including text, plots, or+ marimo UI elements.```pythondef my_rag_model(messages, config):@@ -60,6 +60,25 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):chat = mo.ui.chat(my_rag_model)```+ Async functions and async generators are also supported, meaning these+ are both valid chat functions:++ ```python+ async def my_rag_model(messages):+ return await my_async_function(messages)+ ```++ ```python+ async def my_rag_model(messages):+ for response in my_async_iterator(messages):+ yield response+ ```++ The last value yielded by the async generator is treated as the model+ response. ui.chat does not yet support streaming responses to the frontend.+ Please file a GitHub issue if this is important to you:+ https://github.com/marimo-team/marimo/issues+**Example: Using a built-in model.**Instead of defining a chatbot function, you can use a built-in model from@@ -136,7 +155,7 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):def _get_chat_history(self, _args: EmptyArgs) -> GetChatHistoryResponse:return GetChatHistoryResponse(messages=self._chat_history)- def _send_prompt(self, args: SendMessageRequest) -> str:+ async def _send_prompt(self, args: SendMessageRequest) -> str:messages = args.messages# If the model is a callable that takes a single argument,@@ -151,6 +170,23 @@ class chat(UIElement[Dict[str, Any], List[ChatMessage]]):else:response = self._model(messages, args.config)+ if inspect.isawaitable(response):+ response = await response+ elif inspect.isasyncgen(response):+ # We support functions that stream the response with an async+ # generator; each yielded value is the latest representation of the+ # response, and the last value is the full value+ latest_response = None+ async for latest_response in response: # noqa: B007+ # TODO(akshayka, mscolnick): Stream response to frontend+ # once bidirectional communication is implemented.+ #+ # RPCs don't yet support bidirectional communication, so we+ # just ignore all the initial responses; ideally we'd stream+ # the response back to the frontend.+ pass+ response = latest_response+content = (as_html(response).text # convert to html if not a stringif not isinstance(response, str)diff --git a/tests/_plugins/ui/_impl/chat/test_chat.py b/tests/_plugins/ui/_impl/chat/test_chat.pyindex e7f960971d..004c0807fb 100644--- a/tests/_plugins/ui/_impl/chat/test_chat.py+++ b/tests/_plugins/ui/_impl/chat/test_chat.py@@ -1,7 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Dict, List+import asyncio+from typing import AsyncIterator, Dict, Listimport pytest@@ -55,7 +56,7 @@ def test_chat_with_config():assert chat._component_args["config"] == config-def test_chat_send_prompt():+async def test_chat_send_prompt():def mock_model(messages: List[ChatMessage], config: ChatModelConfig) -> str:@@ -67,7 +68,7 @@ def test_chat_send_prompt():messages=[ChatMessage(role="user", content="Hello")],config=ChatModelConfig(),)- response: str = chat._send_prompt(request)+ response: str = await chat._send_prompt(request)assert response == "Response to: Hello"assert len(chat._chat_history) == 2@@ -77,6 +78,55 @@ def test_chat_send_prompt():assert chat._chat_history[1].content == "Response to: Hello"+async def test_chat_send_prompt_async_function():+ async def mock_model(+ messages: List[ChatMessage], config: ChatModelConfig+ ) -> str:+ del config+ await asyncio.sleep(0.01)+ return f"Response to: {messages[-1].content}"++ chat = ui.chat(mock_model)+ request = SendMessageRequest(+ messages=[ChatMessage(role="user", content="Hello")],+ config=ChatModelConfig(),+ )+ response: str = await chat._send_prompt(request)++ assert response == "Response to: Hello"+ assert len(chat._chat_history) == 2+ assert chat._chat_history[0].role == "user"+ assert chat._chat_history[0].content == "Hello"+ assert chat._chat_history[1].role == "assistant"+ assert chat._chat_history[1].content == "Response to: Hello"+++async def test_chat_send_prompt_async_generator():+ async def mock_model(+ messages: List[ChatMessage], config: ChatModelConfig+ ) -> AsyncIterator[str]:+ del config+ del messages+ for i in range(3):+ await asyncio.sleep(0.01)+ yield str(i)++ chat = ui.chat(mock_model)+ request = SendMessageRequest(+ messages=[ChatMessage(role="user", content="Hello")],+ config=ChatModelConfig(),+ )+ response: str = await chat._send_prompt(request)++ # the last yielded value is the response+ assert response == "2"+ assert len(chat._chat_history) == 2+ assert chat._chat_history[0].role == "user"+ assert chat._chat_history[0].content == "Hello"+ assert chat._chat_history[1].role == "assistant"+ assert chat._chat_history[1].content == "2"++def test_chat_get_history():def mock_model(messages: List[ChatMessage], config: ChatModelConfig@@ -134,7 +184,7 @@ def test_chat_convert_value_invalid():chat._convert_value({"invalid": "format"})-def test_chat_with_on_message():+async def test_chat_with_on_message():def mock_model(messages: List[ChatMessage], config: ChatModelConfig) -> str:@@ -153,7 +203,7 @@ def test_chat_with_on_message():messages=[ChatMessage(role="user", content="Hello")],config=ChatModelConfig(),)- chat._send_prompt(request)+ await chat._send_prompt(request)assert on_message_called@@ -198,6 +248,6 @@ async def test_chat_send_message_enqueues_ui_element_request(messages=[ChatMessage(role="user", content="Hello")],config=ChatModelConfig(),)- chatbot._send_prompt(request)+ await chatbot._send_prompt(request)assert len(control_requests) == 1assert isinstance(control_requests[0], SetUIElementValueRequest)