Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import re
  17. from typing import Optional
  18. import threading
  19. import requests
  20. from huggingface_hub import snapshot_download
  21. from zhipuai import ZhipuAI
  22. import os
  23. from abc import ABC
  24. from ollama import Client
  25. import dashscope
  26. from openai import OpenAI
  27. from FlagEmbedding import FlagModel
  28. import torch
  29. import numpy as np
  30. import asyncio
  31. from api.utils.file_utils import get_home_cache_dir
  32. from rag.utils import num_tokens_from_string, truncate
  33. class Base(ABC):
  34. def __init__(self, key, model_name):
  35. pass
  36. def encode(self, texts: list, batch_size=32):
  37. raise NotImplementedError("Please implement encode method!")
  38. def encode_queries(self, text: str):
  39. raise NotImplementedError("Please implement encode method!")
  40. class DefaultEmbedding(Base):
  41. _model = None
  42. _model_lock = threading.Lock()
  43. def __init__(self, key, model_name, **kwargs):
  44. """
  45. If you have trouble downloading HuggingFace models, -_^ this might help!!
  46. For Linux:
  47. export HF_ENDPOINT=https://hf-mirror.com
  48. For Windows:
  49. Good luck
  50. ^_-
  51. """
  52. if not DefaultEmbedding._model:
  53. with DefaultEmbedding._model_lock:
  54. if not DefaultEmbedding._model:
  55. try:
  56. DefaultEmbedding._model = FlagModel(os.path.join(get_home_cache_dir(), re.sub(r"^[a-zA-Z]+/", "", model_name)),
  57. query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:",
  58. use_fp16=torch.cuda.is_available())
  59. except Exception as e:
  60. model_dir = snapshot_download(repo_id="BAAI/bge-large-zh-v1.5",
  61. local_dir=os.path.join(get_home_cache_dir(), re.sub(r"^[a-zA-Z]+/", "", model_name)),
  62. local_dir_use_symlinks=False)
  63. DefaultEmbedding._model = FlagModel(model_dir,
  64. query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:",
  65. use_fp16=torch.cuda.is_available())
  66. self._model = DefaultEmbedding._model
  67. def encode(self, texts: list, batch_size=32):
  68. texts = [truncate(t, 2048) for t in texts]
  69. token_count = 0
  70. for t in texts:
  71. token_count += num_tokens_from_string(t)
  72. res = []
  73. for i in range(0, len(texts), batch_size):
  74. res.extend(self._model.encode(texts[i:i + batch_size]).tolist())
  75. return np.array(res), token_count
  76. def encode_queries(self, text: str):
  77. token_count = num_tokens_from_string(text)
  78. return self._model.encode_queries([text]).tolist()[0], token_count
  79. class OpenAIEmbed(Base):
  80. def __init__(self, key, model_name="text-embedding-ada-002",
  81. base_url="https://api.openai.com/v1"):
  82. if not base_url:
  83. base_url = "https://api.openai.com/v1"
  84. self.client = OpenAI(api_key=key, base_url=base_url)
  85. self.model_name = model_name
  86. def encode(self, texts: list, batch_size=32):
  87. texts = [truncate(t, 8196) for t in texts]
  88. res = self.client.embeddings.create(input=texts,
  89. model=self.model_name)
  90. return np.array([d.embedding for d in res.data]
  91. ), res.usage.total_tokens
  92. def encode_queries(self, text):
  93. res = self.client.embeddings.create(input=[truncate(text, 8196)],
  94. model=self.model_name)
  95. return np.array(res.data[0].embedding), res.usage.total_tokens
  96. class BaiChuanEmbed(OpenAIEmbed):
  97. def __init__(self, key,
  98. model_name='Baichuan-Text-Embedding',
  99. base_url='https://api.baichuan-ai.com/v1'):
  100. if not base_url:
  101. base_url = "https://api.baichuan-ai.com/v1"
  102. super().__init__(key, model_name, base_url)
  103. class QWenEmbed(Base):
  104. def __init__(self, key, model_name="text_embedding_v2", **kwargs):
  105. dashscope.api_key = key
  106. self.model_name = model_name
  107. def encode(self, texts: list, batch_size=10):
  108. import dashscope
  109. try:
  110. res = []
  111. token_count = 0
  112. texts = [truncate(t, 2048) for t in texts]
  113. for i in range(0, len(texts), batch_size):
  114. resp = dashscope.TextEmbedding.call(
  115. model=self.model_name,
  116. input=texts[i:i + batch_size],
  117. text_type="document"
  118. )
  119. embds = [[] for _ in range(len(resp["output"]["embeddings"]))]
  120. for e in resp["output"]["embeddings"]:
  121. embds[e["text_index"]] = e["embedding"]
  122. res.extend(embds)
  123. token_count += resp["usage"]["total_tokens"]
  124. return np.array(res), token_count
  125. except Exception as e:
  126. raise Exception("Account abnormal. Please ensure it's on good standing to use QWen's "+self.model_name)
  127. return np.array([]), 0
  128. def encode_queries(self, text):
  129. try:
  130. resp = dashscope.TextEmbedding.call(
  131. model=self.model_name,
  132. input=text[:2048],
  133. text_type="query"
  134. )
  135. return np.array(resp["output"]["embeddings"][0]
  136. ["embedding"]), resp["usage"]["total_tokens"]
  137. except Exception as e:
  138. raise Exception("Account abnormal. Please ensure it's on good standing to use QWen's "+self.model_name)
  139. return np.array([]), 0
  140. class ZhipuEmbed(Base):
  141. def __init__(self, key, model_name="embedding-2", **kwargs):
  142. self.client = ZhipuAI(api_key=key)
  143. self.model_name = model_name
  144. def encode(self, texts: list, batch_size=32):
  145. arr = []
  146. tks_num = 0
  147. for txt in texts:
  148. res = self.client.embeddings.create(input=txt,
  149. model=self.model_name)
  150. arr.append(res.data[0].embedding)
  151. tks_num += res.usage.total_tokens
  152. return np.array(arr), tks_num
  153. def encode_queries(self, text):
  154. res = self.client.embeddings.create(input=text,
  155. model=self.model_name)
  156. return np.array(res.data[0].embedding), res.usage.total_tokens
  157. class OllamaEmbed(Base):
  158. def __init__(self, key, model_name, **kwargs):
  159. self.client = Client(host=kwargs["base_url"])
  160. self.model_name = model_name
  161. def encode(self, texts: list, batch_size=32):
  162. arr = []
  163. tks_num = 0
  164. for txt in texts:
  165. res = self.client.embeddings(prompt=txt,
  166. model=self.model_name)
  167. arr.append(res["embedding"])
  168. tks_num += 128
  169. return np.array(arr), tks_num
  170. def encode_queries(self, text):
  171. res = self.client.embeddings(prompt=text,
  172. model=self.model_name)
  173. return np.array(res["embedding"]), 128
  174. class FastEmbed(Base):
  175. _model = None
  176. def __init__(
  177. self,
  178. key: Optional[str] = None,
  179. model_name: str = "BAAI/bge-small-en-v1.5",
  180. cache_dir: Optional[str] = None,
  181. threads: Optional[int] = None,
  182. **kwargs,
  183. ):
  184. from fastembed import TextEmbedding
  185. if not FastEmbed._model:
  186. self._model = TextEmbedding(model_name, cache_dir, threads, **kwargs)
  187. def encode(self, texts: list, batch_size=32):
  188. # Using the internal tokenizer to encode the texts and get the total
  189. # number of tokens
  190. encodings = self._model.model.tokenizer.encode_batch(texts)
  191. total_tokens = sum(len(e) for e in encodings)
  192. embeddings = [e.tolist() for e in self._model.embed(texts, batch_size)]
  193. return np.array(embeddings), total_tokens
  194. def encode_queries(self, text: str):
  195. # Using the internal tokenizer to encode the texts and get the total
  196. # number of tokens
  197. encoding = self._model.model.tokenizer.encode(text)
  198. embedding = next(self._model.query_embed(text)).tolist()
  199. return np.array(embedding), len(encoding.ids)
  200. class XinferenceEmbed(Base):
  201. def __init__(self, key, model_name="", base_url=""):
  202. self.client = OpenAI(api_key="xxx", base_url=base_url)
  203. self.model_name = model_name
  204. def encode(self, texts: list, batch_size=32):
  205. res = self.client.embeddings.create(input=texts,
  206. model=self.model_name)
  207. return np.array([d.embedding for d in res.data]
  208. ), res.usage.total_tokens
  209. def encode_queries(self, text):
  210. res = self.client.embeddings.create(input=[text],
  211. model=self.model_name)
  212. return np.array(res.data[0].embedding), res.usage.total_tokens
  213. class YoudaoEmbed(Base):
  214. _client = None
  215. def __init__(self, key=None, model_name="maidalun1020/bce-embedding-base_v1", **kwargs):
  216. from BCEmbedding import EmbeddingModel as qanthing
  217. if not YoudaoEmbed._client:
  218. try:
  219. print("LOADING BCE...")
  220. YoudaoEmbed._client = qanthing(model_name_or_path=os.path.join(
  221. get_home_cache_dir(),
  222. "bce-embedding-base_v1"))
  223. except Exception as e:
  224. YoudaoEmbed._client = qanthing(
  225. model_name_or_path=model_name.replace(
  226. "maidalun1020", "InfiniFlow"))
  227. def encode(self, texts: list, batch_size=10):
  228. res = []
  229. token_count = 0
  230. for t in texts:
  231. token_count += num_tokens_from_string(t)
  232. for i in range(0, len(texts), batch_size):
  233. embds = YoudaoEmbed._client.encode(texts[i:i + batch_size])
  234. res.extend(embds)
  235. return np.array(res), token_count
  236. def encode_queries(self, text):
  237. embds = YoudaoEmbed._client.encode([text])
  238. return np.array(embds[0]), num_tokens_from_string(text)
  239. class JinaEmbed(Base):
  240. def __init__(self, key, model_name="jina-embeddings-v2-base-zh",
  241. base_url="https://api.jina.ai/v1/embeddings"):
  242. self.base_url = "https://api.jina.ai/v1/embeddings"
  243. self.headers = {
  244. "Content-Type": "application/json",
  245. "Authorization": f"Bearer {key}"
  246. }
  247. self.model_name = model_name
  248. def encode(self, texts: list, batch_size=None):
  249. texts = [truncate(t, 8196) for t in texts]
  250. data = {
  251. "model": self.model_name,
  252. "input": texts,
  253. 'encoding_type': 'float'
  254. }
  255. res = requests.post(self.base_url, headers=self.headers, json=data).json()
  256. return np.array([d["embedding"] for d in res["data"]]), res["usage"]["total_tokens"]
  257. def encode_queries(self, text):
  258. embds, cnt = self.encode([text])
  259. return np.array(embds[0]), cnt
  260. class InfinityEmbed(Base):
  261. _model = None
  262. def __init__(
  263. self,
  264. model_names: list[str] = ("BAAI/bge-small-en-v1.5",),
  265. engine_kwargs: dict = {},
  266. key = None,
  267. ):
  268. from infinity_emb import EngineArgs
  269. from infinity_emb.engine import AsyncEngineArray
  270. self._default_model = model_names[0]
  271. self.engine_array = AsyncEngineArray.from_args([EngineArgs(model_name_or_path = model_name, **engine_kwargs) for model_name in model_names])
  272. async def _embed(self, sentences: list[str], model_name: str = ""):
  273. if not model_name:
  274. model_name = self._default_model
  275. engine = self.engine_array[model_name]
  276. was_already_running = engine.is_running
  277. if not was_already_running:
  278. await engine.astart()
  279. embeddings, usage = await engine.embed(sentences=sentences)
  280. if not was_already_running:
  281. await engine.astop()
  282. return embeddings, usage
  283. def encode(self, texts: list[str], model_name: str = "") -> tuple[np.ndarray, int]:
  284. # Using the internal tokenizer to encode the texts and get the total
  285. # number of tokens
  286. embeddings, usage = asyncio.run(self._embed(texts, model_name))
  287. return np.array(embeddings), usage
  288. def encode_queries(self, text: str) -> tuple[np.ndarray, int]:
  289. # Using the internal tokenizer to encode the texts and get the total
  290. # number of tokens
  291. return self.encode([text])
  292. class MistralEmbed(Base):
  293. def __init__(self, key, model_name="mistral-embed",
  294. base_url=None):
  295. from mistralai.client import MistralClient
  296. self.client = MistralClient(api_key=key)
  297. self.model_name = model_name
  298. def encode(self, texts: list, batch_size=32):
  299. texts = [truncate(t, 8196) for t in texts]
  300. res = self.client.embeddings(input=texts,
  301. model=self.model_name)
  302. return np.array([d.embedding for d in res.data]
  303. ), res.usage.total_tokens
  304. def encode_queries(self, text):
  305. res = self.client.embeddings(input=[truncate(text, 8196)],
  306. model=self.model_name)
  307. return np.array(res.data[0].embedding), res.usage.total_tokens