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

# Tạo embeddings

> Sử dụng CometAPI POST /v1/embeddings để tạo vector embeddings cho dữ liệu đầu vào văn bản với một embedding model được chọn.

CometAPI hỗ trợ các embedding model từ nhiều nhà cung cấp thông qua một endpoint duy nhất. Truyền vào một hoặc nhiều chuỗi văn bản và nhận về các vector số cho semantic search, phân cụm, phân loại hoặc retrieval-augmented generation (RAG). Xem [danh sách model](/vi/overview/models) để biết các embedding model khả dụng và giá.

<Tip>
  Các model `text-embedding-3-*` hỗ trợ tham số `dimensions`, cho phép rút gọn vector embedding mà không làm giảm đáng kể độ chính xác. Điều này có thể giúp giảm chi phí lưu trữ trong khi vẫn giữ lại phần lớn thông tin ngữ nghĩa.
</Tip>

<Info>
  Để nhúng nhiều văn bản trong một request, hãy truyền một mảng chuỗi vào tham số `input`. Batch input hiệu quả hơn đáng kể so với việc thực hiện từng request riêng lẻ.
</Info>

***


## OpenAPI

````yaml api/openapi/text/post-embeddings.openapi.json POST /v1/embeddings
openapi: 3.1.0
info:
  title: Embeddings API
  version: 1.0.0
servers:
  - url: https://api.cometapi.com
security:
  - bearerAuth: []
paths:
  /v1/embeddings:
    post:
      summary: Create Embeddings
      operationId: createEmbeddings
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - model
                - input
              properties:
                model:
                  type: string
                  description: >-
                    The embedding model to use. See the [Models
                    page](/overview/models) for current embedding model IDs.
                  example: text-embedding-3-small
                input:
                  oneOf:
                    - type: string
                      description: A single text string to embed.
                    - type: array
                      description: >-
                        An array of strings to embed in a single request. Each
                        string can be up to 8,191 tokens.
                      items:
                        type: string
                    - type: array
                      description: An array of token arrays.
                      items:
                        type: array
                        items:
                          type: integer
                  description: >-
                    The text to embed. Can be a single string, an array of
                    strings, or an array of token arrays. Each input must not
                    exceed the model's maximum token limit (8,191 tokens for
                    `text-embedding-3-*` models).
                encoding_format:
                  type: string
                  description: >-
                    The format of the returned embedding vectors. `float`
                    returns an array of floating-point numbers. `base64` returns
                    a base64-encoded string representation, which can reduce
                    response size for large batches.
                  enum:
                    - float
                    - base64
                  default: float
                dimensions:
                  type: integer
                  description: >-
                    The number of dimensions for the output embedding vector.
                    Only supported by `text-embedding-3-*` models. Reducing
                    dimensions can lower storage costs while maintaining most of
                    the embedding's utility.
                  minimum: 1
                user:
                  type: string
                  description: >-
                    A unique identifier for your end-user, which can help
                    monitor and detect abuse.
            examples:
              Single Text:
                summary: Single Text
                value:
                  model: text-embedding-3-small
                  input: The food was delicious and the waiter was friendly.
              Batch Input:
                summary: Batch Input
                value:
                  model: text-embedding-3-small
                  input:
                    - Hello world
                    - How are you?
                    - Embedding example
                  encoding_format: float
              With Dimensions:
                summary: Reduced Dimensions
                value:
                  model: text-embedding-3-small
                  input: Search query text
                  dimensions: 256
      responses:
        '200':
          description: A list of embedding vectors for the input text(s).
          content:
            application/json:
              schema:
                type: object
                properties:
                  object:
                    type: string
                    description: The object type, always `list`.
                    enum:
                      - list
                    example: list
                  data:
                    type: array
                    description: >-
                      An array of embedding objects, one per input text. When
                      multiple inputs are provided, results are returned in the
                      same order as the input.
                    items:
                      type: object
                      properties:
                        object:
                          type: string
                          description: The object type, always `embedding`.
                          enum:
                            - embedding
                          example: embedding
                        index:
                          type: integer
                          description: >-
                            The index of this embedding in the input array
                            (starting from 0).
                          example: 0
                        embedding:
                          type: array
                          description: >-
                            The embedding vector as an array of floating-point
                            numbers. The length depends on the model and
                            `dimensions` parameter.
                          items:
                            type: number
                          example:
                            - -0.0021
                            - -0.0491
                            - 0.0209
                            - 0.0314
                            - -0.0453
                  model:
                    type: string
                    description: The model used to generate the embeddings.
                    example: text-embedding-3-small
                  usage:
                    type: object
                    description: Token usage statistics for this request.
                    properties:
                      prompt_tokens:
                        type: integer
                        description: The number of tokens in the input text(s).
                        example: 2
                      total_tokens:
                        type: integer
                        description: >-
                          The total number of tokens processed (same as
                          `prompt_tokens` for embeddings).
                        example: 2
              example:
                object: list
                data:
                  - object: embedding
                    index: 0
                    embedding:
                      - -0.0021
                      - -0.0491
                      - 0.0209
                      - 0.0314
                      - -0.0453
                model: text-embedding-3-small
                usage:
                  prompt_tokens: 2
                  total_tokens: 2
      x-codeSamples:
        - lang: Python
          label: Single Text
          source: |
            import os
            from openai import OpenAI

            client = OpenAI(
                base_url="https://api.cometapi.com/v1",
                api_key=os.environ["COMETAPI_KEY"],
            )

            response = client.embeddings.create(
                model="text-embedding-3-small",
                input="The food was delicious and the waiter was friendly.",
            )

            print(response.data[0].embedding[:5])  # First 5 dimensions
            print(f"Dimensions: {len(response.data[0].embedding)}")
        - lang: Python
          label: Batch Input
          source: |
            import os
            from openai import OpenAI

            client = OpenAI(
                base_url="https://api.cometapi.com/v1",
                api_key=os.environ["COMETAPI_KEY"],
            )

            response = client.embeddings.create(
                model="text-embedding-3-small",
                input=["Hello world", "How are you?", "Embedding example"],
            )

            for item in response.data:
                print(f"Index {item.index}: {len(item.embedding)} dimensions")
        - lang: Python
          label: Reduced Dimensions
          source: |
            import os
            from openai import OpenAI

            client = OpenAI(
                base_url="https://api.cometapi.com/v1",
                api_key=os.environ["COMETAPI_KEY"],
            )

            # Use fewer dimensions to reduce storage costs
            response = client.embeddings.create(
                model="text-embedding-3-small",
                input="Search query text",
                dimensions=256,
            )

            print(f"Dimensions: {len(response.data[0].embedding)}")  # 256
        - lang: JavaScript
          label: Single Text
          source: |
            import OpenAI from "openai";

            const client = new OpenAI({
                baseURL: "https://api.cometapi.com/v1",
                apiKey: process.env.COMETAPI_KEY,
            });

            const response = await client.embeddings.create({
                model: "text-embedding-3-small",
                input: "The food was delicious and the waiter was friendly.",
            });

            console.log(response.data[0].embedding.slice(0, 5));
            console.log(`Dimensions: ${response.data[0].embedding.length}`);
        - lang: JavaScript
          label: Batch Input
          source: |
            import OpenAI from "openai";

            const client = new OpenAI({
                baseURL: "https://api.cometapi.com/v1",
                apiKey: process.env.COMETAPI_KEY,
            });

            const response = await client.embeddings.create({
                model: "text-embedding-3-small",
                input: ["Hello world", "How are you?", "Embedding example"],
            });

            for (const item of response.data) {
                console.log(`Index ${item.index}: ${item.embedding.length} dimensions`);
            }
        - lang: JavaScript
          label: Reduced Dimensions
          source: >
            import OpenAI from "openai";


            const client = new OpenAI({
                baseURL: "https://api.cometapi.com/v1",
                apiKey: process.env.COMETAPI_KEY,
            });


            // Use fewer dimensions to reduce storage costs

            const response = await client.embeddings.create({
                model: "text-embedding-3-small",
                input: "Search query text",
                dimensions: 256,
            });


            console.log(`Dimensions: ${response.data[0].embedding.length}`); //
            256
        - lang: Shell
          label: Single Text
          source: |
            curl https://api.cometapi.com/v1/embeddings \
              -H "Content-Type: application/json" \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -d '{
                "model": "text-embedding-3-small",
                "input": "The food was delicious and the waiter was friendly."
              }'
        - lang: Shell
          label: Batch Input
          source: |
            curl https://api.cometapi.com/v1/embeddings \
              -H "Content-Type: application/json" \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -d '{
                "model": "text-embedding-3-small",
                "input": ["Hello world", "How are you?", "Embedding example"]
              }'
        - lang: Shell
          label: Reduced Dimensions
          source: |
            curl https://api.cometapi.com/v1/embeddings \
              -H "Content-Type: application/json" \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -d '{
                "model": "text-embedding-3-small",
                "input": "Search query text",
                "dimensions": 256
              }'
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Bearer token authentication. Use your CometAPI key.

````