CustomAppConfig.py 5.3 KB

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