Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

embedding_model.py 32KB

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