Skip to content

文本嵌入

将文本转换为数值向量表示,用于语义搜索、聚类和推荐。

创建嵌入

POST https://ciyuanx.io/v1/embeddings

bash
curl https://ciyuanx.io/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "text-embedding-3-small",
    "input": "Your text here"
  }'
python
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://ciyuanx.io/v1",
)

response = client.embeddings.create(
    model="text-embedding-3-small",
    input="Your text here",
)

embedding = response.data[0].embedding
print(f"Embedding dimension: {len(embedding)}")
typescript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: "YOUR_API_KEY",
  baseURL: "https://ciyuanx.io/v1",
});

const response = await client.embeddings.create({
  model: "text-embedding-3-small",
  input: "Your text here",
});

console.log(`Embedding dimension: ${response.data[0].embedding.length}`);

请求参数

参数类型必需描述
modelstring要使用的嵌入模型 ID
inputstring 或 array要嵌入的文本,可以是单个字符串或字符串数组
dimensionsinteger输出嵌入的维度数(仅 text-embedding-3 及更新的模型支持)
encoding_formatstring返回格式,float(默认)或 base64

响应

响应在 data 数组中返回嵌入向量:

json
{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": [0.0023, -0.0091, 0.0145, "..."]
    }
  ],
  "model": "text-embedding-3-small",
  "usage": {
    "prompt_tokens": 5,
    "total_tokens": 5
  }
}

最佳实践

高效使用嵌入

  • 批量处理时,在 input 中传入字符串数组以减少请求次数
  • 缓存常用文本的嵌入结果,避免重复计算
  • 计算相似度时使用余弦相似度比较向量

提示

使用嵌入进行语义搜索、文档相似性和推荐系统。