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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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:
  55. with DefaultEmbedding._model_lock:
  56. from FlagEmbedding import FlagModel
  57. import torch
  58. if not DefaultEmbedding._model or model_name != DefaultEmbedding._model_name:
  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(DefaultEmbedding):
  217. def __init__(
  218. self,
  219. key: str | None = None,
  220. model_name: str = "BAAI/bge-small-en-v1.5",
  221. cache_dir: str | None = None,
  222. threads: int | None = None,
  223. **kwargs,
  224. ):
  225. if not settings.LIGHTEN:
  226. with FastEmbed._model_lock:
  227. from fastembed import TextEmbedding
  228. if not DefaultEmbedding._model or model_name != DefaultEmbedding._model_name:
  229. try:
  230. DefaultEmbedding._model = TextEmbedding(model_name, cache_dir, threads, **kwargs)
  231. DefaultEmbedding._model_name = model_name
  232. except Exception:
  233. cache_dir = snapshot_download(repo_id="BAAI/bge-small-en-v1.5",
  234. local_dir=os.path.join(get_home_cache_dir(),
  235. re.sub(r"^[a-zA-Z0-9]+/", "", model_name)),
  236. local_dir_use_symlinks=False)
  237. DefaultEmbedding._model = TextEmbedding(model_name, cache_dir, threads, **kwargs)
  238. self._model = DefaultEmbedding._model
  239. self._model_name = model_name
  240. def encode(self, texts: list):
  241. # Using the internal tokenizer to encode the texts and get the total
  242. # number of tokens
  243. encodings = self._model.model.tokenizer.encode_batch(texts)
  244. total_tokens = sum(len(e) for e in encodings)
  245. embeddings = [e.tolist() for e in self._model.embed(texts, batch_size=16)]
  246. return np.array(embeddings), total_tokens
  247. def encode_queries(self, text: str):
  248. # Using the internal tokenizer to encode the texts and get the total
  249. # number of tokens
  250. encoding = self._model.model.tokenizer.encode(text)
  251. embedding = next(self._model.query_embed(text)).tolist()
  252. return np.array(embedding), len(encoding.ids)
  253. class XinferenceEmbed(Base):
  254. def __init__(self, key, model_name="", base_url=""):
  255. if base_url.split("/")[-1] != "v1":
  256. base_url = os.path.join(base_url, "v1")
  257. self.client = OpenAI(api_key=key, base_url=base_url)
  258. self.model_name = model_name
  259. def encode(self, texts: list):
  260. batch_size = 16
  261. ress = []
  262. total_tokens = 0
  263. for i in range(0, len(texts), batch_size):
  264. res = self.client.embeddings.create(input=texts[i:i + batch_size], model=self.model_name)
  265. ress.extend([d.embedding for d in res.data])
  266. total_tokens += res.usage.total_tokens
  267. return np.array(ress), total_tokens
  268. def encode_queries(self, text):
  269. res = self.client.embeddings.create(input=[text],
  270. model=self.model_name)
  271. return np.array(res.data[0].embedding), res.usage.total_tokens
  272. class YoudaoEmbed(Base):
  273. _client = None
  274. def __init__(self, key=None, model_name="maidalun1020/bce-embedding-base_v1", **kwargs):
  275. if not settings.LIGHTEN and not YoudaoEmbed._client:
  276. from BCEmbedding import EmbeddingModel as qanthing
  277. try:
  278. logging.info("LOADING BCE...")
  279. YoudaoEmbed._client = qanthing(model_name_or_path=os.path.join(
  280. get_home_cache_dir(),
  281. "bce-embedding-base_v1"))
  282. except Exception:
  283. YoudaoEmbed._client = qanthing(
  284. model_name_or_path=model_name.replace(
  285. "maidalun1020", "InfiniFlow"))
  286. def encode(self, texts: list):
  287. batch_size = 10
  288. res = []
  289. token_count = 0
  290. for t in texts:
  291. token_count += num_tokens_from_string(t)
  292. for i in range(0, len(texts), batch_size):
  293. embds = YoudaoEmbed._client.encode(texts[i:i + batch_size])
  294. res.extend(embds)
  295. return np.array(res), token_count
  296. def encode_queries(self, text):
  297. embds = YoudaoEmbed._client.encode([text])
  298. return np.array(embds[0]), num_tokens_from_string(text)
  299. class JinaEmbed(Base):
  300. def __init__(self, key, model_name="jina-embeddings-v3",
  301. base_url="https://api.jina.ai/v1/embeddings"):
  302. self.base_url = "https://api.jina.ai/v1/embeddings"
  303. self.headers = {
  304. "Content-Type": "application/json",
  305. "Authorization": f"Bearer {key}"
  306. }
  307. self.model_name = model_name
  308. def encode(self, texts: list):
  309. texts = [truncate(t, 8196) for t in texts]
  310. batch_size = 16
  311. ress = []
  312. token_count = 0
  313. for i in range(0, len(texts), batch_size):
  314. data = {
  315. "model": self.model_name,
  316. "input": texts[i:i + batch_size],
  317. 'encoding_type': 'float'
  318. }
  319. res = requests.post(self.base_url, headers=self.headers, json=data).json()
  320. ress.extend([d["embedding"] for d in res["data"]])
  321. token_count += res["usage"]["total_tokens"]
  322. return np.array(ress), token_count
  323. def encode_queries(self, text):
  324. embds, cnt = self.encode([text])
  325. return np.array(embds[0]), cnt
  326. class InfinityEmbed(Base):
  327. _model = None
  328. def __init__(
  329. self,
  330. model_names: list[str] = ("BAAI/bge-small-en-v1.5",),
  331. engine_kwargs: dict = {},
  332. key = None,
  333. ):
  334. from infinity_emb import EngineArgs
  335. from infinity_emb.engine import AsyncEngineArray
  336. self._default_model = model_names[0]
  337. self.engine_array = AsyncEngineArray.from_args([EngineArgs(model_name_or_path = model_name, **engine_kwargs) for model_name in model_names])
  338. async def _embed(self, sentences: list[str], model_name: str = ""):
  339. if not model_name:
  340. model_name = self._default_model
  341. engine = self.engine_array[model_name]
  342. was_already_running = engine.is_running
  343. if not was_already_running:
  344. await engine.astart()
  345. embeddings, usage = await engine.embed(sentences=sentences)
  346. if not was_already_running:
  347. await engine.astop()
  348. return embeddings, usage
  349. def encode(self, texts: list[str], model_name: str = "") -> tuple[np.ndarray, int]:
  350. # Using the internal tokenizer to encode the texts and get the total
  351. # number of tokens
  352. embeddings, usage = asyncio.run(self._embed(texts, model_name))
  353. return np.array(embeddings), usage
  354. def encode_queries(self, text: str) -> tuple[np.ndarray, int]:
  355. # Using the internal tokenizer to encode the texts and get the total
  356. # number of tokens
  357. return self.encode([text])
  358. class MistralEmbed(Base):
  359. def __init__(self, key, model_name="mistral-embed",
  360. base_url=None):
  361. from mistralai.client import MistralClient
  362. self.client = MistralClient(api_key=key)
  363. self.model_name = model_name
  364. def encode(self, texts: list):
  365. texts = [truncate(t, 8196) for t in texts]
  366. batch_size = 16
  367. ress = []
  368. token_count = 0
  369. for i in range(0, len(texts), batch_size):
  370. res = self.client.embeddings(input=texts[i:i + batch_size],
  371. model=self.model_name)
  372. ress.extend([d.embedding for d in res.data])
  373. token_count += res.usage.total_tokens
  374. return np.array(ress), token_count
  375. def encode_queries(self, text):
  376. res = self.client.embeddings(input=[truncate(text, 8196)],
  377. model=self.model_name)
  378. return np.array(res.data[0].embedding), res.usage.total_tokens
  379. class BedrockEmbed(Base):
  380. def __init__(self, key, model_name,
  381. **kwargs):
  382. import boto3
  383. self.bedrock_ak = json.loads(key).get('bedrock_ak', '')
  384. self.bedrock_sk = json.loads(key).get('bedrock_sk', '')
  385. self.bedrock_region = json.loads(key).get('bedrock_region', '')
  386. self.model_name = model_name
  387. self.client = boto3.client(service_name='bedrock-runtime', region_name=self.bedrock_region,
  388. aws_access_key_id=self.bedrock_ak, aws_secret_access_key=self.bedrock_sk)
  389. def encode(self, texts: list):
  390. texts = [truncate(t, 8196) for t in texts]
  391. embeddings = []
  392. token_count = 0
  393. for text in texts:
  394. if self.model_name.split('.')[0] == 'amazon':
  395. body = {"inputText": text}
  396. elif self.model_name.split('.')[0] == 'cohere':
  397. body = {"texts": [text], "input_type": 'search_document'}
  398. response = self.client.invoke_model(modelId=self.model_name, body=json.dumps(body))
  399. model_response = json.loads(response["body"].read())
  400. embeddings.extend([model_response["embedding"]])
  401. token_count += num_tokens_from_string(text)
  402. return np.array(embeddings), token_count
  403. def encode_queries(self, text):
  404. embeddings = []
  405. token_count = num_tokens_from_string(text)
  406. if self.model_name.split('.')[0] == 'amazon':
  407. body = {"inputText": truncate(text, 8196)}
  408. elif self.model_name.split('.')[0] == 'cohere':
  409. body = {"texts": [truncate(text, 8196)], "input_type": 'search_query'}
  410. response = self.client.invoke_model(modelId=self.model_name, body=json.dumps(body))
  411. model_response = json.loads(response["body"].read())
  412. embeddings.extend(model_response["embedding"])
  413. return np.array(embeddings), token_count
  414. class GeminiEmbed(Base):
  415. def __init__(self, key, model_name='models/text-embedding-004',
  416. **kwargs):
  417. self.key = key
  418. self.model_name = 'models/' + model_name
  419. def encode(self, texts: list):
  420. texts = [truncate(t, 2048) for t in texts]
  421. token_count = sum(num_tokens_from_string(text) for text in texts)
  422. genai.configure(api_key=self.key)
  423. batch_size = 16
  424. ress = []
  425. for i in range(0, len(texts), batch_size):
  426. result = genai.embed_content(
  427. model=self.model_name,
  428. content=texts[i, i + batch_size],
  429. task_type="retrieval_document",
  430. title="Embedding of single string")
  431. ress.extend(result['embedding'])
  432. return np.array(ress),token_count
  433. def encode_queries(self, text):
  434. genai.configure(api_key=self.key)
  435. result = genai.embed_content(
  436. model=self.model_name,
  437. content=truncate(text,2048),
  438. task_type="retrieval_document",
  439. title="Embedding of single string")
  440. token_count = num_tokens_from_string(text)
  441. return np.array(result['embedding']),token_count
  442. class NvidiaEmbed(Base):
  443. def __init__(
  444. self, key, model_name, base_url="https://integrate.api.nvidia.com/v1/embeddings"
  445. ):
  446. if not base_url:
  447. base_url = "https://integrate.api.nvidia.com/v1/embeddings"
  448. self.api_key = key
  449. self.base_url = base_url
  450. self.headers = {
  451. "accept": "application/json",
  452. "Content-Type": "application/json",
  453. "authorization": f"Bearer {self.api_key}",
  454. }
  455. self.model_name = model_name
  456. if model_name == "nvidia/embed-qa-4":
  457. self.base_url = "https://ai.api.nvidia.com/v1/retrieval/nvidia/embeddings"
  458. self.model_name = "NV-Embed-QA"
  459. if model_name == "snowflake/arctic-embed-l":
  460. self.base_url = "https://ai.api.nvidia.com/v1/retrieval/snowflake/arctic-embed-l/embeddings"
  461. def encode(self, texts: list):
  462. batch_size = 16
  463. ress = []
  464. token_count = 0
  465. for i in range(0, len(texts), batch_size):
  466. payload = {
  467. "input": texts[i : i + batch_size],
  468. "input_type": "query",
  469. "model": self.model_name,
  470. "encoding_format": "float",
  471. "truncate": "END",
  472. }
  473. res = requests.post(self.base_url, headers=self.headers, json=payload).json()
  474. ress.extend([d["embedding"] for d in res["data"]])
  475. token_count += res["usage"]["total_tokens"]
  476. return np.array(ress), token_count
  477. def encode_queries(self, text):
  478. embds, cnt = self.encode([text])
  479. return np.array(embds[0]), cnt
  480. class LmStudioEmbed(LocalAIEmbed):
  481. def __init__(self, key, model_name, base_url):
  482. if not base_url:
  483. raise ValueError("Local llm url cannot be None")
  484. if base_url.split("/")[-1] != "v1":
  485. base_url = os.path.join(base_url, "v1")
  486. self.client = OpenAI(api_key="lm-studio", base_url=base_url)
  487. self.model_name = model_name
  488. class OpenAI_APIEmbed(OpenAIEmbed):
  489. def __init__(self, key, model_name, base_url):
  490. if not base_url:
  491. raise ValueError("url cannot be None")
  492. if base_url.split("/")[-1] != "v1":
  493. base_url = os.path.join(base_url, "v1")
  494. self.client = OpenAI(api_key=key, base_url=base_url)
  495. self.model_name = model_name.split("___")[0]
  496. class CoHereEmbed(Base):
  497. def __init__(self, key, model_name, base_url=None):
  498. from cohere import Client
  499. self.client = Client(api_key=key)
  500. self.model_name = model_name
  501. def encode(self, texts: list):
  502. batch_size = 16
  503. ress = []
  504. token_count = 0
  505. for i in range(0, len(texts), batch_size):
  506. res = self.client.embed(
  507. texts=texts[i : i + batch_size],
  508. model=self.model_name,
  509. input_type="search_document",
  510. embedding_types=["float"],
  511. )
  512. ress.extend([d for d in res.embeddings.float])
  513. token_count += res.meta.billed_units.input_tokens
  514. return np.array(ress), token_count
  515. def encode_queries(self, text):
  516. res = self.client.embed(
  517. texts=[text],
  518. model=self.model_name,
  519. input_type="search_query",
  520. embedding_types=["float"],
  521. )
  522. return np.array(res.embeddings.float[0]), int(
  523. res.meta.billed_units.input_tokens
  524. )
  525. class TogetherAIEmbed(OllamaEmbed):
  526. def __init__(self, key, model_name, base_url="https://api.together.xyz/v1"):
  527. if not base_url:
  528. base_url = "https://api.together.xyz/v1"
  529. super().__init__(key, model_name, base_url=base_url)
  530. class PerfXCloudEmbed(OpenAIEmbed):
  531. def __init__(self, key, model_name, base_url="https://cloud.perfxlab.cn/v1"):
  532. if not base_url:
  533. base_url = "https://cloud.perfxlab.cn/v1"
  534. super().__init__(key, model_name, base_url)
  535. class UpstageEmbed(OpenAIEmbed):
  536. def __init__(self, key, model_name, base_url="https://api.upstage.ai/v1/solar"):
  537. if not base_url:
  538. base_url = "https://api.upstage.ai/v1/solar"
  539. super().__init__(key, model_name, base_url)
  540. class SILICONFLOWEmbed(Base):
  541. def __init__(
  542. self, key, model_name, base_url="https://api.siliconflow.cn/v1/embeddings"
  543. ):
  544. if not base_url:
  545. base_url = "https://api.siliconflow.cn/v1/embeddings"
  546. self.headers = {
  547. "accept": "application/json",
  548. "content-type": "application/json",
  549. "authorization": f"Bearer {key}",
  550. }
  551. self.base_url = base_url
  552. self.model_name = model_name
  553. def encode(self, texts: list):
  554. batch_size = 16
  555. ress = []
  556. token_count = 0
  557. for i in range(0, len(texts), batch_size):
  558. texts_batch = texts[i : i + batch_size]
  559. payload = {
  560. "model": self.model_name,
  561. "input": texts_batch,
  562. "encoding_format": "float",
  563. }
  564. res = requests.post(self.base_url, json=payload, headers=self.headers).json()
  565. if "data" not in res or not isinstance(res["data"], list) or len(res["data"]) != len(texts_batch):
  566. raise ValueError(f"SILICONFLOWEmbed.encode got invalid response from {self.base_url}")
  567. ress.extend([d["embedding"] for d in res["data"]])
  568. token_count += res["usage"]["total_tokens"]
  569. return np.array(ress), token_count
  570. def encode_queries(self, text):
  571. payload = {
  572. "model": self.model_name,
  573. "input": text,
  574. "encoding_format": "float",
  575. }
  576. res = requests.post(self.base_url, json=payload, headers=self.headers).json()
  577. if "data" not in res or not isinstance(res["data"], list) or len(res["data"])!= 1:
  578. raise ValueError(f"SILICONFLOWEmbed.encode_queries got invalid response from {self.base_url}")
  579. return np.array(res["data"][0]["embedding"]), res["usage"]["total_tokens"]
  580. class ReplicateEmbed(Base):
  581. def __init__(self, key, model_name, base_url=None):
  582. from replicate.client import Client
  583. self.model_name = model_name
  584. self.client = Client(api_token=key)
  585. def encode(self, texts: list):
  586. batch_size = 16
  587. token_count = sum([num_tokens_from_string(text) for text in texts])
  588. ress = []
  589. for i in range(0, len(texts), batch_size):
  590. res = self.client.run(self.model_name, input={"texts": texts[i : i + batch_size]})
  591. ress.extend(res)
  592. return np.array(ress), token_count
  593. def encode_queries(self, text):
  594. res = self.client.embed(self.model_name, input={"texts": [text]})
  595. return np.array(res), num_tokens_from_string(text)
  596. class BaiduYiyanEmbed(Base):
  597. def __init__(self, key, model_name, base_url=None):
  598. import qianfan
  599. key = json.loads(key)
  600. ak = key.get("yiyan_ak", "")
  601. sk = key.get("yiyan_sk", "")
  602. self.client = qianfan.Embedding(ak=ak, sk=sk)
  603. self.model_name = model_name
  604. def encode(self, texts: list, batch_size=16):
  605. res = self.client.do(model=self.model_name, texts=texts).body
  606. return (
  607. np.array([r["embedding"] for r in res["data"]]),
  608. res["usage"]["total_tokens"],
  609. )
  610. def encode_queries(self, text):
  611. res = self.client.do(model=self.model_name, texts=[text]).body
  612. return (
  613. np.array([r["embedding"] for r in res["data"]]),
  614. res["usage"]["total_tokens"],
  615. )
  616. class VoyageEmbed(Base):
  617. def __init__(self, key, model_name, base_url=None):
  618. import voyageai
  619. self.client = voyageai.Client(api_key=key)
  620. self.model_name = model_name
  621. def encode(self, texts: list):
  622. batch_size = 16
  623. ress = []
  624. token_count = 0
  625. for i in range(0, len(texts), batch_size):
  626. res = self.client.embed(
  627. texts=texts[i : i + batch_size], model=self.model_name, input_type="document"
  628. )
  629. ress.extend(res.embeddings)
  630. token_count += res.total_tokens
  631. return np.array(ress), token_count
  632. def encode_queries(self, text):
  633. res = self.client.embed(
  634. texts=text, model=self.model_name, input_type="query"
  635. )
  636. return np.array(res.embeddings)[0], res.total_tokens
  637. class HuggingFaceEmbed(Base):
  638. def __init__(self, key, model_name, base_url=None):
  639. if not model_name:
  640. raise ValueError("Model name cannot be None")
  641. self.key = key
  642. self.model_name = model_name.split("___")[0]
  643. self.base_url = base_url or "http://127.0.0.1:8080"
  644. def encode(self, texts: list):
  645. embeddings = []
  646. for text in texts:
  647. response = requests.post(
  648. f"{self.base_url}/embed",
  649. json={"inputs": text},
  650. headers={'Content-Type': 'application/json'}
  651. )
  652. if response.status_code == 200:
  653. embedding = response.json()
  654. embeddings.append(embedding[0])
  655. else:
  656. raise Exception(f"Error: {response.status_code} - {response.text}")
  657. return np.array(embeddings), sum([num_tokens_from_string(text) for text in texts])
  658. def encode_queries(self, text):
  659. response = requests.post(
  660. f"{self.base_url}/embed",
  661. json={"inputs": text},
  662. headers={'Content-Type': 'application/json'}
  663. )
  664. if response.status_code == 200:
  665. embedding = response.json()
  666. return np.array(embedding[0]), num_tokens_from_string(text)
  667. else:
  668. raise Exception(f"Error: {response.status_code} - {response.text}")
  669. class VolcEngineEmbed(OpenAIEmbed):
  670. def __init__(self, key, model_name, base_url="https://ark.cn-beijing.volces.com/api/v3"):
  671. if not base_url:
  672. base_url = "https://ark.cn-beijing.volces.com/api/v3"
  673. ark_api_key = json.loads(key).get('ark_api_key', '')
  674. model_name = json.loads(key).get('ep_id', '') + json.loads(key).get('endpoint_id', '')
  675. super().__init__(ark_api_key,model_name,base_url)