Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

embedding_model.py 3.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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 os
  22. import numpy as np
  23. from rag.utils import num_tokens_from_string
  24. flag_model = FlagModel("BAAI/bge-large-zh-v1.5",
  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. token_count = 0
  47. for t in texts: token_count += num_tokens_from_string(t)
  48. res = []
  49. for i in range(0, len(texts), batch_size):
  50. res.extend(self.model.encode(texts[i:i + batch_size]).tolist())
  51. return np.array(res), token_count
  52. def encode_queries(self, text: str):
  53. token_count = num_tokens_from_string(text)
  54. return self.model.encode_queries([text]).tolist()[0], token_count
  55. class OpenAIEmbed(Base):
  56. def __init__(self, key, model_name="text-embedding-ada-002"):
  57. self.client = OpenAI(api_key=key)
  58. self.model_name = model_name
  59. def encode(self, texts: list, batch_size=32):
  60. res = self.client.embeddings.create(input=texts,
  61. model=self.model_name)
  62. return np.array([d.embedding for d in res.data]), res.usage.total_tokens
  63. def encode_queries(self, text):
  64. res = self.client.embeddings.create(input=[text],
  65. model=self.model_name)
  66. return np.array(res.data[0].embedding), res.usage.total_tokens
  67. class QWenEmbed(Base):
  68. def __init__(self, key, model_name="text_embedding_v2"):
  69. dashscope.api_key = key
  70. self.model_name = model_name
  71. def encode(self, texts: list, batch_size=10):
  72. import dashscope
  73. res = []
  74. token_count = 0
  75. texts = [txt[:2048] for txt in texts]
  76. for i in range(0, len(texts), batch_size):
  77. resp = dashscope.TextEmbedding.call(
  78. model=self.model_name,
  79. input=texts[i:i+batch_size],
  80. text_type="document"
  81. )
  82. embds = [[]] * len(resp["output"]["embeddings"])
  83. for e in resp["output"]["embeddings"]:
  84. embds[e["text_index"]] = e["embedding"]
  85. res.extend(embds)
  86. token_count += resp["usage"]["input_tokens"]
  87. return np.array(res), token_count
  88. def encode_queries(self, text):
  89. resp = dashscope.TextEmbedding.call(
  90. model=self.model_name,
  91. input=text[:2048],
  92. text_type="query"
  93. )
  94. return np.array(resp["output"]["embeddings"][0]["embedding"]), resp["usage"]["input_tokens"]