> ## Documentation Index
> Fetch the complete documentation index at: https://docs.laburen.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent - Query Agent

> Add agent messages to conversation history. Designed for integrating with external systems like WhatsApp, Chatwoot, and CRM platforms to sync agent messages into the conversation thread.

**Key Features:**

* Add agent messages to existing or new conversations
* Support for external channel integrations (WhatsApp, Chatwoot, CRM)
* Automatic contact creation and association

<Note>
  This endpoint is different from the [Query endpoint](/api-reference/endpoint/agents/query), which sends user messages and receives AI responses. This endpoint is for adding agent messages to the conversation history.
</Note>

### Path

<ParamField path="id" type="string" required>
  The ID of the agent (CUID format).
</ParamField>

### Body

#### Required

<ParamField body="query" type="string" required>
  The agent message text to add to the conversation history.
</ParamField>

#### Optional - Basic Configuration

<ParamField body="streaming" type="boolean" default="false">
  If `true`, responds with Server-Sent Events in real-time.
</ParamField>

<ParamField body="conversationId" type="string">
  ID of the conversation to add the message to. Auto-generated if not provided.

  <Warning>
    **For Chatwoot/CRM integrations**: The `conversationId` format is **essential** to ensure messages are placed in the correct conversation. Use the format `crmchatsappai_{accountId}_{customerId}` to match existing conversations. Without the correct format, messages may be added to the wrong conversation thread.
  </Warning>
</ParamField>

<ParamField body="visitorId" type="string">
  Unique ID of the visitor/user. Auto-generated if not provided.
</ParamField>

<ParamField body="channel" type="string" default="api">
  Source channel for the message. Valid values: `api`, `dashboard`, `website`, `form`, `whatsapp`, `telegram`, `slack`, `meta`, `crisp`, `zapier`, `mail`, `mercadolibre`, `agent_builder`, `chatwoot`, `crmchatsappai`.
</ParamField>

<ParamField body="channelExternalId" type="string">
  External channel identifier for integration with third-party systems. Format varies by integration:

  * **WhatsApp**: `{organizationId}_{agentId}_{telephoneNumber}`

  Used to link messages from external platforms to conversations in Laburen.

  <Warning>
    **For WhatsApp Embedding**: The `channelExternalId` is **essential** to ensure messages are placed in the correct conversation. Without it, messages may be added to the wrong conversation thread.
  </Warning>
</ParamField>

<ParamField body="isDraft" type="boolean" default="false">
  If `true`, creates a draft message. Requires authentication.
</ParamField>

<ParamField body="contactId" type="string">
  ID of an existing contact to associate with the conversation.
</ParamField>

#### Optional - Contact

<ParamField body="contact" type="object">
  Contact data to create or associate with the conversation. If a contact with matching email, phone number, or userId exists, it will be used. Otherwise, a new contact will be created.

  <Expandable title="Contact object">
    <ParamField body="email" type="string">
      Contact's email address.
    </ParamField>

    <ParamField body="phoneNumber" type="string">
      Contact's phone number.
    </ParamField>

    <ParamField body="userId" type="string">
      External user ID from your system.
    </ParamField>

    <ParamField body="firstName" type="string">
      Contact's first name.
    </ParamField>

    <ParamField body="lastName" type="string">
      Contact's last name.
    </ParamField>
  </Expandable>
</ParamField>

#### Optional - Metadata

<ParamField body="metadata" type="object">
  Additional metadata for the message.

  <Expandable title="Metadata object">
    <ParamField body="contextDataAgents" type="string">
      Context data for WhatsApp integrations.
    </ParamField>

    <ParamField body="channel" type="string">
      Channel override (alternative to top-level `channel` field).
    </ParamField>
  </Expandable>
</ParamField>

### Response (without streaming)

<ResponseField name="messageId" type="string">
  ID of the created message.
</ResponseField>

<ResponseField name="conversationId" type="string">
  ID of the conversation (save this to continue adding messages to the same conversation).
</ResponseField>

<ResponseField name="visitorId" type="string">
  ID of the visitor/user.
</ResponseField>

<ResponseField name="status" type="string">
  Conversation status (e.g., `UNRESOLVED`, `RESOLVED`).
</ResponseField>

### Error Responses

| Status Code | Type         | Description                                                                                     |
| ----------- | ------------ | ----------------------------------------------------------------------------------------------- |
| 401         | UNAUTHORIZED | Missing or invalid authentication when `isDraft` is `true`, or when required for the operation. |
| 404         | NOT\_FOUND   | Agent with the specified ID does not exist.                                                     |

<RequestExample>
  ```bash cURL (WhatsApp Integration) theme={null}
  curl --location --request POST 'https://dashboard.laburen.com/api/agents/cm68elcks00a0y7qaeljq2qin/query-agent' \
  --header 'Authorization: Bearer <API_KEY>' \
  --header 'Content-Type: application/json' \
  --data-raw '{
      "visitorId": "{{$json.contacts[0].wa_id}}",
      "query": "{{ $('Combino mensaje con cada fletero').last().json.mensaje}}",
      "streaming": false,
      "channel": "whatsapp",
      "channelExternalId": "cmepre3cg0194pmyckdoynlud_cmi4us1tn03ekn1lr7vf230e9_{{ $json.contacts[0].wa_id }}"
  }'
  ```

  ```bash cURL (CRM Integration) theme={null}
  curl --location --request POST 'https://dashboard.laburen.com/api/agents/cm68elcks00a0y7qaeljq2qin/query-agent' \
  --header 'Authorization: Bearer 844b4b95-bd79-4583-b6df-83bfa10a8f42' \
  --header 'Content-Type: application/json' \
  --data-raw '{
      "visitorId": "crmchatsappai_27_REMPLAZAR_ID",
      "query": "¡Hola [NOMBRE]! Hace un tiempo recibimos tu consulta por el proyecto Osten Tower. Te escribimos para adelantarte el lanzamiento de Osten Tower II. ¡No te pierdas la oportunidad de ser parte de este increíble emprendimiento en Puerto Madero!¿Te gustaría saber más?",
      "conversationId": "crmchatsappai_27_REMPLAZAR_ID",
      "streaming": false,
      "channel": "api"
  }'
  ```

  ```javascript JavaScript theme={null}
  const apiUrl = 'https://dashboard.laburen.com/api';
  const apiKey = '<API_KEY>';
  const agentId = 'clxxxxxxxxxxxxxxxxx';

  // Add agent message to conversation
  const response = await fetch(`${apiUrl}/agents/${agentId}/query-agent`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`,
    },
    body: JSON.stringify({
      query: 'Hello! How can I help you today?',
      visitorId: 'visitor-abc123',
      conversationId: 'clxxxxxxxxxxxxxxxxx', // Optional: to add to existing conversation
      channel: 'whatsapp',
      channelExternalId: 'org123_agent456_+1234567890', // Format: {organizationId}_{agentId}_{telephoneNumber}
      contact: {
        phoneNumber: '+1234567890',
        firstName: 'John',
        lastName: 'Doe',
      },
    }),
  });

  const data = await response.json();
  console.log('Message ID:', data.messageId);
  console.log('Conversation ID:', data.conversationId);
  ```

  ```python Python theme={null}
  import requests

  api_url = "https://dashboard.laburen.com/api"
  api_key = "<API_KEY>"
  agent_id = "clxxxxxxxxxxxxxxxxx"

  # Add agent message to conversation
  response = requests.post(
      f"{api_url}/agents/{agent_id}/query-agent",
      headers={
          "Content-Type": "application/json",
          "Authorization": f"Bearer {api_key}",
      },
      json={
          "query": "Hello! How can I help you today?",
          "visitorId": "visitor-abc123",
          "conversationId": "clxxxxxxxxxxxxxxxxx",  # Optional: to add to existing conversation
          "channel": "whatsapp",
          "channelExternalId": "org123_agent456_+1234567890",  # Format: {organizationId}_{agentId}_{telephoneNumber}
          "contact": {
              "phoneNumber": "+1234567890",
              "firstName": "John",
              "lastName": "Doe",
          },
      },
  )

  data = response.json()
  print("Message ID:", data["messageId"])
  print("Conversation ID:", data["conversationId"])
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "messageId": "clxxxxxxxxxxxxxxxxx",
    "conversationId": "clxxxxxxxxxxxxxxxxx",
    "visitorId": "visitor-abc123",
    "status": "UNRESOLVED"
  }
  ```
</ResponseExample>

### Integration Examples

#### WhatsApp Embedding Integration

When integrating with WhatsApp via our app

```json theme={null}
{
  "visitorId": "{{$json.contacts[0].wa_id}}",
  "query": "{{ $('Combino mensaje con cada fletero').last().json.mensaje}}",
  "streaming": false,
  "channel": "whatsapp",
  "channelExternalId": "{organizationId}_{agentId}_{{$json.contacts[0].wa_id}}"
}
```

The `channelExternalId` format: `{organizationId}_{agentId}_{telephoneNumber}`

<Warning>
  **Critical**: The `channelExternalId` is **essential** for WhatsApp Embedding integration. Without it, messages will not be placed in the correct conversation thread. Always include this field with the exact format `{organizationId}_{agentId}_{telephoneNumber}` when using WhatsApp channel.
</Warning>

#### Chatwoot

For our chatwoot or external ones:

```json theme={null}
{
  "visitorId": "crmchatsappai_{accountId}_{customerId}",
  "query": "Your message text here",
  "conversationId": "crmchatsappai_{accountId}_{customerId}",
  "streaming": false,
  "channel": "api"
}
```

<Warning>
  **Critical**: The `conversationId` format is **essential** for Chatwoot/CRM integrations. Use the exact format `crmchatsappai_{accountId}_{customerId}` to match existing conversations. Without the correct format, messages will not be placed in the correct conversation thread.
</Warning>
