Building the chat interface

Now let's see how we integrate our streaming agent workflow with Chainlit. We use Steps to show real-time progress as each agent executes.

Full chat flow

How user messages flow through Chainlit to LangGraph agents and back

app.py
python
@cl.on_message
async def main(message: cl.Message):
    """Handle incoming messages with debugging visualization"""
    user_question = message.content

    # Create main workflow step
    async with cl.Step(name="Agent Workflow", type="llm") as workflow_step:
        node_steps = {}
        final_result = None

        # Stream through agent execution
        async for event in process_question_stream(user_question):
            event_type = event.get("type")

            if event_type == "node_start":
                node_name = event["node"]
                display_names = {
                    "guardrails_agent": "Guardrails Check",
                    "sql_agent": "Generate SQL Query",
                    "execute_sql": "Execute SQL Query",
                    "analysis_agent": "Generate Answer",
                    "error_agent": "Handle Error",
                    "decide_graph_need": "Decide Graph Need",
                    "viz_agent": "Generate Graph"
                }

                node_step = cl.Step(
                    name=display_names.get(node_name, node_name),
                    type="tool",
                    parent_id=workflow_step.id
                )
                await node_step.send()
                node_steps[node_name] = node_step

            elif event_type == "node_end":
                # Update step with output...
                pass

            elif event_type == "final":
                final_result = event["result"]

        workflow_step.output = "Workflow completed"
        await workflow_step.update()

    # Send final response
    if final_result:
        await cl.Message(content=final_result["final_answer"]).send()

The main message handler streams agent events to the UI.

Yes! Each agent step appears as a collapsible section in the chat. You see "Guardrails Check" appear first, then "Generate SQL Query", then "Execute SQL Query", and so on. Users can click to expand any step and see what happened inside. The final answer appears as a normal chat message below all the steps.

Matching exercise: Match UI Components to purposes

Loading practice…

Quiz: Quiz

Loading practice…

The chat interface is wired up and streaming agent steps in real time. Next, we will add interactive Plotly charts directly into the chat messages.