LangGraph
Use the LangGraph adapter when a LangGraph graph or agent writes your replies: it streams the run into the chat, and emit() sends components from inside any node or tool.
Code on this page is fragments; the complete example is a whole file.
pip install "dyui[langgraph]" # installs langgraph>=1.0dyui.integrations.langgraph has two functions:
stream(graph, input, config=None, **kwargs)runs the graph withstream_mode=["messages", "custom"]and yields what DyUI understands: AI message chunks as text (parsed fordyuifences), thinking blocks asReasoning, and components youemit().emit(item, writer=None, *, config=None), called inside any node or tool, sends a component (or a{"ui": ...}dict) straight to the chat.
A sketch of a two-node research graph (search and llm stand for your own search function and chat model):
import dyuifrom dyui import uifrom dyui.integrations.langgraph import emit, stream as lg_streamfrom langchain_core.messages import SystemMessagefrom langchain_core.runnables import RunnableConfigfrom langgraph.graph import END, START, MessagesState, StateGraph
app = dyui.App(title="Research Agent")
async def research(state: MessagesState, config: RunnableConfig): emit(ui.Step("Searching sources", "running", id="search"), config=config) results = await search(state["messages"][-1].content) emit(ui.Step("Searching sources", "done", id="search"), config=config) emit(ui.Sources(*[ui.Source(r.title, r.url) for r in results]), config=config) return {"messages": []}
async def answer(state: MessagesState): system = SystemMessage("Answer from the sources.\n\n" + app.catalog.prompt()) return {"messages": [await llm.ainvoke([system, *state["messages"]])]}
builder = StateGraph(MessagesState)builder.add_node("research", research)builder.add_node("answer", answer)builder.add_edge(START, "research")builder.add_edge("research", "answer")builder.add_edge("answer", END)graph = builder.compile()
@app.on_messageasync def reply(msg: dyui.Message, chat: dyui.Chat): async for part in lg_stream(graph, {"messages": chat.history}, config={"configurable": {"thread_id": chat.thread_id}}): yield partemit() on every Python version
Section titled “emit() on every Python version”On Python 3.11+, emit(item) finds the current LangGraph run by itself. On Python 3.10, LangGraph can’t propagate its run context into nodes, so pass the run explicitly. These forms work on every version, so prefer them in code that others will run:
from langchain_core.runnables import RunnableConfigfrom langchain_core.tools import toolfrom langgraph.prebuilt import ToolRuntime
async def search(state, config: RunnableConfig): # a graph node emit(ui.Table(["Title", "URL"], rows), config=config)
@tooldef forecast(city: str, runtime: ToolRuntime) -> str: # a tool emit(ui.Chart("line", [ui.Series(city, [18, 20, 17])]), writer=runtime) return "18–20°C"writer= accepts a LangGraph StreamWriter, or a Runtime / ToolRuntime (its stream writer and config are used). If emit() can’t find a run, for example outside a graph or on 3.10 without config/writer, it logs a warning and drops the component rather than raising. It does the same when langgraph isn’t installed.
- Add
app.catalog.prompt()to the system prompt of the node that writes the final answer, and the model’s components render like any other. chat.historyis a list of{"role", "content"}dicts, which LangGraph’sMessagesStateaccepts directly. If your graph has a checkpointer that already remembers the thread, send only the new message:{"messages": [{"role": "user", "content": msg.text}]}.- An emitted
{"ui": ...}dict is validated like model output, so it can’t be the developer-onlyhtml. Emit aui.Html(...)instance instead. - Tool-call chunks without text are skipped. A complete
AIMessageis only shown if it wasn’t already streamed.
Complete example
Section titled “Complete example”A prebuilt ReAct agent whose tool emits a chart while the model streams its answer.
"""A LangGraph agent whose tool emits DyUI components while the model streams text."""import osfrom functools import lru_cache
import dyuifrom dyui import uifrom dyui.integrations.langgraph import emit, stream as lg_streamfrom langchain_core.tools import toolfrom langgraph.checkpoint.memory import InMemorySaverfrom langgraph.prebuilt import ToolRuntime, create_react_agent
MODEL = os.getenv("DYUI_LANGCHAIN_MODEL", "openai:gpt-5") # pip install langchain langchain-openai
app = dyui.App(title="Weather Agent", starters=["Compare the weather in Paris and Rome"])
@tooldef forecast(city: str, runtime: ToolRuntime) -> str: """Get a 3-day temperature forecast for a city.""" temps = {"paris": [18, 20, 17], "rome": [24, 26, 25]}.get(city.lower(), [20, 20, 20]) emit(ui.Chart(kind="line", title=f"{city}: next 3 days", unit="C", labels=["Mon", "Tue", "Wed"], series=[{"name": city, "data": temps}]), writer=runtime) # the injected ToolRuntime (portable to Python 3.10) return f"{city}: {temps} C"
@lru_cache(maxsize=1)def graph(): # built on first use, so the app starts without an API key return create_react_agent(MODEL, tools=[forecast], checkpointer=InMemorySaver(), prompt="You are a weather assistant. Be brief.")
@app.on_messageasync def reply(msg: dyui.Message, chat: dyui.Chat): config = {"configurable": {"thread_id": chat.thread_id}} async for part in lg_stream(graph(), {"messages": [{"role": "user", "content": msg.text}]}, config=config): yield part-
Save it as
langgraph_agent.pyin a new, empty file, or download it. -
Put
OPENAI_API_KEY=sk-...in a.envfile next to it (LangChain’s OpenAI model reads it; setDYUI_LANGCHAIN_MODELfor another<provider>:<model>). -
Run it:
Terminal window pip install "dyui[langgraph]" langchain langchain-openaidyui run langgraph_agent.py -
Open http://localhost:8000 and send a message.
See also
Section titled “See also”- LangGraph agent: the same file, explained.
- Steps & reasoning: live steps from nodes.