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

# Stream Speech

> Real-time text to speech conversion with audio streaming for immediate playback.

**Key Features:**
- Real-time audio generation
- Progressive audio chunks
- Lower latency for long texts
- Streaming audio playback

**Use Cases:**
- Live voice assistants
- Real-time narration
- Interactive voice applications
- Immediate audio feedback

**Audio Format:** MP3 chunks delivered via server-sent events

Note: Example requests/responses shown here are illustrative. When using the live "Try it" tool, you may see two responses: an HTTP status preview and the API's streaming output.




## OpenAPI

````yaml /openapi_aql.yaml post /api/v2/AQL/Stream/TextToSpeech
openapi: 3.0.3
info:
  title: AQL AI Developer APIs
  version: 1.0.0
  description: >
    AQL AI Developer APIs provide access to AQL Chat, RAG Answer,
    Speech-to-Text, and Text-to-Speech capabilities. These AI-powered APIs
    enable you to build intelligent applications with natural language
    understanding, voice processing, and knowledge retrieval. AQL technology
    excels particularly in Arabic language and dialect processing.


    ## Prerequisites and Setup


    ### Prerequisites


    Before using these APIs, ensure you have:


    1. **Active Widebot Account** with API access enabled

    2. **API Key** from your account settings

    3. **Bot ID** from your API Page

    4. **API Quotas** configured for your use case

    5. **Indexed Documents** (for RAG API) via AI Knowledge Feature


    ### Authentication


    All APIs use header-based authentication:

    - `x-user-auth`: Your API key

    - `x-bot`: Your bot ID with quota limits


    ### Base URL


    All endpoints use: `https://gateway.widebot.net`


    ## Common Error Codes


    ### Error Response Structure


    ```json

    {
        "StatusCode": 401,
        "Response": "Invalid authentication token",
        "Consumption": "0/1000"
    }

    ```


    ### Error Codes Reference


    | Code | Error | Description | Solution |

    |------|-------|-------------|----------|

    | 401 | Unauthorized | Invalid x-user-auth API key | Check your API key from
    account settings |

    | 402 | Payment Required | API exceeds consumption quota | Increase quota or
    wait for reset |

    | 429 | Too Many Requests | Concurrent limit exceeded | Reduce request
    frequency |

    | 400 | Bad Request | Invalid parameters or missing quota | Verify request
    parameters |

    | 500 | Internal Error | Unexpected server error | Contact support if
    persistent |


    ## Common Response Structure


    ### Standard Response Format


    All APIs return the same structure:


    ```json

    {
        "StatusCode": 200,
        "Response": { },
        "Consumption": "used/total"
    }

    ```


    **Fields Explained:**

    - `StatusCode`: HTTP status code

    - `Response`: API-specific response data

    - `Consumption`: Current usage vs quota limit


    ## Quick Start Guide


    ### 1. Environment Setup


    Create environment variables:

    - `auth_token`: Your authentication token

    - `bot_id`: Your bot ID


    ### 2. Test Connection


    Start with AQL Chat API for basic testing:


    ```json

    {
        "Message": "مرحباً، اختبار الاتصال"
    }

    ```


    ### 3. Explore APIs in Order


    1. **AQL Chat** - Language model interactions

    2. **RAG Answer** - Document-based Q&A (requires indexed docs)

    3. **Speech to Text** - Audio transcription

    4. **Text to Speech** - Voice generation


    ## Usage Monitoring


    ### Consumption Tracking


    Monitor usage in each response:

    - Track token consumption for text APIs

    - Monitor character usage for TTS

    - Watch audio duration for STT


    ### Best Practices


    - Set up monitoring alerts at 80% quota usage

    - Use streaming APIs for real-time applications

    - Cache results when appropriate

    - Optimize parameters for cost efficiency


    ## Arabic Language Features


    ### Why Choose Widebot for Arabic?


    - **Industry-leading dialect recognition** (Egyptian, Gulf, Levantine,
    Maghrebi)

    - **Cultural context understanding** in language generation

    - **Natural pronunciation** in text-to-speech

    - **Colloquial expression handling** in all APIs


    ### Arabic-Specific Tips


    - Use `ar-eg` language code for best results

    - Select appropriate Arabic voices for your region

    - Leverage dialect-specific features in STT

    - Test with regional content for optimization


    ## Integration Examples


    ### Common Integration Patterns


    1. **Voice Assistant**: STT → AQL Chat → TTS

    2. **Document Q&A**: RAG Answer → TTS (for audio responses)

    3. **Content Creation**: AQL Chat → TTS (for audio content)

    4. **Transcription Service**: STT → AQL Chat (for cleanup/formatting)


    ### Multi-API Workflows


    Combine APIs for powerful applications:

    - Process audio input → Generate AI response → Convert to speech

    - Answer from documents → Enhance with AI → Deliver as audio
servers:
  - url: https://gateway.widebot.net
    description: Production server
security:
  - UserAuth: []
    BotId: []
tags:
  - name: AQL Chat
    description: >
      AQL Chat API provides access to Widebot's AQL language model for natural
      language understanding and generation, with exceptional capabilities in
      Arabic and its various dialects.


      ### How It Works


      1. You send a message or query to the API

      2. Optionally configure generation parameters like temperature and token
      limits

      3. The AQL model processes your input and generates a contextually
      relevant response

      4. Response includes the generated text along with token usage metrics


      ### Arabic Language Excellence


      Our AQL model excels at understanding and generating Arabic content,
      including various regional dialects and colloquial expressions. The model
      demonstrates superior comprehension of cultural context, idiomatic
      expressions, and dialectical nuances across the Arab world.


      ### API Versions


      - **V1 API**: Standard text-based conversations

      - **V2 API**: Multimodal support (text + images)

      - **Streaming API**: Real-time response generation


      ### Consumption Calculation


      Consumption is calculated based on the total number of tokens processed
      (input + output). A token is approximately 4 characters in English or 1-2
      characters in Arabic.


      ### PromptStyle Options


      - 0: Base (standard responses)

      - 1: Expert (technical/formal)

      - 2: Conversational (casual, dialogic)

      - 3: Structured (organized with sections)

      - 4: Concise (brief, to-the-point)

      - 5: Detailed (comprehensive explanations)


      ### Configuration Parameters


      - **Temperature**: Controls randomness (0.0-1.0)

      - **MaxTokens**: Maximum response length

      - **TopProbability**: Nucleus sampling probability

      - **RepetitionPenalty**: Reduces word repetition


      ### Usage Tips


      - For factual queries, use lower temperature (0.1-0.3)

      - For creative content, use higher temperature (0.7-1.0)

      - Monitor token consumption to optimize costs

      - Use V2 API for image analysis capabilities

      - Leverage streaming for real-time applications
  - name: RAG Knowledge
    description: >
      Manage knowledge units for RAG: get an upload URL, add knowledge, list
      entries, fetch by ID, update, and delete. Complete these steps before
      calling answering APIs.


      ### Typical Flow

      1. Get an upload URL and upload the file

      2. Add Knowledge (register the uploaded file or a URL)

      3. Retrieve/Update/Delete as needed
  - name: RAG Answering
    description: >
      Answer questions using previously indexed knowledge with citations.
      Supports standard and streaming responses.


      ### How Answering Works

      1. Submit a question and specify which indexes to search

      2. Retrieve relevant passages from your knowledge

      3. Generate a grounded answer including source citations
  - name: Speech to Text
    description: >
      Speech-to-Text API converts spoken language in audio files into written
      text, with exceptional performance for Arabic language and dialect
      recognition.


      ### How It Works


      1. You upload an audio file or provide an audio URL

      2. Specify a session ID to track the conversion

      3. Optionally set language and audio parameters

      4. The API processes the audio and returns the transcribed text


      ### Arabic Excellence


      Our Speech to Text API demonstrates industry-leading accuracy for Arabic
      dialects and accents, including Egyptian, Gulf, Levantine, and Maghrebi
      variations. The model effectively handles colloquial expressions, regional
      pronunciations, and mixed dialect speech.


      ### Supported Languages


      Arabic (MSA), Arabic (Egyptian), English, Turkish, Ukrainian, Urdu,
      Swedish, Spanish, Russian, Korean, Italian, Japanese, Indonesian, Hindi,
      Hebrew, French, Greek, German, Mandarin Chinese, Asturian


      ### Key Features


      - **Real-time Transcription**: Streaming API for live processing

      - **Translation Capabilities**: Convert speech to different languages

      - **Noise Filtering**: Advanced audio preprocessing

      - **Multiple Dialect Recognition**: Specialized Arabic dialect handling

      - **Session-based Processing**: Track related transcriptions


      ### Usage Tips


      - Use clear audio with minimal background noise

      - Set SetDefaultSampleRate to true for optimal accuracy

      - For long audio files, consider breaking into smaller chunks

      - Use appropriate language settings for best results

      - Leverage streaming API for real-time applications

      - Choose WAV format for highest transcription quality
  - name: Text to Speech
    description: >
      Text-to-Speech API converts text into natural-sounding audio in multiple
      languages and voices, optimized for Arabic and its dialects with
      exceptional quality.


      ### How It Works


      1. Send text content along with language and speaker preferences

      2. The API processes your text using neural voice synthesis

      3. The response includes a URL to access the generated audio file
      (typically available for 24 hours)


      ### Arabic Excellence


      The API excels in Arabic, handling nuances, pronunciation, and dialectical
      variations, producing speech that accurately reflects regional intonation
      patterns.


      ### Supported Languages


      Arabic (MSA), Arabic (Egyptian), Arabic (Saudi), English, Turkish,
      Ukrainian, Urdu, Swedish, Spanish, Russian, Korean, Italian, Japanese,
      Indonesian, Hindi, Hebrew, French, Greek, German, Mandarin Chinese,
      Asturian


      ### Available Speakers


      #### Arabic Male

      - **Hesham** - **HIGHLY RECOMMENDED** for MSA and Egyptian dialect

      - **Rawy** - **HIGHLY RECOMMENDED** for Saudi dialect

      - Other options: Mohamed, Adel, Hytham, Masry, Adam, Hesham-formal (slower
      rate)


      #### Arabic Female

      - Lina, Mona, Alice, Customer_Service, Esraa

      - **Hala** (Recommended for Saudi dialect)


      ### Limitations


      1. **Lack of Punctuation in Long Paragraphs** - Without commas or periods,
      the model may add wrong pauses

      2. **Spelling Sensitivity** - Arabic spelling must be accurate

      3. **Voice Cloning Inconsistency** - Quality depends on the reference file

      4. **Speaker—Language Mismatch** - Using Arabic text with English speaker
      produces unnatural output


      ### Usage Tips


      - Keep LanguageCode and Speaker consistent

      - Use Temperature to adjust speech variation

      - Add punctuation for natural prosody

      - Check quota before long texts

      - Cache audio files if reusing them

      - Use Streaming API for real-time audio

      - **For Saudi dialect, use Rawy (male) or Hala (female)**

      - **For MSA/Egyptian dialect, use Hesham (male)**
paths:
  /api/v2/AQL/Stream/TextToSpeech:
    post:
      tags:
        - Text to Speech
      summary: Stream Speech
      description: >
        Real-time text to speech conversion with audio streaming for immediate
        playback.


        **Key Features:**

        - Real-time audio generation

        - Progressive audio chunks

        - Lower latency for long texts

        - Streaming audio playback


        **Use Cases:**

        - Live voice assistants

        - Real-time narration

        - Interactive voice applications

        - Immediate audio feedback


        **Audio Format:** MP3 chunks delivered via server-sent events


        Note: Example requests/responses shown here are illustrative. When using
        the live "Try it" tool, you may see two responses: an HTTP status
        preview and the API's streaming output.
      operationId: textToSpeechStreaming
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TTSStreamRequest'
            examples:
              streamingArabic:
                summary: Streaming Arabic TTS
                description: Real-time Arabic text to speech conversion
                value:
                  TextMessage: مرحباً! هذا مثال على التحويل الصوتي المباشر للنص العربي
                  LanguageCode: ar
                  Speaker: Hesham
                  ModelType: v1
                  StreamChunkSize: 300
      responses:
        '200':
          description: Streaming audio generation with progressive chunks
          content:
            text/event-stream:
              schema:
                type: string
                description: Server-sent events with audio chunks
              examples:
                streamingAudio:
                  summary: Example streaming audio response
                  value: >
                    data: {"chunk_id": 1, "audio_data":
                    "UklGRl4AAABXQVZFZm10...", "chunk_size": 1024}


                    data: {"chunk_id": 2, "audio_data":
                    "VFJBVEVZRjQAAABXQVZF...", "chunk_size": 1024}


                    data: {"chunk_id": 3, "audio_data": "ZGF0YQQ=",
                    "chunk_size": 512}


                    data: {"status": "complete", "total_chunks": 3,
                    "total_duration": 4.2, "consumption": "58/15000"}
components:
  schemas:
    TTSStreamRequest:
      type: object
      required:
        - TextMessage
        - LanguageCode
        - Speaker
        - ModelType
      properties:
        TextMessage:
          type: string
          description: Text to convert to speech
          example: مرحباً! هذا بث صوتي لحظي.
        LanguageCode:
          type: string
          description: Language code for speech
          example: ar
        Speaker:
          type: string
          description: Voice to use for generation
          example: Hesham
        ModelType:
          type: string
          description: >-
            Required. Voice model version. One of: v1, v1-fast, v2, v3, v4, or
            eval-*.
          example: v1
        Temperature:
          type: number
          format: float
          minimum: 0
          maximum: 1
          example: 0.8
          description: Controls speech variation
        OutputSampleRate:
          type: integer
          example: 24000
          description: Audio sample rate
        StreamChunkSize:
          type: integer
          maximum: 400
          example: 300
          description: Size of audio chunks for streaming
  securitySchemes:
    UserAuth:
      type: apiKey
      in: header
      name: x-user-auth
      description: Your API key from account settings
    BotId:
      type: apiKey
      in: header
      name: x-bot
      description: Your bot ID from account settings

````