CustomAppConfig.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. from typing import Any
  2. from chromadb.api.types import Documents, Embeddings
  3. from dotenv import load_dotenv
  4. from embedchain.config.vectordbs import ElasticsearchDBConfig
  5. from embedchain.models import EmbeddingFunctions, Providers, VectorDatabases, VectorDimensions
  6. from .BaseAppConfig import BaseAppConfig
  7. load_dotenv()
  8. class CustomAppConfig(BaseAppConfig):
  9. """
  10. Config to initialize an embedchain custom `App` instance, with extra config options.
  11. """
  12. def __init__(
  13. self,
  14. log_level=None,
  15. embedding_fn: EmbeddingFunctions = None,
  16. embedding_fn_model=None,
  17. db=None,
  18. host=None,
  19. port=None,
  20. id=None,
  21. collection_name=None,
  22. provider: Providers = None,
  23. open_source_app_config=None,
  24. deployment_name=None,
  25. db_type: VectorDatabases = None,
  26. es_config: ElasticsearchDBConfig = None,
  27. ):
  28. """
  29. :param log_level: Optional. (String) Debug level
  30. ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'].
  31. :param embedding_fn: Optional. Embedding function to use.
  32. :param embedding_fn_model: Optional. Model name to use for embedding function.
  33. :param db: Optional. (Vector) database to use for embeddings.
  34. :param host: Optional. Hostname for the database server.
  35. :param port: Optional. Port for the database server.
  36. :param id: Optional. ID of the app. Document metadata will have this id.
  37. :param collection_name: Optional. Collection name for the database.
  38. :param provider: Optional. (Providers): LLM Provider to use.
  39. :param open_source_app_config: Optional. Config instance needed for open source apps.
  40. :param db_type: Optional. type of Vector database to use.
  41. :param es_config: Optional. elasticsearch database config to be used for connection
  42. """
  43. if provider:
  44. self.provider = provider
  45. else:
  46. raise ValueError("CustomApp must have a provider assigned.")
  47. self.open_source_app_config = open_source_app_config
  48. super().__init__(
  49. log_level=log_level,
  50. embedding_fn=CustomAppConfig.embedding_function(
  51. embedding_function=embedding_fn, model=embedding_fn_model, deployment_name=deployment_name
  52. ),
  53. db=db,
  54. host=host,
  55. port=port,
  56. id=id,
  57. collection_name=collection_name,
  58. db_type=db_type,
  59. vector_dim=CustomAppConfig.get_vector_dimension(embedding_function=embedding_fn),
  60. es_config=es_config,
  61. )
  62. @staticmethod
  63. def langchain_default_concept(embeddings: Any):
  64. """
  65. Langchains default function layout for embeddings.
  66. """
  67. def embed_function(texts: Documents) -> Embeddings:
  68. return embeddings.embed_documents(texts)
  69. return embed_function
  70. @staticmethod
  71. def embedding_function(embedding_function: EmbeddingFunctions, model: str = None, deployment_name: str = None):
  72. if not isinstance(embedding_function, EmbeddingFunctions):
  73. raise ValueError(
  74. f"Invalid option: '{embedding_function}'. Expecting one of the following options: {list(map(lambda x: x.value, EmbeddingFunctions))}" # noqa: E501
  75. )
  76. if embedding_function == EmbeddingFunctions.OPENAI:
  77. from langchain.embeddings import OpenAIEmbeddings
  78. if model:
  79. embeddings = OpenAIEmbeddings(model=model)
  80. else:
  81. if deployment_name:
  82. embeddings = OpenAIEmbeddings(deployment=deployment_name)
  83. else:
  84. embeddings = OpenAIEmbeddings()
  85. return CustomAppConfig.langchain_default_concept(embeddings)
  86. elif embedding_function == EmbeddingFunctions.HUGGING_FACE:
  87. from langchain.embeddings import HuggingFaceEmbeddings
  88. embeddings = HuggingFaceEmbeddings(model_name=model)
  89. return CustomAppConfig.langchain_default_concept(embeddings)
  90. elif embedding_function == EmbeddingFunctions.VERTEX_AI:
  91. from langchain.embeddings import VertexAIEmbeddings
  92. embeddings = VertexAIEmbeddings(model_name=model)
  93. return CustomAppConfig.langchain_default_concept(embeddings)
  94. elif embedding_function == EmbeddingFunctions.GPT4ALL:
  95. # Note: We could use langchains GPT4ALL embedding, but it's not available in all versions.
  96. from chromadb.utils import embedding_functions
  97. return embedding_functions.SentenceTransformerEmbeddingFunction(model_name=model)
  98. @staticmethod
  99. def get_vector_dimension(embedding_function: EmbeddingFunctions):
  100. if not isinstance(embedding_function, EmbeddingFunctions):
  101. raise ValueError(f"Invalid option: '{embedding_function}'.")
  102. if embedding_function == EmbeddingFunctions.OPENAI:
  103. return VectorDimensions.OPENAI.value
  104. elif embedding_function == EmbeddingFunctions.HUGGING_FACE:
  105. return VectorDimensions.HUGGING_FACE.value
  106. elif embedding_function == EmbeddingFunctions.VERTEX_AI:
  107. return VectorDimensions.VERTEX_AI.value
  108. elif embedding_function == EmbeddingFunctions.GPT4ALL:
  109. return VectorDimensions.GPT4ALL.value