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.

embedding_model.py 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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 logging
  17. import re
  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. import numpy as np
  28. import asyncio
  29. from api import settings
  30. from api.utils.file_utils import get_home_cache_dir
  31. from rag.utils import num_tokens_from_string, truncate
  32. import google.generativeai as genai
  33. import json
  34. class Base(ABC):
  35. def __init__(self, key, model_name):
  36. pass
  37. def encode(self, texts: list):
  38. raise NotImplementedError("Please implement encode method!")
  39. def encode_queries(self, text: str):
  40. raise NotImplementedError("Please implement encode method!")
  41. class DefaultEmbedding(Base):
  42. _model = None
  43. _model_name = ""
  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 settings.LIGHTEN and not DefaultEmbedding._model:
  55. with DefaultEmbedding._model_lock:
  56. from FlagEmbedding import FlagModel
  57. import torch
  58. if not DefaultEmbedding._model:
  59. try:
  60. DefaultEmbedding._model = FlagModel(os.path.join(get_home_cache_dir(), re.sub(r"^[a-zA-Z0-9]+/", "", model_name)),
  61. query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:",
  62. use_fp16=torch.cuda.is_available())
  63. DefaultEmbedding._model_name = model_name
  64. except Exception:
  65. model_dir = snapshot_download(repo_id="BAAI/bge-large-zh-v1.5",
  66. local_dir=os.path.join(get_home_cache_dir(), re.sub(r"^[a-zA-Z0-9]+/", "", model_name)),
  67. local_dir_use_symlinks=False)
  68. DefaultEmbedding._model = FlagModel(model_dir,
  69. query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:",
  70. use_fp16=torch.cuda.is_available())
  71. self._model = DefaultEmbedding._model
  72. self._model_name = DefaultEmbedding._model_name
  73. def encode(self, texts: list):
  74. batch_size = 16
  75. texts = [truncate(t, 2048) for t in texts]
  76. token_count = 0
  77. for t in texts:
  78. token_count += num_tokens_from_string(t)
  79. ress = []
  80. for i in range(0, len(texts), batch_size):
  81. ress.extend(self._model.encode(texts[i:i + batch_size]).tolist())
  82. return np.array(ress), token_count
  83. def encode_queries(self, text: str):
  84. token_count = num_tokens_from_string(text)
  85. return self._model.encode_queries([text]).tolist()[0], token_count
  86. class OpenAIEmbed(Base):
  87. def __init__(self, key, model_name="text-embedding-ada-002",
  88. base_url="https://api.openai.com/v1"):
  89. if not base_url:
  90. base_url = "https://api.openai.com/v1"
  91. self.client = OpenAI(api_key=key, base_url=base_url)
  92. self.model_name = model_name
  93. def encode(self, texts: list):
  94. # OpenAI requires batch size <=16
  95. batch_size = 16
  96. texts = [truncate(t, 8191) for t in texts]
  97. ress = []
  98. total_tokens = 0
  99. for i in range(0, len(texts), batch_size):
  100. res = self.client.embeddings.create(input=texts[i:i + batch_size],
  101. model=self.model_name)
  102. ress.extend([d.embedding for d in res.data])
  103. total_tokens += res.usage.total_tokens
  104. return np.array(ress), total_tokens
  105. def encode_queries(self, text):
  106. res = self.client.embeddings.create(input=[truncate(text, 8191)],
  107. model=self.model_name)
  108. return np.array(res.data[0].embedding), res.usage.total_tokens
  109. class LocalAIEmbed(Base):
  110. def __init__(self, key, model_name, base_url):
  111. if not base_url:
  112. raise ValueError("Local embedding model url cannot be None")
  113. if base_url.split("/")[-1] != "v1":
  114. base_url = os.path.join(base_url, "v1")
  115. self.client = OpenAI(api_key="empty", base_url=base_url)
  116. self.model_name = model_name.split("___")[0]
  117. def encode(self, texts: list):
  118. batch_size = 16
  119. ress = []
  120. for i in range(0, len(texts), batch_size):
  121. res = self.client.embeddings.create(input=texts[i:i + batch_size], model=self.model_name)
  122. ress.extend([d.embedding for d in res.data])
  123. # local embedding for LmStudio donot count tokens
  124. return np.array(ress), 1024
  125. def encode_queries(self, text):
  126. embds, cnt = self.encode([text])
  127. return np.array(embds[0]), cnt
  128. class AzureEmbed(OpenAIEmbed):
  129. def __init__(self, key, model_name, **kwargs):
  130. from openai.lib.azure import AzureOpenAI
  131. api_key = json.loads(key).get('api_key', '')
  132. api_version = json.loads(key).get('api_version', '2024-02-01')
  133. self.client = AzureOpenAI(api_key=api_key, azure_endpoint=kwargs["base_url"], api_version=api_version)
  134. self.model_name = model_name
  135. class BaiChuanEmbed(OpenAIEmbed):
  136. def __init__(self, key,
  137. model_name='Baichuan-Text-Embedding',
  138. base_url='https://api.baichuan-ai.com/v1'):
  139. if not base_url:
  140. base_url = "https://api.baichuan-ai.com/v1"
  141. super().__init__(key, model_name, base_url)
  142. class QWenEmbed(Base):
  143. def __init__(self, key, model_name="text_embedding_v2", **kwargs):
  144. self.key = key
  145. self.model_name = model_name
  146. def encode(self, texts: list):
  147. import dashscope
  148. batch_size = 4
  149. try:
  150. res = []
  151. token_count = 0
  152. texts = [truncate(t, 2048) for t in texts]
  153. for i in range(0, len(texts), batch_size):
  154. resp = dashscope.TextEmbedding.call(
  155. model=self.model_name,
  156. input=texts[i:i + batch_size],
  157. api_key=self.key,
  158. text_type="document"
  159. )
  160. embds = [[] for _ in range(len(resp["output"]["embeddings"]))]
  161. for e in resp["output"]["embeddings"]:
  162. embds[e["text_index"]] = e["embedding"]
  163. res.extend(embds)
  164. token_count += resp["usage"]["total_tokens"]
  165. return np.array(res), token_count
  166. except Exception as e:
  167. raise Exception("Account abnormal. Please ensure it's on good standing to use QWen's "+self.model_name)
  168. return np.array([]), 0
  169. def encode_queries(self, text):
  170. try:
  171. resp = dashscope.TextEmbedding.call(
  172. model=self.model_name,
  173. input=text[:2048],
  174. api_key=self.key,
  175. text_type="query"
  176. )
  177. return np.array(resp["output"]["embeddings"][0]
  178. ["embedding"]), resp["usage"]["total_tokens"]
  179. except Exception:
  180. raise Exception("Account abnormal. Please ensure it's on good standing to use QWen's "+self.model_name)
  181. return np.array([]), 0
  182. class ZhipuEmbed(Base):
  183. def __init__(self, key, model_name="embedding-2", **kwargs):
  184. self.client = ZhipuAI(api_key=key)
  185. self.model_name = model_name
  186. def encode(self, texts: list):
  187. arr = []
  188. tks_num = 0
  189. for txt in texts:
  190. res = self.client.embeddings.create(input=txt,
  191. model=self.model_name)
  192. arr.append(res.data[0].embedding)
  193. tks_num += res.usage.total_tokens
  194. return np.array(arr), tks_num
  195. def encode_queries(self, text):
  196. res = self.client.embeddings.create(input=text,
  197. model=self.model_name)
  198. return np.array(res.data[0].embedding), res.usage.total_tokens
  199. class OllamaEmbed(Base):
  200. def __init__(self, key, model_name, **kwargs):
  201. self.client = Client(host=kwargs["base_url"])
  202. self.model_name = model_name
  203. def encode(self, texts: list):
  204. arr = []
  205. tks_num = 0
  206. for txt in texts:
  207. res = self.client.embeddings(prompt=txt,
  208. model=self.model_name)
  209. arr.append(res["embedding"])
  210. tks_num += 128
  211. return np.array(arr), tks_num
  212. def encode_queries(self, text):
  213. res = self.client.embeddings(prompt=text,
  214. model=self.model_name)
  215. return np.array(res["embedding"]), 128
  216. class FastEmbed(Base):
  217. _model = None
  218. _model_name = ""
  219. _model_lock = threading.Lock()
  220. def __init__(
  221. self,
  222. key: str | None = None,
  223. model_name: str = "BAAI/bge-small-en-v1.5",
  224. cache_dir: str | None = None,
  225. threads: int | None = None,
  226. **kwargs,
  227. ):
  228. if not settings.LIGHTEN and not FastEmbed._model:
  229. with FastEmbed._model_lock:
  230. from fastembed import TextEmbedding
  231. if not FastEmbed._model or model_name != FastEmbed._model_name:
  232. try:
  233. FastEmbed._model = TextEmbedding(model_name, cache_dir, threads, **kwargs)
  234. FastEmbed._model_name = model_name
  235. except Exception:
  236. cache_dir = snapshot_download(repo_id="BAAI/bge-small-en-v1.5",
  237. local_dir=os.path.join(get_home_cache_dir(),
  238. re.sub(r"^[a-zA-Z0-9]+/", "", model_name)),
  239. local_dir_use_symlinks=False)
  240. FastEmbed._model = TextEmbedding(model_name, cache_dir, threads, **kwargs)
  241. self._model = FastEmbed._model
  242. self._model_name = model_name
  243. def encode(self, texts: list):
  244. # Using the internal tokenizer to encode the texts and get the total
  245. # number of tokens
  246. encodings = self._model.model.tokenizer.encode_batch(texts)
  247. total_tokens = sum(len(e) for e in encodings)
  248. embeddings = [e.tolist() for e in self._model.embed(texts, batch_size=16)]
  249. return np.array(embeddings), total_tokens
  250. def encode_queries(self, text: str):
  251. # Using the internal tokenizer to encode the texts and get the total
  252. # number of tokens
  253. encoding = self._model.model.tokenizer.encode(text)
  254. embedding = next(self._model.query_embed(text)).tolist()
  255. return np.array(embedding), len(encoding.ids)
  256. class XinferenceEmbed(Base):
  257. def __init__(self, key, model_name="", base_url=""):
  258. if base_url.split("/")[-1] != "v1":
  259. base_url = os.path.join(base_url, "v1")
  260. self.client = OpenAI(api_key=key, base_url=base_url)
  261. self.model_name = model_name
  262. def encode(self, texts: list):
  263. batch_size = 16
  264. ress = []
  265. total_tokens = 0
  266. for i in range(0, len(texts), batch_size):
  267. res = self.client.embeddings.create(input=texts[i:i + batch_size], model=self.model_name)
  268. ress.extend([d.embedding for d in res.data])
  269. total_tokens += res.usage.total_tokens
  270. return np.array(ress), total_tokens
  271. def encode_queries(self, text):
  272. res = self.client.embeddings.create(input=[text],
  273. model=self.model_name)
  274. return np.array(res.data[0].embedding), res.usage.total_tokens
  275. class YoudaoEmbed(Base):
  276. _client = None
  277. def __init__(self, key=None, model_name="maidalun1020/bce-embedding-base_v1", **kwargs):
  278. if not settings.LIGHTEN and not YoudaoEmbed._client:
  279. from BCEmbedding import EmbeddingModel as qanthing
  280. try:
  281. logging.info("LOADING BCE...")
  282. YoudaoEmbed._client = qanthing(model_name_or_path=os.path.join(
  283. get_home_cache_dir(),
  284. "bce-embedding-base_v1"))
  285. except Exception:
  286. YoudaoEmbed._client = qanthing(
  287. model_name_or_path=model_name.replace(
  288. "maidalun1020", "InfiniFlow"))
  289. def encode(self, texts: list):
  290. batch_size = 10
  291. res = []
  292. token_count = 0
  293. for t in texts:
  294. token_count += num_tokens_from_string(t)
  295. for i in range(0, len(texts), batch_size):
  296. embds = YoudaoEmbed._client.encode(texts[i:i + batch_size])
  297. res.extend(embds)
  298. return np.array(res), token_count
  299. def encode_queries(self, text):
  300. embds = YoudaoEmbed._client.encode([text])
  301. return np.array(embds[0]), num_tokens_from_string(text)
  302. class JinaEmbed(Base):
  303. def __init__(self, key, model_name="jina-embeddings-v3",
  304. base_url="https://api.jina.ai/v1/embeddings"):
  305. self.base_url = "https://api.jina.ai/v1/embeddings"
  306. self.headers = {
  307. "Content-Type": "application/json",
  308. "Authorization": f"Bearer {key}"
  309. }
  310. self.model_name = model_name
  311. def encode(self, texts: list):
  312. texts = [truncate(t, 8196) for t in texts]
  313. batch_size = 16
  314. ress = []
  315. token_count = 0
  316. for i in range(0, len(texts), batch_size):
  317. data = {
  318. "model": self.model_name,
  319. "input": texts[i:i + batch_size],
  320. 'encoding_type': 'float'
  321. }
  322. res = requests.post(self.base_url, headers=self.headers, json=data).json()
  323. ress.extend([d["embedding"] for d in res["data"]])
  324. token_count += res["usage"]["total_tokens"]
  325. return np.array(ress), token_count
  326. def encode_queries(self, text):
  327. embds, cnt = self.encode([text])
  328. return np.array(embds[0]), cnt
  329. class InfinityEmbed(Base):
  330. _model = None
  331. def __init__(
  332. self,
  333. model_names: list[str] = ("BAAI/bge-small-en-v1.5",),
  334. engine_kwargs: dict = {},
  335. key = None,
  336. ):
  337. from infinity_emb import EngineArgs
  338. from infinity_emb.engine import AsyncEngineArray
  339. self._default_model = model_names[0]
  340. self.engine_array = AsyncEngineArray.from_args([EngineArgs(model_name_or_path = model_name, **engine_kwargs) for model_name in model_names])
  341. async def _embed(self, sentences: list[str], model_name: str = ""):
  342. if not model_name:
  343. model_name = self._default_model
  344. engine = self.engine_array[model_name]
  345. was_already_running = engine.is_running
  346. if not was_already_running:
  347. await engine.astart()
  348. embeddings, usage = await engine.embed(sentences=sentences)
  349. if not was_already_running:
  350. await engine.astop()
  351. return embeddings, usage
  352. def encode(self, texts: list[str], model_name: str = "") -> tuple[np.ndarray, int]:
  353. # Using the internal tokenizer to encode the texts and get the total
  354. # number of tokens
  355. embeddings, usage = asyncio.run(self._embed(texts, model_name))
  356. return np.array(embeddings), usage
  357. def encode_queries(self, text: str) -> tuple[np.ndarray, int]:
  358. # Using the internal tokenizer to encode the texts and get the total
  359. # number of tokens
  360. return self.encode([text])
  361. class MistralEmbed(Base):
  362. def __init__(self, key, model_name="mistral-embed",
  363. base_url=None):
  364. from mistralai.client import MistralClient
  365. self.client = MistralClient(api_key=key)
  366. self.model_name = model_name
  367. def encode(self, texts: list):
  368. texts = [truncate(t, 8196) for t in texts]
  369. batch_size = 16
  370. ress = []
  371. token_count = 0
  372. for i in range(0, len(texts), batch_size):
  373. res = self.client.embeddings(input=texts[i:i + batch_size],
  374. model=self.model_name)
  375. ress.extend([d.embedding for d in res.data])
  376. token_count += res.usage.total_tokens
  377. return np.array(ress), token_count
  378. def encode_queries(self, text):
  379. res = self.client.embeddings(input=[truncate(text, 8196)],
  380. model=self.model_name)
  381. return np.array(res.data[0].embedding), res.usage.total_tokens
  382. class BedrockEmbed(Base):
  383. def __init__(self, key, model_name,
  384. **kwargs):
  385. import boto3
  386. self.bedrock_ak = json.loads(key).get('bedrock_ak', '')
  387. self.bedrock_sk = json.loads(key).get('bedrock_sk', '')
  388. self.bedrock_region = json.loads(key).get('bedrock_region', '')
  389. self.model_name = model_name
  390. self.client = boto3.client(service_name='bedrock-runtime', region_name=self.bedrock_region,
  391. aws_access_key_id=self.bedrock_ak, aws_secret_access_key=self.bedrock_sk)
  392. def encode(self, texts: list):
  393. texts = [truncate(t, 8196) for t in texts]
  394. embeddings = []
  395. token_count = 0
  396. for text in texts:
  397. if self.model_name.split('.')[0] == 'amazon':
  398. body = {"inputText": text}
  399. elif self.model_name.split('.')[0] == 'cohere':
  400. body = {"texts": [text], "input_type": 'search_document'}
  401. response = self.client.invoke_model(modelId=self.model_name, body=json.dumps(body))
  402. model_response = json.loads(response["body"].read())
  403. embeddings.extend([model_response["embedding"]])
  404. token_count += num_tokens_from_string(text)
  405. return np.array(embeddings), token_count
  406. def encode_queries(self, text):
  407. embeddings = []
  408. token_count = num_tokens_from_string(text)
  409. if self.model_name.split('.')[0] == 'amazon':
  410. body = {"inputText": truncate(text, 8196)}
  411. elif self.model_name.split('.')[0] == 'cohere':
  412. body = {"texts": [truncate(text, 8196)], "input_type": 'search_query'}
  413. response = self.client.invoke_model(modelId=self.model_name, body=json.dumps(body))
  414. model_response = json.loads(response["body"].read())
  415. embeddings.extend(model_response["embedding"])
  416. return np.array(embeddings), token_count
  417. class GeminiEmbed(Base):
  418. def __init__(self, key, model_name='models/text-embedding-004',
  419. **kwargs):
  420. self.key = key
  421. self.model_name = 'models/' + model_name
  422. def encode(self, texts: list):
  423. texts = [truncate(t, 2048) for t in texts]
  424. token_count = sum(num_tokens_from_string(text) for text in texts)
  425. genai.configure(api_key=self.key)
  426. batch_size = 16
  427. ress = []
  428. for i in range(0, len(texts), batch_size):
  429. result = genai.embed_content(
  430. model=self.model_name,
  431. content=texts[i, i + batch_size],
  432. task_type="retrieval_document",
  433. title="Embedding of single string")
  434. ress.extend(result['embedding'])
  435. return np.array(ress),token_count
  436. def encode_queries(self, text):
  437. genai.configure(api_key=self.key)
  438. result = genai.embed_content(
  439. model=self.model_name,
  440. content=truncate(text,2048),
  441. task_type="retrieval_document",
  442. title="Embedding of single string")
  443. token_count = num_tokens_from_string(text)
  444. return np.array(result['embedding']),token_count
  445. class NvidiaEmbed(Base):
  446. def __init__(
  447. self, key, model_name, base_url="https://integrate.api.nvidia.com/v1/embeddings"
  448. ):
  449. if not base_url:
  450. base_url = "https://integrate.api.nvidia.com/v1/embeddings"
  451. self.api_key = key
  452. self.base_url = base_url
  453. self.headers = {
  454. "accept": "application/json",
  455. "Content-Type": "application/json",
  456. "authorization": f"Bearer {self.api_key}",
  457. }
  458. self.model_name = model_name
  459. if model_name == "nvidia/embed-qa-4":
  460. self.base_url = "https://ai.api.nvidia.com/v1/retrieval/nvidia/embeddings"
  461. self.model_name = "NV-Embed-QA"
  462. if model_name == "snowflake/arctic-embed-l":
  463. self.base_url = "https://ai.api.nvidia.com/v1/retrieval/snowflake/arctic-embed-l/embeddings"
  464. def encode(self, texts: list):
  465. batch_size = 16
  466. ress = []
  467. token_count = 0
  468. for i in range(0, len(texts), batch_size):
  469. payload = {
  470. "input": texts[i : i + batch_size],
  471. "input_type": "query",
  472. "model": self.model_name,
  473. "encoding_format": "float",
  474. "truncate": "END",
  475. }
  476. res = requests.post(self.base_url, headers=self.headers, json=payload).json()
  477. ress.extend([d["embedding"] for d in res["data"]])
  478. token_count += res["usage"]["total_tokens"]
  479. return np.array(ress), token_count
  480. def encode_queries(self, text):
  481. embds, cnt = self.encode([text])
  482. return np.array(embds[0]), cnt
  483. class LmStudioEmbed(LocalAIEmbed):
  484. def __init__(self, key, model_name, base_url):
  485. if not base_url:
  486. raise ValueError("Local llm url cannot be None")
  487. if base_url.split("/")[-1] != "v1":
  488. base_url = os.path.join(base_url, "v1")
  489. self.client = OpenAI(api_key="lm-studio", base_url=base_url)
  490. self.model_name = model_name
  491. class OpenAI_APIEmbed(OpenAIEmbed):
  492. def __init__(self, key, model_name, base_url):
  493. if not base_url:
  494. raise ValueError("url cannot be None")
  495. if base_url.split("/")[-1] != "v1":
  496. base_url = os.path.join(base_url, "v1")
  497. self.client = OpenAI(api_key=key, base_url=base_url)
  498. self.model_name = model_name.split("___")[0]
  499. class CoHereEmbed(Base):
  500. def __init__(self, key, model_name, base_url=None):
  501. from cohere import Client
  502. self.client = Client(api_key=key)
  503. self.model_name = model_name
  504. def encode(self, texts: list):
  505. batch_size = 16
  506. ress = []
  507. token_count = 0
  508. for i in range(0, len(texts), batch_size):
  509. res = self.client.embed(
  510. texts=texts[i : i + batch_size],
  511. model=self.model_name,
  512. input_type="search_document",
  513. embedding_types=["float"],
  514. )
  515. ress.extend([d for d in res.embeddings.float])
  516. token_count += res.meta.billed_units.input_tokens
  517. return np.array(ress), token_count
  518. def encode_queries(self, text):
  519. res = self.client.embed(
  520. texts=[text],
  521. model=self.model_name,
  522. input_type="search_query",
  523. embedding_types=["float"],
  524. )
  525. return np.array(res.embeddings.float[0]), int(
  526. res.meta.billed_units.input_tokens
  527. )
  528. class TogetherAIEmbed(OllamaEmbed):
  529. def __init__(self, key, model_name, base_url="https://api.together.xyz/v1"):
  530. if not base_url:
  531. base_url = "https://api.together.xyz/v1"
  532. super().__init__(key, model_name, base_url=base_url)
  533. class PerfXCloudEmbed(OpenAIEmbed):
  534. def __init__(self, key, model_name, base_url="https://cloud.perfxlab.cn/v1"):
  535. if not base_url:
  536. base_url = "https://cloud.perfxlab.cn/v1"
  537. super().__init__(key, model_name, base_url)
  538. class UpstageEmbed(OpenAIEmbed):
  539. def __init__(self, key, model_name, base_url="https://api.upstage.ai/v1/solar"):
  540. if not base_url:
  541. base_url = "https://api.upstage.ai/v1/solar"
  542. super().__init__(key, model_name, base_url)
  543. class SILICONFLOWEmbed(Base):
  544. def __init__(
  545. self, key, model_name, base_url="https://api.siliconflow.cn/v1/embeddings"
  546. ):
  547. if not base_url:
  548. base_url = "https://api.siliconflow.cn/v1/embeddings"
  549. self.headers = {
  550. "accept": "application/json",
  551. "content-type": "application/json",
  552. "authorization": f"Bearer {key}",
  553. }
  554. self.base_url = base_url
  555. self.model_name = model_name
  556. def encode(self, texts: list):
  557. batch_size = 16
  558. ress = []
  559. token_count = 0
  560. for i in range(0, len(texts), batch_size):
  561. texts_batch = texts[i : i + batch_size]
  562. payload = {
  563. "model": self.model_name,
  564. "input": texts_batch,
  565. "encoding_format": "float",
  566. }
  567. res = requests.post(self.base_url, json=payload, headers=self.headers).json()
  568. if "data" not in res or not isinstance(res["data"], list) or len(res["data"]) != len(texts_batch):
  569. raise ValueError(f"SILICONFLOWEmbed.encode got invalid response from {self.base_url}")
  570. ress.extend([d["embedding"] for d in res["data"]])
  571. token_count += res["usage"]["total_tokens"]
  572. return np.array(ress), token_count
  573. def encode_queries(self, text):
  574. payload = {
  575. "model": self.model_name,
  576. "input": text,
  577. "encoding_format": "float",
  578. }
  579. res = requests.post(self.base_url, json=payload, headers=self.headers).json()
  580. if "data" not in res or not isinstance(res["data"], list) or len(res["data"])!= 1:
  581. raise ValueError(f"SILICONFLOWEmbed.encode_queries got invalid response from {self.base_url}")
  582. return np.array(res["data"][0]["embedding"]), res["usage"]["total_tokens"]
  583. class ReplicateEmbed(Base):
  584. def __init__(self, key, model_name, base_url=None):
  585. from replicate.client import Client
  586. self.model_name = model_name
  587. self.client = Client(api_token=key)
  588. def encode(self, texts: list):
  589. batch_size = 16
  590. token_count = sum([num_tokens_from_string(text) for text in texts])
  591. ress = []
  592. for i in range(0, len(texts), batch_size):
  593. res = self.client.run(self.model_name, input={"texts": texts[i : i + batch_size]})
  594. ress.extend(res)
  595. return np.array(ress), token_count
  596. def encode_queries(self, text):
  597. res = self.client.embed(self.model_name, input={"texts": [text]})
  598. return np.array(res), num_tokens_from_string(text)
  599. class BaiduYiyanEmbed(Base):
  600. def __init__(self, key, model_name, base_url=None):
  601. import qianfan
  602. key = json.loads(key)
  603. ak = key.get("yiyan_ak", "")
  604. sk = key.get("yiyan_sk", "")
  605. self.client = qianfan.Embedding(ak=ak, sk=sk)
  606. self.model_name = model_name
  607. def encode(self, texts: list, batch_size=16):
  608. res = self.client.do(model=self.model_name, texts=texts).body
  609. return (
  610. np.array([r["embedding"] for r in res["data"]]),
  611. res["usage"]["total_tokens"],
  612. )
  613. def encode_queries(self, text):
  614. res = self.client.do(model=self.model_name, texts=[text]).body
  615. return (
  616. np.array([r["embedding"] for r in res["data"]]),
  617. res["usage"]["total_tokens"],
  618. )
  619. class VoyageEmbed(Base):
  620. def __init__(self, key, model_name, base_url=None):
  621. import voyageai
  622. self.client = voyageai.Client(api_key=key)
  623. self.model_name = model_name
  624. def encode(self, texts: list):
  625. batch_size = 16
  626. ress = []
  627. token_count = 0
  628. for i in range(0, len(texts), batch_size):
  629. res = self.client.embed(
  630. texts=texts[i : i + batch_size], model=self.model_name, input_type="document"
  631. )
  632. ress.extend(res.embeddings)
  633. token_count += res.total_tokens
  634. return np.array(ress), token_count
  635. def encode_queries(self, text):
  636. res = self.client.embed(
  637. texts=text, model=self.model_name, input_type="query"
  638. )
  639. return np.array(res.embeddings)[0], res.total_tokens
  640. class HuggingFaceEmbed(Base):
  641. def __init__(self, key, model_name, base_url=None):
  642. if not model_name:
  643. raise ValueError("Model name cannot be None")
  644. self.key = key
  645. self.model_name = model_name.split("___")[0]
  646. self.base_url = base_url or "http://127.0.0.1:8080"
  647. def encode(self, texts: list):
  648. embeddings = []
  649. for text in texts:
  650. response = requests.post(
  651. f"{self.base_url}/embed",
  652. json={"inputs": text},
  653. headers={'Content-Type': 'application/json'}
  654. )
  655. if response.status_code == 200:
  656. embedding = response.json()
  657. embeddings.append(embedding[0])
  658. else:
  659. raise Exception(f"Error: {response.status_code} - {response.text}")
  660. return np.array(embeddings), sum([num_tokens_from_string(text) for text in texts])
  661. def encode_queries(self, text):
  662. response = requests.post(
  663. f"{self.base_url}/embed",
  664. json={"inputs": text},
  665. headers={'Content-Type': 'application/json'}
  666. )
  667. if response.status_code == 200:
  668. embedding = response.json()
  669. return np.array(embedding[0]), num_tokens_from_string(text)
  670. else:
  671. raise Exception(f"Error: {response.status_code} - {response.text}")
  672. class VolcEngineEmbed(OpenAIEmbed):
  673. def __init__(self, key, model_name, base_url="https://ark.cn-beijing.volces.com/api/v3"):
  674. if not base_url:
  675. base_url = "https://ark.cn-beijing.volces.com/api/v3"
  676. ark_api_key = json.loads(key).get('ark_api_key', '')
  677. model_name = json.loads(key).get('ep_id', '') + json.loads(key).get('endpoint_id', '')
  678. super().__init__(ark_api_key,model_name,base_url)