aws_bedrock.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import os
  2. from typing import Optional
  3. from langchain.llms import Bedrock
  4. from embedchain.config import BaseLlmConfig
  5. from embedchain.helpers.json_serializable import register_deserializable
  6. from embedchain.llm.base import BaseLlm
  7. @register_deserializable
  8. class AWSBedrockLlm(BaseLlm):
  9. def __init__(self, config: Optional[BaseLlmConfig] = None):
  10. super().__init__(config)
  11. def get_llm_model_answer(self, prompt) -> str:
  12. response = self._get_answer(prompt, self.config)
  13. return response
  14. def _get_answer(self, prompt: str, config: BaseLlmConfig) -> str:
  15. try:
  16. import boto3
  17. except ModuleNotFoundError:
  18. raise ModuleNotFoundError(
  19. "The required dependencies for AWSBedrock are not installed."
  20. 'Please install with `pip install --upgrade "embedchain[aws-bedrock]"`'
  21. ) from None
  22. self.boto_client = boto3.client("bedrock-runtime", "us-west-2" or os.environ.get("AWS_REGION"))
  23. kwargs = {
  24. "model_id": config.model or "amazon.titan-text-express-v1",
  25. "client": self.boto_client,
  26. "model_kwargs": config.model_kwargs
  27. or {
  28. "temperature": config.temperature,
  29. },
  30. }
  31. if config.stream:
  32. from langchain.callbacks.streaming_stdout import \
  33. StreamingStdOutCallbackHandler
  34. callbacks = [StreamingStdOutCallbackHandler()]
  35. llm = Bedrock(**kwargs, streaming=config.stream, callbacks=callbacks)
  36. else:
  37. llm = Bedrock(**kwargs)
  38. return llm(prompt)