The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Fix flaky test_claude_agent_sdk_streaming: add retry and stronger prompt
yuneng-jiang9d06f535445a
diff --git a/tests/proxy_e2e_anthropic_messages_tests/test_claude_agent_sdk.py b/tests/proxy_e2e_anthropic_messages_tests/test_claude_agent_sdk.pyindex 8e8033d885f..6e31b216b17 100644--- a/tests/proxy_e2e_anthropic_messages_tests/test_claude_agent_sdk.py+++ b/tests/proxy_e2e_anthropic_messages_tests/test_claude_agent_sdk.py@@ -41,12 +41,65 @@ def litellm_proxy_config():}+MAX_RETRIES = 3+++async def _run_streaming_test(model_name: str) -> tuple[list[str], str]:+ """+ Run a single streaming test attempt for the given model.++ Returns (received_chunks, full_response).+ """+ options = ClaudeAgentOptions(+ system_prompt=(+ "You are a helpful AI assistant. "+ "Always follow the user's instructions exactly."+ ),+ model=model_name,+ max_turns=5,+ )++ test_query = (+ "Respond with exactly the following text and nothing else:\n"+ "Hello from LiteLLM!"+ )++ received_chunks: list[str] = []+ full_response = ""++ async with ClaudeSDKClient(options=options) as client:+ await client.query(test_query)++ async for msg in client.receive_response():+ if hasattr(msg, 'type'):+ if msg.type == 'content_block_delta':+ if hasattr(msg, 'delta') and hasattr(msg.delta, 'text'):+ chunk_text = msg.delta.text+ received_chunks.append(chunk_text)+ full_response += chunk_text+ elif msg.type == 'content_block_start':+ if hasattr(msg, 'content_block') and hasattr(msg.content_block, 'text'):+ chunk_text = msg.content_block.text+ received_chunks.append(chunk_text)+ full_response += chunk_text++ # Fallback to content handling+ if hasattr(msg, 'content'):+ for content_block in msg.content:+ if hasattr(content_block, 'text'):+ chunk_text = content_block.text+ received_chunks.append(chunk_text)+ full_response += chunk_text++ return received_chunks, full_response++@pytest.mark.asyncio@pytest.mark.parametrize("model_name,model_description", TEST_MODELS)async def test_claude_agent_sdk_streaming(litellm_proxy_config, model_name, model_description):"""Test streaming messages with Claude Agent SDK through LiteLLM proxy.-+This validates:1. Claude Agent SDK can connect to LiteLLM proxy2. Streaming works correctly@@ -55,68 +108,41 @@ async def test_claude_agent_sdk_streaming(litellm_proxy_config, model_name, modeprint(f"\n{'='*60}")print(f"Testing: {model_name} ({model_description})")print(f"{'='*60}")-- # Configure agent options- options = ClaudeAgentOptions(- system_prompt="You are a helpful AI assistant. Be concise.",- model=model_name,- max_turns=5,++ last_error: Exception | None = None++ for attempt in range(1, MAX_RETRIES + 1):+ try:+ received_chunks, full_response = await _run_streaming_test(model_name)++ # Assertions+ print(f"\n✅ Received {len(received_chunks)} chunks")+ print(f"📝 Full response: {full_response[:100]}...")++ # Verify we got a response+ assert len(full_response) > 0, f"No response received from {model_name}"++ # Verify streaming (should have multiple chunks for most responses)+ # Note: Very short responses might come in 1 chunk, so we just verify we got content+ assert len(received_chunks) > 0, f"No chunks received from {model_name}"++ # Verify response contains expected content (case insensitive)+ assert "hello" in full_response.lower(), (+ f"Response doesn't contain expected greeting: {full_response}"+ )++ print(f"✅ Test passed for {model_name} (attempt {attempt})")+ return # Success++ except Exception as e:+ last_error = e+ print(f"⚠️ Attempt {attempt}/{MAX_RETRIES} failed for {model_name}: {e}")+ if attempt < MAX_RETRIES:+ await asyncio.sleep(2)++ pytest.fail(+ f"Test failed for {model_name} ({model_description}) after {MAX_RETRIES} attempts: {last_error}")-- # Test query- test_query = "Say 'Hello from LiteLLM!' and nothing else."-- # Track streaming- received_chunks = []- full_response = ""-- try:- async with ClaudeSDKClient(options=options) as client:- await client.query(test_query)-- # Collect streaming response- async for msg in client.receive_response():- # Handle different message types- if hasattr(msg, 'type'):- if msg.type == 'content_block_delta':- # Streaming text delta- if hasattr(msg, 'delta') and hasattr(msg.delta, 'text'):- chunk_text = msg.delta.text- received_chunks.append(chunk_text)- full_response += chunk_text- elif msg.type == 'content_block_start':- # Start of content block- if hasattr(msg, 'content_block') and hasattr(msg.content_block, 'text'):- chunk_text = msg.content_block.text- received_chunks.append(chunk_text)- full_response += chunk_text-- # Fallback to content handling- if hasattr(msg, 'content'):- for content_block in msg.content:- if hasattr(content_block, 'text'):- chunk_text = content_block.text- received_chunks.append(chunk_text)- full_response += chunk_text-- # Assertions- print(f"\n✅ Received {len(received_chunks)} chunks")- print(f"📝 Full response: {full_response[:100]}...")-- # Verify we got a response- assert len(full_response) > 0, f"No response received from {model_name}"-- # Verify streaming (should have multiple chunks for most responses)- # Note: Very short responses might come in 1 chunk, so we just verify we got content- assert len(received_chunks) > 0, f"No chunks received from {model_name}"-- # Verify response contains expected content (case insensitive)- assert "hello" in full_response.lower(), f"Response doesn't contain expected greeting: {full_response}"-- print(f"✅ Test passed for {model_name}")-- except Exception as e:- pytest.fail(f"Test failed for {model_name} ({model_description}): {str(e)}")if __name__ == "__main__":