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

# Query Completion

> Generate completion using relevant chunks as context.



## OpenAPI

````yaml https://app.stainless.com/api/spec/documented/morphik/openapi.documented.yml post /query
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers: []
security: []
paths:
  /query:
    post:
      summary: Query Completion
      description: Generate completion using relevant chunks as context.
      operationId: query_completion_query_post
      parameters:
        - name: authorization
          in: header
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Authorization
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CompletionQueryRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CompletionResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      x-codeSamples:
        - lang: JavaScript
          source: |-
            import Morphik from 'morphik';

            const client = new Morphik({
              apiKey: process.env['MORPHIK_API_KEY'], // This is the default and can be omitted
            });

            const response = await client.query.generateCompletion();

            console.log(response.completion);
        - lang: cURL
          source: |-
            curl https://api.morphik.ai/query \
                -H 'Content-Type: application/json' \
                -H "Authorization: Bearer $MORPHIK_API_KEY" \
                -d '{}'
components:
  schemas:
    CompletionQueryRequest:
      properties:
        query:
          anyOf:
            - type: string
              minLength: 1
            - type: 'null'
          title: Query
          description: >-
            Natural-language query used to retrieve relevant chunks or
            documents.
        query_image:
          anyOf:
            - type: string
            - type: 'null'
          title: Query Image
          description: >-
            Base64-encoded image to use as query for Morphik multimodal
            retrieval. Requires use_colpali=True. Mutually exclusive with
            'query'.
        filters:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Filters
          description: >-
            Metadata filters supporting logical operators ($and/$or/$not/$nor)
            and field predicates
            ($eq/$ne/$gt/$gte/$lt/$lte/$in/$nin/$exists/$type/$regex/$contains).
        k:
          type: integer
          exclusiveMinimum: 0
          title: K
          description: Maximum number of chunks or documents to return.
          default: 4
        min_score:
          type: number
          title: Min Score
          description: Minimum similarity score a result must meet before it is returned.
          default: 0
        use_reranking:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Use Reranking
          description: >-
            When provided, overrides the workspace reranking configuration for
            this request.
        use_colpali:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Use Colpali
          description: >-
            When provided, uses Morphik's finetuned ColPali style embeddings
            (recommended to be True for high quality retrieval).
        output_format:
          anyOf:
            - $ref: '#/components/schemas/OutputFormat'
            - type: 'null'
          description: >-
            How to return image chunks: base64 (default), url, or text (markdown
            format)
          default: base64
        padding:
          type: integer
          minimum: 0
          title: Padding
          description: >-
            Number of additional chunks/pages to retrieve before and after
            matched chunks (ColPali only)
          default: 0
        folder_name:
          anyOf:
            - type: string
            - items:
                type: string
              type: array
            - type: 'null'
          title: Folder Name
          description: >-
            Optional folder scope. Accepts a folder PATH (e.g.,
            '/Company/Reports') or list of paths.
        folder_depth:
          anyOf:
            - type: integer
            - type: 'null'
          title: Folder Depth
          description: >-
            Folder scope depth. 0 or None = exact folder only, -1 = include all
            descendants, n > 0 = include descendants up to n levels deeper.
        end_user_id:
          anyOf:
            - type: string
            - type: 'null'
          title: End User Id
          description: Optional end-user scope for the operation
        max_tokens:
          anyOf:
            - type: integer
            - type: 'null'
          title: Max Tokens
          description: Maximum number of tokens allowed in the generated completion.
        temperature:
          anyOf:
            - type: number
            - type: 'null'
          title: Temperature
          description: >-
            Sampling temperature passed to the completion model (None uses
            provider default).
        prompt_overrides:
          anyOf:
            - $ref: '#/components/schemas/QueryPromptOverrides'
            - type: 'null'
          description: >-
            Optional customizations for entity extraction, resolution, and query
            prompts
        schema:
          anyOf:
            - {}
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Schema
          description: >-
            Schema for structured output, can be a Pydantic model or JSON schema
            dict
        chat_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Chat Id
          description: Optional chat session ID for persisting conversation history
        stream_response:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Stream Response
          description: Whether to stream the response back in chunks
          default: false
        llm_config:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Llm Config
          description: >-
            LiteLLM-compatible model configuration (e.g., model name, API key,
            base URL)
        inline_citations:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Inline Citations
          description: >-
            Whether to include inline citations with filename and page number in
            the response
          default: false
      type: object
      title: CompletionQueryRequest
      description: Request model for completion generation
    CompletionResponse:
      properties:
        completion:
          anyOf:
            - type: string
            - $ref: '#/components/schemas/StructuredCompletion'
          title: Completion
        usage:
          additionalProperties:
            type: integer
          type: object
          title: Usage
        finish_reason:
          anyOf:
            - type: string
            - type: 'null'
          title: Finish Reason
        sources:
          items:
            $ref: '#/components/schemas/ChunkSource'
          type: array
          title: Sources
          default: []
        metadata:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Metadata
      type: object
      required:
        - completion
        - usage
      title: CompletionResponse
      description: Response from completion generation
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    OutputFormat:
      type: string
      enum:
        - base64
        - url
        - text
      title: OutputFormat
      description: Output format for image chunks in retrieval results.
    QueryPromptOverrides:
      properties:
        entity_extraction:
          anyOf:
            - $ref: '#/components/schemas/EntityExtractionPromptOverride'
            - type: 'null'
          description: >-
            Overrides for entity extraction prompts - controls how entities are
            identified in text during queries
        entity_resolution:
          anyOf:
            - $ref: '#/components/schemas/EntityResolutionPromptOverride'
            - type: 'null'
          description: >-
            Overrides for entity resolution prompts - controls how variant forms
            are grouped during queries
        query:
          anyOf:
            - $ref: '#/components/schemas/QueryPromptOverride'
            - type: 'null'
          description: >-
            Overrides for query prompts - controls response generation style,
            format, and tone
      additionalProperties: false
      type: object
      title: QueryPromptOverrides
      description: >-
        Container for query-related prompt overrides.


        Use this class when customizing prompts for query operations, which may

        include customizations for entity extraction, entity resolution, and

        the query/response generation itself.


        This is the most feature-complete override class, supporting all
        customization types.


        Available customizations:

        - entity_extraction: Customize how entities are identified in text

        - entity_resolution: Customize how entity variants are grouped

        - query: Customize response generation style, format, and tone


        Each type has its own required placeholders. See the specific class
        documentation

        for details and examples.
    StructuredCompletion:
      properties: {}
      additionalProperties: true
      type: object
      title: StructuredCompletion
      description: Structured completion object for schema-based responses
    ChunkSource:
      properties:
        document_id:
          type: string
          title: Document Id
        chunk_number:
          type: integer
          title: Chunk Number
        score:
          anyOf:
            - type: number
            - type: 'null'
          title: Score
      type: object
      required:
        - document_id
        - chunk_number
      title: ChunkSource
      description: Source information for a chunk used in completion
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
    EntityExtractionPromptOverride:
      properties:
        prompt_template:
          anyOf:
            - type: string
            - type: 'null'
          title: Prompt Template
          description: >-
            Custom prompt template, MUST include both {content} and {examples}
            placeholders. The {content} placeholder will be replaced with the
            text to analyze, and {examples} will be replaced with formatted
            examples.
        examples:
          anyOf:
            - items:
                $ref: '#/components/schemas/EntityExtractionExample'
              type: array
            - type: 'null'
          title: Examples
          description: >-
            Examples of entities to extract, used to guide the LLM toward
            domain-specific entity types and patterns.
      type: object
      title: EntityExtractionPromptOverride
      description: >-
        Configuration for customizing entity extraction prompts.


        This allows you to override both the prompt template used for entity
        extraction

        and provide domain-specific examples of entities to be extracted.


        If only examples are provided (without a prompt_template), they will be

        incorporated into the default prompt. If only prompt_template is
        provided,

        it will be used with default examples (if any).


        Required placeholders:

        - {content}: Will be replaced with the text to analyze for entity
        extraction

        - {examples}: Will be replaced with formatted examples of entities to
        extract


        Example prompt template:

        ```

        Extract entities from the following text. Look for entities similar to
        these examples:


        {examples}


        Text to analyze:

        {content}


        Extracted entities (in JSON format):

        ```
    EntityResolutionPromptOverride:
      properties:
        prompt_template:
          anyOf:
            - type: string
            - type: 'null'
          title: Prompt Template
          description: >-
            Custom prompt template that MUST include both {entities_str} and
            {examples_json} placeholders. The {entities_str} placeholder will be
            replaced with the extracted entities, and {examples_json} will be
            replaced with JSON-formatted examples of entity resolution groups.
        examples:
          anyOf:
            - items:
                $ref: '#/components/schemas/EntityResolutionExample'
              type: array
            - type: 'null'
          title: Examples
          description: >-
            Examples of entity resolution groups showing how variants of the
            same entity should be resolved to their canonical forms. This is
            particularly useful for domain-specific terminology, abbreviations,
            and naming conventions.
      type: object
      title: EntityResolutionPromptOverride
      description: >-
        Configuration for customizing entity resolution prompts.


        Entity resolution identifies and groups variant forms of the same
        entity.

        This override allows you to customize how this process works by
        providing

        a custom prompt template and/or domain-specific examples.


        If only examples are provided (without a prompt_template), they will be

        incorporated into the default prompt. If only prompt_template is
        provided,

        it will be used with default examples (if any).


        Required placeholders:

        - {entities_str}: Will be replaced with the extracted entities

        - {examples_json}: Will be replaced with JSON-formatted examples of
        entity resolution groups


        Example prompt template:

        ```

        I have extracted the following entities:


        {entities_str}


        Below are examples of how different entity references can be grouped
        together:


        {examples_json}


        Group the above entities by resolving which mentions refer to the same
        entity.

        Return the results in JSON format.

        ```
    QueryPromptOverride:
      properties:
        prompt_template:
          anyOf:
            - type: string
            - type: 'null'
          title: Prompt Template
          description: >-
            Custom prompt template for generating responses to queries. REQUIRED
            PLACEHOLDERS: {question} and {context} must be included in the
            template. The {question} placeholder will be replaced with the user
            query, and {context} will be replaced with the retrieved content.
            Use this to control response style, format, and tone.
        system_prompt:
          anyOf:
            - type: string
            - type: 'null'
          title: System Prompt
          description: >-
            Custom system prompt that replaces Morphik's default query agent
            instructions. Use this to fully control the assistant's behavior
            when generating responses.
      type: object
      title: QueryPromptOverride
      description: >-
        Configuration for customizing query prompts.


        This allows you to customize how responses are generated during query
        operations.

        Query prompts guide the LLM on how to format and style responses, what
        tone to use,

        and how to incorporate retrieved information into the response.


        Required placeholders:

        - {question}: Will be replaced with the user's query

        - {context}: Will be replaced with the retrieved content/context


        Example prompt template:

        ```

        Answer the following question based on the provided information.


        Question: {question}


        Context:

        {context}


        Answer:

        ```
    EntityExtractionExample:
      properties:
        label:
          type: string
          title: Label
          description: The entity label (e.g., 'John Doe', 'Apple Inc.')
        type:
          type: string
          title: Type
          description: The entity type (e.g., 'PERSON', 'ORGANIZATION', 'PRODUCT')
        properties:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Properties
          description: 'Optional properties of the entity (e.g., {''role'': ''CEO'', ''age'': 42})'
      type: object
      required:
        - label
        - type
      title: EntityExtractionExample
      description: >-
        Example entity for guiding entity extraction.


        Used to provide domain-specific examples to the LLM of what entities to
        extract.

        These examples help steer the extraction process toward entities
        relevant to your domain.
    EntityResolutionExample:
      properties:
        canonical:
          type: string
          title: Canonical
          description: The canonical (standard/preferred) form of the entity
        variants:
          items:
            type: string
          type: array
          title: Variants
          description: List of variant forms that should resolve to the canonical form
      type: object
      required:
        - canonical
        - variants
      title: EntityResolutionExample
      description: >-
        Example for entity resolution, showing how variants should be grouped.


        Entity resolution is the process of identifying when different
        references

        (variants) in text refer to the same real-world entity. These examples

        help the LLM understand domain-specific patterns for resolving entities.

````