Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: Add batch requests on Anthropic Client (#1574)
Matthew Zhoub03af8eb60b5
diff --git a/letta/llm_api/anthropic_client.py b/letta/llm_api/anthropic_client.pyindex 99e315b85..944858c2c 100644--- a/letta/llm_api/anthropic_client.py+++ b/letta/llm_api/anthropic_client.py@@ -1,11 +1,14 @@import jsonimport re-from typing import List, Optional, Union+from typing import Dict, List, Optional, Unionimport anthropicfrom anthropic import AsyncStreamfrom anthropic.types import Message as AnthropicMessagefrom anthropic.types.beta import BetaRawMessageStreamEvent+from anthropic.types.beta.message_create_params import MessageCreateParamsNonStreaming+from anthropic.types.beta.messages import BetaMessageBatch+from anthropic.types.beta.messages.batch_create_params import Requestfrom letta.errors import (ContextWindowExceededError,@@ -55,6 +58,27 @@ class AnthropicClient(LLMClientBase):request_data["stream"] = Truereturn await client.beta.messages.create(**request_data, betas=["tools-2024-04-04"])+ @trace_method+ async def batch_async(self, requests: Dict[str, dict]) -> BetaMessageBatch:+ """+ Send a batch of requests to the Anthropic API asynchronously.++ Args:+ requests (Dict[str, dict]): A mapping from custom_id to request parameter dicts.++ Returns:+ List[dict]: A list of response dictionaries corresponding to each request.+ """+ client = self._get_anthropic_client(async_client=True)++ anthropic_requests = [+ Request(custom_id=custom_id, params=MessageCreateParamsNonStreaming(**params)) for custom_id, params in requests.items()+ ]++ batch_response = await client.beta.messages.batches.create(requests=anthropic_requests)++ return batch_response+@trace_methoddef _get_anthropic_client(self, async_client: bool = False) -> Union[anthropic.AsyncAnthropic, anthropic.Anthropic]:override_key = ProviderManager().get_anthropic_override_key()diff --git a/tests/test_llm_clients.py b/tests/test_llm_clients.pynew file mode 100644index 000000000..00493d2a2--- /dev/null+++ b/tests/test_llm_clients.py@@ -0,0 +1,58 @@+import pytest++from letta.llm_api.anthropic_client import AnthropicClient+from letta.schemas.llm_config import LLMConfig+++def anthropic_client():+ llm_config = LLMConfig(+ model="claude-3-7-sonnet-20250219",+ model_endpoint_type="anthropic",+ model_endpoint="https://api.anthropic.com/v1",+ context_window=32000,+ handle=f"anthropic/claude-3-5-sonnet-20241022",+ put_inner_thoughts_in_kwargs=False,+ max_tokens=4096,+ enable_reasoner=True,+ max_reasoning_tokens=1024,+ )++ yield AnthropicClient(llm_config=llm_config)+++# ======================================================================================================================+# AnthropicClient+# ======================================================================================================================+++async def test_batch_async_live(anthropic_client):+ input_requests = {+ "my-first-request": {+ "model": "claude-3-7-sonnet-20250219",+ "max_tokens": 1024,+ "messages": [+ {+ "role": "user",+ "content": "Hello, world",+ }+ ],+ },+ "my-second-request": {+ "model": "claude-3-7-sonnet-20250219",+ "max_tokens": 1024,+ "messages": [+ {+ "role": "user",+ "content": "Hi again, friend",+ }+ ],+ },+ }++ response = await anthropic_client.batch_async(input_requests)+ assert response.id.startswith("msgbatch_")+ assert response.processing_status in {"in_progress", "succeeded"}+ assert response.request_counts.processing + response.request_counts.succeeded == len(input_requests.keys())+ assert response.created_at < response.expires_at