# Programmatic Control

> Drive agent runs from code in a React Native app, with no chat UI required.

## What is this? [#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 with `copilotkit.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 with `copilotkit.runAgent({ agent, resume })` for standard AG-UI interrupts, or with `copilotkit.runAgent({ agent, forwardedProps: { command: { resume, interruptEvent } } })` for the `on_interrupt` custom events that the LangGraph adapter sends.

## When should I use this? [#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](/react-native/openai-agents-python/custom-look-and-feel/headless-ui))
- Read agent state and results from code
- Send a speech-to-text transcript as a user turn

## Sending a message from code [#sending-a-message-from-code]

<Steps>
  <Step>
    ### Install the OpenAI Agents AG-UI adapter

    ```bash
    pip install ag-ui-openai-agents openai-agents
    ```

  </Step>
  <Step>
    ### Wire the agent once, and chat and code share it

    `copilotkit.runAgent`, `agent.subscribe` and `agent.addMessage` drive runs
    against the same AG-UI endpoint your chat UI posts to, so there is no
    second backend to set up. Mount the `OpenAIAgentsAgent` the way any chat
    demo does, and every entry point sees the same model, tools and
    instructions.

~~~~python title="agent_server.py"
app = FastAPI(title="OpenAI Agents SDK Agent Server", lifespan=lifespan)
for name, agent in AGENTS.items():
    add_openai_agents_fastapi_endpoint(app, agent, f"/{name}", include_health=False)
~~~~

    The server keeps no sessions. Every run carries the thread's messages
    from the client, so a headless run on the same agent continues its
    thread, and a fresh `threadId` starts a new one.

  </Step>
</Steps>

<Callout type="info" title="Headless interrupts come from approval-gated tools">
  The headless interrupt-resolver pattern (read the interrupt off the agent,
  answer it with a `resume`) works with a server tool marked
  `needs_approval=True`. The run ends with an interrupt for the call, and a
  `resume` of `{"approved": true}` runs it (see the human-in-the-loop setup).
  To ask the user from code without a backend tool, use the frontend-tool
  Promise pattern: register the tool with `useFrontendTool` and an `async`
  handler, and resolve its promise when your own UI has the answer.
</Callout>

Add a user message with `agent.addMessage`, then call `copilotkit.runAgent({ agent })`. Call `copilotkit.stopAgent({ agent })` to cancel a run in flight.

```tsx title="src/AgentTrigger.tsx"
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({ // [!code highlight:5]
      id: `user-${Date.now()}`,
      role: "user",
      content: "Summarize the latest sales data",
    });

    try {
      await copilotkit.runAgent({ agent }); // [!code highlight]
    } 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()` [#copilotkitrunagent-vs-agentrunagent]

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's `onError`.
- **`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 [#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.

```tsx
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](/react-native/openai-agents-python/frontend-tools).

## Subscribing to agent events [#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:

```tsx
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 [#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 with [`useHumanInTheLoop`](/react-native/openai-agents-python/human-in-the-loop) instead. It works on every framework that supports tool calls. The `agent.addMessage`, `copilotkit.runAgent`, and `agent.subscribe` primitives above still apply. Only the interrupt path depends on the framework.

For every method on the core, see the [`useCopilotKit` reference](/reference/react-native/hooks/useCopilotKit).

<IntegrationGrid path="programmatic-control" />
