您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

embedding_model.py 25KB

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