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

# 文字向量化（Embedding）

> 將文字轉換為向量嵌入，適用於語意搜尋、文字相似度計算、聚類分析等情境

## 簡介

將文字轉換為向量嵌入，適用於語意搜尋、文字相似度計算、聚類分析等情境。

## 認證

Bearer Token，如 `Bearer sk-xxxxxxxxxx`

## 請求參數

<ParamField body="model" type="string" required>
  模型名稱，如 `text-embedding-3-small`、`text-embedding-3-large`
</ParamField>

<ParamField body="input" type="string | array" required>
  要嵌入的文字，可以是字串或字串陣列
</ParamField>

<ParamField body="encoding_format" type="string">
  回傳格式：`float` 或 `base64`
</ParamField>

<ParamField body="dimensions" type="integer">
  輸出向量維度（僅部分模型支援）
</ParamField>

## cURL 範例

```bash theme={null}
curl https://api.mixroute.ai/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxxxxxxxxx" \
  -d '{
    "model": "text-embedding-3-small",
    "input": "你好，世界"
  }'
```

## Python 範例

```python theme={null}
from openai import OpenAI

client = OpenAI(
    api_key="sk-xxxxxxxxxx",
    base_url="https://api.mixroute.ai/v1"
)

response = client.embeddings.create(
    model="text-embedding-3-small",
    input="你好，世界"
)

print(response.data[0].embedding)
print(f"向量維度：{len(response.data[0].embedding)}")
```

## 支援的模型

| 模型                     | 維度   | 說明              |
| ---------------------- | ---- | --------------- |
| text-embedding-3-small | 1536 | 高性價比，適合大多數情境    |
| text-embedding-3-large | 3072 | 高精度，適合對精度要求高的情境 |
| text-embedding-ada-002 | 1536 | 舊版模型            |

## 注意事項

* 部分模型支援透過 `dimensions` 參數自訂輸出維度
* 批次嵌入時，`input` 可傳入字串陣列

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.mixroute.ai/v1/embeddings \
    --header 'Authorization: Bearer sk-xxxxxxxxxx' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "text-embedding-3-small",
      "input": "你好，世界"
    }'
  ```

  ```python Python theme={null}
  from openai import OpenAI

  client = OpenAI(
      api_key="sk-xxxxxxxxxx",
      base_url="https://api.mixroute.ai/v1"
  )

  response = client.embeddings.create(
      model="text-embedding-3-small",
      input="你好，世界"
  )
  print(response.data[0].embedding)
  ```

  ```javascript JavaScript theme={null}
  const OpenAI = require('openai');

  const client = new OpenAI({
    apiKey: 'sk-xxxxxxxxxx',
    baseURL: 'https://api.mixroute.ai/v1'
  });

  const response = await client.embeddings.create({
    model: 'text-embedding-3-small',
    input: '你好，世界'
  });
  console.log(response.data[0].embedding);
  ```

  ```php PHP theme={null}
  <?php
  $client = new GuzzleHttp\Client();
  $response = $client->post('https://api.mixroute.ai/v1/embeddings', [
      'headers' => [
          'Authorization' => 'Bearer sk-xxxxxxxxxx',
          'Content-Type' => 'application/json',
      ],
      'json' => [
          'model' => 'text-embedding-3-small',
          'input' => '你好，世界'
      ]
  ]);
  echo $response->getBody();
  ```

  ```go Go theme={null}
  package main

  import (
      "context"
      "fmt"
      openai "github.com/sashabaranov/go-openai"
  )

  func main() {
      config := openai.DefaultConfig("sk-xxxxxxxxxx")
      config.BaseURL = "https://api.mixroute.ai/v1"
      client := openai.NewClientWithConfig(config)

      resp, _ := client.CreateEmbeddings(
          context.Background(),
          openai.EmbeddingRequest{
              Model: "text-embedding-3-small",
              Input: []string{"你好，世界"},
          },
      )
      fmt.Println(resp.Data[0].Embedding)
  }
  ```

  ```java Java theme={null}
  import java.net.http.*;
  import java.net.URI;

  HttpClient client = HttpClient.newHttpClient();
  String json = """
      {
        "model": "text-embedding-3-small",
        "input": "你好，世界"
      }
      """;
  HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("https://api.mixroute.ai/v1/embeddings"))
      .header("Authorization", "Bearer sk-xxxxxxxxxx")
      .header("Content-Type", "application/json")
      .POST(HttpRequest.BodyPublishers.ofString(json))
      .build();
  HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
  System.out.println(response.body());
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'

  uri = URI('https://api.mixroute.ai/v1/embeddings')
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri)
  request['Authorization'] = 'Bearer sk-xxxxxxxxxx'
  request['Content-Type'] = 'application/json'
  request.body = {
    model: 'text-embedding-3-small',
    input: '你好，世界'
  }.to_json

  response = http.request(request)
  puts response.body
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "object": "list",
    "data": [
      {
        "object": "embedding",
        "index": 0,
        "embedding": [0.0023064255, -0.009327292, 0.015797347, ...]
      }
    ],
    "model": "text-embedding-3-small",
    "usage": {
      "prompt_tokens": 5,
      "total_tokens": 5
    }
  }
  ```
</ResponseExample>
