# openai.BadRequestError: 向量长度必须为1以计算余弦相似度

- **ID:** `llm/embedding-vector-normalization-mismatch`
- **领域:** llm
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

OpenAI 的嵌入 API 默认返回单位归一化向量，但自定义嵌入模型或手动预处理可能产生未归一化的向量，导致余弦相似度计算失败或返回错误结果。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| openai==1.3.0 | active | — | — |
| openai==1.12.0 | active | — | — |
| text-embedding-ada-002 | active | — | — |
| text-embedding-3-small | active | — | — |
| text-embedding-3-large | active | — | — |

## 解决方案

1. ```
   在插入或查询前手动归一化向量：`vector = vector / np.linalg.norm(vector)`
   ```
2. ```
   使用 OpenAI 默认的嵌入（已归一化），除非必要，否则避免自定义模型或手动归一化。
   ```
3. ```
   如果支持，将向量数据库配置为使用内积距离代替余弦相似度（例如，在 Pinecone 或 Weaviate 中设置 `metric='ip'`）。
   ```

## 无效尝试

- **** — Different embedding models produce vectors with different normalization properties; the root cause is not the model but the normalization step. (65% 失败率)
- **** — Dimension is unrelated to normalization; padding introduces noise and doesn't fix the length constraint. (80% 失败率)
