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 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. from zhipuai import ZhipuAI
  17. import os
  18. from abc import ABC
  19. import dashscope
  20. from openai import OpenAI
  21. from FlagEmbedding import FlagModel
  22. import torch
  23. import numpy as np
  24. from huggingface_hub import snapshot_download
  25. from api.utils.file_utils import get_project_base_directory
  26. from rag.utils import num_tokens_from_string
  27. try:
  28. model_dir = snapshot_download(
  29. repo_id="BAAI/bge-large-zh-v1.5",
  30. local_dir=os.path.join(
  31. get_project_base_directory(),
  32. "rag/res/bge-large-zh-v1.5"),
  33. local_files_only=True)
  34. except Exception as e:
  35. model_dir = snapshot_download(repo_id="BAAI/bge-large-zh-v1.5")
  36. flag_model = FlagModel(model_dir,
  37. query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:",
  38. use_fp16=torch.cuda.is_available())
  39. class Base(ABC):
  40. def __init__(self, key, model_name):
  41. pass
  42. def encode(self, texts: list, batch_size=32):
  43. raise NotImplementedError("Please implement encode method!")
  44. def encode_queries(self, text: str):
  45. raise NotImplementedError("Please implement encode method!")
  46. class HuEmbedding(Base):
  47. def __init__(self, key="", model_name=""):
  48. """
  49. If you have trouble downloading HuggingFace models, -_^ this might help!!
  50. For Linux:
  51. export HF_ENDPOINT=https://hf-mirror.com
  52. For Windows:
  53. Good luck
  54. ^_-
  55. """
  56. self.model = flag_model
  57. def encode(self, texts: list, batch_size=32):
  58. texts = [t[:2000] for t in texts]
  59. token_count = 0
  60. for t in texts:
  61. token_count += num_tokens_from_string(t)
  62. res = []
  63. for i in range(0, len(texts), batch_size):
  64. res.extend(self.model.encode(texts[i:i + batch_size]).tolist())
  65. return np.array(res), token_count
  66. def encode_queries(self, text: str):
  67. token_count = num_tokens_from_string(text)
  68. return self.model.encode_queries([text]).tolist()[0], token_count
  69. class OpenAIEmbed(Base):
  70. def __init__(self, key, model_name="text-embedding-ada-002"):
  71. self.client = OpenAI(api_key=key)
  72. self.model_name = model_name
  73. def encode(self, texts: list, batch_size=32):
  74. res = self.client.embeddings.create(input=texts,
  75. model=self.model_name)
  76. return np.array([d.embedding for d in res.data]
  77. ), res.usage.total_tokens
  78. def encode_queries(self, text):
  79. res = self.client.embeddings.create(input=[text],
  80. model=self.model_name)
  81. return np.array(res.data[0].embedding), res.usage.total_tokens
  82. class QWenEmbed(Base):
  83. def __init__(self, key, model_name="text_embedding_v2"):
  84. dashscope.api_key = key
  85. self.model_name = model_name
  86. def encode(self, texts: list, batch_size=10):
  87. import dashscope
  88. res = []
  89. token_count = 0
  90. texts = [txt[:2048] for txt in texts]
  91. for i in range(0, len(texts), batch_size):
  92. resp = dashscope.TextEmbedding.call(
  93. model=self.model_name,
  94. input=texts[i:i + batch_size],
  95. text_type="document"
  96. )
  97. embds = [[] for _ in range(len(resp["output"]["embeddings"]))]
  98. for e in resp["output"]["embeddings"]:
  99. embds[e["text_index"]] = e["embedding"]
  100. res.extend(embds)
  101. token_count += resp["usage"]["total_tokens"]
  102. return np.array(res), token_count
  103. def encode_queries(self, text):
  104. resp = dashscope.TextEmbedding.call(
  105. model=self.model_name,
  106. input=text[:2048],
  107. text_type="query"
  108. )
  109. return np.array(resp["output"]["embeddings"][0]
  110. ["embedding"]), resp["usage"]["total_tokens"]
  111. class ZhipuEmbed(Base):
  112. def __init__(self, key, model_name="embedding-2"):
  113. self.client = ZhipuAI(api_key=key)
  114. self.model_name = model_name
  115. def encode(self, texts: list, batch_size=32):
  116. res = self.client.embeddings.create(input=texts,
  117. model=self.model_name)
  118. return np.array([d.embedding for d in res.data]
  119. ), res.usage.total_tokens
  120. def encode_queries(self, text):
  121. res = self.client.embeddings.create(input=text,
  122. model=self.model_name)
  123. return np.array(res["data"][0]["embedding"]), res.usage.total_tokens