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

# Respostas em segundo plano

> Execute respostas de longa duração em segundo plano e recupere os resultados por meio de polling ou streaming.

Use o modo `background` quando uma resposta pode levar muito tempo para ser concluída, como uso de ferramentas em múltiplas etapas ou tarefas de geração extensas.
A API retorna imediatamente com uma resposta em fila, e você recupera o resultado depois por meio de polling ou streaming.

## Criar uma resposta em segundo plano

Defina `background` como `true` e `stream` como `false`.
A API cria a resposta, inicia o processamento de forma assíncrona e retorna imediatamente com `status: "queued"`.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm responses create \
    --background \
    --model meetkai:functionary-pt \
    --input '"Write a 500-word essay about the history of the internet."' \
    -H 'X-On-Behalf-Of: <end-user-id>'
  ```

  ```ts MKA1 SDK theme={null}
  import { SDK } from '@meetkai/mka1';

  const mka1 = new SDK({
    bearerAuth: `Bearer ${YOUR_API_KEY}`,
  });

  const response = await mka1.llm.responses.create({
    xOnBehalfOf: '<end-user-id>',
    responsesCreateRequest: {
      model: 'meetkai:functionary-pt',
      input: 'Write a 500-word essay about the history of the internet.',
      background: true,
      stream: false,
    },
  });

  console.log(response.id, response.status); // resp_abc123 queued
  ```

  ```ts OpenAI SDK theme={null}
  import OpenAI from 'openai';

  const openai = new OpenAI({
    apiKey: '<mka1-api-key>',
    baseURL: 'https://apigw.mka1.com/api/v1/llm/',
    defaultHeaders: { 'X-On-Behalf-Of': '<end-user-id>' },
  });

  const response = await openai.responses.create({
    model: 'meetkai:functionary-pt',
    input: 'Write a 500-word essay about the history of the internet.',
    background: true,
    stream: false,
  });

  console.log(response.id, response.status); // resp_abc123 queued
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(bearerAuth: "Bearer YOUR_API_KEY");

  var res = await sdk.Llm.Responses.CreateAsync(
      body: new ResponsesCreateRequest()
      {
          Model = "meetkai:functionary-pt",
          Input = ResponsesCreateRequestInput.CreateStr(
              "Write a 500-word essay about the history of the internet."),
          Background = true,
          Stream = false,
      },
      xOnBehalfOf: "<end-user-id>"
  );

  Console.WriteLine($"{res.ResponseObject!.Id} {res.ResponseObject!.Status}"); // resp_abc123 queued
  ```

  ```python Python SDK theme={null}
  from mka1 import SDK

  sdk = SDK(bearer_auth="Bearer YOUR_API_KEY")

  res = sdk.llm.responses.create(
      model="meetkai:functionary-pt",
      input="Write a 500-word essay about the history of the internet.",
      background=True,
      stream=False,
      x_on_behalf_of="<end-user-id>",
  )

  print(res.id, res.status)  # resp_abc123 queued
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/responses \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "model": "meetkai:functionary-pt",
      "input": "Write a 500-word essay about the history of the internet.",
      "background": true,
      "stream": false
    }'
  ```
</CodeGroup>

Salve o `id` para recuperar o resultado depois.

## Consulte o resultado (Polling)

Chame `GET /responses/{response_id}` até que o status atinja um estado terminal.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm responses get --response-id resp_abc123
  ```

  ```ts MKA1 SDK theme={null}
  let polled = await mka1.llm.responses.get({
    responseId: response.id,
    xOnBehalfOf: '<end-user-id>',
  });

  while (polled.status === 'queued' || polled.status === 'in_progress') {
    await new Promise(r => setTimeout(r, 2000));
    polled = await mka1.llm.responses.get({
      responseId: response.id,
      xOnBehalfOf: '<end-user-id>',
    });
  }

  console.log(polled.status); // completed
  console.log(polled.output);
  ```

  ```ts OpenAI SDK theme={null}
  let polled = await openai.responses.retrieve(response.id);

  while (polled.status === 'queued' || polled.status === 'in_progress') {
    await new Promise(r => setTimeout(r, 2000));
    polled = await openai.responses.retrieve(response.id);
  }

  console.log(polled.status); // completed
  console.log(polled.output);
  ```

  ```csharp C# SDK theme={null}
  var polled = await sdk.Llm.Responses.GetAsync(new GetResponseRequest()
  {
      ResponseId = res.ResponseObject!.Id,
      XOnBehalfOf = "<end-user-id>",
  });

  while (polled.ResponseObject!.Status == "queued" || polled.ResponseObject!.Status == "in_progress")
  {
      await Task.Delay(2000);
      polled = await sdk.Llm.Responses.GetAsync(new GetResponseRequest()
      {
          ResponseId = res.ResponseObject!.Id,
          XOnBehalfOf = "<end-user-id>",
      });
  }

  Console.WriteLine(polled.ResponseObject!.Status); // completed
  ```

  ```python Python SDK theme={null}
  import time

  polled = sdk.llm.responses.get(
      response_id=res.id,
      x_on_behalf_of="<end-user-id>",
  )

  while polled.status in ("queued", "in_progress"):
      time.sleep(2)
      polled = sdk.llm.responses.get(
          response_id=res.id,
          x_on_behalf_of="<end-user-id>",
      )

  print(polled.status)  # completed
  print(polled.output)
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/responses/resp_abc123 \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>'
  ```
</CodeGroup>

Uma resposta passa pelos seguintes status durante o processamento:

| Status        | Significado                                        |
| ------------- | -------------------------------------------------- |
| `queued`      | A solicitação está aguardando para ser processada  |
| `in_progress` | O modelo está gerando a saída                      |
| `completed`   | A geração foi concluída com sucesso                |
| `failed`      | Ocorreu um erro durante o processamento            |
| `incomplete`  | A resposta foi interrompida (ex: limite de tokens) |
| `cancelled`   | A resposta foi cancelada antes da conclusão        |

Faça polling em um intervalo razoável (por exemplo, a cada dois segundos) até que o status não seja mais `queued` ou `in_progress`.

## Faça streaming de eventos de uma resposta em segundo plano

Se você deseja atualizações em tempo real em vez de polling, recupere a resposta com `stream` definido como `true`.
A API retorna eventos enviados pelo servidor à medida que a resposta é processada.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm responses get --response-id resp_abc123 --stream
  ```

  ```ts MKA1 SDK theme={null}
  const streamed = await mka1.llm.responses.get({
    responseId: response.id,
    stream: true,
    xOnBehalfOf: '<end-user-id>',
  });
  ```

  ```ts OpenAI SDK theme={null}
  const stream = await openai.responses.retrieve(response.id, {
    stream: true,
  });

  for await (const event of stream) {
    console.log(event.type);
  }
  ```

  ```csharp C# SDK theme={null}
  var streamed = await sdk.Llm.Responses.GetAsync(new GetResponseRequest()
  {
      ResponseId = res.ResponseObject!.Id,
      Stream = true,
      XOnBehalfOf: "<end-user-id>",
  });
  ```

  ```python Python SDK theme={null}
  streamed = sdk.llm.responses.get(
      response_id=res.id,
      stream=True,
      x_on_behalf_of="<end-user-id>",
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/responses/resp_abc123?stream=true \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>'
  ```
</CodeGroup>

Os eventos chegam à medida que são produzidos. O stream é encerrado após um evento terminal como `response.completed` ou `response.failed`.

Se a resposta já estiver concluída quando você chamar este endpoint, você receberá um único evento terminal com a resposta final e o stream será encerrado imediatamente.

## Faça streaming de eventos no momento da criação

Você também pode fazer streaming de eventos diretamente ao criar uma resposta em segundo plano, definindo tanto `background` quanto `stream` como `true`.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm responses create \
    --background \
    --stream \
    --model meetkai:functionary-pt \
    --input '"Write a 500-word essay about the history of the internet."'
  ```

  ```ts MKA1 SDK theme={null}
  const result = await mka1.llm.responses.create({
    xOnBehalfOf: '<end-user-id>',
    responsesCreateRequest: {
      model: 'meetkai:functionary-pt',
      input: 'Write a 500-word essay about the history of the internet.',
      background: true,
      stream: true,
    },
  });
  ```

  ```ts OpenAI SDK theme={null}
  const stream = await openai.responses.create({
    model: 'meetkai:functionary-pt',
    input: 'Write a 500-word essay about the history of the internet.',
    background: true,
    stream: true,
  });

  for await (const event of stream) {
    console.log(event.type);
    // response.queued → response.created → ... → response.completed
  }
  ```

  ```csharp C# SDK theme={null}
  var res = await sdk.Llm.Responses.CreateAsync(
      body: new ResponsesCreateRequest()
      {
          Model = "meetkai:functionary-pt",
          Input = ResponsesCreateRequestInput.CreateStr(
              "Write a 500-word essay about the history of the internet."),
          Background = true,
          Stream = true,
      },
      xOnBehalfOf: "<end-user-id>"
  );
  ```

  ```python Python SDK theme={null}
  res = sdk.llm.responses.create(
      model="meetkai:functionary-pt",
      input="Write a 500-word essay about the history of the internet.",
      background=True,
      stream=True,
      x_on_behalf_of="<end-user-id>",
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/responses \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "model": "meetkai:functionary-pt",
      "input": "Write a 500-word essay about the history of the internet.",
      "background": true,
      "stream": true
    }'
  ```
</CodeGroup>

O primeiro evento é `response.queued`, seguido por `response.created`, eventos intermediários como `response.output_text.delta`, e finalmente um evento terminal como `response.completed`.

Isso é útil quando você deseja mostrar o progresso em uma interface enquanto o trabalho é executado em segundo plano.
Se o cliente se desconectar, a resposta continuará sendo processada e poderá ser recuperada posteriormente.

## Cancelar uma resposta em segundo plano

Se você não precisar mais do resultado, cancele uma resposta em fila ou em andamento.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm responses cancel --response-id resp_abc123
  ```

  ```ts MKA1 SDK theme={null}
  const cancelled = await mka1.llm.responses.cancel({
    responseId: response.id,
    xOnBehalfOf: '<end-user-id>',
  });

  console.log(cancelled.status); // cancelled
  ```

  ```ts OpenAI SDK theme={null}
  const cancelled = await openai.responses.cancel(response.id);

  console.log(cancelled.status); // cancelled
  ```

  ```csharp C# SDK theme={null}
  var cancelled = await sdk.Llm.Responses.CancelAsync(
      responseId: res.ResponseObject!.Id,
      xOnBehalfOf: "<end-user-id>"
  );

  Console.WriteLine(cancelled.Status); // cancelled
  ```

  ```python Python SDK theme={null}
  cancelled = sdk.llm.responses.cancel(
      response_id=res.id,
      x_on_behalf_of="<end-user-id>",
  )

  print(cancelled.status)  # cancelled
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/responses/resp_abc123/cancel \
    --request POST \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>'
  ```
</CodeGroup>

O status da resposta muda para `cancelled`.
Respostas que já foram concluídas ou falharam não podem ser canceladas.

## Próximos passos

* Veja [gerar uma resposta](/pt/docs/generate-a-response) para o básico sobre criação de respostas
* Veja [gerenciar agentes](/pt/docs/managing-agents) quando precisar de definições de agente reutilizáveis e execuções persistentes
* Consulte a [referência da API de Respostas](/pt/api-reference/introduction) para a lista completa de parâmetros e campos de resposta
