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

<AgentInstructions>

## Submitting Feedback

If you encounter incorrect, outdated, or confusing documentation on this page, submit feedback:

POST https://docs.omni.co/feedback

```json
{
  "path": "/api/ai/generate-a-query",
  "feedback": "Description of the issue"
}
```

Only submit feedback when you have something specific and actionable to report.

</AgentInstructions>

# Generate a query

> Generate a structured Omni query from natural language using AI



## OpenAPI

````yaml /api/openapi.yaml post /v1/ai/generate-query
openapi: 3.1.0
info:
  title: Omni API
  description: >
    The Omni REST API provides programmatic access to your Omni instance for
    managing users, documents, queries, schedules, and more.  
  version: 1.0.0
  contact:
    name: Omni Support
    url: https://docs.omni.co
servers:
  - url: https://{instance}.omniapp.co/api
    description: Production
    variables:
      instance:
        default: blobsrus
        description: Your production Omni instance subdomain
  - url: https://{instance}.playground.exploreomni.dev/api
    description: Playground
    variables:
      instance:
        default: blobsrus
        description: Your playground Omni instance subdomain
security:
  - bearerAuth: []
  - orgApiKey: []
tags:
  - name: AI
    description: AI-powered query generation
  - name: API Tokens
    description: >-
      Manage API tokens (Organization keys, Personal Access Tokens, MCP OAuth
      grants)
  - name: Connections
    description: Manage database connections
  - name: Connection environments
    description: Manage connection environments database connections
  - name: Content
    description: Unified content retrieval (documents and folders)
  - name: Content migration
    description: Export and import dashboards
  - name: Content validator
    description: Validate content against models and perform find/replace operations
  - name: Dashboard downloads
    description: Download dashboards and tiles as PDF, PNG, XLSX, CSV, or JSON files
  - name: Dashboard filters and controls
    description: Read and update dashboard filter and control default values
  - name: dbt
    description: Manage dbt configuration for connections
  - name: Documents
    description: Create, retrieve, and manage documents
  - name: Document favorites
    description: Favorite and unfavorite documents
  - name: Document labels
    description: Apply and manage labels on documents
  - name: Document permissions
    description: Manage document-level access
  - name: Labels
    description: >
      Manage labels in an organization. Labels can be applied to documents and
      folders to help organize and categorize content.


      **Label types:**

      - **Basic labels**: Can be created and managed by any user

      - **Verified labels**: Indicate curated or officially sanctioned content.
      Admin-only.

      - **Homepage labels**: Appear on the organization homepage. Admin-only.
  - name: Folders
    description: Create and organize content folders
  - name: Folder permissions
    description: Manage folder-level access
  - name: Jobs
    description: Check status of asynchronous jobs
  - name: Models
    description: Create and manage data models
  - name: Model branches
    description: Manage model branches and merge changes
  - name: Model git configuration
    description: Manage git configuration for shared models
  - name: Queries
    description: Execute workbook queries
  - name: Schedules
    description: Create and manage scheduled tasks
  - name: Schedule recipients
    description: Manage schedule recipients
  - name: Schema refresh schedules
    description: Manage automated schema refresh schedules for connections
  - name: Topics
    description: Retrieve topic information from models
  - name: Uploads
    description: Manage file uploads
  - name: Users
    description: Manage users
  - name: User attributes
    description: Manage user attribute definitions
  - name: User groups
    description: Manage user groups
  - name: User model roles
    description: Manage model and connection role assignments for users
  - name: User group model roles
    description: Manage model and connection role assignments for user groups
  - name: Uploads
    description: Manage CSV and spreadsheet uploads
paths:
  /v1/ai/generate-query:
    post:
      tags:
        - AI
      summary: Generate a query
      description: Generate a structured Omni query from natural language using AI
      operationId: generateQuery
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - modelId
                - prompt
              properties:
                modelId:
                  type: string
                  format: uuid
                  description: The ID of the model to run the query against
                currentTopicName:
                  type: string
                  description: >-
                    Name of the base topic/table. If left empty, AI will
                    automatically choose a topic based on the question.
                prompt:
                  type: string
                  description: >-
                    Natural language instruction describing the desired query
                    output
                workbookUrl:
                  type: boolean
                  description: >-
                    When `true`, returns an Omni workbook URL that opens and
                    runs the generated query
                branchId:
                  type: string
                  description: >-
                    The ID of the model branch to use to generate the query. If
                    not provided, the `main` branch will be used. To retrieve
                    branch IDs, use the [List models](/api/models/list-models)
                    endpoint with `modelKind=BRANCH`.
                runQuery:
                  type: boolean
                  default: true
                  description: >
                    When `true` (default), the generated query is executed
                    against the database and results are included in the
                    response. 


                    When `false`, only the generated query object is returned
                    without executing it. Set to `false` to preview what query
                    would be generated without incurring a database query.
                contextQuery:
                  type: object
                  description: >-
                    A query object to provide as context. Use this to reference
                    previous queries or provide additional context for the
                    generation.
                queryAllViews:
                  type: boolean
                  default: false
                  description: >
                    When `true` and the model's
                    [`query_all_views_and_fields`](/modeling/models/ai-settings)
                    setting is enabled, allows the AI to query views that are
                    not included in topics. If the setting is disabled, this
                    parameter has no effect.


                    When both the API parameter and model setting are enabled:


                    - The AI can select from any view in the model, including
                    views not in topics

                    - The AI will prefer topic-organized views unless the
                    question clearly targets a standalone view


                    **Note:** Users with topic-locked permissions cannot use
                    this parameter, even if the model setting is enabled.
            example:
              modelId: 123e4567-e89b-12d3-a456-426614174000
              currentTopicName: orders
              prompt: Show me total revenue by product category for the last quarter
      responses:
        '200':
          description: Successfully generated query
          content:
            application/json:
              schema:
                type: object
                properties:
                  query:
                    type: object
                    properties:
                      model_job:
                        type: object
                        description: >-
                          A structured Omni query object that can be used with
                          the [Query run API](/api/queries/run-query)
                        properties:
                          model_id:
                            type: string
                            format: uuid
                            description: Model identifier
                          table:
                            type: string
                            description: Base table/topic name
                          fields:
                            type: array
                            items:
                              type: string
                            description: Array of field names to include in query
                          calculations:
                            type: array
                            items:
                              type: object
                            description: Custom calculations
                          filters:
                            type: object
                            description: Filter conditions
                          sorts:
                            type: array
                            items:
                              type: object
                              properties:
                                column_name:
                                  type: string
                                sort_descending:
                                  type: boolean
                                is_column_sort:
                                  type: boolean
                                null_sort:
                                  type: string
                            description: Sort specifications
                          limit:
                            oneOf:
                              - type: integer
                              - type: 'null'
                            description: Result row limit
                          pivots:
                            type: array
                            items:
                              type: object
                            description: Pivot configurations
                          fill_fields:
                            type: array
                            items:
                              type: string
                            description: Fields to fill
                          column_totals:
                            type: object
                            description: Column totals configuration
                          row_totals:
                            type: object
                            description: Row totals configuration
                          column_limit:
                            type: integer
                            description: Column limit for pivots
                          default_group_by:
                            type: boolean
                            description: Enable default grouping
                          join_via_map:
                            type: object
                            description: Join configuration map
                          join_paths_from_topic_name:
                            type: string
                            description: Topic name for join paths
                          version:
                            type: integer
                            description: Query version
                          period_over_period_computations:
                            type: array
                            items:
                              type: object
                            description: Period over period calculations
                          query_references:
                            type: object
                            description: Query references
                          metadata:
                            type: object
                            description: Query metadata
                          custom_summary_types:
                            type: object
                            description: Custom summary type definitions
              example:
                query:
                  model_job:
                    model_id: bcf0cffd-ec1b-44d5-945a-a261ebe407fc
                    table: order_items
                    fields:
                      - products.item_name
                      - order_items.total_sale_price
                    calculations: []
                    filters: {}
                    sorts:
                      - column_name: order_items.total_sale_price
                        sort_descending: true
                        is_column_sort: false
                        null_sort: OMNI_DEFAULT
                    limit: 10
                    pivots: []
                    fill_fields: []
                    column_totals: {}
                    row_totals: {}
                    column_limit: 50
                    default_group_by: true
                    join_via_map: {}
                    join_paths_from_topic_name: order_items
                    version: 5
                    period_over_period_computations: []
                    query_references: {}
                    metadata: {}
                    custom_summary_types: {}
        '400':
          description: |
            Bad Request

            Possible error messages:
            - `Invalid method`
            - `Invalid JSON`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '403':
          description: |
            Forbidden

            Possible error messages:

            - `Feature not enabled`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
      security:
        - bearerAuth: []
components:
  schemas:
    Error:
      type: object
      properties:
        error:
          type: string
          description: HTTP response code for the error
          example: <response_code>
        message:
          type: string
          description: Detailed error description
          example: <error_reason>
  responses:
    TooManyRequests:
      description: Too Many Requests - Rate limit exceeded (60 requests/minute)
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    InternalServerError:
      description: Internal Server Error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >
        Can be either an [Organization API
        Key](/api/authentication#organization-api-keys) or [Personal Access
        Token (PAT)](/api/authentication#personal-access-tokens-pat).


        Include in the `Authorization` header as: `Bearer YOUR_TOKEN`
    orgApiKey:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >
        Requires an [Organization API
        Key](/api/authentication#organization-api-keys). Personal Access Tokens
        (PATs) are not supported for this endpoint.


        Include in the `Authorization` header as: `Bearer ORGANIZATION_API_KEY`

````