You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

embedding_model.py 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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. self.client = OpenAI(api_key="xxx", base_url=base_url)
  228. self.model_name = model_name
  229. def encode(self, texts: list, batch_size=32):
  230. res = self.client.embeddings.create(input=texts,
  231. model=self.model_name)
  232. return np.array([d.embedding for d in res.data]
  233. ), res.usage.total_tokens
  234. def encode_queries(self, text):
  235. res = self.client.embeddings.create(input=[text],
  236. model=self.model_name)
  237. return np.array(res.data[0].embedding), res.usage.total_tokens
  238. class YoudaoEmbed(Base):
  239. _client = None
  240. def __init__(self, key=None, model_name="maidalun1020/bce-embedding-base_v1", **kwargs):
  241. from BCEmbedding import EmbeddingModel as qanthing
  242. if not YoudaoEmbed._client:
  243. try:
  244. print("LOADING BCE...")
  245. YoudaoEmbed._client = qanthing(model_name_or_path=os.path.join(
  246. get_home_cache_dir(),
  247. "bce-embedding-base_v1"))
  248. except Exception as e:
  249. YoudaoEmbed._client = qanthing(
  250. model_name_or_path=model_name.replace(
  251. "maidalun1020", "InfiniFlow"))
  252. def encode(self, texts: list, batch_size=10):
  253. res = []
  254. token_count = 0
  255. for t in texts:
  256. token_count += num_tokens_from_string(t)
  257. for i in range(0, len(texts), batch_size):
  258. embds = YoudaoEmbed._client.encode(texts[i:i + batch_size])
  259. res.extend(embds)
  260. return np.array(res), token_count
  261. def encode_queries(self, text):
  262. embds = YoudaoEmbed._client.encode([text])
  263. return np.array(embds[0]), num_tokens_from_string(text)
  264. class JinaEmbed(Base):
  265. def __init__(self, key, model_name="jina-embeddings-v2-base-zh",
  266. base_url="https://api.jina.ai/v1/embeddings"):
  267. self.base_url = "https://api.jina.ai/v1/embeddings"
  268. self.headers = {
  269. "Content-Type": "application/json",
  270. "Authorization": f"Bearer {key}"
  271. }
  272. self.model_name = model_name
  273. def encode(self, texts: list, batch_size=None):
  274. texts = [truncate(t, 8196) for t in texts]
  275. data = {
  276. "model": self.model_name,
  277. "input": texts,
  278. 'encoding_type': 'float'
  279. }
  280. res = requests.post(self.base_url, headers=self.headers, json=data).json()
  281. return np.array([d["embedding"] for d in res["data"]]), res["usage"]["total_tokens"]
  282. def encode_queries(self, text):
  283. embds, cnt = self.encode([text])
  284. return np.array(embds[0]), cnt
  285. class InfinityEmbed(Base):
  286. _model = None
  287. def __init__(
  288. self,
  289. model_names: list[str] = ("BAAI/bge-small-en-v1.5",),
  290. engine_kwargs: dict = {},
  291. key = None,
  292. ):
  293. from infinity_emb import EngineArgs
  294. from infinity_emb.engine import AsyncEngineArray
  295. self._default_model = model_names[0]
  296. self.engine_array = AsyncEngineArray.from_args([EngineArgs(model_name_or_path = model_name, **engine_kwargs) for model_name in model_names])
  297. async def _embed(self, sentences: list[str], model_name: str = ""):
  298. if not model_name:
  299. model_name = self._default_model
  300. engine = self.engine_array[model_name]
  301. was_already_running = engine.is_running
  302. if not was_already_running:
  303. await engine.astart()
  304. embeddings, usage = await engine.embed(sentences=sentences)
  305. if not was_already_running:
  306. await engine.astop()
  307. return embeddings, usage
  308. def encode(self, texts: list[str], model_name: str = "") -> tuple[np.ndarray, int]:
  309. # Using the internal tokenizer to encode the texts and get the total
  310. # number of tokens
  311. embeddings, usage = asyncio.run(self._embed(texts, model_name))
  312. return np.array(embeddings), usage
  313. def encode_queries(self, text: str) -> tuple[np.ndarray, int]:
  314. # Using the internal tokenizer to encode the texts and get the total
  315. # number of tokens
  316. return self.encode([text])
  317. class MistralEmbed(Base):
  318. def __init__(self, key, model_name="mistral-embed",
  319. base_url=None):
  320. from mistralai.client import MistralClient
  321. self.client = MistralClient(api_key=key)
  322. self.model_name = model_name
  323. def encode(self, texts: list, batch_size=32):
  324. texts = [truncate(t, 8196) for t in texts]
  325. res = self.client.embeddings(input=texts,
  326. model=self.model_name)
  327. return np.array([d.embedding for d in res.data]
  328. ), res.usage.total_tokens
  329. def encode_queries(self, text):
  330. res = self.client.embeddings(input=[truncate(text, 8196)],
  331. model=self.model_name)
  332. return np.array(res.data[0].embedding), res.usage.total_tokens
  333. class BedrockEmbed(Base):
  334. def __init__(self, key, model_name,
  335. **kwargs):
  336. import boto3
  337. self.bedrock_ak = json.loads(key).get('bedrock_ak', '')
  338. self.bedrock_sk = json.loads(key).get('bedrock_sk', '')
  339. self.bedrock_region = json.loads(key).get('bedrock_region', '')
  340. self.model_name = model_name
  341. self.client = boto3.client(service_name='bedrock-runtime', region_name=self.bedrock_region,
  342. aws_access_key_id=self.bedrock_ak, aws_secret_access_key=self.bedrock_sk)
  343. def encode(self, texts: list, batch_size=32):
  344. texts = [truncate(t, 8196) for t in texts]
  345. embeddings = []
  346. token_count = 0
  347. for text in texts:
  348. if self.model_name.split('.')[0] == 'amazon':
  349. body = {"inputText": text}
  350. elif self.model_name.split('.')[0] == 'cohere':
  351. body = {"texts": [text], "input_type": 'search_document'}
  352. response = self.client.invoke_model(modelId=self.model_name, body=json.dumps(body))
  353. model_response = json.loads(response["body"].read())
  354. embeddings.extend([model_response["embedding"]])
  355. token_count += num_tokens_from_string(text)
  356. return np.array(embeddings), token_count
  357. def encode_queries(self, text):
  358. embeddings = []
  359. token_count = num_tokens_from_string(text)
  360. if self.model_name.split('.')[0] == 'amazon':
  361. body = {"inputText": truncate(text, 8196)}
  362. elif self.model_name.split('.')[0] == 'cohere':
  363. body = {"texts": [truncate(text, 8196)], "input_type": 'search_query'}
  364. response = self.client.invoke_model(modelId=self.model_name, body=json.dumps(body))
  365. model_response = json.loads(response["body"].read())
  366. embeddings.extend([model_response["embedding"]])
  367. return np.array(embeddings), token_count
  368. class GeminiEmbed(Base):
  369. def __init__(self, key, model_name='models/text-embedding-004',
  370. **kwargs):
  371. genai.configure(api_key=key)
  372. self.model_name = 'models/' + model_name
  373. def encode(self, texts: list, batch_size=32):
  374. texts = [truncate(t, 2048) for t in texts]
  375. token_count = sum(num_tokens_from_string(text) for text in texts)
  376. result = genai.embed_content(
  377. model=self.model_name,
  378. content=texts,
  379. task_type="retrieval_document",
  380. title="Embedding of list of strings")
  381. return np.array(result['embedding']),token_count
  382. def encode_queries(self, text):
  383. result = genai.embed_content(
  384. model=self.model_name,
  385. content=truncate(text,2048),
  386. task_type="retrieval_document",
  387. title="Embedding of single string")
  388. token_count = num_tokens_from_string(text)
  389. return np.array(result['embedding']),token_count
  390. class NvidiaEmbed(Base):
  391. def __init__(
  392. self, key, model_name, base_url="https://integrate.api.nvidia.com/v1/embeddings"
  393. ):
  394. if not base_url:
  395. base_url = "https://integrate.api.nvidia.com/v1/embeddings"
  396. self.api_key = key
  397. self.base_url = base_url
  398. self.headers = {
  399. "accept": "application/json",
  400. "Content-Type": "application/json",
  401. "authorization": f"Bearer {self.api_key}",
  402. }
  403. self.model_name = model_name
  404. if model_name == "nvidia/embed-qa-4":
  405. self.base_url = "https://ai.api.nvidia.com/v1/retrieval/nvidia/embeddings"
  406. self.model_name = "NV-Embed-QA"
  407. if model_name == "snowflake/arctic-embed-l":
  408. self.base_url = "https://ai.api.nvidia.com/v1/retrieval/snowflake/arctic-embed-l/embeddings"
  409. def encode(self, texts: list, batch_size=None):
  410. payload = {
  411. "input": texts,
  412. "input_type": "query",
  413. "model": self.model_name,
  414. "encoding_format": "float",
  415. "truncate": "END",
  416. }
  417. res = requests.post(self.base_url, headers=self.headers, json=payload).json()
  418. return (
  419. np.array([d["embedding"] for d in res["data"]]),
  420. res["usage"]["total_tokens"],
  421. )
  422. def encode_queries(self, text):
  423. embds, cnt = self.encode([text])
  424. return np.array(embds[0]), cnt
  425. class LmStudioEmbed(LocalAIEmbed):
  426. def __init__(self, key, model_name, base_url):
  427. if not base_url:
  428. raise ValueError("Local llm url cannot be None")
  429. if base_url.split("/")[-1] != "v1":
  430. base_url = os.path.join(base_url, "v1")
  431. self.client = OpenAI(api_key="lm-studio", base_url=base_url)
  432. self.model_name = model_name
  433. class OpenAI_APIEmbed(OpenAIEmbed):
  434. def __init__(self, key, model_name, base_url):
  435. if not base_url:
  436. raise ValueError("url cannot be None")
  437. if base_url.split("/")[-1] != "v1":
  438. base_url = os.path.join(base_url, "v1")
  439. self.client = OpenAI(api_key=key, base_url=base_url)
  440. self.model_name = model_name.split("___")[0]
  441. class CoHereEmbed(Base):
  442. def __init__(self, key, model_name, base_url=None):
  443. from cohere import Client
  444. self.client = Client(api_key=key)
  445. self.model_name = model_name
  446. def encode(self, texts: list, batch_size=32):
  447. res = self.client.embed(
  448. texts=texts,
  449. model=self.model_name,
  450. input_type="search_query",
  451. embedding_types=["float"],
  452. )
  453. return np.array([d for d in res.embeddings.float]), int(
  454. res.meta.billed_units.input_tokens
  455. )
  456. def encode_queries(self, text):
  457. res = self.client.embed(
  458. texts=[text],
  459. model=self.model_name,
  460. input_type="search_query",
  461. embedding_types=["float"],
  462. )
  463. return np.array([d for d in res.embeddings.float]), int(
  464. res.meta.billed_units.input_tokens
  465. )
  466. class TogetherAIEmbed(OllamaEmbed):
  467. def __init__(self, key, model_name, base_url="https://api.together.xyz/v1"):
  468. if not base_url:
  469. base_url = "https://api.together.xyz/v1"
  470. super().__init__(key, model_name, base_url)
  471. class PerfXCloudEmbed(OpenAIEmbed):
  472. def __init__(self, key, model_name, base_url="https://cloud.perfxlab.cn/v1"):
  473. if not base_url:
  474. base_url = "https://cloud.perfxlab.cn/v1"
  475. super().__init__(key, model_name, base_url)
  476. class UpstageEmbed(OpenAIEmbed):
  477. def __init__(self, key, model_name, base_url="https://api.upstage.ai/v1/solar"):
  478. if not base_url:
  479. base_url = "https://api.upstage.ai/v1/solar"
  480. super().__init__(key, model_name, base_url)
  481. class SILICONFLOWEmbed(Base):
  482. def __init__(
  483. self, key, model_name, base_url="https://api.siliconflow.cn/v1/embeddings"
  484. ):
  485. if not base_url:
  486. base_url = "https://api.siliconflow.cn/v1/embeddings"
  487. self.headers = {
  488. "accept": "application/json",
  489. "content-type": "application/json",
  490. "authorization": f"Bearer {key}",
  491. }
  492. self.base_url = base_url
  493. self.model_name = model_name
  494. def encode(self, texts: list, batch_size=32):
  495. payload = {
  496. "model": self.model_name,
  497. "input": texts,
  498. "encoding_format": "float",
  499. }
  500. res = requests.post(self.base_url, json=payload, headers=self.headers).json()
  501. return (
  502. np.array([d["embedding"] for d in res["data"]]),
  503. res["usage"]["total_tokens"],
  504. )
  505. def encode_queries(self, text):
  506. payload = {
  507. "model": self.model_name,
  508. "input": text,
  509. "encoding_format": "float",
  510. }
  511. res = requests.post(self.base_url, json=payload, headers=self.headers).json()
  512. return np.array(res["data"][0]["embedding"]), res["usage"]["total_tokens"]
  513. class ReplicateEmbed(Base):
  514. def __init__(self, key, model_name, base_url=None):
  515. from replicate.client import Client
  516. self.model_name = model_name
  517. self.client = Client(api_token=key)
  518. def encode(self, texts: list, batch_size=32):
  519. res = self.client.run(self.model_name, input={"texts": json.dumps(texts)})
  520. return np.array(res), sum([num_tokens_from_string(text) for text in texts])
  521. def encode_queries(self, text):
  522. res = self.client.embed(self.model_name, input={"texts": [text]})
  523. return np.array(res), num_tokens_from_string(text)
  524. class BaiduYiyanEmbed(Base):
  525. def __init__(self, key, model_name, base_url=None):
  526. import qianfan
  527. key = json.loads(key)
  528. ak = key.get("yiyan_ak", "")
  529. sk = key.get("yiyan_sk", "")
  530. self.client = qianfan.Embedding(ak=ak, sk=sk)
  531. self.model_name = model_name
  532. def encode(self, texts: list, batch_size=32):
  533. res = self.client.do(model=self.model_name, texts=texts).body
  534. return (
  535. np.array([r["embedding"] for r in res["data"]]),
  536. res["usage"]["total_tokens"],
  537. )
  538. def encode_queries(self, text):
  539. res = self.client.do(model=self.model_name, texts=[text]).body
  540. return (
  541. np.array([r["embedding"] for r in res["data"]]),
  542. res["usage"]["total_tokens"],
  543. )
  544. class VoyageEmbed(Base):
  545. def __init__(self, key, model_name, base_url=None):
  546. import voyageai
  547. self.client = voyageai.Client(api_key=key)
  548. self.model_name = model_name
  549. def encode(self, texts: list, batch_size=32):
  550. res = self.client.embed(
  551. texts=texts, model=self.model_name, input_type="document"
  552. )
  553. return np.array(res.embeddings), res.total_tokens
  554. def encode_queries(self, text):
  555. res = self.client.embed
  556. res = self.client.embed(
  557. texts=text, model=self.model_name, input_type="query"
  558. )
  559. return np.array(res.embeddings), res.total_tokens