> ## 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.

# テキスト埋め込み

> テキストをベクトル埋め込みに変換

# テキスト埋め込み

Embeddings APIはテキストを高次元のベクトル表現に変換し、セマンティック検索、クラスタリング、RAGアプリケーションに役立ちます。

## エンドポイント

```text theme={null}
POST https://api.mixroute.ai/v1/embeddings
```

## 認証

```text theme={null}
Authorization: Bearer sk-xxxxxxxxxx
```

## リクエストボディ

| パラメーター | 型 | 必須 | 説明 |
| - | - | - | - |
| `model` | string | はい | 埋め込みモデルID |
| `input` | string/array | はい | 埋め込み対象のテキスト（単数または複数） |
| `encoding_format` | string | いいえ | 出力形式: `float`または`base64` |
| `input_type` | string | Cohere only | search\_document、search\_query、classification、またはclustering。 |
| `dimensions` | integer | いいえ | OpenAIのtext-embedding-3など、このフィールドを公開するモデル/ルートの出力次元数です。ネイティブのCohereのoutput\_dimensionが同じ対応関係を持つとは限りません。 |

## リクエスト例

### 単一テキスト

```bash theme={null}
curl -X POST https://api.mixroute.ai/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxxxxxxxxx" \
  -d '{
    "model": "text-embedding-3-small",
    "input": "The quick brown fox jumps over the lazy dog."
  }'
```

### 複数テキストの一括処理

```bash theme={null}
curl -X POST https://api.mixroute.ai/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxxxxxxxxx" \
  -d '{
    "model": "text-embedding-3-small",
    "input": [
      "First document text",
      "Second document text",
      "Third document text"
    ]
  }'
```

## カスタム次元数

効率を高めるために埋め込みの次元数を削減します。

```bash theme={null}
curl -X POST https://api.mixroute.ai/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxxxxxxxxx" \
  -d '{
    "model": "text-embedding-3-large",
    "input": "Sample text for embedding",
    "dimensions": 512
  }'
```

## 対応モデル

| モデル | 次元数 | 説明 |
| - | - | - |
| `text-embedding-3-small` | 1536 | 高速で費用対効果に優れる |
| `text-embedding-3-large` | 3072 | より高い精度 |
| `text-embedding-ada-002` | 1536 | 旧モデル |
| `embed-v4.0` | 1536 | 長文コンテキストのテキストに対応する、多言語検索向けのCohereの埋め込みモデル。 |
| `embed-english-v3.0` | 1024 | 英語の検索に最適化されたCohereのテキスト埋め込みモデル。 |
| `embed-multilingual-v3.0` | 1024 | 言語横断検索向けのCohereテキスト埋め込みモデル。 |

## Cohereの埋め込み

保存するドキュメントには`input_type=search_document`、クエリには`search_query`を使用してください。両方でモデルと次元数を同一にしてください。テキスト互換エンドポイントは`data[].embedding`にベクトルを返します。ネイティブの画像/PDF埋め込み入力は、このテキスト入力スキーマと相互に置き換えられるものではありません。

```bash theme={null}
curl --request POST "https://api.mixroute.ai/v1/embeddings" \
  --header "Authorization: Bearer $MIXROUTE_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "embed-v4.0",
  "input": [
    "An API reference for developers."
  ],
  "input_type": "search_document",
  "encoding_format": "float"
}'
```

## 使用例

### セマンティック検索

```python theme={null}
import numpy as np

def cosine_similarity(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))

# Compare query embedding with document embeddings
similarities = [cosine_similarity(query_embedding, doc) for doc in doc_embeddings]
```

### ドキュメントのクラスタリング

```python theme={null}
from sklearn.cluster import KMeans

# Cluster documents by embedding similarity
kmeans = KMeans(n_clusters=5)
clusters = kmeans.fit_predict(embeddings)
```

## ベストプラクティス

* **バッチリクエスト**：効率化のため、1つのリクエストで複数のテキストを送信します
* **ベクトルの正規化**：一貫した類似度スコアを得るために、埋め込みを正規化します
* **次元数の選択**：ストレージ容量や速度を重視する場合は、少ない次元数を使用
* **長いテキストの分割**: 埋め込みを生成する前に、長いドキュメントを意味のある単位に分割してください

<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": "Hello, world"
    }'
  ```

  ```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="Hello, world"
  )
  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: 'Hello, world'
  });
  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' => 'Hello, world'
      ]
  ]);
  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{"Hello, world"},
          },
      )
      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": "Hello, world"
      }
      """;
  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: 'Hello, world'
  }.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>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.