Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

embedding_model.py 4.5KB

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