You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 requests
  19. from huggingface_hub import snapshot_download
  20. from zhipuai import ZhipuAI
  21. import os
  22. from abc import ABC
  23. from ollama import Client
  24. import dashscope
  25. from openai import OpenAI
  26. from FlagEmbedding import FlagModel
  27. import torch
  28. import numpy as np
  29. from api.utils.file_utils import get_home_cache_dir
  30. from rag.utils import num_tokens_from_string, truncate
  31. class Base(ABC):
  32. def __init__(self, key, model_name):
  33. pass
  34. def encode(self, texts: list, batch_size=32):
  35. raise NotImplementedError("Please implement encode method!")
  36. def encode_queries(self, text: str):
  37. raise NotImplementedError("Please implement encode method!")
  38. class DefaultEmbedding(Base):
  39. _model = None
  40. def __init__(self, key, model_name, **kwargs):
  41. """
  42. If you have trouble downloading HuggingFace models, -_^ this might help!!
  43. For Linux:
  44. export HF_ENDPOINT=https://hf-mirror.com
  45. For Windows:
  46. Good luck
  47. ^_-
  48. """
  49. if not DefaultEmbedding._model:
  50. try:
  51. self._model = FlagModel(os.path.join(get_home_cache_dir(), re.sub(r"^[a-zA-Z]+/", "", model_name)),
  52. query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:",
  53. use_fp16=torch.cuda.is_available())
  54. except Exception as e:
  55. model_dir = snapshot_download(repo_id="BAAI/bge-large-zh-v1.5",
  56. local_dir=os.path.join(get_home_cache_dir(), re.sub(r"^[a-zA-Z]+/", "", model_name)),
  57. local_dir_use_symlinks=False)
  58. self._model = FlagModel(model_dir,
  59. query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:",
  60. use_fp16=torch.cuda.is_available())
  61. def encode(self, texts: list, batch_size=32):
  62. texts = [truncate(t, 2048) for t in texts]
  63. token_count = 0
  64. for t in texts:
  65. token_count += num_tokens_from_string(t)
  66. res = []
  67. for i in range(0, len(texts), batch_size):
  68. res.extend(self._model.encode(texts[i:i + batch_size]).tolist())
  69. return np.array(res), token_count
  70. def encode_queries(self, text: str):
  71. token_count = num_tokens_from_string(text)
  72. return self._model.encode_queries([text]).tolist()[0], token_count
  73. class OpenAIEmbed(Base):
  74. def __init__(self, key, model_name="text-embedding-ada-002",
  75. base_url="https://api.openai.com/v1"):
  76. if not base_url:
  77. base_url = "https://api.openai.com/v1"
  78. self.client = OpenAI(api_key=key, base_url=base_url)
  79. self.model_name = model_name
  80. def encode(self, texts: list, batch_size=32):
  81. texts = [truncate(t, 8196) for t in texts]
  82. res = self.client.embeddings.create(input=texts,
  83. model=self.model_name)
  84. return np.array([d.embedding for d in res.data]
  85. ), res.usage.total_tokens
  86. def encode_queries(self, text):
  87. res = self.client.embeddings.create(input=[truncate(text, 8196)],
  88. model=self.model_name)
  89. return np.array(res.data[0].embedding), res.usage.total_tokens
  90. class BaiChuanEmbed(OpenAIEmbed):
  91. def __init__(self, key,
  92. model_name='Baichuan-Text-Embedding',
  93. base_url='https://api.baichuan-ai.com/v1'):
  94. if not base_url:
  95. base_url = "https://api.baichuan-ai.com/v1"
  96. super().__init__(key, model_name, base_url)
  97. class QWenEmbed(Base):
  98. def __init__(self, key, model_name="text_embedding_v2", **kwargs):
  99. dashscope.api_key = key
  100. self.model_name = model_name
  101. def encode(self, texts: list, batch_size=10):
  102. import dashscope
  103. try:
  104. res = []
  105. token_count = 0
  106. texts = [truncate(t, 2048) for t in texts]
  107. for i in range(0, len(texts), batch_size):
  108. resp = dashscope.TextEmbedding.call(
  109. model=self.model_name,
  110. input=texts[i:i + batch_size],
  111. text_type="document"
  112. )
  113. embds = [[] for _ in range(len(resp["output"]["embeddings"]))]
  114. for e in resp["output"]["embeddings"]:
  115. embds[e["text_index"]] = e["embedding"]
  116. res.extend(embds)
  117. token_count += resp["usage"]["total_tokens"]
  118. return np.array(res), token_count
  119. except Exception as e:
  120. raise Exception("Account abnormal. Please ensure it's on good standing.")
  121. return np.array([]), 0
  122. def encode_queries(self, text):
  123. try:
  124. resp = dashscope.TextEmbedding.call(
  125. model=self.model_name,
  126. input=text[:2048],
  127. text_type="query"
  128. )
  129. return np.array(resp["output"]["embeddings"][0]
  130. ["embedding"]), resp["usage"]["total_tokens"]
  131. except Exception as e:
  132. raise Exception("Account abnormal. Please ensure it's on good standing.")
  133. return np.array([]), 0
  134. class ZhipuEmbed(Base):
  135. def __init__(self, key, model_name="embedding-2", **kwargs):
  136. self.client = ZhipuAI(api_key=key)
  137. self.model_name = model_name
  138. def encode(self, texts: list, batch_size=32):
  139. arr = []
  140. tks_num = 0
  141. for txt in texts:
  142. res = self.client.embeddings.create(input=txt,
  143. model=self.model_name)
  144. arr.append(res.data[0].embedding)
  145. tks_num += res.usage.total_tokens
  146. return np.array(arr), tks_num
  147. def encode_queries(self, text):
  148. res = self.client.embeddings.create(input=text,
  149. model=self.model_name)
  150. return np.array(res.data[0].embedding), res.usage.total_tokens
  151. class OllamaEmbed(Base):
  152. def __init__(self, key, model_name, **kwargs):
  153. self.client = Client(host=kwargs["base_url"])
  154. self.model_name = model_name
  155. def encode(self, texts: list, batch_size=32):
  156. arr = []
  157. tks_num = 0
  158. for txt in texts:
  159. res = self.client.embeddings(prompt=txt,
  160. model=self.model_name)
  161. arr.append(res["embedding"])
  162. tks_num += 128
  163. return np.array(arr), tks_num
  164. def encode_queries(self, text):
  165. res = self.client.embeddings(prompt=text,
  166. model=self.model_name)
  167. return np.array(res["embedding"]), 128
  168. class FastEmbed(Base):
  169. _model = None
  170. def __init__(
  171. self,
  172. key: Optional[str] = None,
  173. model_name: str = "BAAI/bge-small-en-v1.5",
  174. cache_dir: Optional[str] = None,
  175. threads: Optional[int] = None,
  176. **kwargs,
  177. ):
  178. from fastembed import TextEmbedding
  179. if not FastEmbed._model:
  180. self._model = TextEmbedding(model_name, cache_dir, threads, **kwargs)
  181. def encode(self, texts: list, batch_size=32):
  182. # Using the internal tokenizer to encode the texts and get the total
  183. # number of tokens
  184. encodings = self._model.model.tokenizer.encode_batch(texts)
  185. total_tokens = sum(len(e) for e in encodings)
  186. embeddings = [e.tolist() for e in self._model.embed(texts, batch_size)]
  187. return np.array(embeddings), total_tokens
  188. def encode_queries(self, text: str):
  189. # Using the internal tokenizer to encode the texts and get the total
  190. # number of tokens
  191. encoding = self._model.model.tokenizer.encode(text)
  192. embedding = next(self._model.query_embed(text)).tolist()
  193. return np.array(embedding), len(encoding.ids)
  194. class XinferenceEmbed(Base):
  195. def __init__(self, key, model_name="", base_url=""):
  196. self.client = OpenAI(api_key="xxx", base_url=base_url)
  197. self.model_name = model_name
  198. def encode(self, texts: list, batch_size=32):
  199. res = self.client.embeddings.create(input=texts,
  200. model=self.model_name)
  201. return np.array([d.embedding for d in res.data]
  202. ), res.usage.total_tokens
  203. def encode_queries(self, text):
  204. res = self.client.embeddings.create(input=[text],
  205. model=self.model_name)
  206. return np.array(res.data[0].embedding), res.usage.total_tokens
  207. class YoudaoEmbed(Base):
  208. _client = None
  209. def __init__(self, key=None, model_name="maidalun1020/bce-embedding-base_v1", **kwargs):
  210. from BCEmbedding import EmbeddingModel as qanthing
  211. if not YoudaoEmbed._client:
  212. try:
  213. print("LOADING BCE...")
  214. YoudaoEmbed._client = qanthing(model_name_or_path=os.path.join(
  215. get_home_cache_dir(),
  216. "bce-embedding-base_v1"))
  217. except Exception as e:
  218. YoudaoEmbed._client = qanthing(
  219. model_name_or_path=model_name.replace(
  220. "maidalun1020", "InfiniFlow"))
  221. def encode(self, texts: list, batch_size=10):
  222. res = []
  223. token_count = 0
  224. for t in texts:
  225. token_count += num_tokens_from_string(t)
  226. for i in range(0, len(texts), batch_size):
  227. embds = YoudaoEmbed._client.encode(texts[i:i + batch_size])
  228. res.extend(embds)
  229. return np.array(res), token_count
  230. def encode_queries(self, text):
  231. embds = YoudaoEmbed._client.encode([text])
  232. return np.array(embds[0]), num_tokens_from_string(text)
  233. class JinaEmbed(Base):
  234. def __init__(self, key, model_name="jina-embeddings-v2-base-zh",
  235. base_url="https://api.jina.ai/v1/embeddings"):
  236. self.base_url = "https://api.jina.ai/v1/embeddings"
  237. self.headers = {
  238. "Content-Type": "application/json",
  239. "Authorization": f"Bearer {key}"
  240. }
  241. self.model_name = model_name
  242. def encode(self, texts: list, batch_size=None):
  243. texts = [truncate(t, 8196) for t in texts]
  244. data = {
  245. "model": self.model_name,
  246. "input": texts,
  247. 'encoding_type': 'float'
  248. }
  249. res = requests.post(self.base_url, headers=self.headers, json=data).json()
  250. return np.array([d["embedding"] for d in res["data"]]), res["usage"]["total_tokens"]
  251. def encode_queries(self, text):
  252. embds, cnt = self.encode([text])
  253. return np.array(embds[0]), cnt