|
| 1 | +import json |
| 2 | +from typing import List, Iterator, AsyncIterator, Dict |
| 3 | + |
| 4 | +import aioboto3 |
| 5 | +from aiolimiter import AsyncLimiter |
| 6 | +from botocore.client import BaseClient |
| 7 | +from langchain_aws import ChatBedrockConverse |
| 8 | +from langchain_community.adapters.openai import convert_dict_to_message |
| 9 | +from pydantic import BaseModel |
| 10 | +from langchain_core.messages import ( |
| 11 | + BaseMessage, |
| 12 | + BaseMessageChunk, |
| 13 | + convert_to_openai_messages, |
| 14 | +) |
| 15 | + |
| 16 | +from fmcore.aws.factory.boto_factory import BotoFactory |
| 17 | +from fmcore.llm.base_llm import BaseLLM |
| 18 | +from fmcore.llm.types.llm_types import LLMConfig |
| 19 | +from fmcore.llm.types.provider_types import LambdaProviderParams |
| 20 | +from fmcore.utils.rate_limit_utils import RateLimiterUtils |
| 21 | +from fmcore.utils.retry_utils import RetryUtil |
| 22 | + |
| 23 | + |
| 24 | +class LambdaLLM(BaseLLM[List[BaseMessage], BaseMessage, BaseMessageChunk], BaseModel): |
| 25 | + """ |
| 26 | + An LLM implementation that routes requests through an AWS Lambda function. |
| 27 | +
|
| 28 | + This class uses both synchronous and asynchronous boto3 Lambda clients to |
| 29 | + interact with an LLM hosted via AWS Lambda. It includes automatic async rate |
| 30 | + limiting and supports OpenAI-style message formatting. |
| 31 | +
|
| 32 | + Attributes: |
| 33 | + sync_client (BaseClient): Boto3 synchronous client for AWS Lambda. |
| 34 | + async_session ( aioboto3.Session): Boto3 asynchronous session for AWS Lambda. |
| 35 | + rate_limiter (AsyncLimiter): Async limiter to enforce API rate limits. |
| 36 | +
|
| 37 | + Note: |
| 38 | + The `async_client` is not stored directly because `aioboto3.client(...)` returns |
| 39 | + an asynchronous context manager, which must be used with `async with` and cannot |
| 40 | + be reused safely across calls. Instead, we store an `aioboto3.Session` instance |
| 41 | + in `async_session`, from which a fresh client is created inside each `async with` |
| 42 | + block |
| 43 | +
|
| 44 | + """ |
| 45 | + |
| 46 | + aliases = ["LAMBDA"] |
| 47 | + |
| 48 | + sync_client: BaseClient |
| 49 | + async_session: aioboto3.Session # Using session here as aioboto3.client returns context manager |
| 50 | + rate_limiter: AsyncLimiter |
| 51 | + |
| 52 | + @classmethod |
| 53 | + def _get_instance(cls, *, llm_config: LLMConfig) -> "LambdaLLM": |
| 54 | + """ |
| 55 | + Factory method to create an instance of LambdaLLM with the given configuration. |
| 56 | +
|
| 57 | + Args: |
| 58 | + llm_config (LLMConfig): The LLM configuration, including model and provider details. |
| 59 | +
|
| 60 | + Returns: |
| 61 | + LambdaLLM: A configured instance of the Lambda-backed LLM. |
| 62 | + """ |
| 63 | + provider_params: LambdaProviderParams = llm_config.provider_params |
| 64 | + |
| 65 | + sync_client = BotoFactory.get_client( |
| 66 | + service_name="lambda", |
| 67 | + region=provider_params.region, |
| 68 | + role_arn=provider_params.role_arn, |
| 69 | + ) |
| 70 | + async_session = BotoFactory.get_async_session( |
| 71 | + service_name="lambda", |
| 72 | + region=provider_params.region, |
| 73 | + role_arn=provider_params.role_arn, |
| 74 | + ) |
| 75 | + |
| 76 | + rate_limiter = RateLimiterUtils.create_async_rate_limiter( |
| 77 | + rate_limit_config=provider_params.rate_limit |
| 78 | + ) |
| 79 | + |
| 80 | + return LambdaLLM( |
| 81 | + config=llm_config, sync_client=sync_client, async_session=async_session, rate_limiter=rate_limiter |
| 82 | + ) |
| 83 | + |
| 84 | + def convert_messages_to_lambda_payload(self, messages: List[BaseMessage]) -> Dict: |
| 85 | + """ |
| 86 | + Converts internal message objects to the payload format expected by the Lambda function. |
| 87 | + We expect all lambdas to be accepting openai messages format |
| 88 | +
|
| 89 | + Args: |
| 90 | + messages (List[BaseMessage]): List of internal message objects. |
| 91 | +
|
| 92 | + Returns: |
| 93 | + Dict: The payload dictionary to send to the Lambda function. |
| 94 | + """ |
| 95 | + return { |
| 96 | + "modelId": self.config.model_id, |
| 97 | + "messages": convert_to_openai_messages(messages), |
| 98 | + "model_params": self.config.model_params.model_dump(), |
| 99 | + } |
| 100 | + |
| 101 | + def convert_lambda_response_to_messages(self, response: Dict) -> BaseMessage: |
| 102 | + """ |
| 103 | + Converts the raw Lambda function response into a BaseMessage. |
| 104 | +
|
| 105 | + This method expects the Lambda response to contain a 'Payload' key with a stream |
| 106 | + of OpenAI-style messages (a list of dictionaries). It parses the stream, extracts |
| 107 | + the first message, and converts it into a BaseMessage instance. |
| 108 | +
|
| 109 | + Args: |
| 110 | + response (Dict): The response dictionary returned from the Lambda invocation. |
| 111 | +
|
| 112 | + Returns: |
| 113 | + BaseMessage: The first parsed message from the response. |
| 114 | + """ |
| 115 | + response_payload: List[Dict] = json.load(response["Payload"]) |
| 116 | + # The Lambda returns a list of messages in OpenAI format. |
| 117 | + # Currently, we only expect a single response message, |
| 118 | + # so we take the first item in the list. |
| 119 | + return convert_dict_to_message(response_payload[0]) |
| 120 | + |
| 121 | + def invoke(self, messages: List[BaseMessage]) -> BaseMessage: |
| 122 | + """ |
| 123 | + Synchronously invokes the Lambda function with given messages. |
| 124 | +
|
| 125 | + Args: |
| 126 | + messages (List[BaseMessage]): Input messages for the model. |
| 127 | +
|
| 128 | + Returns: |
| 129 | + BaseMessage: Response message from the model. |
| 130 | + """ |
| 131 | + payload = self.convert_messages_to_lambda_payload(messages) |
| 132 | + response = self.sync_client.invoke( |
| 133 | + FunctionName=self.config.provider_params.function_arn, |
| 134 | + InvocationType="RequestResponse", |
| 135 | + Payload=json.dumps(payload), |
| 136 | + ) |
| 137 | + return self.convert_lambda_response_to_messages(response) |
| 138 | + |
| 139 | + @RetryUtil.with_backoff(lambda self: self.config.provider_params.retries) |
| 140 | + async def ainvoke(self, messages: List[BaseMessage]) -> BaseMessage: |
| 141 | + """ |
| 142 | + Asynchronously invokes the Lambda function with rate limiting. |
| 143 | +
|
| 144 | + Args: |
| 145 | + messages (List[BaseMessage]): Input messages for the model. |
| 146 | +
|
| 147 | + Returns: |
| 148 | + BaseMessage: Response message from the model. |
| 149 | + """ |
| 150 | + async with self.rate_limiter: |
| 151 | + async with self.async_session.client("lambda") as lambda_client: |
| 152 | + payload = self.convert_messages_to_lambda_payload(messages) |
| 153 | + response = await lambda_client.invoke( |
| 154 | + FunctionName=self.config.provider_params.function_arn, |
| 155 | + InvocationType="RequestResponse", |
| 156 | + Payload=json.dumps(payload), |
| 157 | + ) |
| 158 | + payload = await response["Payload"].read() |
| 159 | + response_payload: List[Dict] = json.loads(payload.decode("utf-8")) |
| 160 | + # The Lambda returns a list of messages in OpenAI format. |
| 161 | + # Currently, we only expect a single response message, |
| 162 | + # so we take the first item in the list. |
| 163 | + return convert_dict_to_message(response_payload[0]) |
| 164 | + |
| 165 | + def stream(self, messages: List[BaseMessage]) -> Iterator[BaseMessageChunk]: |
| 166 | + """ |
| 167 | + Not implemented. Streaming is not supported for LambdaLLM. |
| 168 | +
|
| 169 | + Raises: |
| 170 | + NotImplementedError |
| 171 | + """ |
| 172 | + raise NotImplementedError("Streaming is not implemented for LambdaLLM") |
| 173 | + |
| 174 | + async def astream(self, messages: List[BaseMessage]) -> AsyncIterator[BaseMessageChunk]: |
| 175 | + """ |
| 176 | + Not implemented. Asynchronous streaming is not supported for LambdaLLM. |
| 177 | +
|
| 178 | + Raises: |
| 179 | + NotImplementedError |
| 180 | + """ |
| 181 | + raise NotImplementedError("Streaming is not implemented for LambdaLLM") |
| 182 | + |
| 183 | + def batch(self, messages: List[List[BaseMessage]]) -> List[BaseMessage]: |
| 184 | + """ |
| 185 | + Not implemented. Batch processing is not supported for LambdaLLM. |
| 186 | +
|
| 187 | + Raises: |
| 188 | + NotImplementedError |
| 189 | + """ |
| 190 | + raise NotImplementedError("Batch processing is not implemented for LambdaLLM.") |
| 191 | + |
| 192 | + async def abatch(self, messages: List[List[BaseMessage]]) -> List[BaseMessage]: |
| 193 | + """ |
| 194 | + Not implemented. Asynchronous batch processing is not supported for LambdaLLM. |
| 195 | +
|
| 196 | + Raises: |
| 197 | + NotImplementedError |
| 198 | + """ |
| 199 | + raise NotImplementedError("Batch processing is not implemented for LambdaLLM.") |
0 commit comments