Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

embedding_model.py 5.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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, **kwargs):
  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", base_url="https://api.openai.com/v1"):
  69. if not base_url: base_url="https://api.openai.com/v1"
  70. self.client = OpenAI(api_key=key, base_url=base_url)
  71. self.model_name = model_name
  72. def encode(self, texts: list, batch_size=32):
  73. res = self.client.embeddings.create(input=texts,
  74. model=self.model_name)
  75. return np.array([d.embedding for d in res.data]
  76. ), res.usage.total_tokens
  77. def encode_queries(self, text):
  78. res = self.client.embeddings.create(input=[text],
  79. model=self.model_name)
  80. return np.array(res.data[0].embedding), res.usage.total_tokens
  81. class QWenEmbed(Base):
  82. def __init__(self, key, model_name="text_embedding_v2", **kwargs):
  83. dashscope.api_key = key
  84. self.model_name = model_name
  85. def encode(self, texts: list, batch_size=10):
  86. import dashscope
  87. res = []
  88. token_count = 0
  89. texts = [txt[:2048] for txt in texts]
  90. for i in range(0, len(texts), batch_size):
  91. resp = dashscope.TextEmbedding.call(
  92. model=self.model_name,
  93. input=texts[i:i + batch_size],
  94. text_type="document"
  95. )
  96. embds = [[] for _ in range(len(resp["output"]["embeddings"]))]
  97. for e in resp["output"]["embeddings"]:
  98. embds[e["text_index"]] = e["embedding"]
  99. res.extend(embds)
  100. token_count += resp["usage"]["total_tokens"]
  101. return np.array(res), token_count
  102. def encode_queries(self, text):
  103. resp = dashscope.TextEmbedding.call(
  104. model=self.model_name,
  105. input=text[:2048],
  106. text_type="query"
  107. )
  108. return np.array(resp["output"]["embeddings"][0]
  109. ["embedding"]), resp["usage"]["total_tokens"]
  110. class ZhipuEmbed(Base):
  111. def __init__(self, key, model_name="embedding-2", **kwargs):
  112. self.client = ZhipuAI(api_key=key)
  113. self.model_name = model_name
  114. def encode(self, texts: list, batch_size=32):
  115. arr = []
  116. tks_num = 0
  117. for txt in texts:
  118. res = self.client.embeddings.create(input=txt,
  119. model=self.model_name)
  120. arr.append(res.data[0].embedding)
  121. tks_num += res.usage.total_tokens
  122. return np.array(arr), tks_num
  123. def encode_queries(self, text):
  124. res = self.client.embeddings.create(input=text,
  125. model=self.model_name)
  126. return np.array(res.data[0].embedding), res.usage.total_tokens