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

embedding_model.py 4.7KB

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