OpenSourceApp.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import logging
  2. from typing import Iterable, Union
  3. from embedchain.config import ChatConfig, OpenSourceAppConfig
  4. from embedchain.embedchain import EmbedChain
  5. gpt4all_model = None
  6. class OpenSourceApp(EmbedChain):
  7. """
  8. The OpenSource app.
  9. Same as App, but uses an open source embedding model and LLM.
  10. Has two function: add and query.
  11. adds(data_type, url): adds the data from the given URL to the vector db.
  12. query(query): finds answer to the given query using vector database and LLM.
  13. """
  14. def __init__(self, config: OpenSourceAppConfig = None):
  15. """
  16. :param config: OpenSourceAppConfig instance to load as configuration. Optional.
  17. `ef` defaults to open source.
  18. """
  19. logging.info("Loading open source embedding model. This may take some time...") # noqa:E501
  20. if not config:
  21. config = OpenSourceAppConfig()
  22. if not config.model:
  23. raise ValueError("OpenSourceApp needs a model to be instantiated. Maybe you passed the wrong config type?")
  24. self.instance = OpenSourceApp._get_instance(config.model)
  25. logging.info("Successfully loaded open source embedding model.")
  26. super().__init__(config)
  27. def get_llm_model_answer(self, prompt, config: ChatConfig):
  28. return self._get_gpt4all_answer(prompt=prompt, config=config)
  29. @staticmethod
  30. def _get_instance(model):
  31. try:
  32. from gpt4all import GPT4All
  33. except ModuleNotFoundError:
  34. raise ValueError(
  35. "The GPT4All python package is not installed. Please install it with `pip install GPT4All`"
  36. ) from None
  37. return GPT4All(model)
  38. def _get_gpt4all_answer(self, prompt: str, config: ChatConfig) -> Union[str, Iterable]:
  39. if config.model and config.model != self.config.model:
  40. raise RuntimeError(
  41. "OpenSourceApp does not support switching models at runtime. Please create a new app instance."
  42. )
  43. if config.system_prompt:
  44. raise ValueError("OpenSourceApp does not support `system_prompt`")
  45. response = self.instance.generate(
  46. prompt=prompt,
  47. streaming=config.stream,
  48. top_p=config.top_p,
  49. max_tokens=config.max_tokens,
  50. temp=config.temperature,
  51. )
  52. return response