Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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