Programmatic Control
Drive agent runs from code in a React Native app, with no chat UI required.
What is this?
Programmatic control is what you reach for when you want to drive an agent run from code rather than from a chat composer: a button, a form, a push notification, a voice transcript, or a background task. CopilotKit gives you three primitives that cover every trigger:
agent.addMessage(...): add a message to the conversation without running the agent. Pair it withcopilotkit.runAgent({ agent })when the message should start a turn.copilotkit.runAgent({ agent }): the same entry point the prebuilt chat calls. It runs frontend tools, follow-up runs, and the subscriber lifecycle.agent.subscribe(subscriber): a low-level AG-UI event subscription (onCustomEvent,onRunStartedEvent,onRunFinalized,onRunFailed, and more). Use it withcopilotkit.runAgent({ agent, resume })for standard AG-UI interrupts, or withcopilotkit.runAgent({ agent, forwardedProps: { command: { resume, interruptEvent } } })for theon_interruptcustom events that the LangGraph adapter sends.
When should I use this?
Use programmatic control when you want to:
- Start agent runs from buttons, forms, or other views
- Run one of your frontend tools directly, without an LLM turn
- Build agent features without a chat screen (to build your own chat, see Headless UI)
- Read agent state and results from code
- Send a speech-to-text transcript as a user turn
Sending a message from code
Add a user message with agent.addMessage, then call copilotkit.runAgent({ agent }). Call copilotkit.stopAgent({ agent }) to cancel a run in flight.
import { Button, Text, View } from "react-native";
import { useAgent, useCopilotKit } from "@copilotkit/react-native/headless";
export function AgentTrigger({ agentId }: { agentId: string }) {
const { agent } = useAgent({ agentId });
const { copilotkit } = useCopilotKit();
const run = async () => {
if (agent.isRunning) return;
agent.addMessage({
id: `user-${Date.now()}`,
role: "user",
content: "Summarize the latest sales data",
});
try {
await copilotkit.runAgent({ agent });
} catch (error) {
console.error("CopilotKit runAgent failed:", error);
}
};
const last = agent.messages[agent.messages.length - 1];
return (
<View>
<Button title="Run agent" onPress={run} disabled={agent.isRunning} />
<Button
title="Stop"
onPress={() => copilotkit.stopAgent({ agent })}
disabled={!agent.isRunning}
/>
{last?.role === "assistant" && last.content ? <Text>{last.content}</Text> : null}
</View>
);
}Tap Run agent. The agent's reply streams into agent.messages, and the last assistant message shows under the buttons.
The message id comes from a timestamp. The React Native polyfills install crypto.getRandomValues, not crypto.randomUUID.
copilotkit.runAgent() vs agent.runAgent()
Both methods start the agent, but they work at different levels:
copilotkit.runAgent({ agent }): the default. It runs the full lifecycle: it executes frontend tools, handles follow-up runs, and sends errors to the subscriber system and the provider'sonError.agent.runAgent(options): the low-level method on the agent instance. It sends the request to the runtime but does not execute frontend tools or chain follow-ups. Use it only when you need direct control.
Running a tool without the model
copilotkit.runTool() runs a registered frontend tool directly. The handler runs, the tool's render shows in the chat, and both the tool call and its result are added to agent.messages. No LLM turn happens unless you ask for one.
const { copilotkit } = useCopilotKit();
const { result, error } = await copilotkit.runTool({
name: "filter_tasks",
parameters: { status: "open" },
// false (default): no follow-up. "generate": the agent responds to the result.
followUp: false,
});The tool must be registered with useFrontendTool somewhere under the provider. See Frontend Tools.
Subscribing to agent events
agent.subscribe(subscriber) returns { unsubscribe }. The subscriber accepts every AG-UI lifecycle callback: onCustomEvent, onRunStartedEvent, onRunFinalized, onRunFailed, and the streaming deltas. Use it to drive your own progress UI, to send events to analytics, or to catch pause and resume events and answer them, as shown below.
Subscribe in an effect and unsubscribe in its cleanup:
import { useEffect } from "react";
useEffect(() => {
const { unsubscribe } = agent.subscribe({
onRunStartedEvent: () => setStatus("working"),
onRunFinalized: () => setStatus("done"),
onRunFailed: () => setStatus("failed"),
});
return unsubscribe;
}, [agent]);useAgent can swap in a new agent object once the runtime connects, so keep agent in the effect's dependencies.
Resolving a pause from a button
Interrupt-style pause and resume isn't available on this framework. The headless interrupt pattern needs a runtime with a native
interrupt(...)primitive (LangGraph) or a Promise-resolving frontend-tool path. For all other integrations, pause withuseHumanInTheLoopinstead. It works on every framework that supports tool calls. Theagent.addMessage,copilotkit.runAgent, andagent.subscribeprimitives above still apply. Only the interrupt path depends on the framework.
For every method on the core, see the useCopilotKit reference.
Choose your AI backend
LangGraph (Python)
LangGraph (TypeScript)
LangGraph (FastAPI)
Langchain DeepAgents
Google ADK
Mastra
CrewAI Flows
PydanticAI
Google Antigravity
OpenAI Agents SDK (Python)
Claude Agent SDK (Python)
Claude Agent SDK (TypeScript)
Agno
AG2
LlamaIndex
AWS Strands (Python)
AWS Strands (TypeScript)
MS Agent Framework (Python)
MS Agent Framework (.NET)
MS Agent Harness (.NET)
How is this guide?