Exiting the agent loop

After your agent has finished a workflow, you can signal the end of that workflow by calling the copilotkit_exit() method in your Python code.

The exit call sends an AG-UI custom event named Exit to the frontend. CopilotKit does not act on this event. To react to it in your app, subscribe to the agent with an onCustomEvent handler and check for the name Exit.

In this example, the send_email method adds an assistant message, then exits:

Install the CopilotKit SDK

pip install ag-ui-crewai

Exit the agent loop

Call copilotkit_exit() at the end of the method. It sends the Exit event to the frontend.

from litellm import completion
from crewai.flow.flow import start
from ag_ui_crewai import copilotkit_exit
# ...
@start()
async def send_email(self):
    """Send an email."""


    # get the last message and cast to ToolMessage
    last_message = self.state.messages[-1]
    if last_message["content"] == "CANCEL":
        text_message = "❌ Cancelled sending email."
    else:
        text_message = "✅ Sent email."
    self.state.messages.append({"role": "assistant", "content": text_message, "id": str(uuid.uuid4())})
    # Exit the agent loop after processing
    await copilotkit_exit()

How is this guide?