950a640e
tangwang
embeddings
|
1
|
"""Text embedding client for the local embedding HTTP service."""
|
be52af70
tangwang
first commit
|
2
|
|
950a640e
tangwang
embeddings
|
3
|
import logging
|
950a640e
tangwang
embeddings
|
4
5
|
from datetime import timedelta
from typing import Any, List, Optional, Union
|
be52af70
tangwang
first commit
|
6
|
|
be52af70
tangwang
first commit
|
7
|
import numpy as np
|
950a640e
tangwang
embeddings
|
8
|
import requests
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
9
10
|
logger = logging.getLogger(__name__)
|
be52af70
tangwang
first commit
|
11
|
|
7214c2e7
tangwang
mplemented**
|
12
13
|
from config.services_config import get_embedding_text_base_url
from embeddings.cache_keys import build_text_cache_key
|
4a37d233
tangwang
1. embedding cach...
|
14
|
from embeddings.redis_embedding_cache import RedisEmbeddingCache
|
42e3aea6
tangwang
tidy
|
15
|
|
453992a8
tangwang
需求:
|
16
|
# Try to import REDIS_CONFIG, but allow import to fail
|
3d588bef
tangwang
embeddings
|
17
|
from config.env_config import REDIS_CONFIG
|
be52af70
tangwang
first commit
|
18
|
|
7214c2e7
tangwang
mplemented**
|
19
|
|
950a640e
tangwang
embeddings
|
20
|
class TextEmbeddingEncoder:
|
be52af70
tangwang
first commit
|
21
|
"""
|
950a640e
tangwang
embeddings
|
22
|
Text embedding encoder using network service.
|
be52af70
tangwang
first commit
|
23
|
"""
|
be52af70
tangwang
first commit
|
24
|
|
950a640e
tangwang
embeddings
|
25
|
def __init__(self, service_url: Optional[str] = None):
|
af03fdef
tangwang
embedding模块代码整理
|
26
|
resolved_url = service_url or get_embedding_text_base_url()
|
950a640e
tangwang
embeddings
|
27
28
29
|
self.service_url = str(resolved_url).rstrip("/")
self.endpoint = f"{self.service_url}/embed/text"
self.expire_time = timedelta(days=REDIS_CONFIG.get("cache_expire_days", 180))
|
3d588bef
tangwang
embeddings
|
30
|
self.cache_prefix = str(REDIS_CONFIG.get("embedding_cache_prefix", "embedding")).strip() or "embedding"
|
950a640e
tangwang
embeddings
|
31
32
|
logger.info("Creating TextEmbeddingEncoder instance with service URL: %s", self.service_url)
|
4a37d233
tangwang
1. embedding cach...
|
33
34
35
36
37
|
self.cache = RedisEmbeddingCache(
key_prefix=self.cache_prefix,
namespace="",
expire_time=self.expire_time,
)
|
be52af70
tangwang
first commit
|
38
|
|
200fdddf
tangwang
embed norm
|
39
|
def _call_service(self, request_data: List[str], normalize_embeddings: bool = True) -> List[Any]:
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
40
41
42
43
|
"""
Call the embedding service API.
Args:
|
7bfb9946
tangwang
向量化模块
|
44
|
request_data: List of texts
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
45
46
|
Returns:
|
7bfb9946
tangwang
向量化模块
|
47
|
List of embeddings (list[float]) or nulls (None), aligned to input order
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
48
49
50
51
|
"""
try:
response = requests.post(
self.endpoint,
|
200fdddf
tangwang
embed norm
|
52
|
params={"normalize": "true" if normalize_embeddings else "false"},
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
53
54
55
56
57
58
|
json=request_data,
timeout=60
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
|
950a640e
tangwang
embeddings
|
59
|
logger.error(f"TextEmbeddingEncoder service request failed: {e}", exc_info=True)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
60
61
|
raise
|
be52af70
tangwang
first commit
|
62
63
64
65
|
def encode(
self,
sentences: Union[str, List[str]],
normalize_embeddings: bool = True,
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
66
|
device: str = 'cpu',
|
be52af70
tangwang
first commit
|
67
68
69
|
batch_size: int = 32
) -> np.ndarray:
"""
|
453992a8
tangwang
需求:
|
70
|
Encode text into embeddings via network service with Redis caching.
|
be52af70
tangwang
first commit
|
71
72
73
|
Args:
sentences: Single string or list of strings to encode
|
200fdddf
tangwang
embed norm
|
74
|
normalize_embeddings: Whether to request normalized embeddings from service
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
75
76
|
device: Device parameter ignored for service compatibility
batch_size: Batch size for processing (used for service requests)
|
be52af70
tangwang
first commit
|
77
78
|
Returns:
|
ed948666
tangwang
tidy
|
79
80
|
numpy array of dtype=object,元素均为有效 np.ndarray 向量。
若任一输入无法生成向量,将直接抛出异常。
|
be52af70
tangwang
first commit
|
81
|
"""
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
82
83
84
|
# Convert single string to list
if isinstance(sentences, str):
sentences = [sentences]
|
be52af70
tangwang
first commit
|
85
|
|
453992a8
tangwang
需求:
|
86
|
# Check cache first
|
b2e50710
tangwang
BgeEncoder.encode...
|
87
88
|
uncached_indices: List[int] = []
uncached_texts: List[str] = []
|
453992a8
tangwang
需求:
|
89
|
|
70a318c6
tangwang
fix bug
|
90
|
embeddings: List[Optional[np.ndarray]] = [None] * len(sentences)
|
70a318c6
tangwang
fix bug
|
91
|
for i, text in enumerate(sentences):
|
7214c2e7
tangwang
mplemented**
|
92
|
cached = self._get_cached_embedding(text, normalize_embeddings=normalize_embeddings)
|
70a318c6
tangwang
fix bug
|
93
94
95
96
97
98
99
|
if cached is not None:
embeddings[i] = cached
else:
uncached_indices.append(i)
uncached_texts.append(text)
# Prepare request data for uncached texts (after cache check)
|
7bfb9946
tangwang
向量化模块
|
100
|
request_data = list(uncached_texts)
|
453992a8
tangwang
需求:
|
101
102
103
|
# If there are uncached texts, call service
if uncached_texts:
|
200fdddf
tangwang
embed norm
|
104
|
response_data = self._call_service(request_data, normalize_embeddings=normalize_embeddings)
|
453992a8
tangwang
需求:
|
105
|
|
ed948666
tangwang
tidy
|
106
107
108
109
110
111
112
|
# Process response
for i, text in enumerate(uncached_texts):
original_idx = uncached_indices[i]
if response_data and i < len(response_data):
embedding = response_data[i]
else:
embedding = None
|
7bfb9946
tangwang
向量化模块
|
113
|
|
ed948666
tangwang
tidy
|
114
115
116
117
|
if embedding is not None:
embedding_array = np.array(embedding, dtype=np.float32)
if self._is_valid_embedding(embedding_array):
embeddings[original_idx] = embedding_array
|
7214c2e7
tangwang
mplemented**
|
118
119
120
121
122
|
self._set_cached_embedding(
text,
embedding_array,
normalize_embeddings=normalize_embeddings,
)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
123
|
else:
|
ed948666
tangwang
tidy
|
124
125
126
127
128
|
raise ValueError(
f"Invalid embedding returned from service for text index {original_idx}"
)
else:
raise ValueError(f"No embedding found for text index {original_idx}: {text[:50]}...")
|
453992a8
tangwang
需求:
|
129
|
|
77516841
tangwang
tidy embeddings
|
130
|
# 返回 numpy 数组(dtype=object),元素均为有效 np.ndarray 向量
|
b2e50710
tangwang
BgeEncoder.encode...
|
131
|
return np.array(embeddings, dtype=object)
|
3d588bef
tangwang
embeddings
|
132
|
|
b2e50710
tangwang
BgeEncoder.encode...
|
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
|
def _is_valid_embedding(self, embedding: np.ndarray) -> bool:
"""
Check if embedding is valid (not None, correct shape, no NaN/Inf).
Args:
embedding: Embedding array to validate
Returns:
True if valid, False otherwise
"""
if embedding is None:
return False
if not isinstance(embedding, np.ndarray):
return False
if embedding.size == 0:
return False
# Check for NaN or Inf values
if not np.isfinite(embedding).all():
return False
return True
|
200fdddf
tangwang
embed norm
|
154
155
|
def _get_cached_embedding(
self,
|
4a37d233
tangwang
1. embedding cach...
|
156
|
query: str,
|
7214c2e7
tangwang
mplemented**
|
157
158
|
*,
normalize_embeddings: bool,
|
200fdddf
tangwang
embed norm
|
159
|
) -> Optional[np.ndarray]:
|
4a37d233
tangwang
1. embedding cach...
|
160
|
"""Get embedding from cache if exists (with sliding expiration)."""
|
5bac9649
tangwang
文本 embedding 与图片 ...
|
161
162
|
cache_key = build_text_cache_key(query, normalize=normalize_embeddings)
embedding = self.cache.get(cache_key)
|
4a37d233
tangwang
1. embedding cach...
|
163
|
if embedding is not None:
|
7214c2e7
tangwang
mplemented**
|
164
|
logger.debug(
|
5bac9649
tangwang
文本 embedding 与图片 ...
|
165
|
"Cache hit for text embedding | normalize=%s query=%s key=%s",
|
7214c2e7
tangwang
mplemented**
|
166
167
|
normalize_embeddings,
query,
|
5bac9649
tangwang
文本 embedding 与图片 ...
|
168
|
cache_key,
|
7214c2e7
tangwang
mplemented**
|
169
|
)
|
4a37d233
tangwang
1. embedding cach...
|
170
|
return embedding
|
453992a8
tangwang
需求:
|
171
|
|
200fdddf
tangwang
embed norm
|
172
173
174
|
def _set_cached_embedding(
self,
query: str,
|
200fdddf
tangwang
embed norm
|
175
|
embedding: np.ndarray,
|
7214c2e7
tangwang
mplemented**
|
176
177
|
*,
normalize_embeddings: bool,
|
200fdddf
tangwang
embed norm
|
178
|
) -> bool:
|
4a37d233
tangwang
1. embedding cach...
|
179
|
"""Store embedding in cache."""
|
7214c2e7
tangwang
mplemented**
|
180
|
ok = self.cache.set(build_text_cache_key(query, normalize=normalize_embeddings), embedding)
|
4a37d233
tangwang
1. embedding cach...
|
181
|
if ok:
|
7214c2e7
tangwang
mplemented**
|
182
183
184
185
186
|
logger.debug(
"Successfully cached text embedding | normalize=%s query=%s",
normalize_embeddings,
query,
)
|
4a37d233
tangwang
1. embedding cach...
|
187
|
return ok
|