Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

embedding_model.py 25KB

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