Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

embedding_model.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. if not base_url:
  101. raise ValueError("Local embedding model url cannot be None")
  102. if base_url.split("/")[-1] != "v1":
  103. base_url = os.path.join(base_url, "v1")
  104. self.client = OpenAI(api_key="empty", base_url=base_url)
  105. self.model_name = model_name.split("___")[0]
  106. def encode(self, texts: list, batch_size=32):
  107. res = self.client.embeddings.create(input=texts, model=self.model_name)
  108. return (
  109. np.array([d.embedding for d in res.data]),
  110. 1024,
  111. ) # local embedding for LmStudio donot count tokens
  112. def encode_queries(self, text):
  113. embds, cnt = self.encode([text])
  114. return np.array(embds[0]), cnt
  115. class AzureEmbed(OpenAIEmbed):
  116. def __init__(self, key, model_name, **kwargs):
  117. self.client = AzureOpenAI(api_key=key, azure_endpoint=kwargs["base_url"], api_version="2024-02-01")
  118. self.model_name = model_name
  119. class BaiChuanEmbed(OpenAIEmbed):
  120. def __init__(self, key,
  121. model_name='Baichuan-Text-Embedding',
  122. base_url='https://api.baichuan-ai.com/v1'):
  123. if not base_url:
  124. base_url = "https://api.baichuan-ai.com/v1"
  125. super().__init__(key, model_name, base_url)
  126. class QWenEmbed(Base):
  127. def __init__(self, key, model_name="text_embedding_v2", **kwargs):
  128. dashscope.api_key = key
  129. self.model_name = model_name
  130. def encode(self, texts: list, batch_size=10):
  131. import dashscope
  132. try:
  133. res = []
  134. token_count = 0
  135. texts = [truncate(t, 2048) for t in texts]
  136. for i in range(0, len(texts), batch_size):
  137. resp = dashscope.TextEmbedding.call(
  138. model=self.model_name,
  139. input=texts[i:i + batch_size],
  140. text_type="document"
  141. )
  142. embds = [[] for _ in range(len(resp["output"]["embeddings"]))]
  143. for e in resp["output"]["embeddings"]:
  144. embds[e["text_index"]] = e["embedding"]
  145. res.extend(embds)
  146. token_count += resp["usage"]["total_tokens"]
  147. return np.array(res), token_count
  148. except Exception as e:
  149. raise Exception("Account abnormal. Please ensure it's on good standing to use QWen's "+self.model_name)
  150. return np.array([]), 0
  151. def encode_queries(self, text):
  152. try:
  153. resp = dashscope.TextEmbedding.call(
  154. model=self.model_name,
  155. input=text[:2048],
  156. text_type="query"
  157. )
  158. return np.array(resp["output"]["embeddings"][0]
  159. ["embedding"]), resp["usage"]["total_tokens"]
  160. except Exception as e:
  161. raise Exception("Account abnormal. Please ensure it's on good standing to use QWen's "+self.model_name)
  162. return np.array([]), 0
  163. class ZhipuEmbed(Base):
  164. def __init__(self, key, model_name="embedding-2", **kwargs):
  165. self.client = ZhipuAI(api_key=key)
  166. self.model_name = model_name
  167. def encode(self, texts: list, batch_size=32):
  168. arr = []
  169. tks_num = 0
  170. for txt in texts:
  171. res = self.client.embeddings.create(input=txt,
  172. model=self.model_name)
  173. arr.append(res.data[0].embedding)
  174. tks_num += res.usage.total_tokens
  175. return np.array(arr), tks_num
  176. def encode_queries(self, text):
  177. res = self.client.embeddings.create(input=text,
  178. model=self.model_name)
  179. return np.array(res.data[0].embedding), res.usage.total_tokens
  180. class OllamaEmbed(Base):
  181. def __init__(self, key, model_name, **kwargs):
  182. self.client = Client(host=kwargs["base_url"])
  183. self.model_name = model_name
  184. def encode(self, texts: list, batch_size=32):
  185. arr = []
  186. tks_num = 0
  187. for txt in texts:
  188. res = self.client.embeddings(prompt=txt,
  189. model=self.model_name)
  190. arr.append(res["embedding"])
  191. tks_num += 128
  192. return np.array(arr), tks_num
  193. def encode_queries(self, text):
  194. res = self.client.embeddings(prompt=text,
  195. model=self.model_name)
  196. return np.array(res["embedding"]), 128
  197. class FastEmbed(Base):
  198. _model = None
  199. def __init__(
  200. self,
  201. key: Optional[str] = None,
  202. model_name: str = "BAAI/bge-small-en-v1.5",
  203. cache_dir: Optional[str] = None,
  204. threads: Optional[int] = None,
  205. **kwargs,
  206. ):
  207. from fastembed import TextEmbedding
  208. if not FastEmbed._model:
  209. self._model = TextEmbedding(model_name, cache_dir, threads, **kwargs)
  210. def encode(self, texts: list, batch_size=32):
  211. # Using the internal tokenizer to encode the texts and get the total
  212. # number of tokens
  213. encodings = self._model.model.tokenizer.encode_batch(texts)
  214. total_tokens = sum(len(e) for e in encodings)
  215. embeddings = [e.tolist() for e in self._model.embed(texts, batch_size)]
  216. return np.array(embeddings), total_tokens
  217. def encode_queries(self, text: str):
  218. # Using the internal tokenizer to encode the texts and get the total
  219. # number of tokens
  220. encoding = self._model.model.tokenizer.encode(text)
  221. embedding = next(self._model.query_embed(text)).tolist()
  222. return np.array(embedding), len(encoding.ids)
  223. class XinferenceEmbed(Base):
  224. def __init__(self, key, model_name="", base_url=""):
  225. self.client = OpenAI(api_key="xxx", base_url=base_url)
  226. self.model_name = model_name
  227. def encode(self, texts: list, batch_size=32):
  228. res = self.client.embeddings.create(input=texts,
  229. model=self.model_name)
  230. return np.array([d.embedding for d in res.data]
  231. ), res.usage.total_tokens
  232. def encode_queries(self, text):
  233. res = self.client.embeddings.create(input=[text],
  234. model=self.model_name)
  235. return np.array(res.data[0].embedding), res.usage.total_tokens
  236. class YoudaoEmbed(Base):
  237. _client = None
  238. def __init__(self, key=None, model_name="maidalun1020/bce-embedding-base_v1", **kwargs):
  239. from BCEmbedding import EmbeddingModel as qanthing
  240. if not YoudaoEmbed._client:
  241. try:
  242. print("LOADING BCE...")
  243. YoudaoEmbed._client = qanthing(model_name_or_path=os.path.join(
  244. get_home_cache_dir(),
  245. "bce-embedding-base_v1"))
  246. except Exception as e:
  247. YoudaoEmbed._client = qanthing(
  248. model_name_or_path=model_name.replace(
  249. "maidalun1020", "InfiniFlow"))
  250. def encode(self, texts: list, batch_size=10):
  251. res = []
  252. token_count = 0
  253. for t in texts:
  254. token_count += num_tokens_from_string(t)
  255. for i in range(0, len(texts), batch_size):
  256. embds = YoudaoEmbed._client.encode(texts[i:i + batch_size])
  257. res.extend(embds)
  258. return np.array(res), token_count
  259. def encode_queries(self, text):
  260. embds = YoudaoEmbed._client.encode([text])
  261. return np.array(embds[0]), num_tokens_from_string(text)
  262. class JinaEmbed(Base):
  263. def __init__(self, key, model_name="jina-embeddings-v2-base-zh",
  264. base_url="https://api.jina.ai/v1/embeddings"):
  265. self.base_url = "https://api.jina.ai/v1/embeddings"
  266. self.headers = {
  267. "Content-Type": "application/json",
  268. "Authorization": f"Bearer {key}"
  269. }
  270. self.model_name = model_name
  271. def encode(self, texts: list, batch_size=None):
  272. texts = [truncate(t, 8196) for t in texts]
  273. data = {
  274. "model": self.model_name,
  275. "input": texts,
  276. 'encoding_type': 'float'
  277. }
  278. res = requests.post(self.base_url, headers=self.headers, json=data).json()
  279. return np.array([d["embedding"] for d in res["data"]]), res["usage"]["total_tokens"]
  280. def encode_queries(self, text):
  281. embds, cnt = self.encode([text])
  282. return np.array(embds[0]), cnt
  283. class InfinityEmbed(Base):
  284. _model = None
  285. def __init__(
  286. self,
  287. model_names: list[str] = ("BAAI/bge-small-en-v1.5",),
  288. engine_kwargs: dict = {},
  289. key = None,
  290. ):
  291. from infinity_emb import EngineArgs
  292. from infinity_emb.engine import AsyncEngineArray
  293. self._default_model = model_names[0]
  294. self.engine_array = AsyncEngineArray.from_args([EngineArgs(model_name_or_path = model_name, **engine_kwargs) for model_name in model_names])
  295. async def _embed(self, sentences: list[str], model_name: str = ""):
  296. if not model_name:
  297. model_name = self._default_model
  298. engine = self.engine_array[model_name]
  299. was_already_running = engine.is_running
  300. if not was_already_running:
  301. await engine.astart()
  302. embeddings, usage = await engine.embed(sentences=sentences)
  303. if not was_already_running:
  304. await engine.astop()
  305. return embeddings, usage
  306. def encode(self, texts: list[str], model_name: str = "") -> tuple[np.ndarray, int]:
  307. # Using the internal tokenizer to encode the texts and get the total
  308. # number of tokens
  309. embeddings, usage = asyncio.run(self._embed(texts, model_name))
  310. return np.array(embeddings), usage
  311. def encode_queries(self, text: str) -> tuple[np.ndarray, int]:
  312. # Using the internal tokenizer to encode the texts and get the total
  313. # number of tokens
  314. return self.encode([text])
  315. class MistralEmbed(Base):
  316. def __init__(self, key, model_name="mistral-embed",
  317. base_url=None):
  318. from mistralai.client import MistralClient
  319. self.client = MistralClient(api_key=key)
  320. self.model_name = model_name
  321. def encode(self, texts: list, batch_size=32):
  322. texts = [truncate(t, 8196) for t in texts]
  323. res = self.client.embeddings(input=texts,
  324. model=self.model_name)
  325. return np.array([d.embedding for d in res.data]
  326. ), res.usage.total_tokens
  327. def encode_queries(self, text):
  328. res = self.client.embeddings(input=[truncate(text, 8196)],
  329. model=self.model_name)
  330. return np.array(res.data[0].embedding), res.usage.total_tokens
  331. class BedrockEmbed(Base):
  332. def __init__(self, key, model_name,
  333. **kwargs):
  334. import boto3
  335. self.bedrock_ak = eval(key).get('bedrock_ak', '')
  336. self.bedrock_sk = eval(key).get('bedrock_sk', '')
  337. self.bedrock_region = eval(key).get('bedrock_region', '')
  338. self.model_name = model_name
  339. self.client = boto3.client(service_name='bedrock-runtime', region_name=self.bedrock_region,
  340. aws_access_key_id=self.bedrock_ak, aws_secret_access_key=self.bedrock_sk)
  341. def encode(self, texts: list, batch_size=32):
  342. texts = [truncate(t, 8196) for t in texts]
  343. embeddings = []
  344. token_count = 0
  345. for text in texts:
  346. if self.model_name.split('.')[0] == 'amazon':
  347. body = {"inputText": text}
  348. elif self.model_name.split('.')[0] == 'cohere':
  349. body = {"texts": [text], "input_type": 'search_document'}
  350. response = self.client.invoke_model(modelId=self.model_name, body=json.dumps(body))
  351. model_response = json.loads(response["body"].read())
  352. embeddings.extend([model_response["embedding"]])
  353. token_count += num_tokens_from_string(text)
  354. return np.array(embeddings), token_count
  355. def encode_queries(self, text):
  356. embeddings = []
  357. token_count = num_tokens_from_string(text)
  358. if self.model_name.split('.')[0] == 'amazon':
  359. body = {"inputText": truncate(text, 8196)}
  360. elif self.model_name.split('.')[0] == 'cohere':
  361. body = {"texts": [truncate(text, 8196)], "input_type": 'search_query'}
  362. response = self.client.invoke_model(modelId=self.model_name, body=json.dumps(body))
  363. model_response = json.loads(response["body"].read())
  364. embeddings.extend([model_response["embedding"]])
  365. return np.array(embeddings), token_count
  366. class GeminiEmbed(Base):
  367. def __init__(self, key, model_name='models/text-embedding-004',
  368. **kwargs):
  369. genai.configure(api_key=key)
  370. self.model_name = 'models/' + model_name
  371. def encode(self, texts: list, batch_size=32):
  372. texts = [truncate(t, 2048) for t in texts]
  373. token_count = sum(num_tokens_from_string(text) for text in texts)
  374. result = genai.embed_content(
  375. model=self.model_name,
  376. content=texts,
  377. task_type="retrieval_document",
  378. title="Embedding of list of strings")
  379. return np.array(result['embedding']),token_count
  380. def encode_queries(self, text):
  381. result = genai.embed_content(
  382. model=self.model_name,
  383. content=truncate(text,2048),
  384. task_type="retrieval_document",
  385. title="Embedding of single string")
  386. token_count = num_tokens_from_string(text)
  387. return np.array(result['embedding']),token_count
  388. class NvidiaEmbed(Base):
  389. def __init__(
  390. self, key, model_name, base_url="https://integrate.api.nvidia.com/v1/embeddings"
  391. ):
  392. if not base_url:
  393. base_url = "https://integrate.api.nvidia.com/v1/embeddings"
  394. self.api_key = key
  395. self.base_url = base_url
  396. self.headers = {
  397. "accept": "application/json",
  398. "Content-Type": "application/json",
  399. "authorization": f"Bearer {self.api_key}",
  400. }
  401. self.model_name = model_name
  402. if model_name == "nvidia/embed-qa-4":
  403. self.base_url = "https://ai.api.nvidia.com/v1/retrieval/nvidia/embeddings"
  404. self.model_name = "NV-Embed-QA"
  405. if model_name == "snowflake/arctic-embed-l":
  406. self.base_url = "https://ai.api.nvidia.com/v1/retrieval/snowflake/arctic-embed-l/embeddings"
  407. def encode(self, texts: list, batch_size=None):
  408. payload = {
  409. "input": texts,
  410. "input_type": "query",
  411. "model": self.model_name,
  412. "encoding_format": "float",
  413. "truncate": "END",
  414. }
  415. res = requests.post(self.base_url, headers=self.headers, json=payload).json()
  416. return (
  417. np.array([d["embedding"] for d in res["data"]]),
  418. res["usage"]["total_tokens"],
  419. )
  420. def encode_queries(self, text):
  421. embds, cnt = self.encode([text])
  422. return np.array(embds[0]), cnt
  423. class LmStudioEmbed(LocalAIEmbed):
  424. def __init__(self, key, model_name, base_url):
  425. if not base_url:
  426. raise ValueError("Local llm url cannot be None")
  427. if base_url.split("/")[-1] != "v1":
  428. base_url = os.path.join(base_url, "v1")
  429. self.client = OpenAI(api_key="lm-studio", base_url=base_url)
  430. self.model_name = model_name
  431. class OpenAI_APIEmbed(OpenAIEmbed):
  432. def __init__(self, key, model_name, base_url):
  433. if not base_url:
  434. raise ValueError("url cannot be None")
  435. if base_url.split("/")[-1] != "v1":
  436. base_url = os.path.join(base_url, "v1")
  437. self.client = OpenAI(api_key=key, base_url=base_url)
  438. self.model_name = model_name.split("___")[0]
  439. class CoHereEmbed(Base):
  440. def __init__(self, key, model_name, base_url=None):
  441. from cohere import Client
  442. self.client = Client(api_key=key)
  443. self.model_name = model_name
  444. def encode(self, texts: list, batch_size=32):
  445. res = self.client.embed(
  446. texts=texts,
  447. model=self.model_name,
  448. input_type="search_query",
  449. embedding_types=["float"],
  450. )
  451. return np.array([d for d in res.embeddings.float]), int(
  452. res.meta.billed_units.input_tokens
  453. )
  454. def encode_queries(self, text):
  455. res = self.client.embed(
  456. texts=[text],
  457. model=self.model_name,
  458. input_type="search_query",
  459. embedding_types=["float"],
  460. )
  461. return np.array([d for d in res.embeddings.float]), int(
  462. res.meta.billed_units.input_tokens
  463. )
  464. class TogetherAIEmbed(OllamaEmbed):
  465. def __init__(self, key, model_name, base_url="https://api.together.xyz/v1"):
  466. if not base_url:
  467. base_url = "https://api.together.xyz/v1"
  468. super().__init__(key, model_name, base_url)
  469. class PerfXCloudEmbed(OpenAIEmbed):
  470. def __init__(self, key, model_name, base_url="https://cloud.perfxlab.cn/v1"):
  471. if not base_url:
  472. base_url = "https://cloud.perfxlab.cn/v1"
  473. super().__init__(key, model_name, base_url)