EmbedText 调用 OpenAI 兼容的 embeddings 接口。
(ctx context.Context, texts []string)
| 53 | |
| 54 | // EmbedText 调用 OpenAI 兼容的 embeddings 接口。 |
| 55 | func (e *OpenAIEmbedder) EmbedText(ctx context.Context, texts []string) ([][]float32, error) { |
| 56 | if len(texts) == 0 { |
| 57 | return [][]float32{}, nil |
| 58 | } |
| 59 | if e.APIKey == "" { |
| 60 | return nil, errors.New("API key is required for OpenAIEmbedder") |
| 61 | } |
| 62 | |
| 63 | reqBody := openAIEmbeddingRequest{ |
| 64 | Input: texts, |
| 65 | Model: e.Model, |
| 66 | } |
| 67 | data, err := json.Marshal(reqBody) |
| 68 | if err != nil { |
| 69 | return nil, fmt.Errorf("marshal request: %w", err) |
| 70 | } |
| 71 | |
| 72 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, e.BaseURL+"/v1/embeddings", bytes.NewReader(data)) |
| 73 | if err != nil { |
| 74 | return nil, fmt.Errorf("create request: %w", err) |
| 75 | } |
| 76 | |
| 77 | req.Header.Set("Content-Type", "application/json") |
| 78 | req.Header.Set("Authorization", "Bearer "+e.APIKey) |
| 79 | |
| 80 | resp, err := e.Client.Do(req) |
| 81 | if err != nil { |
| 82 | return nil, fmt.Errorf("send request: %w", err) |
| 83 | } |
| 84 | defer func() { _ = resp.Body.Close() }() |
| 85 | |
| 86 | if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 87 | return nil, fmt.Errorf("embeddings API error: %s", resp.Status) |
| 88 | } |
| 89 | |
| 90 | var apiResp openAIEmbeddingResponse |
| 91 | if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil { |
| 92 | return nil, fmt.Errorf("decode response: %w", err) |
| 93 | } |
| 94 | |
| 95 | if len(apiResp.Data) != len(texts) { |
| 96 | return nil, fmt.Errorf("embedding response mismatch: got %d vectors, want %d", len(apiResp.Data), len(texts)) |
| 97 | } |
| 98 | |
| 99 | out := make([][]float32, len(apiResp.Data)) |
| 100 | for i, d := range apiResp.Data { |
| 101 | vec := make([]float32, len(d.Embedding)) |
| 102 | for j, v := range d.Embedding { |
| 103 | vec[j] = float32(v) |
| 104 | } |
| 105 | out[i] = vec |
| 106 | } |
| 107 | |
| 108 | return out, nil |
| 109 | } |