ollama.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import logging
  2. from collections.abc import Iterable
  3. from typing import Optional, Union
  4. from langchain.callbacks.manager import CallbackManager
  5. from langchain.callbacks.stdout import StdOutCallbackHandler
  6. from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
  7. from langchain_community.llms.ollama import Ollama
  8. try:
  9. from ollama import Client
  10. except ImportError:
  11. raise ImportError("Ollama requires extra dependencies. Install with `pip install ollama`") from None
  12. from embedchain.config import BaseLlmConfig
  13. from embedchain.helpers.json_serializable import register_deserializable
  14. from embedchain.llm.base import BaseLlm
  15. logger = logging.getLogger(__name__)
  16. @register_deserializable
  17. class OllamaLlm(BaseLlm):
  18. def __init__(self, config: Optional[BaseLlmConfig] = None):
  19. super().__init__(config=config)
  20. if self.config.model is None:
  21. self.config.model = "llama2"
  22. client = Client(host=config.base_url)
  23. local_models = client.list()["models"]
  24. if not any(model.get("name") == self.config.model for model in local_models):
  25. logger.info(f"Pulling {self.config.model} from Ollama!")
  26. client.pull(self.config.model)
  27. def get_llm_model_answer(self, prompt):
  28. return self._get_answer(prompt=prompt, config=self.config)
  29. @staticmethod
  30. def _get_answer(prompt: str, config: BaseLlmConfig) -> Union[str, Iterable]:
  31. if config.stream:
  32. callbacks = config.callbacks if config.callbacks else [StreamingStdOutCallbackHandler()]
  33. else:
  34. callbacks = [StdOutCallbackHandler()]
  35. llm = Ollama(
  36. model=config.model,
  37. system=config.system_prompt,
  38. temperature=config.temperature,
  39. top_p=config.top_p,
  40. callback_manager=CallbackManager(callbacks),
  41. base_url=config.base_url,
  42. )
  43. return llm.invoke(prompt)