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

embedding_model.py 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. flag_model = FlagModel(os.path.join(
  29. get_project_base_directory(),
  30. "rag/res/bge-large-zh-v1.5"),
  31. query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:",
  32. use_fp16=torch.cuda.is_available())
  33. except Exception as e:
  34. flag_model = FlagModel("BAAI/bge-large-zh-v1.5",
  35. query_instruction_for_retrieval="为这个句子生成表示以用于检索相关文章:",
  36. use_fp16=torch.cuda.is_available())
  37. class Base(ABC):
  38. def __init__(self, key, model_name):
  39. pass
  40. def encode(self, texts: list, batch_size=32):
  41. raise NotImplementedError("Please implement encode method!")
  42. def encode_queries(self, text: str):
  43. raise NotImplementedError("Please implement encode method!")
  44. class HuEmbedding(Base):
  45. def __init__(self, key="", model_name=""):
  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. self.model = flag_model
  55. def encode(self, texts: list, batch_size=32):
  56. texts = [t[:2000] for t in texts]
  57. token_count = 0
  58. for t in texts:
  59. token_count += num_tokens_from_string(t)
  60. res = []
  61. for i in range(0, len(texts), batch_size):
  62. res.extend(self.model.encode(texts[i:i + batch_size]).tolist())
  63. return np.array(res), token_count
  64. def encode_queries(self, text: str):
  65. token_count = num_tokens_from_string(text)
  66. return self.model.encode_queries([text]).tolist()[0], token_count
  67. class OpenAIEmbed(Base):
  68. def __init__(self, key, model_name="text-embedding-ada-002"):
  69. self.client = OpenAI(api_key=key)
  70. self.model_name = model_name
  71. def encode(self, texts: list, batch_size=32):
  72. res = self.client.embeddings.create(input=texts,
  73. model=self.model_name)
  74. return np.array([d.embedding for d in res.data]
  75. ), res.usage.total_tokens
  76. def encode_queries(self, text):
  77. res = self.client.embeddings.create(input=[text],
  78. model=self.model_name)
  79. return np.array(res.data[0].embedding), res.usage.total_tokens
  80. class QWenEmbed(Base):
  81. def __init__(self, key, model_name="text_embedding_v2"):
  82. dashscope.api_key = key
  83. self.model_name = model_name
  84. def encode(self, texts: list, batch_size=10):
  85. import dashscope
  86. res = []
  87. token_count = 0
  88. texts = [txt[:2048] for txt in texts]
  89. for i in range(0, len(texts), batch_size):
  90. resp = dashscope.TextEmbedding.call(
  91. model=self.model_name,
  92. input=texts[i:i + batch_size],
  93. text_type="document"
  94. )
  95. embds = [[] for _ in range(len(resp["output"]["embeddings"]))]
  96. for e in resp["output"]["embeddings"]:
  97. embds[e["text_index"]] = e["embedding"]
  98. res.extend(embds)
  99. token_count += resp["usage"]["total_tokens"]
  100. return np.array(res), token_count
  101. def encode_queries(self, text):
  102. resp = dashscope.TextEmbedding.call(
  103. model=self.model_name,
  104. input=text[:2048],
  105. text_type="query"
  106. )
  107. return np.array(resp["output"]["embeddings"][0]
  108. ["embedding"]), resp["usage"]["total_tokens"]
  109. class ZhipuEmbed(Base):
  110. def __init__(self, key, model_name="embedding-2"):
  111. self.client = ZhipuAI(api_key=key)
  112. self.model_name = model_name
  113. def encode(self, texts: list, batch_size=32):
  114. arr = []
  115. tks_num = 0
  116. for txt in texts:
  117. res = self.client.embeddings.create(input=txt,
  118. model=self.model_name)
  119. arr.append(res.data[0].embedding)
  120. tks_num += res.usage.total_tokens
  121. return np.array(arr), tks_num
  122. def encode_queries(self, text):
  123. res = self.client.embeddings.create(input=text,
  124. model=self.model_name)
  125. return np.array(res.data[0].embedding), res.usage.total_tokens