選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

embedding_model.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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 openai.lib.azure import AzureOpenAI
  22. from zhipuai import ZhipuAI
  23. import os
  24. from abc import ABC
  25. from ollama import Client
  26. import dashscope
  27. from openai import OpenAI
  28. from FlagEmbedding import FlagModel
  29. import torch
  30. import numpy as np
  31. import asyncio
  32. from api.utils.file_utils import get_home_cache_dir
  33. from rag.utils import num_tokens_from_string, truncate
  34. import google.generativeai as genai
  35. class Base(ABC):
  36. def __init__(self, key, model_name):
  37. pass
  38. def encode(self, texts: list, batch_size=32):
  39. raise NotImplementedError("Please implement encode method!")
  40. def encode_queries(self, text: str):
  41. raise NotImplementedError("Please implement encode method!")
  42. class DefaultEmbedding(Base):
  43. _model = None
  44. _model_lock = threading.Lock()
  45. def __init__(self, key, model_name, **kwargs):
  46. """
  47. If you have trouble downloading HuggingFace models, -_^ this might help!!
  48. For Linux:
  49. export HF_ENDPOINT=https://hf-mirror.com
  50. For Windows:
  51. Good luck
  52. ^_-
  53. """
  54. if not DefaultEmbedding._model:
  55. with DefaultEmbedding._model_lock:
  56. if not DefaultEmbedding._model:
  57. try:
  58. DefaultEmbedding._model = FlagModel(os.path.join(get_home_cache_dir(), re.sub(r"^[a-zA-Z]+/", "", model_name)),
  59. query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:",
  60. use_fp16=torch.cuda.is_available())
  61. except Exception as e:
  62. model_dir = snapshot_download(repo_id="BAAI/bge-large-zh-v1.5",
  63. local_dir=os.path.join(get_home_cache_dir(), re.sub(r"^[a-zA-Z]+/", "", model_name)),
  64. local_dir_use_symlinks=False)
  65. DefaultEmbedding._model = FlagModel(model_dir,
  66. query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:",
  67. use_fp16=torch.cuda.is_available())
  68. self._model = DefaultEmbedding._model
  69. def encode(self, texts: list, batch_size=32):
  70. texts = [truncate(t, 2048) for t in texts]
  71. token_count = 0
  72. for t in texts:
  73. token_count += num_tokens_from_string(t)
  74. res = []
  75. for i in range(0, len(texts), batch_size):
  76. res.extend(self._model.encode(texts[i:i + batch_size]).tolist())
  77. return np.array(res), token_count
  78. def encode_queries(self, text: str):
  79. token_count = num_tokens_from_string(text)
  80. return self._model.encode_queries([text]).tolist()[0], token_count
  81. class OpenAIEmbed(Base):
  82. def __init__(self, key, model_name="text-embedding-ada-002",
  83. base_url="https://api.openai.com/v1"):
  84. if not base_url:
  85. base_url = "https://api.openai.com/v1"
  86. self.client = OpenAI(api_key=key, base_url=base_url)
  87. self.model_name = model_name
  88. def encode(self, texts: list, batch_size=32):
  89. texts = [truncate(t, 8196) for t in texts]
  90. res = self.client.embeddings.create(input=texts,
  91. model=self.model_name)
  92. return np.array([d.embedding for d in res.data]
  93. ), res.usage.total_tokens
  94. def encode_queries(self, text):
  95. res = self.client.embeddings.create(input=[truncate(text, 8196)],
  96. model=self.model_name)
  97. return np.array(res.data[0].embedding), res.usage.total_tokens
  98. class LocalAIEmbed(Base):
  99. def __init__(self, key, model_name, base_url):
  100. self.base_url = base_url + "/embeddings"
  101. self.headers = {
  102. "Content-Type": "application/json",
  103. }
  104. self.model_name = model_name.split("___")[0]
  105. def encode(self, texts: list, batch_size=None):
  106. data = {"model": self.model_name, "input": texts, "encoding_type": "float"}
  107. res = requests.post(self.base_url, headers=self.headers, json=data).json()
  108. return np.array([d["embedding"] for d in res["data"]]), 1024
  109. def encode_queries(self, text):
  110. embds, cnt = self.encode([text])
  111. return np.array(embds[0]), cnt
  112. class AzureEmbed(OpenAIEmbed):
  113. def __init__(self, key, model_name, **kwargs):
  114. self.client = AzureOpenAI(api_key=key, azure_endpoint=kwargs["base_url"], api_version="2024-02-01")
  115. self.model_name = model_name
  116. class BaiChuanEmbed(OpenAIEmbed):
  117. def __init__(self, key,
  118. model_name='Baichuan-Text-Embedding',
  119. base_url='https://api.baichuan-ai.com/v1'):
  120. if not base_url:
  121. base_url = "https://api.baichuan-ai.com/v1"
  122. super().__init__(key, model_name, base_url)
  123. class QWenEmbed(Base):
  124. def __init__(self, key, model_name="text_embedding_v2", **kwargs):
  125. dashscope.api_key = key
  126. self.model_name = model_name
  127. def encode(self, texts: list, batch_size=10):
  128. import dashscope
  129. try:
  130. res = []
  131. token_count = 0
  132. texts = [truncate(t, 2048) for t in texts]
  133. for i in range(0, len(texts), batch_size):
  134. resp = dashscope.TextEmbedding.call(
  135. model=self.model_name,
  136. input=texts[i:i + batch_size],
  137. text_type="document"
  138. )
  139. embds = [[] for _ in range(len(resp["output"]["embeddings"]))]
  140. for e in resp["output"]["embeddings"]:
  141. embds[e["text_index"]] = e["embedding"]
  142. res.extend(embds)
  143. token_count += resp["usage"]["total_tokens"]
  144. return np.array(res), token_count
  145. except Exception as e:
  146. raise Exception("Account abnormal. Please ensure it's on good standing to use QWen's "+self.model_name)
  147. return np.array([]), 0
  148. def encode_queries(self, text):
  149. try:
  150. resp = dashscope.TextEmbedding.call(
  151. model=self.model_name,
  152. input=text[:2048],
  153. text_type="query"
  154. )
  155. return np.array(resp["output"]["embeddings"][0]
  156. ["embedding"]), resp["usage"]["total_tokens"]
  157. except Exception as e:
  158. raise Exception("Account abnormal. Please ensure it's on good standing to use QWen's "+self.model_name)
  159. return np.array([]), 0
  160. class ZhipuEmbed(Base):
  161. def __init__(self, key, model_name="embedding-2", **kwargs):
  162. self.client = ZhipuAI(api_key=key)
  163. self.model_name = model_name
  164. def encode(self, texts: list, batch_size=32):
  165. arr = []
  166. tks_num = 0
  167. for txt in texts:
  168. res = self.client.embeddings.create(input=txt,
  169. model=self.model_name)
  170. arr.append(res.data[0].embedding)
  171. tks_num += res.usage.total_tokens
  172. return np.array(arr), tks_num
  173. def encode_queries(self, text):
  174. res = self.client.embeddings.create(input=text,
  175. model=self.model_name)
  176. return np.array(res.data[0].embedding), res.usage.total_tokens
  177. class OllamaEmbed(Base):
  178. def __init__(self, key, model_name, **kwargs):
  179. self.client = Client(host=kwargs["base_url"])
  180. self.model_name = model_name
  181. def encode(self, texts: list, batch_size=32):
  182. arr = []
  183. tks_num = 0
  184. for txt in texts:
  185. res = self.client.embeddings(prompt=txt,
  186. model=self.model_name)
  187. arr.append(res["embedding"])
  188. tks_num += 128
  189. return np.array(arr), tks_num
  190. def encode_queries(self, text):
  191. res = self.client.embeddings(prompt=text,
  192. model=self.model_name)
  193. return np.array(res["embedding"]), 128
  194. class FastEmbed(Base):
  195. _model = None
  196. def __init__(
  197. self,
  198. key: Optional[str] = None,
  199. model_name: str = "BAAI/bge-small-en-v1.5",
  200. cache_dir: Optional[str] = None,
  201. threads: Optional[int] = None,
  202. **kwargs,
  203. ):
  204. from fastembed import TextEmbedding
  205. if not FastEmbed._model:
  206. self._model = TextEmbedding(model_name, cache_dir, threads, **kwargs)
  207. def encode(self, texts: list, batch_size=32):
  208. # Using the internal tokenizer to encode the texts and get the total
  209. # number of tokens
  210. encodings = self._model.model.tokenizer.encode_batch(texts)
  211. total_tokens = sum(len(e) for e in encodings)
  212. embeddings = [e.tolist() for e in self._model.embed(texts, batch_size)]
  213. return np.array(embeddings), total_tokens
  214. def encode_queries(self, text: str):
  215. # Using the internal tokenizer to encode the texts and get the total
  216. # number of tokens
  217. encoding = self._model.model.tokenizer.encode(text)
  218. embedding = next(self._model.query_embed(text)).tolist()
  219. return np.array(embedding), len(encoding.ids)
  220. class XinferenceEmbed(Base):
  221. def __init__(self, key, model_name="", base_url=""):
  222. self.client = OpenAI(api_key="xxx", base_url=base_url)
  223. self.model_name = model_name
  224. def encode(self, texts: list, batch_size=32):
  225. res = self.client.embeddings.create(input=texts,
  226. model=self.model_name)
  227. return np.array([d.embedding for d in res.data]
  228. ), res.usage.total_tokens
  229. def encode_queries(self, text):
  230. res = self.client.embeddings.create(input=[text],
  231. model=self.model_name)
  232. return np.array(res.data[0].embedding), res.usage.total_tokens
  233. class YoudaoEmbed(Base):
  234. _client = None
  235. def __init__(self, key=None, model_name="maidalun1020/bce-embedding-base_v1", **kwargs):
  236. from BCEmbedding import EmbeddingModel as qanthing
  237. if not YoudaoEmbed._client:
  238. try:
  239. print("LOADING BCE...")
  240. YoudaoEmbed._client = qanthing(model_name_or_path=os.path.join(
  241. get_home_cache_dir(),
  242. "bce-embedding-base_v1"))
  243. except Exception as e:
  244. YoudaoEmbed._client = qanthing(
  245. model_name_or_path=model_name.replace(
  246. "maidalun1020", "InfiniFlow"))
  247. def encode(self, texts: list, batch_size=10):
  248. res = []
  249. token_count = 0
  250. for t in texts:
  251. token_count += num_tokens_from_string(t)
  252. for i in range(0, len(texts), batch_size):
  253. embds = YoudaoEmbed._client.encode(texts[i:i + batch_size])
  254. res.extend(embds)
  255. return np.array(res), token_count
  256. def encode_queries(self, text):
  257. embds = YoudaoEmbed._client.encode([text])
  258. return np.array(embds[0]), num_tokens_from_string(text)
  259. class JinaEmbed(Base):
  260. def __init__(self, key, model_name="jina-embeddings-v2-base-zh",
  261. base_url="https://api.jina.ai/v1/embeddings"):
  262. self.base_url = "https://api.jina.ai/v1/embeddings"
  263. self.headers = {
  264. "Content-Type": "application/json",
  265. "Authorization": f"Bearer {key}"
  266. }
  267. self.model_name = model_name
  268. def encode(self, texts: list, batch_size=None):
  269. texts = [truncate(t, 8196) for t in texts]
  270. data = {
  271. "model": self.model_name,
  272. "input": texts,
  273. 'encoding_type': 'float'
  274. }
  275. res = requests.post(self.base_url, headers=self.headers, json=data).json()
  276. return np.array([d["embedding"] for d in res["data"]]), res["usage"]["total_tokens"]
  277. def encode_queries(self, text):
  278. embds, cnt = self.encode([text])
  279. return np.array(embds[0]), cnt
  280. class InfinityEmbed(Base):
  281. _model = None
  282. def __init__(
  283. self,
  284. model_names: list[str] = ("BAAI/bge-small-en-v1.5",),
  285. engine_kwargs: dict = {},
  286. key = None,
  287. ):
  288. from infinity_emb import EngineArgs
  289. from infinity_emb.engine import AsyncEngineArray
  290. self._default_model = model_names[0]
  291. self.engine_array = AsyncEngineArray.from_args([EngineArgs(model_name_or_path = model_name, **engine_kwargs) for model_name in model_names])
  292. async def _embed(self, sentences: list[str], model_name: str = ""):
  293. if not model_name:
  294. model_name = self._default_model
  295. engine = self.engine_array[model_name]
  296. was_already_running = engine.is_running
  297. if not was_already_running:
  298. await engine.astart()
  299. embeddings, usage = await engine.embed(sentences=sentences)
  300. if not was_already_running:
  301. await engine.astop()
  302. return embeddings, usage
  303. def encode(self, texts: list[str], model_name: str = "") -> tuple[np.ndarray, int]:
  304. # Using the internal tokenizer to encode the texts and get the total
  305. # number of tokens
  306. embeddings, usage = asyncio.run(self._embed(texts, model_name))
  307. return np.array(embeddings), usage
  308. def encode_queries(self, text: str) -> tuple[np.ndarray, int]:
  309. # Using the internal tokenizer to encode the texts and get the total
  310. # number of tokens
  311. return self.encode([text])
  312. class MistralEmbed(Base):
  313. def __init__(self, key, model_name="mistral-embed",
  314. base_url=None):
  315. from mistralai.client import MistralClient
  316. self.client = MistralClient(api_key=key)
  317. self.model_name = model_name
  318. def encode(self, texts: list, batch_size=32):
  319. texts = [truncate(t, 8196) for t in texts]
  320. res = self.client.embeddings(input=texts,
  321. model=self.model_name)
  322. return np.array([d.embedding for d in res.data]
  323. ), res.usage.total_tokens
  324. def encode_queries(self, text):
  325. res = self.client.embeddings(input=[truncate(text, 8196)],
  326. model=self.model_name)
  327. return np.array(res.data[0].embedding), res.usage.total_tokens
  328. class BedrockEmbed(Base):
  329. def __init__(self, key, model_name,
  330. **kwargs):
  331. import boto3
  332. self.bedrock_ak = eval(key).get('bedrock_ak', '')
  333. self.bedrock_sk = eval(key).get('bedrock_sk', '')
  334. self.bedrock_region = eval(key).get('bedrock_region', '')
  335. self.model_name = model_name
  336. self.client = boto3.client(service_name='bedrock-runtime', region_name=self.bedrock_region,
  337. aws_access_key_id=self.bedrock_ak, aws_secret_access_key=self.bedrock_sk)
  338. def encode(self, texts: list, batch_size=32):
  339. texts = [truncate(t, 8196) for t in texts]
  340. embeddings = []
  341. token_count = 0
  342. for text in texts:
  343. if self.model_name.split('.')[0] == 'amazon':
  344. body = {"inputText": text}
  345. elif self.model_name.split('.')[0] == 'cohere':
  346. body = {"texts": [text], "input_type": 'search_document'}
  347. response = self.client.invoke_model(modelId=self.model_name, body=json.dumps(body))
  348. model_response = json.loads(response["body"].read())
  349. embeddings.extend([model_response["embedding"]])
  350. token_count += num_tokens_from_string(text)
  351. return np.array(embeddings), token_count
  352. def encode_queries(self, text):
  353. embeddings = []
  354. token_count = num_tokens_from_string(text)
  355. if self.model_name.split('.')[0] == 'amazon':
  356. body = {"inputText": truncate(text, 8196)}
  357. elif self.model_name.split('.')[0] == 'cohere':
  358. body = {"texts": [truncate(text, 8196)], "input_type": 'search_query'}
  359. response = self.client.invoke_model(modelId=self.model_name, body=json.dumps(body))
  360. model_response = json.loads(response["body"].read())
  361. embeddings.extend([model_response["embedding"]])
  362. return np.array(embeddings), token_count
  363. class GeminiEmbed(Base):
  364. def __init__(self, key, model_name='models/text-embedding-004',
  365. **kwargs):
  366. genai.configure(api_key=key)
  367. self.model_name = 'models/' + model_name
  368. def encode(self, texts: list, batch_size=32):
  369. texts = [truncate(t, 2048) for t in texts]
  370. token_count = sum(num_tokens_from_string(text) for text in texts)
  371. result = genai.embed_content(
  372. model=self.model_name,
  373. content=texts,
  374. task_type="retrieval_document",
  375. title="Embedding of list of strings")
  376. return np.array(result['embedding']),token_count
  377. def encode_queries(self, text):
  378. result = genai.embed_content(
  379. model=self.model_name,
  380. content=truncate(text,2048),
  381. task_type="retrieval_document",
  382. title="Embedding of single string")
  383. token_count = num_tokens_from_string(text)
  384. return np.array(result['embedding']),token_count