Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

embedding_model.py 26KB

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