> ## 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.

# Salida multimodal

> Genera audio hablado e imágenes desde la API de MKA1 usando el recurso Responses.

La API de MKA1 puede devolver texto, audio e imágenes. El texto es la modalidad de salida predeterminada.
Usa `modalities` y `audio` para habilitar la salida de voz, o agrega la herramienta `image_generation` para producir imágenes.

## Tipos de salida soportados

| Modalidad   | Cómo habilitar                            | Formato de salida               |
| ----------- | ----------------------------------------- | ------------------------------- |
| Texto       | Predeterminado — sin configuración extra  | `output_text` en la respuesta   |
| Audio (voz) | Establece `modalities: ["text", "audio"]` | Audio en base64 + transcripción |
| Imagen      | Agrega la herramienta `image_generation`  | URL de imagen o base64          |

## Generar audio (texto a voz)

Solicita salida de audio estableciendo `modalities` a `["text", "audio"]` y especificando una voz y formato en el parámetro `audio`. La respuesta incluye tanto la transcripción de texto como los datos de audio codificados en base64.

### Configuración de audio

| Parámetro | Opciones                              | Predeterminado |
| --------- | ------------------------------------- | -------------- |
| `voice`   | `alloy` y otros perfiles de voz       | `alloy`        |
| `format`  | `wav`, `mp3`, `flac`, `opus`, `pcm16` | `wav`          |

El audio se sintetiza a 24 kHz, 16 bits mono.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm responses create \
    -H 'X-On-Behalf-Of: <end-user-id>' \
    --body '{
      "model": "meetkai:functionary-es-mini",
      "input": "Say hello in a friendly way. Keep it very short.",
      "modalities": ["text", "audio"],
      "audio": { "voice": "alloy", "format": "wav" }
    }'
  ```

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

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

  const result = await mka1.llm.responses.create({
    model: 'meetkai:functionary-es-mini',
    input: 'Say hello in a friendly way. Keep it very short.',
    modalities: ['text', 'audio'],
    audio: { voice: 'alloy', format: 'wav' },
  }, { headers: { 'X-On-Behalf-Of': '<end-user-id>' } });

  // The output includes an output_audio item with base64 data and a transcript
  ```

  ```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-es-mini',
    input: 'Say hello in a friendly way. Keep it very short.',
    modalities: ['text', 'audio'],
    audio: { voice: 'alloy', format: 'wav' },
    stream: false,
  });

  // Find the audio output
  const audioItem = response.output.find((item) => item.type === 'output_audio');
  // audioItem.data contains base64-encoded WAV
  // audioItem.transcript contains the spoken text
  ```

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

  var sdk = new SDK(
      bearerAuth: $"Bearer {YOUR_API_KEY}",
      serverUrl: "https://apigw.mka1.com"
  );

  var result = await sdk.Llm.Responses.CreateAsync(new ResponsesCreateRequest()
  {
      Model = "meetkai:functionary-es-mini",
      Input = ResponsesCreateRequestInput.CreateStr("Say hello in a friendly way. Keep it very short."),
      Modalities = new List<ResponsesCreateRequestModality>
      {
          ResponsesCreateRequestModality.Text,
          ResponsesCreateRequestModality.Audio,
      },
      Audio = new Audio()
      {
          Voice = "alloy",
          Format = ResponsesCreateRequestFormat.Wav,
      },
  });

  // The output includes an output_audio item with base64 data and a transcript
  ```

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

  sdk = SDK(bearer_auth="Bearer YOUR_API_KEY")

  result = sdk.llm.responses.create(
      model="meetkai:functionary-es-mini",
      input="Say hello in a friendly way. Keep it very short.",
      modalities=["text", "audio"],
      audio={"voice": "alloy", "format": "wav"},
  )

  # The output includes an output_audio item with base64 data and a transcript
  ```

  ```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-es-mini",
      "input": "Say hello in a friendly way. Keep it very short.",
      "modalities": ["text", "audio"],
      "audio": { "voice": "alloy", "format": "wav" }
    }'
  ```
</CodeGroup>

La respuesta contiene un elemento `output_audio` con el audio codificado en base64 y una transcripción de lo que se dijo:

```json theme={null}
{
  "status": "completed",
  "output": [
    {
      "type": "message",
      "role": "assistant",
      "content": [
        { "type": "output_text", "text": "Hello!" }
      ]
    },
    {
      "type": "output_audio",
      "id": "audio_460caf1079b34fa0b4aa74448dff4ea7",
      "data": "<Base64-encoded WAV audio data>",
      "transcript": "Hi there!",
      "status": "completed"
    }
  ]
}
```

El campo `data` contiene el archivo de audio completo (268 KB en este ejemplo). El campo `transcript` contiene el texto que el modelo eligió decir — que puede diferir ligeramente del texto de salida.

### Guardar audio en un archivo

<CodeGroup>
  ```bash CLI theme={null}
  # Genera audio y extrae los datos base64, luego decodifica a un archivo
  mka1 llm responses create \
    --body '{
      "model": "meetkai:functionary-es-mini",
      "input": "Read this sentence aloud: The quick brown fox jumps over the lazy dog.",
      "modalities": ["text", "audio"],
      "audio": { "voice": "alloy", "format": "mp3" }
    }' \
    --output-format json \
    --jq '.output[] | select(.type == "output_audio") | .data' | base64 -d > output.mp3
  ```

  ```ts MKA1 SDK theme={null}
  import { writeFileSync } from 'fs';

  const result = await mka1.llm.responses.create({
    model: 'meetkai:functionary-es-mini',
    input: 'Read this sentence aloud: The quick brown fox jumps over the lazy dog.',
    modalities: ['text', 'audio'],
    audio: { voice: 'alloy', format: 'mp3' },
  });

  // Find the audio output in the response
  const audioItem = result.output.find((item) => item.type === 'output_audio');
  if (audioItem) {
    const audioBuffer = Buffer.from(audioItem.data, 'base64');
    writeFileSync('output.mp3', audioBuffer);
  }
  ```

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

  const response = await openai.responses.create({
    model: 'meetkai:functionary-es-mini',
    input: 'Read this sentence aloud: The quick brown fox jumps over the lazy dog.',
    modalities: ['text', 'audio'],
    audio: { voice: 'alloy', format: 'mp3' },
    stream: false,
  });

  const audioItem = response.output.find((item) => item.type === 'output_audio');
  if (audioItem) {
    const audioBuffer = Buffer.from(audioItem.data, 'base64');
    writeFileSync('output.mp3', audioBuffer);
  }
  ```

  ```csharp C# SDK theme={null}
  var result = await sdk.Llm.Responses.CreateAsync(new ResponsesCreateRequest()
  {
      Model = "meetkai:functionary-es-mini",
      Input = ResponsesCreateRequestInput.CreateStr(
          "Read this sentence aloud: The quick brown fox jumps over the lazy dog."),
      Modalities = new List<ResponsesCreateRequestModality>
      {
          ResponsesCreateRequestModality.Text,
          ResponsesCreateRequestModality.Audio,
      },
      Audio = new Audio()
      {
          Voice = "alloy",
          Format = ResponsesCreateRequestFormat.Mp3,
      },
  });

  // Save the audio output to a file
  // (iterate result.Output to find the output_audio item and decode its base64 data)
  ```

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

  result = sdk.llm.responses.create(
      model="meetkai:functionary-es-mini",
      input="Read this sentence aloud: The quick brown fox jumps over the lazy dog.",
      modalities=["text", "audio"],
      audio={"voice": "alloy", "format": "mp3"},
  )

  # Find the audio output in the response
  for item in result.output:
      if item.type == "output_audio":
          audio_bytes = base64.b64decode(item.data)
          with open("output.mp3", "wb") as f:
              f.write(audio_bytes)
  ```

  ```bash bash theme={null}
  # Genera audio y extrae los datos base64, luego decodifica a un archivo
  curl -s https://apigw.mka1.com/api/v1/llm/responses \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --data '{
      "model": "meetkai:functionary-es-mini",
      "input": "Read this sentence aloud: The quick brown fox jumps over the lazy dog.",
      "modalities": ["text", "audio"],
      "audio": { "voice": "alloy", "format": "mp3" }
    }' | jq -r '.output[] | select(.type == "output_audio") | .data' | base64 -d > output.mp3
  ```
</CodeGroup>

### Idiomas soportados

La salida de audio soporta detección automática de idioma y más de 20 idiomas incluyendo inglés, chino, hindi, español, árabe, bengalí, portugués, ruso, japonés, panyabí, alemán, coreano, francés, turco, italiano, tailandés, polaco, neerlandés, indonesio, vietnamita y urdu.

## Generar imágenes

Usa la herramienta `image_generation` para crear imágenes a partir de indicaciones de texto. El modelo interpreta tu mensaje, genera una indicación para el modelo de imágenes y devuelve el resultado.

### Modelos de generación de imágenes

| Modelo                  | Mejor para                                            |
| ----------------------- | ----------------------------------------------------- |
| `meetkai:flux-2-klein`  | Generación rápida, propósito general (predeterminado) |
| `meetkai:z-image-turbo` | Imágenes de alta calidad y detalle                    |

### Opciones de generación de imágenes

| Parámetro       | Opciones                                      | Predeterminado |
| --------------- | --------------------------------------------- | -------------- |
| `size`          | `1024x1024`, `1024x1536`, `1536x1024`, `auto` | `auto`         |
| `quality`       | `low`, `medium`, `high`, `auto`               | `auto`         |
| `output_format` | `png`, `webp`, `jpeg`                         | `png`          |
| `background`    | `transparent`, `opaque`, `auto`               | `auto`         |

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm responses create --body '{
    "model": "meetkai:functionary-es-mini",
    "input": "Generate an image of a sunset over a mountain lake.",
    "tools": [
      {
        "type": "image_generation",
        "model": "meetkai:functionary-es-mini",
        "quality": "high",
        "size": "1024x1024",
        "output_format": "png"
      }
    ]
  }'
  ```

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

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

  const result = await mka1.llm.responses.create({
    model: 'meetkai:functionary-es-mini',
    input: 'Generate an image of a sunset over a mountain lake.',
    tools: [
      {
        type: 'image_generation',
        model: 'meetkai:functionary-es-mini',
        quality: 'high',
        size: '1024x1024',
        output_format: 'png',
      },
    ],
  }, { headers: { 'X-On-Behalf-Of': '<end-user-id>' } });

  // The output includes an image_generation_call item with a result URL
  const imageCall = result.output.find((item) => item.type === 'image_generation_call');
  console.log('Image URL:', imageCall?.result);
  ```

  ```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-es-mini',
    input: 'Generate an image of a sunset over a mountain lake.',
    tools: [{ type: 'image_generation' }],
    stream: false,
  });

  const imageCall = response.output.find((item) => item.type === 'image_generation_call');
  console.log('Image URL:', imageCall?.result);
  ```

  ```csharp C# SDK theme={null}
  var result = await sdk.Llm.Responses.CreateAsync(new ResponsesCreateRequest()
  {
      Model = "meetkai:functionary-es-mini",
      Input = ResponsesCreateRequestInput.CreateStr(
          "Generate an image of a sunset over a mountain lake."),
      Tools = new List<ResponsesCreateRequestTool>
      {
          ResponsesCreateRequestTool.CreateImageGenerationToolDefinition(
              new ImageGenerationToolDefinition()
              {
                  Model = "meetkai:flux2-klein",
                  Quality = ImageGenerationToolDefinitionQuality.High,
                  Size = ImageGenerationToolDefinitionSize.OneThousandAndTwentyFourx1024,
                  OutputFormat = OutputFormat.Png,
              }
          ),
      },
  });

  // The output includes an image_generation_call item with a result URL
  ```

  ```python Python SDK theme={null}
  result = sdk.llm.responses.create(
      model="meetkai:functionary-es-mini",
      input="Generate an image of a sunset over a mountain lake.",
      tools=[
          {
              "type": "image_generation",
              "model": "meetkai:functionary-es-mini",
              "quality": "high",
              "size": "1024x1024",
              "output_format": "png",
          },
      ],
  )

  # The output includes an image_generation_call item with a result URL
  for item in result.output:
      if item.type == "image_generation_call":
          print("Image URL:", item.result)
  ```

  ```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-es-mini",
      "input": "Generate an image of a sunset over a mountain lake.",
      "tools": [
        {
          "type": "image_generation",
          "model": "meetkai:functionary-es-mini",
          "quality": "high",
          "size": "1024x1024",
          "output_format": "png"
        }
      ]
    }'
  ```
</CodeGroup>

La respuesta incluye un elemento `image_generation_call` con la URL de la imagen generada y la indicación revisada utilizada por el modelo de imágenes:

```json theme={null}
{
  "status": "completed",
  "output": [
    {
      "type": "message",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "I'll generate an image of a beautiful sunset over a mountain lake for you."
        }
      ]
    },
    {
      "type": "image_generation_call",
      "id": "ig_abc123",
      "status": "completed",
      "result": "<Generated Image URL>",
      "revised_prompt": "A breathtaking sunset over a pristine mountain lake, with golden and orange hues reflecting on the calm water surface. Snow-capped mountain peaks in the background, dramatic clouds in the sky with vibrant sunset colors of pink, purple, and orange.",
      "size": "auto",
      "quality": "auto",
      "output_format": "png"
    }
  ]
}
```

El campo `result` contiene una URL a la imagen generada. El campo `revised_prompt` muestra la indicación expandida que usó el modelo de imágenes — el LLM mejora tu instrucción breve en una descripción detallada de la imagen.

### Forzar la generación de imágenes

Usa `tool_choice` para asegurar que el modelo genere una imagen en vez de responder solo con texto.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm responses create --body '{
    "model": "meetkai:functionary-es-mini",
    "input": "A red circle on a white background.",
    "tools": [{ "type": "image_generation" }],
    "tool_choice": { "type": "image_generation" }
  }'
  ```

  ```ts MKA1 SDK theme={null}
  const result = await mka1.llm.responses.create({
    model: 'meetkai:functionary-es-mini',
    input: 'A red circle on a white background.',
    tools: [{ type: 'image_generation' }],
    toolChoice: { type: 'image_generation' },
  });
  ```

  ```ts OpenAI SDK theme={null}
  const response = await openai.responses.create({
    model: 'meetkai:functionary-es-mini',
    input: 'A red circle on a white background.',
    tools: [{ type: 'image_generation' }],
    tool_choice: { type: 'image_generation' },
    stream: false,
  });
  ```

  ```csharp C# SDK theme={null}
  var result = await sdk.Llm.Responses.CreateAsync(new ResponsesCreateRequest()
  {
      Model = "meetkai:functionary-es-mini",
      Input = ResponsesCreateRequestInput.CreateStr("A red circle on a white background."),
      Tools = new List<ResponsesCreateRequestTool>
      {
          ResponsesCreateRequestTool.CreateImageGenerationToolDefinition(
              new ImageGenerationToolDefinition()
          ),
      },
      ToolChoice = ToolChoice.CreateHostedToolChoice(new HostedToolChoice()
      {
          Type = HostedToolChoiceType.ImageGeneration,
      }),
  });
  ```

  ```python Python SDK theme={null}
  result = sdk.llm.responses.create(
      model="meetkai:functionary-es-mini",
      input="A red circle on a white background.",
      tools=[{"type": "image_generation"}],
      tool_choice={"type": "image_generation"},
  )
  ```

  ```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>' \
    --data '{
      "model": "meetkai:functionary-es-mini",
      "input": "A red circle on a white background.",
      "tools": [{ "type": "image_generation" }],
      "tool_choice": { "type": "image_generation" }
    }'
  ```
</CodeGroup>

### Estructura de la salida de imagen

El arreglo `output` de la respuesta contiene estos elementos cuando se genera una imagen:

1. `function_call` — la llamada del modelo a la herramienta de generación de imágenes con la indicación refinada
2. `image_generation_call` — el resultado de la generación con `status: "completed"` y `result` (URL de la imagen)
3. `function_call_output` — la salida cruda de la herramienta que contiene la URL
4. `message` — la respuesta de texto del modelo describiendo o haciendo referencia a la imagen

Las URLs de imágenes expiran después de 1 hora. Descárgalas o guárdalas en caché si necesitas acceso a largo plazo.

## APIs independientes

Para acceso directo sin pasar por la API de Responses, MKA1 también ofrece endpoints independientes:

### API de texto a voz

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm speech speak \
    --text 'Hello, welcome to the MKA1 platform.' \
    --language en \
    --output-file output.wav
  ```

  ```ts MKA1 SDK theme={null}
  const ttsResult = await mka1.llm.speech.speak({
    text: 'Hello, welcome to the MKA1 platform.',
    language: 'en',
  });
  ```

  ```csharp C# SDK theme={null}
  var res = await sdk.Llm.Speech.SpeakAsync(new TextToSpeechRequest()
  {
      Text = "Hello, welcome to the MKA1 platform.",
  });
  ```

  ```python Python SDK theme={null}
  result = sdk.llm.speech.speak(
      text="Hello, welcome to the MKA1 platform.",
      language="en",
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/speech/tts \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --data '{
      "text": "Hello, welcome to the MKA1 platform.",
      "language": "en"
    }'
  ```
</CodeGroup>

### API de imágenes

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm images create \
    --model meetkai:functionary-es-mini \
    --prompt 'A futuristic city skyline at dusk' \
    --size 1024x1024 \
    --quality hd
  ```

  ```ts MKA1 SDK theme={null}
  const imageResult = await mka1.llm.images.generate({
    model: 'meetkai:functionary-es-mini',
    prompt: 'A futuristic city skyline at dusk',
    size: '1024x1024',
    quality: 'hd',
  });
  ```

  ```csharp C# SDK theme={null}
  var imageResult = await sdk.Llm.Images.CreateAsync(new ImageGenerationRequest()
  {
      Model = "meetkai:z-image-turbo",
      Prompt = "A futuristic city skyline at dusk",
      Size = ImageGenerationRequestSize.OneThousandAndTwentyFourx1024,
      Quality = ImageGenerationRequestQuality.Hd,
  });
  ```

  ```python Python SDK theme={null}
  image_result = sdk.llm.images.create(
      model="meetkai:functionary-es-mini",
      prompt="A futuristic city skyline at dusk",
      size="1024x1024",
      quality="hd",
  )
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/images/generations \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --data '{
      "model": "meetkai:functionary-es-mini",
      "prompt": "A futuristic city skyline at dusk",
      "size": "1024x1024",
      "quality": "hd"
    }'
  ```
</CodeGroup>

## Próximos pasos

* [Entrada multimodal](/es/docs/multimodal-input) — envía imágenes, audio y documentos al modelo
* [Voz](/es/docs/speech) — transcribe audio y genera voz con los endpoints independientes de voz
* [Modo de voz avanzado](/es/docs/advanced-voice-mode) — conversaciones de voz en tiempo real con LiveKit
* [Generar una respuesta](/es/docs/generate-a-response) — solicitudes de texto e intercambios multi-turno
