# Client Actions > Let your agent ask your app to run code, then hand the result back so it can finish its answer ## What Are Client Actions? A client action is a custom action whose code runs in your app instead of on QwryAI's servers. When the agent decides it needs one, for example to read the customer's cart or open a page in your app, it stops and asks your app to run it. The answer ends with `finishReason: "tool-calls"` and a `tool-call` part that names the action and its input. Your app runs the action, submits the result, and asks the agent to continue. The agent then answers using that result. > [!NOTE] > > Client actions are the [custom actions](/docs/user-guides/chatbot/actions/custom-action) set to **Run client-side code**, with **Wait for response** on. `toolName` in the API is the action's name. For the agent to use an action over the API, open **Playground**, pick the **API** channel and switch the action on in its **Actions** tab. ## Flow **1. Send a chat message** Send the customer's message to the chat endpoint as usual. **2. Receive a client action request** The answer has `finishReason: "tool-calls"` and a `tool-call` part with `toolCallId`, `toolName` and `input`. **3. Run the action in your app** Use `toolName` and `input` to decide what to run, and run it. **4. Submit the result** Send the result to `POST /api/v2/agents/{agentId}/conversations/{conversationId}/tool-result` with the `toolCallId` and an `output`. **5. Continue the conversation** Call the chat endpoint again with the `conversationId`. Leave out `message` to let the agent continue from the result, or include one if the customer said something new. ## Message Parts An answer's `parts` can hold three kinds of part: > [card] text | /docs/api-reference/v2/streaming | Text the agent wrote: `{ "type": "text", "text": "…" }`. > [card] tool-call | /docs/api-reference/v2/client-actions | An action call: `toolCallId`, `toolName` and `input`. > [card] tool-result | /docs/api-reference/v2/streaming | The result of an action QwryAI ran itself: `toolCallId`, `toolName` and `output`. A client action's `tool-call` has no matching `tool-result` in the answer: that's the part your app supplies. ## Detecting a Client Action ```json { "data": { "id": "5b0e7c1a-2f4d-4c55-9a51-6d8e3f2b9c10", "role": "assistant", "parts": [ { "type": "text", "text": "Let me look at your cart." }, { "type": "tool-call", "toolCallId": "a7c4e9d2-3b1f-4a68-8e5c-0f9d2b6a1c37", "toolName": "get_cart", "input": { "includeSavedItems": false } } ], "metadata": { "conversationId": "fd5ae9e1-9b30-4503-b346-ccd4d7ef16a3", "userMessageId": "0c4f6a2e-8d13-4b7a-b0e9-1a2c3d4e5f60", "userId": "customer_1042", "finishReason": "tool-calls", "usage": { "credits": 1 } } } } ``` When `finishReason` is `tool-calls`, look for the `tool-call` parts without a matching `tool-result`. ## Submitting the Result ```http POST https://api.qwryai.com/api/v2/agents/{agentId}/conversations/{conversationId}/tool-result ``` ### Request Body | Field | Type | Required | Description | | - | - | - | - | | `toolCallId` | `string` | Yes | The `toolCallId` from the `tool-call` part. | | `output` | any JSON | No | What the action returned. Up to 256 KB. Leave it out to send `null`. | ### Response ```json { "data": { "success": true } } ``` Each `toolCallId` takes one result. Submitting it again, or after it expires, returns `404 RESOURCE_TOOL_CALL_NOT_FOUND`. ## Continuing the Conversation After you submit the result, call the chat endpoint again with the same `conversationId`: * **Leave out `message`** to let the agent continue from the result alone. * **Include `message`** if the customer has said something new since. ```bash curl -X POST 'https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID/chat' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{ "conversationId": "fd5ae9e1-9b30-4503-b346-ccd4d7ef16a3" }' ``` > [!WARNING] > > Submit the result before you retry an answer: retrying while a client action is still waiting returns `409 CHAT_CONVERSATION_NOT_ONGOING`. An unanswered client action also expires, after which its `toolCallId` is refused. ## Streaming Client Actions With streaming on, a client action arrives as two events: **1. tool-input-start** The action call begins. Carries `toolCallId` and `toolName`. **2. tool-input-available** The complete `input`, right after. There are no partial input events. The stream's `finish` event then has `finishReason: "tool-calls"`. See [Streaming](/docs/api-reference/v2/streaming) for every event. ## Code Examples ```javascript const BASE = "https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID"; const headers = { Authorization: "Bearer YOUR_API_KEY", "Content-Type": "application/json" }; async function chat(body) { const response = await fetch(`${BASE}/chat`, { method: "POST", headers, body: JSON.stringify({ ...body, stream: false }), }); return (await response.json()).data; } const actions = { get_cart: async () => ({ items: [{ sku: "TEE-BLK-M", quantity: 2 }], total: "49.00" }), }; // Step 1: send the customer's message let answer = await chat({ message: "What's in my cart?" }); const conversationId = answer.metadata.conversationId; // Step 2: run client actions until the agent finishes while (answer.metadata.finishReason === "tool-calls") { const done = new Set(answer.parts.filter((p) => p.type === "tool-result").map((p) => p.toolCallId)); for (const part of answer.parts) { if (part.type !== "tool-call" || done.has(part.toolCallId)) continue; const output = await actions[part.toolName](part.input); await fetch(`${BASE}/conversations/${conversationId}/tool-result`, { method: "POST", headers, body: JSON.stringify({ toolCallId: part.toolCallId, output }), }); } // Step 3: let the agent continue answer = await chat({ conversationId }); } console.log(answer.parts.filter((p) => p.type === "text").map((p) => p.text).join("")); ``` ```python import requests BASE = "https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID" HEADERS = {"Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json"} def chat(body): response = requests.post(f"{BASE}/chat", headers=HEADERS, json={**body, "stream": False}) return response.json()["data"] def get_cart(_input): return {"items": [{"sku": "TEE-BLK-M", "quantity": 2}], "total": "49.00"} actions = {"get_cart": get_cart} # Step 1: send the customer's message answer = chat({"message": "What's in my cart?"}) conversation_id = answer["metadata"]["conversationId"] # Step 2: run client actions until the agent finishes while answer["metadata"]["finishReason"] == "tool-calls": done = {p["toolCallId"] for p in answer["parts"] if p["type"] == "tool-result"} for part in answer["parts"]: if part["type"] != "tool-call" or part["toolCallId"] in done: continue output = actions[part["toolName"]](part["input"]) requests.post( f"{BASE}/conversations/{conversation_id}/tool-result", headers=HEADERS, json={"toolCallId": part["toolCallId"], "output": output}, ) # Step 3: let the agent continue answer = chat({"conversationId": conversation_id}) print("".join(p["text"] for p in answer["parts"] if p["type"] == "text")) ``` ```bash # Step 1: send a message curl -X POST 'https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID/chat' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{"message": "What is in my cart?", "stream": false}' # Step 2: submit the result (toolCallId from the response) curl -X POST 'https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID/conversations/CONVERSATION_ID/tool-result' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{"toolCallId": "TOOL_CALL_ID", "output": {"items": [{"sku": "TEE-BLK-M", "quantity": 2}]}}' # Step 3: continue the conversation curl -X POST 'https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID/chat' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{"conversationId": "CONVERSATION_ID", "stream": false}' ``` ## Error Handling | Code | Status | Description | | - | - | - | | `RESOURCE_TOOL_CALL_NOT_FOUND` | 404 | No client action is waiting for this `toolCallId` in this conversation. It expired, or its result was already submitted. | | `VALIDATION_INVALID_BODY` | 400 | The body failed validation, such as a missing `toolCallId`, an unknown field or an `output` over 256 KB. `details` names the field. | | `CHAT_CONVERSATION_NOT_ONGOING` | 409 | The conversation ended or was taken over, or you retried while a client action was waiting. | | `CHAT_CONVERSATION_MISMATCH` | 403 | The conversation doesn't belong to this agent. |