# Execute Agent

POST https://services.leadconnectorhq.com/agent-studio/agent/{agentId}/execute

Executes the specified agent and returns a non-streaming JSON response with the complete agent output. The agent must be in active status and belong to the specified location. locationId is required in the request body. 

**Session Management:**
- For the first message in a new session, do not include the `executionId` in the request payload.
- The API will return an `executionId` along with the agent response, which uniquely identifies this conversation session.
- To continue the conversation within the same session, include the `executionId` from the previous response in subsequent requests. This allows the agent to maintain conversation context and history across multiple interactions.

## Authentication

Send `Authorization: Bearer <token>` using:

- **Sub-Account token: OAuth access token or Private Integration Token.** Scopes: `agent-studio.write`

## Parameters

### Header Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `Version` | string | Yes | API Version |

### Path Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `agentId` | string | Yes | Agent ID to execute (must be in active status and belong to the location) |

### Query Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `source` | string | No | Origin channel attributed to this execution for auditing (e.g. public_api, internal) |

## OpenAPI Specification

```json
{
  "openapi": "3.0.0",
  "info": {
    "title": "LeadConnector API",
    "version": "v3"
  },
  "servers": [
    {
      "url": "https://services.leadconnectorhq.com"
    }
  ],
  "paths": {
    "/agent-studio/agent/{agentId}/execute": {
      "post": {
        "summary": "Execute Agent",
        "operationId": "executeAgent",
        "description": "Executes the specified agent and returns a non-streaming JSON response with the complete agent output. The agent must be in active status and belong to the specified location. locationId is required in the request body. \n\n**Session Management:**\n- For the first message in a new session, do not include the `executionId` in the request payload.\n- The API will return an `executionId` along with the agent response, which uniquely identifies this conversation session.\n- To continue the conversation within the same session, include the `executionId` from the previous response in subsequent requests. This allows the agent to maintain conversation context and history across multiple interactions.",
        "parameters": [
          {
            "name": "Version",
            "in": "header",
            "description": "API Version",
            "required": true,
            "schema": {
              "type": "string",
              "enum": [
                "v3"
              ]
            }
          },
          {
            "name": "agentId",
            "required": true,
            "in": "path",
            "schema": {
              "type": "string"
            },
            "example": "p1q2r3s4t5u6v7w8x9y0z1a2",
            "description": "Agent ID to execute (must be in active status and belong to the location)"
          },
          {
            "name": "source",
            "required": false,
            "in": "query",
            "schema": {
              "type": "string"
            },
            "example": "api",
            "description": "Origin channel attributed to this execution for auditing (e.g. public_api, internal)"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ExecutePublicAgentDTO"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Agent executed successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ExecutePublicAgentResponseDTO"
                }
              }
            }
          },
          "400": {
            "description": "Agent is not active or invalid request - locationId is required"
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UnauthorizedDTO"
                }
              }
            }
          },
          "403": {
            "description": "User does not have required scopes to execute this agent"
          },
          "404": {
            "description": "Agent not found"
          },
          "422": {
            "description": "Unprocessable Entity",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UnprocessableDTO"
                }
              }
            }
          },
          "500": {
            "description": "Internal Server Error",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/InternalServerErrorDTO"
                }
              }
            }
          }
        },
        "security": [
          {
            "Location-Access": [
              "agent-studio.write"
            ]
          }
        ]
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearer": {
        "scheme": "bearer",
        "bearerFormat": "JWT",
        "name": "Authorization",
        "in": "header",
        "description": "Use the Access Token generated with user type as Sub-Account (OR) Private Integration Token of Sub-Account.",
        "type": "http"
      },
      "Location-Access": {
        "scheme": "bearer",
        "bearerFormat": "JWT",
        "name": "Authorization",
        "in": "header",
        "description": "Use the Access Token generated with user type as Sub-Account (OR) Private Integration Token of Sub-Account.",
        "type": "http"
      },
      "Location-Access-Only": {
        "scheme": "bearer",
        "bearerFormat": "JWT",
        "name": "Authorization",
        "in": "header",
        "description": "Use the Access Token generated with user type as Sub-Account.",
        "type": "http"
      },
      "Agency-Access": {
        "scheme": "bearer",
        "bearerFormat": "JWT",
        "name": "Authorization",
        "in": "header",
        "description": "Use the Access Token generated with user type as Agency (OR) Private Integration Token of Agency.",
        "type": "http"
      },
      "Agency-Access-Only": {
        "scheme": "bearer",
        "bearerFormat": "JWT",
        "name": "Authorization",
        "in": "header",
        "description": "Use the Access Token generated with user type as Agency.",
        "type": "http"
      }
    },
    "schemas": {
      "ExecutePublicAgentDTO": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string",
            "description": "Message to send to the agent",
            "example": "How can you help me with my marketing?"
          },
          "executionId": {
            "type": "string",
            "description": "Unique session identifier that maintains conversational context across multiple interactions within the same agent session. Omit this field for the first message in a new session. Include the executionId returned from the previous response to maintain context in subsequent messages.",
            "example": "a1b2c3d4e5f6g7h8i9j0k1l2"
          },
          "inputVariables": {
            "type": "object",
            "description": "Input variables to pass to the agent. These should match the input variables defined in the agent configuration.",
            "example": {
              "customerName": "John Doe",
              "orderNumber": "ORD-12345"
            }
          },
          "versionId": {
            "type": "string",
            "description": "Published version ID to execute. If not provided, the latest published production version will be used.",
            "example": "b2b1c1d2-3e4f-5a6b-7c8d-9e0f1a2b3c4d"
          },
          "attachments": {
            "description": "Attachments for the message",
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "type": {
                  "type": "string",
                  "description": "Type of attachment",
                  "example": "image"
                },
                "imageUrl": {
                  "type": "string",
                  "description": "URL of the image attachment",
                  "example": "https://example.com/image.png"
                }
              },
              "required": [
                "type",
                "imageUrl"
              ],
              "title": "PublicAttachmentSchema"
            },
            "example": [
              {
                "type": "image",
                "url": "https://example.com/image.png",
                "mimeType": "image/png"
              }
            ]
          },
          "locationId": {
            "type": "string",
            "description": "Location ID",
            "example": "C2QujeCh8ZnC7al2InWR"
          },
          "contactId": {
            "type": "string",
            "description": "Contact ID to associate with this execution. When provided, contact data will be hydrated and made available to the agent.",
            "example": "cid_abc123def456"
          }
        },
        "required": [
          "message",
          "locationId"
        ],
        "title": "ExecutePublicAgentDTO"
      },
      "ExecutePublicAgentResponseDTO": {
        "type": "object",
        "properties": {
          "success": {
            "type": "boolean",
            "description": "Success status",
            "example": true
          },
          "executionId": {
            "type": "string",
            "description": "Unique session identifier that maintains conversational context across multiple interactions within the same agent session. Use this ID in subsequent requests to continue the conversation.",
            "example": "a1b2c3d4e5f6g7h8i9j0k1l2"
          },
          "interactionId": {
            "type": "string",
            "description": "Unique identifier for a single interaction cycle, consisting of one user input and the corresponding agent response. Each message exchange generates a new interactionId.",
            "example": "m9n8o7p6q5r4s3t2u1v0w9x8"
          },
          "response": {
            "type": "string",
            "description": "Agent response text",
            "example": "I can help you with various tasks..."
          },
          "type": {
            "type": "string",
            "description": "Response type",
            "example": "text"
          },
          "nextExpectedInput": {
            "type": "string",
            "description": "Expected input type for next interaction",
            "example": "text"
          },
          "goalCompletion": {
            "type": "boolean",
            "description": "When end node is added in the graph, this will be true if the agent reached the end node in the graph",
            "example": false
          },
          "executionStatus": {
            "type": "string",
            "description": "Execution status",
            "example": "completed"
          },
          "flowSwitch": {
            "type": "boolean",
            "description": "Whether flow was switched",
            "example": false
          },
          "attachments": {
            "type": "array",
            "description": "Response attachments",
            "example": []
          },
          "generativeOutputs": {
            "type": "array",
            "description": "Generated outputs",
            "example": []
          }
        },
        "required": [
          "success",
          "executionId",
          "interactionId",
          "response",
          "type",
          "nextExpectedInput",
          "goalCompletion",
          "executionStatus",
          "flowSwitch",
          "attachments",
          "generativeOutputs"
        ],
        "title": "ExecutePublicAgentResponseDTO"
      },
      "UnauthorizedDTO": {
        "type": "object",
        "properties": {
          "statusCode": {
            "type": "number",
            "example": 401
          },
          "message": {
            "type": "string",
            "example": "Invalid token: access token is invalid"
          },
          "error": {
            "type": "string",
            "example": "Unauthorized"
          }
        },
        "title": "UnauthorizedDTO"
      },
      "UnprocessableDTO": {
        "type": "object",
        "properties": {
          "statusCode": {
            "type": "number",
            "example": 422
          },
          "message": {
            "example": [
              "Unprocessable Entity"
            ],
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "error": {
            "type": "string",
            "example": "Unprocessable Entity"
          }
        },
        "title": "UnprocessableDTO"
      },
      "InternalServerErrorDTO": {
        "type": "object",
        "properties": {
          "statusCode": {
            "type": "number",
            "example": 500,
            "description": "HTTP status code"
          },
          "message": {
            "type": "string",
            "example": "Internal Server Error",
            "description": "Error message"
          }
        },
        "title": "InternalServerErrorDTO"
      }
    }
  }
}
```

## Code Examples

**cURL**

```bash
curl -L -X POST 'https://services.leadconnectorhq.com/agent-studio/agent/<agentId>/execute' \
  -H 'Authorization: Bearer <TOKEN>' \
  -H 'Version: v3' \
  -H 'Content-Type: application/json' \
  --data-raw '{
  "message": "How can you help me with my marketing?",
  "executionId": "a1b2c3d4e5f6g7h8i9j0k1l2",
  "inputVariables": {
    "customerName": "John Doe",
    "orderNumber": "ORD-12345"
  },
  "versionId": "b2b1c1d2-3e4f-5a6b-7c8d-9e0f1a2b3c4d",
  "attachments": [
    {
      "type": "image",
      "url": "https://example.com/image.png",
      "mimeType": "image/png"
    }
  ],
  "locationId": "C2QujeCh8ZnC7al2InWR",
  "contactId": "cid_abc123def456"
}'
```

**Node.js**

```javascript
const options = {
  method: 'POST',
  headers: {
    Authorization: 'Bearer <TOKEN>',
    Version: 'v3',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
      "message": "How can you help me with my marketing?",
      "executionId": "a1b2c3d4e5f6g7h8i9j0k1l2",
      "inputVariables": {
        "customerName": "John Doe",
        "orderNumber": "ORD-12345"
      },
      "versionId": "b2b1c1d2-3e4f-5a6b-7c8d-9e0f1a2b3c4d",
      "attachments": [
        {
          "type": "image",
          "url": "https://example.com/image.png",
          "mimeType": "image/png"
        }
      ],
      "locationId": "C2QujeCh8ZnC7al2InWR",
      "contactId": "cid_abc123def456"
  })
};

try {
  const response = await fetch('https://services.leadconnectorhq.com/agent-studio/agent/<agentId>/execute', options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

**Python**

```python
import requests

url = "https://services.leadconnectorhq.com/agent-studio/agent/{agentId}/execute"

headers = {
    "Authorization": "Bearer <TOKEN>",
    "Version": "v3"
}

payload = {
    "message": "How can you help me with my marketing?",
    "executionId": "a1b2c3d4e5f6g7h8i9j0k1l2",
    "inputVariables": {
        "customerName": "John Doe",
        "orderNumber": "ORD-12345"
    },
    "versionId": "b2b1c1d2-3e4f-5a6b-7c8d-9e0f1a2b3c4d",
    "attachments": [
        {
            "type": "image",
            "url": "https://example.com/image.png",
            "mimeType": "image/png"
        }
    ],
    "locationId": "C2QujeCh8ZnC7al2InWR",
    "contactId": "cid_abc123def456"
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())
```

**PHP**

```php
<?php
$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => 'https://services.leadconnectorhq.com/agent-studio/agent/<agentId>/execute',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_HTTPHEADER => [
    'Authorization: Bearer <TOKEN>',
    'Version: v3',
    'Content-Type: application/json',
  ],
  CURLOPT_POSTFIELDS => '{
  "message": "How can you help me with my marketing?",
  "executionId": "a1b2c3d4e5f6g7h8i9j0k1l2",
  "inputVariables": {
    "customerName": "John Doe",
    "orderNumber": "ORD-12345"
  },
  "versionId": "b2b1c1d2-3e4f-5a6b-7c8d-9e0f1a2b3c4d",
  "attachments": [
    {
      "type": "image",
      "url": "https://example.com/image.png",
      "mimeType": "image/png"
    }
  ],
  "locationId": "C2QujeCh8ZnC7al2InWR",
  "contactId": "cid_abc123def456"
}',
]);

$response = curl_exec($curl);
curl_close($curl);
echo $response;
```

**Java**

```java
HttpResponse<String> response = Unirest
  .post("https://services.leadconnectorhq.com/agent-studio/agent/<agentId>/execute")
  .header("Authorization", "Bearer <TOKEN>")
  .header("Version", "v3")
  .header("Content-Type", "application/json")
  .body("{\"message\":\"How can you help me with my marketing?\",\"executionId\":\"a1b2c3d4e5f6g7h8i9j0k1l2\",\"inputVariables\":{\"customerName\":\"John Doe\",\"orderNumber\":\"ORD-12345\"},\"versionId\":\"b2b1c1d2-3e4f-5a6b-7c8d-9e0f1a2b3c4d\",\"attachments\":[{\"type\":\"image\",\"url\":\"https://example.com/image.png\",\"mimeType\":\"image/png\"}],\"locationId\":\"C2QujeCh8ZnC7al2InWR\",\"contactId\":\"cid_abc123def456\"}")
  .asString();
```

**Go**

```go
package main

import (
  "fmt"
  "net/http"
  "io"
  "strings"
)

func main() {
  url := "https://services.leadconnectorhq.com/agent-studio/agent/<agentId>/execute"
  payload := strings.NewReader(`{
  "message": "How can you help me with my marketing?",
  "executionId": "a1b2c3d4e5f6g7h8i9j0k1l2",
  "inputVariables": {
    "customerName": "John Doe",
    "orderNumber": "ORD-12345"
  },
  "versionId": "b2b1c1d2-3e4f-5a6b-7c8d-9e0f1a2b3c4d",
  "attachments": [
    {
      "type": "image",
      "url": "https://example.com/image.png",
      "mimeType": "image/png"
    }
  ],
  "locationId": "C2QujeCh8ZnC7al2InWR",
  "contactId": "cid_abc123def456"
}`)
  req, _ := http.NewRequest("POST", url, payload)
  req.Header.Add("Authorization", "Bearer <TOKEN>")
  req.Header.Add("Version", "v3")

  res, _ := http.DefaultClient.Do(req)
  defer res.Body.Close()
  body, _ := io.ReadAll(res.Body)
  fmt.Println(string(body))
}
```

**Ruby**

```ruby
require 'uri'
require 'net/http'

url = URI("https://services.leadconnectorhq.com/agent-studio/agent/<agentId>/execute")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = "Bearer <TOKEN>"
request["Version"] = "v3"
request["Content-Type"] = "application/json"
request.body = '{
  "message": "How can you help me with my marketing?",
  "executionId": "a1b2c3d4e5f6g7h8i9j0k1l2",
  "inputVariables": {
    "customerName": "John Doe",
    "orderNumber": "ORD-12345"
  },
  "versionId": "b2b1c1d2-3e4f-5a6b-7c8d-9e0f1a2b3c4d",
  "attachments": [
    {
      "type": "image",
      "url": "https://example.com/image.png",
      "mimeType": "image/png"
    }
  ],
  "locationId": "C2QujeCh8ZnC7al2InWR",
  "contactId": "cid_abc123def456"
}'

response = http.request(request)
puts response.read_body
```

**PowerShell**

```powershell
$headers = @{
  "Authorization" = "Bearer <TOKEN>"
  "Version" = "v3"
}

$body = '{
  "message": "How can you help me with my marketing?",
  "executionId": "a1b2c3d4e5f6g7h8i9j0k1l2",
  "inputVariables": {
    "customerName": "John Doe",
    "orderNumber": "ORD-12345"
  },
  "versionId": "b2b1c1d2-3e4f-5a6b-7c8d-9e0f1a2b3c4d",
  "attachments": [
    {
      "type": "image",
      "url": "https://example.com/image.png",
      "mimeType": "image/png"
    }
  ],
  "locationId": "C2QujeCh8ZnC7al2InWR",
  "contactId": "cid_abc123def456"
}'

$response = Invoke-RestMethod -Uri 'https://services.leadconnectorhq.com/agent-studio/agent/<agentId>/execute' -Method 'POST' -Headers $headers -Body $body -ContentType 'application/json'
$response | ConvertTo-Json
```
