Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

embedding_model.py 27KB

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