CustomAppConfig.py 5.6 KB

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