214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434 | class OpenAIEmbedding(BaseEmbedding):
"""OpenAI类用于嵌入。
Args:
mode (str): 嵌入的模式。
默认为OpenAIEmbeddingMode.TEXT_SEARCH_MODE。
选项包括:
- OpenAIEmbeddingMode.SIMILARITY_MODE
- OpenAIEmbeddingMode.TEXT_SEARCH_MODE
model (str): 嵌入的模型。
默认为OpenAIEmbeddingModelType.TEXT_EMBED_ADA_002。
选项包括:
- OpenAIEmbeddingModelType.DAVINCI
- OpenAIEmbeddingModelType.CURIE
- OpenAIEmbeddingModelType.BABBAGE
- OpenAIEmbeddingModelType.ADA
- OpenAIEmbeddingModelType.TEXT_EMBED_ADA_002"""
additional_kwargs: Dict[str, Any] = Field(
default_factory=dict, description="Additional kwargs for the OpenAI API."
)
api_key: str = Field(description="The OpenAI API key.")
api_base: Optional[str] = Field(
default=DEFAULT_OPENAI_API_BASE, description="The base URL for OpenAI API."
)
api_version: Optional[str] = Field(
default=DEFAULT_OPENAI_API_VERSION, description="The version for OpenAI API."
)
max_retries: int = Field(
default=10, description="Maximum number of retries.", gte=0
)
timeout: float = Field(default=60.0, description="Timeout for each request.", gte=0)
default_headers: Optional[Dict[str, str]] = Field(
default=None, description="The default headers for API requests."
)
reuse_client: bool = Field(
default=True,
description=(
"Reuse the OpenAI client between requests. When doing anything with large "
"volumes of async API calls, setting this to false can improve stability."
),
)
dimensions: Optional[int] = Field(
default=None,
description=(
"The number of dimensions on the output embedding vectors. "
"Works only with v3 embedding models."
),
)
_query_engine: str = PrivateAttr()
_text_engine: str = PrivateAttr()
_client: Optional[OpenAI] = PrivateAttr()
_aclient: Optional[AsyncOpenAI] = PrivateAttr()
_http_client: Optional[httpx.Client] = PrivateAttr()
def __init__(
self,
mode: str = OpenAIEmbeddingMode.TEXT_SEARCH_MODE,
model: str = OpenAIEmbeddingModelType.TEXT_EMBED_ADA_002,
embed_batch_size: int = 100,
dimensions: Optional[int] = None,
additional_kwargs: Optional[Dict[str, Any]] = None,
api_key: Optional[str] = None,
api_base: Optional[str] = None,
api_version: Optional[str] = None,
max_retries: int = 10,
timeout: float = 60.0,
reuse_client: bool = True,
callback_manager: Optional[CallbackManager] = None,
default_headers: Optional[Dict[str, str]] = None,
http_client: Optional[httpx.Client] = None,
num_workers: Optional[int] = None,
**kwargs: Any,
) -> None:
additional_kwargs = additional_kwargs or {}
if dimensions is not None:
additional_kwargs["dimensions"] = dimensions
api_key, api_base, api_version = self._resolve_credentials(
api_key=api_key,
api_base=api_base,
api_version=api_version,
)
self._query_engine = get_engine(mode, model, _QUERY_MODE_MODEL_DICT)
self._text_engine = get_engine(mode, model, _TEXT_MODE_MODEL_DICT)
if "model_name" in kwargs:
model_name = kwargs.pop("model_name")
self._query_engine = self._text_engine = model_name
else:
model_name = model
super().__init__(
embed_batch_size=embed_batch_size,
dimensions=dimensions,
callback_manager=callback_manager,
model_name=model_name,
additional_kwargs=additional_kwargs,
api_key=api_key,
api_base=api_base,
api_version=api_version,
max_retries=max_retries,
reuse_client=reuse_client,
timeout=timeout,
default_headers=default_headers,
num_workers=num_workers,
**kwargs,
)
self._client = None
self._aclient = None
self._http_client = http_client
def _resolve_credentials(
self,
api_key: Optional[str] = None,
api_base: Optional[str] = None,
api_version: Optional[str] = None,
) -> Tuple[Optional[str], str, str]:
return resolve_openai_credentials(api_key, api_base, api_version)
def _get_client(self) -> OpenAI:
if not self.reuse_client:
return OpenAI(**self._get_credential_kwargs())
if self._client is None:
self._client = OpenAI(**self._get_credential_kwargs())
return self._client
def _get_aclient(self) -> AsyncOpenAI:
if not self.reuse_client:
return AsyncOpenAI(**self._get_credential_kwargs())
if self._aclient is None:
self._aclient = AsyncOpenAI(**self._get_credential_kwargs())
return self._aclient
@classmethod
def class_name(cls) -> str:
return "OpenAIEmbedding"
def _get_credential_kwargs(self) -> Dict[str, Any]:
return {
"api_key": self.api_key,
"base_url": self.api_base,
"max_retries": self.max_retries,
"timeout": self.timeout,
"default_headers": self.default_headers,
"http_client": self._http_client,
}
def _get_query_embedding(self, query: str) -> List[float]:
"""获取查询嵌入。"""
client = self._get_client()
return get_embedding(
client,
query,
engine=self._query_engine,
**self.additional_kwargs,
)
async def _aget_query_embedding(self, query: str) -> List[float]:
"""_get_query_embedding的异步版本。"""
aclient = self._get_aclient()
return await aget_embedding(
aclient,
query,
engine=self._query_engine,
**self.additional_kwargs,
)
def _get_text_embedding(self, text: str) -> List[float]:
"""获取文本嵌入。"""
client = self._get_client()
return get_embedding(
client,
text,
engine=self._text_engine,
**self.additional_kwargs,
)
async def _aget_text_embedding(self, text: str) -> List[float]:
"""异步获取文本嵌入。"""
aclient = self._get_aclient()
return await aget_embedding(
aclient,
text,
engine=self._text_engine,
**self.additional_kwargs,
)
def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""获取文本嵌入。
默认情况下,这是对_get_text_embedding的包装器。
可以针对批量查询进行重写。
"""
client = self._get_client()
return get_embeddings(
client,
texts,
engine=self._text_engine,
**self.additional_kwargs,
)
async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""异步获取文本嵌入。"""
aclient = self._get_aclient()
return await aget_embeddings(
aclient,
texts,
engine=self._text_engine,
**self.additional_kwargs,
)
|