22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182 | class JinaEmbedding(BaseEmbedding):
"""JinaAI类用于嵌入。
Args:
model(str):用于嵌入的模型。
默认为`jina-embeddings-v2-base-en`"""
api_key: str = Field(default=None, description="The JinaAI API key.")
model: str = Field(
default="jina-embeddings-v2-base-en",
description="The model to use when calling Jina AI API",
)
_session: Any = PrivateAttr()
_encoding_queries: str = PrivateAttr()
_encoding_documents: str = PrivateAttr()
def __init__(
self,
model: str = "jina-embeddings-v2-base-en",
embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE,
api_key: Optional[str] = None,
callback_manager: Optional[CallbackManager] = None,
encoding_queries: Optional[str] = None,
encoding_documents: Optional[str] = None,
**kwargs: Any,
) -> None:
super().__init__(
embed_batch_size=embed_batch_size,
callback_manager=callback_manager,
model=model,
api_key=api_key,
**kwargs,
)
self._encoding_queries = encoding_queries or "float"
self._encoding_documents = encoding_documents or "float"
assert (
self._encoding_documents in VALID_ENCODING
), f"Encoding Documents parameter {self._encoding_documents} not supported. Please choose one of {VALID_ENCODING}"
assert (
self._encoding_queries in VALID_ENCODING
), f"Encoding Queries parameter {self._encoding_documents} not supported. Please choose one of {VALID_ENCODING}"
self.api_key = get_from_param_or_env("api_key", api_key, "JINAAI_API_KEY", "")
self.model = model
self._session = requests.Session()
self._session.headers.update(
{"Authorization": f"Bearer {api_key}", "Accept-Encoding": "identity"}
)
@classmethod
def class_name(cls) -> str:
return "JinaAIEmbedding"
def _get_query_embedding(self, query: str) -> List[float]:
"""获取查询嵌入。"""
return self._get_embeddings([query], encoding_type=self._encoding_queries)[0]
async def _aget_query_embedding(self, query: str) -> List[float]:
"""_get_query_embedding的异步版本。"""
result = await self._aget_embeddings(
[query], encoding_type=self._encoding_queries
)
return result[0]
def _get_text_embedding(self, text: str) -> List[float]:
"""获取文本嵌入。"""
return self._get_text_embeddings([text])[0]
async def _aget_text_embedding(self, text: str) -> List[float]:
"""异步获取文本嵌入。"""
result = await self._aget_text_embeddings([text])
return result[0]
def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
return self._get_embeddings(texts=texts, encoding_type=self._encoding_documents)
async def _aget_text_embeddings(
self,
texts: List[str],
) -> List[List[float]]:
return await self._aget_embeddings(
texts=texts, encoding_type=self._encoding_documents
)
def _get_embeddings(
self, texts: List[str], encoding_type: str = "float"
) -> List[List[float]]:
"""获取嵌入。"""
# Call Jina AI Embedding API
resp = self._session.post( # type: ignore
API_URL,
json={"input": texts, "model": self.model, "encoding_type": encoding_type},
).json()
if "data" not in resp:
raise RuntimeError(resp["detail"])
embeddings = resp["data"]
# Sort resulting embeddings by index
sorted_embeddings = sorted(embeddings, key=lambda e: e["index"]) # type: ignore
# Return just the embeddings
if encoding_type == "ubinary":
return [
np.unpackbits(np.array(result["embedding"], dtype="uint8")).tolist()
for result in sorted_embeddings
]
elif encoding_type == "binary":
return [
np.unpackbits(
(np.array(result["embedding"]) + 128).astype("uint8")
).tolist()
for result in sorted_embeddings
]
return [result["embedding"] for result in sorted_embeddings]
async def _aget_embeddings(
self, texts: List[str], encoding_type: str = "float"
) -> List[List[float]]:
"""异步获取文本嵌入。"""
import aiohttp
async with aiohttp.ClientSession(trust_env=True) as session:
headers = {
"Authorization": f"Bearer {self.api_key}",
"Accept-Encoding": "identity",
}
async with session.post(
f"{API_URL}",
json={
"input": texts,
"model": self.model,
"encoding_type": encoding_type,
},
headers=headers,
) as response:
resp = await response.json()
response.raise_for_status()
embeddings = resp["data"]
# Sort resulting embeddings by index
sorted_embeddings = sorted(embeddings, key=lambda e: e["index"]) # type: ignore
# Return just the embeddings
if encoding_type == "ubinary":
return [
np.unpackbits(
np.array(result["embedding"], dtype="uint8")
).tolist()
for result in sorted_embeddings
]
elif encoding_type == "binary":
return [
np.unpackbits(
(np.array(result["embedding"]) + 128).astype("uint8")
).tolist()
for result in sorted_embeddings
]
return [result["embedding"] for result in sorted_embeddings]
|