Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: add support for AWS Bedrock (Anthropic) (#689)
mlong93e9790d07ca65
diff --git a/letta/credentials.py b/letta/credentials.pydeleted file mode 100644index 91d9cce71..000000000--- a/letta/credentials.py+++ /dev/null@@ -1,149 +0,0 @@-import configparser-import os-from dataclasses import dataclass-from typing import Optional--from letta.config import get_field, set_field-from letta.constants import LETTA_DIR--SUPPORTED_AUTH_TYPES = ["bearer_token", "api_key"]---@dataclass-class LettaCredentials:- # credentials for Letta- credentials_path: str = os.path.join(LETTA_DIR, "credentials")-- # openai config- openai_auth_type: str = "bearer_token"- openai_key: Optional[str] = os.getenv("OPENAI_API_KEY")-- # gemini config- google_ai_key: Optional[str] = None- google_ai_service_endpoint: Optional[str] = None-- # anthropic config- anthropic_key: Optional[str] = os.getenv("ANTHROPIC_API_KEY")-- # cohere config- cohere_key: Optional[str] = None-- # azure config- azure_auth_type: str = "api_key"- azure_key: Optional[str] = os.getenv("AZURE_OPENAI_API_KEY")-- # groq config- groq_key: Optional[str] = os.getenv("GROQ_API_KEY")-- # base llm / model- azure_version: Optional[str] = None- azure_endpoint: Optional[str] = None- azure_deployment: Optional[str] = None- # embeddings- azure_embedding_version: Optional[str] = None- azure_embedding_endpoint: Optional[str] = None- azure_embedding_deployment: Optional[str] = None-- # custom llm API config- openllm_auth_type: Optional[str] = None- openllm_key: Optional[str] = None-- @classmethod- def load(cls) -> "LettaCredentials":- config = configparser.ConfigParser()-- # allow overriding with env variables- if os.getenv("MEMGPT_CREDENTIALS_PATH"):- credentials_path = os.getenv("MEMGPT_CREDENTIALS_PATH")- else:- credentials_path = LettaCredentials.credentials_path-- if os.path.exists(credentials_path):- # read existing credentials- config.read(credentials_path)- config_dict = {- # openai- "openai_auth_type": get_field(config, "openai", "auth_type"),- "openai_key": get_field(config, "openai", "key"),- # azure- "azure_auth_type": get_field(config, "azure", "auth_type"),- "azure_key": get_field(config, "azure", "key"),- "azure_version": get_field(config, "azure", "version"),- "azure_endpoint": get_field(config, "azure", "endpoint"),- "azure_deployment": get_field(config, "azure", "deployment"),- "azure_embedding_version": get_field(config, "azure", "embedding_version"),- "azure_embedding_endpoint": get_field(config, "azure", "embedding_endpoint"),- "azure_embedding_deployment": get_field(config, "azure", "embedding_deployment"),- # gemini- "google_ai_key": get_field(config, "google_ai", "key"),- # "google_ai_service_endpoint": get_field(config, "google_ai", "service_endpoint"),- # anthropic- "anthropic_key": get_field(config, "anthropic", "key"),- # cohere- "cohere_key": get_field(config, "cohere", "key"),- # groq- "groq_key": get_field(config, "groq", "key"),- # open llm- "openllm_auth_type": get_field(config, "openllm", "auth_type"),- "openllm_key": get_field(config, "openllm", "key"),- # path- "credentials_path": credentials_path,- }- config_dict = {k: v for k, v in config_dict.items() if v is not None}- return cls(**config_dict)-- # create new config- config = cls(credentials_path=credentials_path)- config.save() # save updated config- return config-- def save(self):- pass-- config = configparser.ConfigParser()- # openai config- set_field(config, "openai", "auth_type", self.openai_auth_type)- set_field(config, "openai", "key", self.openai_key)-- # azure config- set_field(config, "azure", "auth_type", self.azure_auth_type)- set_field(config, "azure", "key", self.azure_key)- set_field(config, "azure", "version", self.azure_version)- set_field(config, "azure", "endpoint", self.azure_endpoint)- set_field(config, "azure", "deployment", self.azure_deployment)- set_field(config, "azure", "embedding_version", self.azure_embedding_version)- set_field(config, "azure", "embedding_endpoint", self.azure_embedding_endpoint)- set_field(config, "azure", "embedding_deployment", self.azure_embedding_deployment)-- # gemini- set_field(config, "google_ai", "key", self.google_ai_key)- # set_field(config, "google_ai", "service_endpoint", self.google_ai_service_endpoint)-- # anthropic- set_field(config, "anthropic", "key", self.anthropic_key)-- # cohere- set_field(config, "cohere", "key", self.cohere_key)-- # groq- set_field(config, "groq", "key", self.groq_key)-- # openllm config- set_field(config, "openllm", "auth_type", self.openllm_auth_type)- set_field(config, "openllm", "key", self.openllm_key)-- if not os.path.exists(LETTA_DIR):- os.makedirs(LETTA_DIR, exist_ok=True)- with open(self.credentials_path, "w", encoding="utf-8") as f:- config.write(f)-- @staticmethod- def exists():- # allow overriding with env variables- if os.getenv("MEMGPT_CREDENTIALS_PATH"):- credentials_path = os.getenv("MEMGPT_CREDENTIALS_PATH")- else:- credentials_path = LettaCredentials.credentials_path-- assert not os.path.isdir(credentials_path), f"Credentials path {credentials_path} cannot be set to a directory."- return os.path.exists(credentials_path)diff --git a/letta/llm_api/anthropic.py b/letta/llm_api/anthropic.pyindex fb42e696e..888a8b491 100644--- a/letta/llm_api/anthropic.py+++ b/letta/llm_api/anthropic.py@@ -1,7 +1,8 @@import jsonimport re-from typing import List, Optional, Union+from typing import List, Optional, Tuple, Union+from letta.llm_api.aws_bedrock import get_bedrock_clientfrom letta.llm_api.helpers import make_post_requestfrom letta.schemas.message import Messagefrom letta.schemas.openai.chat_completion_request import ChatCompletionRequest, Tool@@ -299,23 +300,11 @@ def convert_anthropic_response_to_chatcompletion()-def anthropic_chat_completions_request(- url: str,- api_key: str,+def _prepare_anthropic_request(data: ChatCompletionRequest,inner_thoughts_xml_tag: Optional[str] = "thinking",-) -> ChatCompletionResponse:- """https://docs.anthropic.com/claude/docs/tool-use"""-- url = smart_urljoin(url, "messages")- headers = {- "Content-Type": "application/json",- "x-api-key": api_key,- # NOTE: beta headers for tool calling- "anthropic-version": "2023-06-01",- "anthropic-beta": "tools-2024-04-04",- }-+) -> dict:+ """Prepare the request data for Anthropic API format."""# convert the toolsanthropic_tools = None if data.tools is None else convert_tools_to_anthropic_format(data.tools)@@ -325,57 +314,105 @@ def anthropic_chat_completions_request(if "functions" in data:raise ValueError(f"'functions' unexpected in Anthropic API payload")- # If tools == None, strip from the payload+ # Handle toolsif "tools" in data and data["tools"] is None:data.pop("tools")- data.pop("tool_choice", None) # extra safe, should exist always (default="auto")- # Remap to our converted tools- if anthropic_tools is not None:+ data.pop("tool_choice", None)+ elif anthropic_tools is not None:data["tools"] = anthropic_tools-- # TODO: Add support for other tool_choice options like "auto", "any"if len(anthropic_tools) == 1:data["tool_choice"] = {- "type": "tool", # Changed from "function" to "tool"- "name": anthropic_tools[0]["name"], # Directly specify name without nested "function" object- "disable_parallel_tool_use": True, # Force single tool use+ "type": "tool",+ "name": anthropic_tools[0]["name"],+ "disable_parallel_tool_use": True,}# Move 'system' to the top level- # 'messages: Unexpected role "system". The Messages API accepts a top-level `system` parameter, not "system" as an input message role.'assert data["messages"][0]["role"] == "system", f"Expected 'system' role in messages[0]:\n{data['messages'][0]}"data["system"] = data["messages"][0]["content"]data["messages"] = data["messages"][1:]- # set `content` to None if missing+ # Process messagesfor message in data["messages"]:if "content" not in message:message["content"] = None# Convert to Anthropic format-msg_objs = [Message.dict_to_message(user_id=None, agent_id=None, openai_message_dict=m) for m in data["messages"]]data["messages"] = [m.to_anthropic_dict(inner_thoughts_xml_tag=inner_thoughts_xml_tag) for m in msg_objs]- # Handling Anthropic special requirement for 'user' message in front- # messages: first message must use the "user" role'+ # Ensure first message is userif data["messages"][0]["role"] != "user":data["messages"] = [{"role": "user", "content": DUMMY_FIRST_USER_MESSAGE}] + data["messages"]- # Handle Anthropic's restriction on alternating user/assistant messages+ # Handle alternating messagesdata["messages"] = merge_tool_results_into_user_messages(data["messages"])- # Anthropic also wants max_tokens in the input- # It's also part of ChatCompletions+ # Validate max_tokensassert "max_tokens" in data, data- # Remove extra fields used by OpenAI but not Anthropic- data.pop("frequency_penalty", None)- data.pop("logprobs", None)- data.pop("n", None)- data.pop("top_p", None)- data.pop("presence_penalty", None)- data.pop("user", None)+ # Remove OpenAI-specific fields+ for field in ["frequency_penalty", "logprobs", "n", "top_p", "presence_penalty", "user"]:+ data.pop(field, None)++ return data+++def get_anthropic_endpoint_and_headers(+ base_url: str,+ api_key: str,+ version: str = "2023-06-01",+ beta: Optional[str] = "tools-2024-04-04",+) -> Tuple[str, dict]:+ """+ Dynamically generate the Anthropic endpoint and headers.+ """+ url = smart_urljoin(base_url, "messages")++ headers = {+ "Content-Type": "application/json",+ "x-api-key": api_key,+ "anthropic-version": version,+ }++ # Add beta header if specified+ if beta:+ headers["anthropic-beta"] = beta++ return url, headers++def anthropic_chat_completions_request(+ url: str,+ api_key: str,+ data: ChatCompletionRequest,+ inner_thoughts_xml_tag: Optional[str] = "thinking",+) -> ChatCompletionResponse:+ """https://docs.anthropic.com/claude/docs/tool-use"""+ url, headers = get_anthropic_endpoint_and_headers(url, api_key)+ data = _prepare_anthropic_request(data, inner_thoughts_xml_tag)response_json = make_post_request(url, headers, data)return convert_anthropic_response_to_chatcompletion(response_json=response_json, inner_thoughts_xml_tag=inner_thoughts_xml_tag)+++def anthropic_bedrock_chat_completions_request(+ data: ChatCompletionRequest,+ inner_thoughts_xml_tag: Optional[str] = "thinking",+) -> ChatCompletionResponse:+ """Make a chat completion request to Anthropic via AWS Bedrock."""+ data = _prepare_anthropic_request(data, inner_thoughts_xml_tag)++ # Get the client+ client = get_bedrock_client()++ # Make the request+ response = client.messages.create(+ model=data["model"],+ max_tokens=data["max_tokens"],+ messages=data["messages"],+ tools=data.get("tools", None),+ )++ return convert_anthropic_response_to_chatcompletion(+ response_json=json.loads(response.json()), inner_thoughts_xml_tag=inner_thoughts_xml_tag+ )diff --git a/letta/llm_api/aws_bedrock.py b/letta/llm_api/aws_bedrock.pynew file mode 100644index 000000000..a527f917b--- /dev/null+++ b/letta/llm_api/aws_bedrock.py@@ -0,0 +1,134 @@+import os+from typing import Any, Dict, List, Optional++from anthropic import AnthropicBedrock++from letta.settings import model_settings+++def has_valid_aws_credentials() -> bool:+ """+ Check if AWS credentials are properly configured.+ """+ valid_aws_credentials = os.getenv("AWS_ACCESS_KEY_ID") and os.getenv("AWS_SECRET_ACCESS_KEY") and os.getenv("AWS_REGION")+ return valid_aws_credentials+++def get_bedrock_client():+ """+ Get a Bedrock client+ """+ import boto3++ sts_client = boto3.client(+ "sts",+ aws_access_key_id=model_settings.aws_access_key,+ aws_secret_access_key=model_settings.aws_secret_access_key,+ region_name=model_settings.aws_region,+ )+ credentials = sts_client.get_session_token()["Credentials"]++ bedrock = AnthropicBedrock(+ aws_access_key=credentials["AccessKeyId"],+ aws_secret_key=credentials["SecretAccessKey"],+ aws_session_token=credentials["SessionToken"],+ aws_region=model_settings.aws_region,+ )+ return bedrock+++def bedrock_get_model_list(region_name: str, model_provider: Optional[str] = None, output_modality: str = "TEXT") -> List[dict]:+ """+ Get list of available models from Bedrock.++ Args:+ region_name: AWS region name+ model_provider: Optional provider name to filter models. If None, returns all models.+ output_modality: Output modality to filter models. Defaults to "text".++ Returns:+ List of model summaries+ """+ import boto3++ try:+ bedrock = boto3.client("bedrock", region_name=region_name)+ response = bedrock.list_foundation_models(byProvider=model_provider, byOutputModality=output_modality.upper())+ return response["modelSummaries"]+ except Exception as e:+ print(f"Error getting model list: {str(e)}")+ raise e+++def bedrock_get_model_details(region_name: str, model_id: str) -> Dict[str, Any]:+ """+ Get details for a specific model from Bedrock.+ """+ import boto3+ from botocore.exceptions import ClientError++ try:+ bedrock = boto3.client("bedrock", region_name=region_name)+ response = bedrock.get_foundation_model(modelIdentifier=model_id)+ return response["modelDetails"]+ except ClientError as e:+ print(f"Error getting model details: {str(e)}")+ raise e+++def bedrock_get_model_context_window(model_id: str) -> int:+ """+ Get context window size for a specific model.+ """+ # Bedrock doesn't provide this via API, so we maintain a mapping+ context_windows = {+ "anthropic.claude-3-5-sonnet-20241022-v2:0": 200000,+ "anthropic.claude-3-5-sonnet-20240620-v1:0": 200000,+ "anthropic.claude-3-5-haiku-20241022-v1:0": 200000,+ "anthropic.claude-3-haiku-20240307-v1:0": 200000,+ "anthropic.claude-3-opus-20240229-v1:0": 200000,+ "anthropic.claude-3-sonnet-20240229-v1:0": 200000,+ }+ return context_windows.get(model_id, 200000) # default to 100k if unknown+++"""+{+ "id": "msg_123",+ "type": "message",+ "role": "assistant",+ "model": "anthropic.claude-3-5-sonnet-20241022-v2:0",+ "content": [+ {+ "type": "text",+ "text": "I see the Firefox icon. Let me click on it and then navigate to a weather website."+ },+ {+ "type": "tool_use",+ "id": "toolu_123",+ "name": "computer",+ "input": {+ "action": "mouse_move",+ "coordinate": [+ 708,+ 736+ ]+ }+ },+ {+ "type": "tool_use",+ "id": "toolu_234",+ "name": "computer",+ "input": {+ "action": "left_click"+ }+ }+ ],+ "stop_reason": "tool_use",+ "stop_sequence": null,+ "usage": {+ "input_tokens": 3391,+ "output_tokens": 132+ }+}+"""diff --git a/letta/llm_api/llm_api_tools.py b/letta/llm_api/llm_api_tools.pyindex fc5252d33..8d161eca6 100644--- a/letta/llm_api/llm_api_tools.py+++ b/letta/llm_api/llm_api_tools.py@@ -6,7 +6,8 @@ import requestsfrom letta.constants import CLI_WARNING_PREFIXfrom letta.errors import LettaConfigurationError, RateLimitExceededError-from letta.llm_api.anthropic import anthropic_chat_completions_request+from letta.llm_api.anthropic import anthropic_bedrock_chat_completions_request, anthropic_chat_completions_request+from letta.llm_api.aws_bedrock import has_valid_aws_credentialsfrom letta.llm_api.azure_openai import azure_openai_chat_completions_requestfrom letta.llm_api.google_ai import convert_tools_to_google_ai_format, google_ai_chat_completions_requestfrom letta.llm_api.helpers import add_inner_thoughts_to_functions, unpack_all_inner_thoughts_from_kwargs@@ -374,6 +375,34 @@ def create(auth_key=model_settings.together_api_key,)+ elif llm_config.model_endpoint_type == "bedrock":+ """Anthropic endpoint that goes via /embeddings instead of /chat/completions"""++ if stream:+ raise NotImplementedError(f"Streaming not yet implemented for Anthropic (via the /embeddings endpoint).")+ if not use_tool_naming:+ raise NotImplementedError("Only tool calling supported on Anthropic API requests")++ if not has_valid_aws_credentials():+ raise LettaConfigurationError(message="Invalid or missing AWS credentials. Please configure valid AWS credentials.")++ tool_call = None+ if force_tool_call is not None:+ tool_call = {"type": "function", "function": {"name": force_tool_call}}+ assert functions is not None++ return anthropic_bedrock_chat_completions_request(+ data=ChatCompletionRequest(+ model=llm_config.model,+ messages=[cast_message_to_subtype(m.to_openai_dict()) for m in messages],+ tools=[{"type": "function", "function": f} for f in functions] if functions else None,+ tool_choice=tool_call,+ # user=str(user_id),+ # NOTE: max_tokens is required for Anthropic API+ max_tokens=1024, # TODO make dynamic+ ),+ )+# local modelelse:if stream:diff --git a/letta/schemas/embedding_config.py b/letta/schemas/embedding_config.pyindex 7a8236c37..c0a569a7b 100644--- a/letta/schemas/embedding_config.py+++ b/letta/schemas/embedding_config.py@@ -23,6 +23,7 @@ class EmbeddingConfig(BaseModel):embedding_endpoint_type: Literal["openai","anthropic",+ "bedrock","cohere","google_ai","azure",diff --git a/letta/schemas/llm_config.py b/letta/schemas/llm_config.pyindex 970579ea9..da578a331 100644--- a/letta/schemas/llm_config.py+++ b/letta/schemas/llm_config.py@@ -36,6 +36,7 @@ class LLMConfig(BaseModel):"hugging-face","mistral","together", # completions endpoint+ "bedrock",] = Field(..., description="The endpoint type for the model.")model_endpoint: Optional[str] = Field(None, description="The endpoint for the model.")model_wrapper: Optional[str] = Field(None, description="The wrapper for the model.")diff --git a/letta/schemas/providers.py b/letta/schemas/providers.pyindex 407418a95..ce05e22ac 100644--- a/letta/schemas/providers.py+++ b/letta/schemas/providers.py@@ -699,3 +699,54 @@ class VLLMCompletionsProvider(Provider):class CohereProvider(OpenAIProvider):pass+++class AnthropicBedrockProvider(Provider):+ name: str = "bedrock"+ aws_region: str = Field(..., description="AWS region for Bedrock")++ def list_llm_models(self):+ from letta.llm_api.aws_bedrock import bedrock_get_model_list++ models = bedrock_get_model_list(self.aws_region, model_provider="anthropic")++ configs = []+ for model_summary in models:+ model_id = model_summary["modelId"]+ configs.append(+ LLMConfig(+ model=model_id,+ model_endpoint_type=self.name,+ model_endpoint=None,+ context_window=self.get_model_context_window(model_id),+ )+ )+ return configs++ def list_embedding_models(self):+ from letta.llm_api.aws_bedrock import bedrock_get_model_list++ # Will return nothing+ models = bedrock_get_model_list(self.aws_region, model_provider="anthropic", output_modality="EMBEDDING")++ configs = []+ for model_summary in models:+ model_id = model_summary["modelId"]+ configs.append(+ EmbeddingConfig(+ model=model_id,+ model_endpoint_type=self.name,+ model_endpoint=None,+ context_window=self.get_model_context_window(model_id),+ )+ )+ return configs++ def get_model_context_window(self, model_name: str) -> Optional[int]:+ # Context windows for Claude models+ from letta.llm_api.aws_bedrock import bedrock_get_model_context_window++ return bedrock_get_model_context_window(model_name)++ def get_handle(self, model_name: str) -> str:+ return f"anthropic/{model_name}"diff --git a/letta/server/server.py b/letta/server/server.pyindex 28d62ec8a..da4af5fea 100644--- a/letta/server/server.py+++ b/letta/server/server.py@@ -17,7 +17,6 @@ import letta.server.utils as server_utilsimport letta.system as systemfrom letta.agent import Agent, save_agentfrom letta.chat_only_agent import ChatOnlyAgent-from letta.credentials import LettaCredentialsfrom letta.data_sources.connectors import DataConnector, load_data# TODO use custom interface@@ -43,6 +42,7 @@ from letta.schemas.message import Message, MessageCreate, MessageRole, MessageUpfrom letta.schemas.organization import Organizationfrom letta.schemas.passage import Passagefrom letta.schemas.providers import (+ AnthropicBedrockProvider,AnthropicProvider,AzureProvider,GoogleAIProvider,@@ -271,8 +271,6 @@ class SyncServer(Server):# The default interface that will get assigned to agents ON LOADself.default_interface_factory = default_interface_factory- self.credentials = LettaCredentials.load()-# Initialize the metadata storeconfig = LettaConfig.load()if settings.letta_pg_uri_no_default:@@ -384,6 +382,12 @@ class SyncServer(Server):base_url=model_settings.vllm_api_base,))+ if model_settings.aws_access_key and model_settings.aws_secret_access_key and model_settings.aws_region:+ self._enabled_providers.append(+ AnthropicBedrockProvider(+ aws_region=model_settings.aws_region,+ )+ )def load_agent(self, agent_id: str, actor: User, interface: Union[AgentInterface, None] = None) -> Agent:"""Updated method to load agents from persisted storage"""diff --git a/letta/settings.py b/letta/settings.pyindex b8dd17bf3..dde4cecb2 100644--- a/letta/settings.py+++ b/letta/settings.py@@ -35,6 +35,12 @@ class ModelSettings(BaseSettings):# groqgroq_api_key: Optional[str] = None+ # Bedrock+ aws_access_key: Optional[str] = None+ aws_secret_access_key: Optional[str] = None+ aws_region: Optional[str] = None+ bedrock_anthropic_version: Optional[str] = "bedrock-2023-05-31"+# anthropicanthropic_api_key: Optional[str] = Nonediff --git a/poetry.lock b/poetry.lockindex 61ab6cf60..36d49021c 100644--- a/poetry.lock+++ b/poetry.lock@@ -153,6 +153,30 @@ files = [{file = "annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89"},]+[[package]]+name = "anthropic"+version = "0.43.0"+description = "The official Python library for the anthropic API"+optional = false+python-versions = ">=3.8"+files = [+ {file = "anthropic-0.43.0-py3-none-any.whl", hash = "sha256:f748a703f77b3244975e1aace3a935840dc653a4714fb6bba644f97cc76847b4"},+ {file = "anthropic-0.43.0.tar.gz", hash = "sha256:06801f01d317a431d883230024318d48981758058bf7e079f33fb11f64b5a5c1"},+]++[package.dependencies]+anyio = ">=3.5.0,<5"+distro = ">=1.7.0,<2"+httpx = ">=0.23.0,<1"+jiter = ">=0.4.0,<1"+pydantic = ">=1.9.0,<3"+sniffio = "*"+typing-extensions = ">=4.10,<5"++[package.extras]+bedrock = ["boto3 (>=1.28.57)", "botocore (>=1.31.57)"]+vertex = ["google-auth (>=2,<3)"]+[[package]]name = "anyio"version = "4.8.0"@@ -2418,13 +2442,13 @@ tenacity = ">=8.1.0,<8.4.0 || >8.4.0,<10"[[package]]name = "langchain-core"-version = "0.3.29"+version = "0.3.30"description = "Building applications with LLMs through composability"optional = falsepython-versions = "<4.0,>=3.9"files = [- {file = "langchain_core-0.3.29-py3-none-any.whl", hash = "sha256:817db1474871611a81105594a3e4d11704949661008e455a10e38ca9ff601a1a"},- {file = "langchain_core-0.3.29.tar.gz", hash = "sha256:773d6aeeb612e7ce3d996c0be403433d8c6a91e77bbb7a7461c13e15cfbe5b06"},+ {file = "langchain_core-0.3.30-py3-none-any.whl", hash = "sha256:0a4c4e02fac5968b67fbb0142c00c2b976c97e45fce62c7ac9eb1636a6926493"},+ {file = "langchain_core-0.3.30.tar.gz", hash = "sha256:0f1281b4416977df43baf366633ad18e96c5dcaaeae6fcb8a799f9889c853243"},][package.dependencies]@@ -2487,13 +2511,13 @@ types-requests = ">=2.31.0.2,<3.0.0.0"[[package]]name = "langsmith"-version = "0.2.10"+version = "0.2.11"description = "Client library to connect to the LangSmith LLM Tracing and Evaluation Platform."optional = falsepython-versions = "<4.0,>=3.9"files = [- {file = "langsmith-0.2.10-py3-none-any.whl", hash = "sha256:b02f2f174189ff72e54c88b1aa63343defd6f0f676c396a690c63a4b6495dcc2"},- {file = "langsmith-0.2.10.tar.gz", hash = "sha256:153c7b3ccbd823528ff5bec84801e7e50a164e388919fc583252df5b27dd7830"},+ {file = "langsmith-0.2.11-py3-none-any.whl", hash = "sha256:084cf66a7f093c25e6b30fb4005008ec5fa9843110e2f0b265ce133c6a0225e6"},+ {file = "langsmith-0.2.11.tar.gz", hash = "sha256:edf070349dbfc63dc4fc30e22533a11d77768e99ef269399b221c48fee25c737"},][package.dependencies]@@ -3296,13 +3320,13 @@ files = [[[package]]name = "openai"-version = "1.59.7"+version = "1.59.8"description = "The official Python library for the openai API"optional = falsepython-versions = ">=3.8"files = [- {file = "openai-1.59.7-py3-none-any.whl", hash = "sha256:cfa806556226fa96df7380ab2e29814181d56fea44738c2b0e581b462c268692"},- {file = "openai-1.59.7.tar.gz", hash = "sha256:043603def78c00befb857df9f0a16ee76a3af5984ba40cb7ee5e2f40db4646bf"},+ {file = "openai-1.59.8-py3-none-any.whl", hash = "sha256:a8b8ee35c4083b88e6da45406d883cf6bd91a98ab7dd79178b8bc24c8bfb09d9"},+ {file = "openai-1.59.8.tar.gz", hash = "sha256:ac4bda5fa9819fdc6127e8ea8a63501f425c587244bc653c7c11a8ad84f953e1"},][package.dependencies]@@ -4767,13 +4791,13 @@ fastembed-gpu = ["fastembed-gpu (==0.3.6)"][[package]]name = "qdrant-client"-version = "1.12.2"+version = "1.13.0"description = "Client library for the Qdrant vector search engine"optional = truepython-versions = ">=3.9"files = [- {file = "qdrant_client-1.12.2-py3-none-any.whl", hash = "sha256:a0ae500a46a679ff3521ba3f1f1cf3d72b57090a768cec65fc317066bcbac1e6"},- {file = "qdrant_client-1.12.2.tar.gz", hash = "sha256:2777e09b3e89bb22bb490384d8b1fa8140f3915287884f18984f7031a346aba5"},+ {file = "qdrant_client-1.13.0-py3-none-any.whl", hash = "sha256:63a063d5232618b609f2c438caf6f3afd3bd110dd80d01be20c596e516efab6b"},+ {file = "qdrant_client-1.13.0.tar.gz", hash = "sha256:9708e3194081619b38194c99e7c369064e3f3f328d8a8ef1d71a87425a5ddf0c"},][package.dependencies]@@ -4789,8 +4813,8 @@ pydantic = ">=1.10.8"urllib3 = ">=1.26.14,<3"[package.extras]-fastembed = ["fastembed (==0.5.0)"]-fastembed-gpu = ["fastembed-gpu (==0.5.0)"]+fastembed = ["fastembed (==0.5.1)"]+fastembed-gpu = ["fastembed-gpu (==0.5.1)"][[package]]name = "questionary"@@ -4808,19 +4832,19 @@ prompt_toolkit = ">=2.0,<4.0"[[package]]name = "referencing"-version = "0.36.0"+version = "0.36.1"description = "JSON Referencing + Python"optional = falsepython-versions = ">=3.9"files = [- {file = "referencing-0.36.0-py3-none-any.whl", hash = "sha256:01fc2916bab821aa3284d645bbbb41ba39609e7ff47072416a39ec2fb04d10d9"},- {file = "referencing-0.36.0.tar.gz", hash = "sha256:246db964bb6101905167895cd66499cfb2aabc5f83277d008c52afe918ef29ba"},+ {file = "referencing-0.36.1-py3-none-any.whl", hash = "sha256:363d9c65f080d0d70bc41c721dce3c7f3e77fc09f269cd5c8813da18069a6794"},+ {file = "referencing-0.36.1.tar.gz", hash = "sha256:ca2e6492769e3602957e9b831b94211599d2aade9477f5d44110d2530cf9aade"},][package.dependencies]attrs = ">=22.2.0"rpds-py = ">=0.7.0"-typing-extensions = {version = "*", markers = "python_version < \"3.13\""}+typing-extensions = {version = ">=4.4.0", markers = "python_version < \"3.13\""}[[package]]name = "regex"@@ -5716,13 +5740,13 @@ standard = ["colorama (>=0.4)", "httptools (>=0.5.0)", "python-dotenv (>=0.13)",[[package]]name = "virtualenv"-version = "20.29.0"+version = "20.29.1"description = "Virtual Python Environment builder"optional = truepython-versions = ">=3.8"files = [- {file = "virtualenv-20.29.0-py3-none-any.whl", hash = "sha256:c12311863497992dc4b8644f8ea82d3b35bb7ef8ee82e6630d76d0197c39baf9"},- {file = "virtualenv-20.29.0.tar.gz", hash = "sha256:6345e1ff19d4b1296954cee076baaf58ff2a12a84a338c62b02eda39f20aa982"},+ {file = "virtualenv-20.29.1-py3-none-any.whl", hash = "sha256:4e4cb403c0b0da39e13b46b1b2476e505cb0046b25f242bee80f62bf990b2779"},+ {file = "virtualenv-20.29.1.tar.gz", hash = "sha256:b8b8970138d32fb606192cb97f6cd4bb644fa486be9308fb9b63f81091b5dc35"},][package.dependencies]@@ -6282,6 +6306,7 @@ testing = ["coverage[toml]", "zope.event", "zope.testing"][extras]all = ["autoflake", "black", "datasets", "docker", "fastapi", "isort", "langchain", "langchain-community", "locust", "pexpect", "pg8000", "pgvector", "pre-commit", "psycopg2", "psycopg2-binary", "pyright", "pytest-asyncio", "pytest-order", "uvicorn", "websockets", "wikipedia"]+bedrock = []cloud-tool-sandbox = ["e2b-code-interpreter"]dev = ["autoflake", "black", "datasets", "isort", "locust", "pexpect", "pre-commit", "pyright", "pytest-asyncio", "pytest-order"]external-tools = ["docker", "langchain", "langchain-community", "wikipedia"]@@ -6293,4 +6318,4 @@ tests = ["wikipedia"][metadata]lock-version = "2.0"python-versions = "<3.14,>=3.10"-content-hash = "f1cb65b567ce1063354e088b2d3b714b2701aa046a38bb6624d35d12a9a0cfc9"+content-hash = "f79e70bc03fff20fcd97a1be2c7421d94458df8ffd92096c487b9dbb81f23164"diff --git a/pyproject.toml b/pyproject.tomlindex 211382e76..cc22753b7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -76,6 +76,7 @@ grpcio-tools = "^1.68.1"llama-index = "^0.12.2"llama-index-embeddings-openai = "^0.3.1"e2b-code-interpreter = {version = "^1.0.3", optional = true}+anthropic = "^0.43.0"letta_client = "^0.1.16"[tool.poetry.extras]@@ -87,6 +88,7 @@ cloud-tool-sandbox = ["e2b-code-interpreter"]external-tools = ["docker", "langchain", "wikipedia", "langchain-community"]tests = ["wikipedia"]all = ["pgvector", "pg8000", "psycopg2-binary", "psycopg2", "pytest", "pytest-asyncio", "pexpect", "black", "pre-commit", "datasets", "pyright", "pytest-order", "autoflake", "isort", "websockets", "fastapi", "uvicorn", "docker", "langchain", "wikipedia", "langchain-community", "locust"]+bedrock = ["boto3"][tool.poetry.group.dev.dependencies]black = "^24.4.2"diff --git a/tests/configs/llm_model_configs/bedrock-claude-3-5-sonnet.json b/tests/configs/llm_model_configs/bedrock-claude-3-5-sonnet.jsonnew file mode 100644index 000000000..af62ae693--- /dev/null+++ b/tests/configs/llm_model_configs/bedrock-claude-3-5-sonnet.json@@ -0,0 +1,8 @@+{+ "context_window": 200000,+ "model": "arn:aws:bedrock:us-west-2:850995572407:inference-profile/us.anthropic.claude-3-5-sonnet-20241022-v2:0",+ "model_endpoint_type": "bedrock",+ "model_endpoint": null,+ "model_wrapper": null,+ "put_inner_thoughts_in_kwargs": true+}diff --git a/tests/test_model_letta_performance.py b/tests/test_model_letta_performance.pyindex 4d72126fa..304d2030a 100644--- a/tests/test_model_letta_performance.py+++ b/tests/test_model_letta_performance.py@@ -339,3 +339,66 @@ def test_together_llama_3_70b_edit_core_memory():response = check_agent_edit_core_memory(filename)# Log out successful responseprint(f"Got successful response from client: \n\n{response}")+++# ======================================================================================================================+# ANTHROPIC BEDROCK TESTS+# ======================================================================================================================[email protected]_bedrock_basic+def test_bedrock_claude_sonnet_3_5_valid_config():+ import json++ from letta.schemas.llm_config import LLMConfig+ from letta.settings import model_settings++ filename = os.path.join(llm_config_dir, "bedrock-claude-3-5-sonnet.json")+ config_data = json.load(open(filename, "r"))+ llm_config = LLMConfig(**config_data)+ model_region = llm_config.model.split(":")[3]+ assert model_settings.aws_region == model_region, "Model region in config file does not match model region in ModelSettings"++[email protected]_bedrock_basic+@retry_until_success(max_attempts=5, sleep_time_seconds=2)+def test_bedrock_claude_sonnet_3_5_returns_valid_first_message():+ filename = os.path.join(llm_config_dir, "bedrock-claude-3-5-sonnet.json")+ response = check_first_response_is_valid_for_llm_endpoint(filename)+ # Log out successful response+ print(f"Got successful response from client: \n\n{response}")++[email protected]_bedrock_basic+@retry_until_success(max_attempts=5, sleep_time_seconds=2)+def test_bedrock_claude_sonnet_3_5_uses_external_tool(mock_e2b_api_key_none):+ filename = os.path.join(llm_config_dir, "bedrock-claude-3-5-sonnet.json")+ response = check_agent_uses_external_tool(filename)+ # Log out successful response+ print(f"Got successful response from client: \n\n{response}")+++# TODO: Debug later+# @pytest.mark.anthropic_bedrock_basic+# @retry_until_success(max_attempts=5, sleep_time_seconds=2)+# def test_bedrock_claude_sonnet_3_5_recall_chat_memory():+# filename = os.path.join(llm_config_dir, "bedrock-claude-3-5-sonnet.json")+# response = check_agent_recall_chat_memory(filename)+# # Log out successful response+# print(f"Got successful response from client: \n\n{response}")++[email protected]_bedrock_basic+@retry_until_success(max_attempts=5, sleep_time_seconds=2)+def test_bedrock_claude_sonnet_3_5_archival_memory_retrieval():+ filename = os.path.join(llm_config_dir, "bedrock-claude-3-5-sonnet.json")+ response = check_agent_archival_memory_retrieval(filename)+ # Log out successful response+ print(f"Got successful response from client: \n\n{response}")++[email protected]_bedrock_basic+@retry_until_success(max_attempts=5, sleep_time_seconds=2)+def test_bedrock_claude_sonnet_3_5_edit_core_memory():+ filename = os.path.join(llm_config_dir, "bedrock-claude-3-5-sonnet.json")+ response = check_agent_edit_core_memory(filename)+ # Log out successful response+ print(f"Got successful response from client: \n\n{response}")diff --git a/tests/test_providers.py b/tests/test_providers.pyindex f416ce806..a575fba54 100644--- a/tests/test_providers.py+++ b/tests/test_providers.py@@ -1,6 +1,7 @@import osfrom letta.schemas.providers import (+ AnthropicBedrockProvider,AnthropicProvider,AzureProvider,GoogleAIProvider,@@ -80,6 +81,17 @@ def test_together():print([m.embedding_model for m in embedding_models])+def test_anthropic_bedrock():+ from letta.settings import model_settings++ provider = AnthropicBedrockProvider(aws_region=model_settings.aws_region)+ models = provider.list_llm_models()+ print([m.model for m in models])++ embedding_models = provider.list_embedding_models()+ print([m.embedding_model for m in embedding_models])++# def test_vllm():# provider = VLLMProvider(base_url=os.getenv("VLLM_API_BASE"))# models = provider.list_llm_models()diff --git a/tests/test_sdk_client.py b/tests/test_sdk_client.pyindex 8f31919f6..d0d976f29 100644--- a/tests/test_sdk_client.py+++ b/tests/test_sdk_client.py@@ -175,6 +175,11 @@ def test_add_and_manage_tags_for_agent(client):def test_agent_tags(client):"""Test creating agents with tags and retrieving tags via the API."""+ # Clear all agents+ all_agents = client.agents.list()+ for agent in all_agents:+ client.agents.delete(agent.id)+# Create multiple agents with different tagsagent1 = client.agents.create(memory_blocks=[