2025-04-17 10:01:33 +00:00
|
|
|
|
# coding=utf-8
|
|
|
|
|
|
"""
|
|
|
|
|
|
@project: MaxKB
|
|
|
|
|
|
@Author:虎
|
|
|
|
|
|
@file: embedding.py
|
|
|
|
|
|
@date:2024/7/12 17:44
|
|
|
|
|
|
@desc:
|
|
|
|
|
|
"""
|
|
|
|
|
|
from typing import Dict, List
|
|
|
|
|
|
|
|
|
|
|
|
import openai
|
|
|
|
|
|
|
|
|
|
|
|
from models_provider.base_model_provider import MaxKBBaseModel
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class OpenAIEmbeddingModel(MaxKBBaseModel):
|
|
|
|
|
|
model_name: str
|
2025-09-28 04:03:03 +00:00
|
|
|
|
optional_params: dict
|
2025-04-17 10:01:33 +00:00
|
|
|
|
|
2025-09-28 04:03:03 +00:00
|
|
|
|
def __init__(self, api_key, base_url, model_name: str, optional_params: dict):
|
2025-04-17 10:01:33 +00:00
|
|
|
|
self.client = openai.OpenAI(api_key=api_key, base_url=base_url).embeddings
|
|
|
|
|
|
self.model_name = model_name
|
2025-09-28 04:03:03 +00:00
|
|
|
|
self.optional_params = optional_params
|
2025-10-22 04:30:47 +00:00
|
|
|
|
|
|
|
|
|
|
def is_cache_model(self):
|
|
|
|
|
|
return False
|
2025-04-17 10:01:33 +00:00
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def new_instance(model_type, model_name, model_credential: Dict[str, object], **model_kwargs):
|
2025-09-28 04:03:03 +00:00
|
|
|
|
optional_params = MaxKBBaseModel.filter_optional_params(model_kwargs)
|
2025-04-17 10:01:33 +00:00
|
|
|
|
return OpenAIEmbeddingModel(
|
|
|
|
|
|
api_key=model_credential.get('api_key'),
|
|
|
|
|
|
model_name=model_name,
|
|
|
|
|
|
base_url=model_credential.get('api_base'),
|
2025-09-28 04:03:03 +00:00
|
|
|
|
optional_params=optional_params
|
2025-04-17 10:01:33 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def embed_query(self, text: str):
|
|
|
|
|
|
res = self.embed_documents([text])
|
|
|
|
|
|
return res[0]
|
|
|
|
|
|
|
|
|
|
|
|
def embed_documents(
|
|
|
|
|
|
self, texts: List[str], chunk_size: int | None = None
|
|
|
|
|
|
) -> List[List[float]]:
|
2025-09-28 04:03:03 +00:00
|
|
|
|
if len(self.optional_params) > 0:
|
|
|
|
|
|
res = self.client.create(
|
|
|
|
|
|
input=texts, model=self.model_name, encoding_format="float",
|
|
|
|
|
|
**self.optional_params
|
|
|
|
|
|
)
|
|
|
|
|
|
else:
|
|
|
|
|
|
res = self.client.create(input=texts, model=self.model_name, encoding_format="float")
|
2025-04-17 10:01:33 +00:00
|
|
|
|
return [e.embedding for e in res.data]
|