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

# Ejecutar Agente

> Ejecuta un agente específico por ID.

### **Ejemplos de Código**

```http cURL theme={null}
curl --request POST \
  --url 'https://api.tess.im/agents/{id}/execute' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'x-workspace-id: YOUR_WORKSPACE_ID' \
  --header 'Content-Type: application/json' \
  --data '{
    "temperature": "1",
    "model": "tess-5",
    "messages": [
        { "role": "user", "content": "Hello, how can you help me today?" }
    ],
    "tools": "no-tools",
    "waitExecution": false,
    "file_ids": [123, 321],
    "memory_collections": [456]
  }'
```

```json Node.js theme={null}
const axios = require('axios');

const data = {
    "temperature": "1",
    "model": "tess-5",
    "messages": [
        { "role": "user", "content": "Hello, how can you help me today?" }
    ],
    "tools": "no-tools",
    "waitExecution": false,
    "file_ids": [123, 321],
    "memory_collections": [456]
  };

const config = {
  method: 'post',
  url: 'https://api.tess.im/agents/{id}/execute',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
      'x-workspace-id': 'YOUR_WORKSPACE_ID',
    'Content-Type': 'application/json'
  },
  data: data
};

try {
  const response = await axios(config);
  console.log(response.data);
} catch (error) {
  console.error(error);
}
```

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

url = "https://api.tess.im/agents/{id}/execute"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
      "x-workspace-id": "YOUR_WORKSPACE_ID",
    "Content-Type": "application/json"
}
data = {
    "temperature": "1",
    "model": "tess-5",
    "messages": [
        { "role": "user", "content": "Hello, how can you help me today?" }
    ],
    "tools": "no-tools",
    "waitExecution": false,
    "file_ids": [123, 321],
    "memory_collections": [456]
  }

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

```php PHP theme={null}
<?php
$curl = curl_init();

$data = [
    "temperature" => "1",
    "model" => "tess-5",
    "messages" => [
        [ "role" => "user", "content" => "Hello, how can you help me today?" ]
    ],
    "tools" => "no-tools",
    "waitExecution" => false,
    "file_ids" => [123, 321],
    "memory_collections" => [456]
];

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.tess.im/agents/{id}/execute",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode($data),
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer YOUR_API_KEY",
      "x-workspace-id: YOUR_WORKSPACE_ID",
    "Content-Type: application/json"
  ]
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "Error: " . $err;
} else {
  echo $response;
}
```

```java Java theme={null}
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        Map<String, Object> data = Map.of(
            "temperature", "1",
            "model", "tess-5",
            "messages", List.of(Map.of("role", "user", "content", "Hello, how can you help me today?")),
            "tools", "no-tools",
            "waitExecution", false,
            "file_ids", List.of(123, 321),
            "memory_collections", List.of(456)
        );

        String jsonPayload = mapper.writeValueAsString(data);

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.tess.im/agents/{id}/execute"))
            .header("Authorization", "Bearer YOUR_API_KEY")
      .header("x-workspace-id", "YOUR_WORKSPACE_ID")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();

        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}
```

```go Go theme={null}
package main

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

func main() {
    payload := `{
        "temperature": "1",
        "model": "tess-5",
        "messages": [
            { "role": "user", "content": "Hello, how can you help me today?" }
        ],
        "tools": "no-tools",
        "waitExecution": false,
        "file_ids": [123, 321],
        "memory_collections": [456]
    }`

    client := &http.Client{}
    req, err := http.NewRequest("POST", "https://api.tess.im/agents/{id}/execute", strings.NewReader(payload))
    if err != nil {
        fmt.Println(err)
        return
    }
    
    req.Header.Add("Authorization", "Bearer YOUR_API_KEY")
    req.Header.Add("x-workspace-id", "YOUR_WORKSPACE_ID")
    req.Header.Add("Content-Type", "application/json")
    
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()
    
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    fmt.Println(string(body))
}
```

```jsonnet .NET theme={null}
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Collections.Generic;

class Program
{
    static async Task Main(string[] args)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", "Bearer YOUR_API_KEY");
            client.DefaultRequestHeaders.Add("x-workspace-id", "YOUR_WORKSPACE_ID");

            var data = new
            {
                temperature = "1",
                model = "tess-5",
                messages = new List<object> { new { role = "user", content = "Hello, how can you help me today?" } },
                tools = "no-tools",
                waitExecution = false,
                file_ids = new List<int> { 123, 321 },
                memory_collections = new List<int> { 456 }
            };

            var jsonPayload = JsonConvert.SerializeObject(data);
            var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

            try
            {
                var response = await client.PostAsync("https://api.tess.im/agents/{id}/execute", content);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }
    }
}
```

```ruby Ruby theme={null}
require 'uri'
require 'net/http'
require 'json'

uri = URI('https://api.tess.im/agents/{id}/execute')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri)
request['Authorization'] = 'Bearer YOUR_API_KEY'
request['x-workspace-id'] = 'YOUR_WORKSPACE_ID'
request['Content-Type'] = 'application/json'
request.body = {
    "temperature": "1",
    "model": "tess-5",
    "messages": [
        { "role": "user", "content": "Hello, how can you help me today?" }
    ],
    "tools": "no-tools",
    "waitExecution": false,
    "file_ids": [123, 321],
    "memory_collections": [456]
}.to_json

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

### **Encabezados**

**x-workspace-id** `integer` *required*

ID del workspace. **Obligatorio a partir del 01/09/2026.** Hasta entonces, si se omite, se usa el workspace seleccionado del usuario (deprecated). Después de la fecha, ausencia → **422**.

### **Parámetros de Ruta**

| **Parámetro** | **Tipo** | **Requerido** | **Descripción** |
| :- | :- | :- | :- |
| `id` | integer | Sí | El ID del agente. |

### **Cuerpo de la Solicitud**

| **Parámetro** | **Tipo** | **Requerido** | **Descripción** |
| :- | :- | :- | :- |
| `temperature` | string | No | Campo de Chat Agent. Temperatura de muestreo entre 0 y 2. Valores más altos generan resultados más creativos (pred.: `"1"`). |
| `model` | string | No | Campo de Chat Agent. Identificador del modelo a utilizar (p. ej., `"tess-6"`). |
| `tools` | string | No | Campo de Chat Agent. Configuración de herramientas del agente (p. ej., `"agent"`, `"no-tools"`). |
| `root_id` | integer | No | Campo de Chat Agent. ID de una ejecución existente para continuar un hilo de conversación. |
| `messages` | array | No | Campo de Chat Agent. Los mensajes del agente. Admite los roles `user`, `assistant` y `developer`. |
| `waitExecution` | boolean | No | Si `true`, espera que la ejecución termine antes de retornar (timeout: 100 s). Predeterminado: `false`. |
| `file_ids` | array | No | Array de IDs de archivos para adjuntar a la ejecución. |
| `memory_collections` | array | No | Array de IDs de [Colecciones de Memoria](https://docs.tess.im/es/list-collections.md) a usar en esta ejecución. Las memorias indexadas en estas colecciones se recuperan automáticamente e inyectan en el contexto del agente mediante búsqueda semántica. |
| Otros campos en la raíz | any | Depende del agente | Esto no es un nombre de campo fijo. Puede enviar otros campos requeridos por su agente directamente en la raíz de la solicitud. Consulte qué campos son obligatorios en [Obtener Agente por ID](https://docs.tess.im/es/api/endpoints/agents/get). |

> [!NOTE]
>
> **Cómo usar memorias en una ejecución**
>
> Para inyectar contexto de memoria en un agente, pasa los IDs de las Colecciones de Memoria en el campo `memory_collections`. El flujo completo es:
>
> 1. **Crear una Colección** — `POST /api/memory-collections` — y guarda el `id` retornado.
> 2. **Crear Memorias** — `POST /api/memories` — pasando `collection_id` y el texto de la memoria en el campo `memory`.
> 3. **Ejecutar el Agente** — incluye `"memory_collections": [id_coleccion]` en el cuerpo de la solicitud.
>
> El agente utilizará automáticamente las memorias relevantes para contextualizar la respuesta.
>
> Consulta la guía completa en [Memorias](https://docs.tess.im/es/memories.md).

#### **Roles de Mensajes (Plantillas de Tipo Chat)**

Para plantillas de tipo chat, el array `messages` admite los siguientes roles:

| **Rol** | **Requerido** | **Descripción** |
| :- | :- | :- |
| `user` | Sí | Mensajes del usuario. Deben estar emparejados con mensajes `assistant`. |
| `assistant` | Sí | Mensajes del asistente. Deben estar emparejados con mensajes `user`. |
| `developer` | No | Mensaje opcional del desarrollador. **Solo permitido como el primer mensaje** en el array. |
| `system` | No | **No soportado**. Usar este rol causará un error. |

**Reglas importantes:**

* Los mensajes deben alternar entre los roles `user` y `assistant` (después del mensaje opcional `developer`).
* El rol `developer` solo puede aparecer como el primer mensaje en el array y será extraído antes de procesar el resto.
* Si dos mensajes consecutivos tienen el mismo rol (por ejemplo, dos mensajes `user`), la API devolverá un error de validación: "Chat messages must be a pair of user/assistant".
* El rol `system` no está soportado y causará un error.

**Ejemplo con mensaje developer:**

```
{
  "messages": [
    { "role": "developer", "content": "Eres un asistente útil." },
    { "role": "user", "content": "¡Hola!" },
    { "role": "assistant", "content": "¡Hola! ¿Cómo puedo ayudarte?" },
    { "role": "user", "content": "¿Cómo está el clima?" }
  ]
}
```

**Ejemplo sin mensaje developer:**

```
{
  "messages": [
    { "role": "user", "content": "¡Hola!" },
    { "role": "assistant", "content": "¡Hola! ¿Cómo puedo ayudarte?" },
    { "role": "user", "content": "¿Cómo está el clima?" }
  ]
}
```

Obtenga más detalles sobre qué opciones acepta este Agente solicitando este endpoint: [Obtener Agente](https://docs.tess.im/es/api/endpoints/agents/get)

### **Respuesta**

```json theme={null}
{
"template_id": "8794",
"responses": [
  {
    "id": 4773337,
    "status": "starting",
    "input": "hello",
    "output": "",
    "credits": 0.000337,
    "root_id": 4773337,
    "created_at": "2025-01-05T19:35:21.000000Z",
    "updated_at": "2025-01-05T19:35:21.000000Z",
    "template_id": 8794
  }
]
}
```


## OpenAPI

````yaml api-reference/agents-execution.openapi.json POST /agents/{id}/execute
openapi: 3.1.0
info:
  title: Tess API - Agent Execution
  version: 1.0.0
servers:
  - url: https://api.tess.im
security: []
paths:
  /agents/{id}/execute:
    post:
      summary: Execute Agent
      description: Execute a specific agent by ID.
      operationId: executeAgent
      parameters:
        - $ref: '#/components/parameters/agentId'
        - $ref: '#/components/parameters/workspaceId'
      requestBody:
        description: >-
          Send a JSON object. Known fields are supported, and you can add custom
          fields directly at the root (for example: `department`,
          `reporting_period`, `include_risks`).
        content:
          application/json:
            schema:
              type: object
              additionalProperties: true
              description: >-
                Free-form JSON object. Send known fields and any custom agent
                fields directly at the root level.
            example:
              temperature: '1'
              model: tess-6
              messages:
                - role: user
                  content: Summarize the latest ticket updates.
              tools: no-tools
              waitExecution: false
              file_ids:
                - 123
                - 321
            examples:
              defaultExecution:
                summary: Default execution payload
                value:
                  temperature: '1'
                  model: tess-6
                  messages:
                    - role: user
                      content: Summarize the latest ticket updates.
                  tools: no-tools
                  waitExecution: false
                  file_ids:
                    - 123
                    - 321
              customFieldsAtRoot:
                summary: Execution with custom root-level fields
                value:
                  temperature: '1'
                  messages:
                    - role: user
                      content: Generate a status report.
                  department: finance
                  reporting_period: 2026-Q1
                  include_risks: true
      responses:
        '200':
          description: 'Execution started (or completed if `waitExecution: true`).'
      security:
        - bearerAuth: []
components:
  parameters:
    agentId:
      name: id
      in: path
      required: true
      schema:
        type: integer
      description: The agent ID.
    workspaceId:
      name: x-workspace-id
      in: header
      required: true
      schema:
        type: integer
      description: >-
        Workspace ID. Required as of 2026-09-01. Until then, if omitted, the
        user's selected workspace is used (deprecated). After the cutoff, a
        missing header returns 422.
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.