aboutsummaryrefslogtreecommitdiff
path: root/packages/openai-sdk-python/test_integration.py
diff options
context:
space:
mode:
authornexxeln <[email protected]>2025-11-11 02:16:34 +0000
committernexxeln <[email protected]>2025-11-11 02:16:34 +0000
commitea9bf13d314a605f3b80c7e8ce7e3141db5438df (patch)
treef4670a996de9097ede0fd40ae33277f70c915e75 /packages/openai-sdk-python/test_integration.py
parentchore: update readme with selfhost link (#573) (diff)
downloadsupermemory-openai-middleware-python.tar.xz
supermemory-openai-middleware-python.zip
add openai middleware functionality for python sdk (#546)openai-middleware-python
add openai middleware functionality fix critical type errors and linting issues update readme with middleware documentation
Diffstat (limited to 'packages/openai-sdk-python/test_integration.py')
-rw-r--r--packages/openai-sdk-python/test_integration.py197
1 files changed, 197 insertions, 0 deletions
diff --git a/packages/openai-sdk-python/test_integration.py b/packages/openai-sdk-python/test_integration.py
new file mode 100644
index 00000000..9bf5880c
--- /dev/null
+++ b/packages/openai-sdk-python/test_integration.py
@@ -0,0 +1,197 @@
+#!/usr/bin/env python3
+"""
+Integration test for Supermemory OpenAI middleware.
+
+This script demonstrates how to test the middleware with real API calls.
+Set your API keys as environment variables to run this test.
+"""
+
+import asyncio
+import os
+from openai import AsyncOpenAI, OpenAI
+from supermemory_openai import (
+ with_supermemory,
+ OpenAIMiddlewareOptions,
+ SupermemoryConfigurationError,
+ SupermemoryAPIError,
+)
+
+
+async def test_async_middleware():
+ """Test async middleware functionality."""
+ print("๐Ÿ”„ Testing Async Middleware...")
+
+ try:
+ # Check for required environment variables
+ if not os.getenv("OPENAI_API_KEY"):
+ print("โŒ OPENAI_API_KEY not set - skipping OpenAI test")
+ return
+
+ if not os.getenv("SUPERMEMORY_API_KEY"):
+ print("โŒ SUPERMEMORY_API_KEY not set - skipping Supermemory test")
+ return
+
+ # Create OpenAI client
+ openai_client = AsyncOpenAI()
+
+ # Wrap with Supermemory middleware
+ openai_with_memory = with_supermemory(
+ openai_client,
+ container_tag="test-user-123",
+ options=OpenAIMiddlewareOptions(
+ mode="profile",
+ verbose=True,
+ add_memory="never" # Don't save test messages
+ )
+ )
+
+ # Test context manager
+ async with openai_with_memory as client:
+ print("โœ… Context manager works")
+
+ # Make a test request
+ response = await client.chat.completions.create(
+ model="gpt-3.5-turbo",
+ messages=[
+ {"role": "user", "content": "Hello! This is a test message."}
+ ],
+ max_tokens=50
+ )
+
+ print(f"โœ… API call successful: {response.choices[0].message.content[:50]}...")
+
+ except SupermemoryConfigurationError as e:
+ print(f"โš ๏ธ Configuration error: {e}")
+ except SupermemoryAPIError as e:
+ print(f"โš ๏ธ Supermemory API error: {e}")
+ except Exception as e:
+ print(f"โŒ Unexpected error: {e}")
+
+
+def test_sync_middleware():
+ """Test sync middleware functionality."""
+ print("\n๐Ÿ”„ Testing Sync Middleware...")
+
+ try:
+ if not os.getenv("OPENAI_API_KEY"):
+ print("โŒ OPENAI_API_KEY not set - skipping OpenAI test")
+ return
+
+ if not os.getenv("SUPERMEMORY_API_KEY"):
+ print("โŒ SUPERMEMORY_API_KEY not set - skipping Supermemory test")
+ return
+
+ # Create sync OpenAI client
+ openai_client = OpenAI()
+
+ # Wrap with Supermemory middleware
+ openai_with_memory = with_supermemory(
+ openai_client,
+ container_tag="test-user-sync-123",
+ options=OpenAIMiddlewareOptions(
+ mode="profile",
+ verbose=True
+ )
+ )
+
+ # Test context manager
+ with openai_with_memory as client:
+ print("โœ… Sync context manager works")
+
+ # Make a test request
+ response = client.chat.completions.create(
+ model="gpt-3.5-turbo",
+ messages=[
+ {"role": "user", "content": "This is a sync test message."}
+ ],
+ max_tokens=50
+ )
+
+ print(f"โœ… Sync API call successful: {response.choices[0].message.content[:50]}...")
+
+ except SupermemoryConfigurationError as e:
+ print(f"โš ๏ธ Configuration error: {e}")
+ except SupermemoryAPIError as e:
+ print(f"โš ๏ธ Supermemory API error: {e}")
+ except Exception as e:
+ print(f"โŒ Unexpected error: {e}")
+
+
+def test_error_handling():
+ """Test error handling without API keys."""
+ print("\n๐Ÿ”„ Testing Error Handling...")
+
+ try:
+ # Test with missing API key
+ openai_client = OpenAI(api_key="fake-key")
+
+ # This should raise SupermemoryConfigurationError
+ with_supermemory(openai_client, "test-user")
+
+ print("โŒ Should have raised SupermemoryConfigurationError")
+
+ except SupermemoryConfigurationError as e:
+ print(f"โœ… Correctly caught configuration error: {e}")
+ except Exception as e:
+ print(f"โŒ Wrong exception type: {type(e).__name__}: {e}")
+
+
+def test_background_tasks():
+ """Test background task management."""
+ print("\n๐Ÿ”„ Testing Background Task Management...")
+
+ try:
+ if not os.getenv("SUPERMEMORY_API_KEY"):
+ print("โŒ SUPERMEMORY_API_KEY not set - skipping background task test")
+ return
+
+ # Create a fake OpenAI client for testing
+ from unittest.mock import Mock, AsyncMock
+
+ openai_client = Mock()
+ openai_client.chat = Mock()
+ openai_client.chat.completions = Mock()
+ openai_client.chat.completions.create = AsyncMock(return_value=Mock())
+
+ # Wrap with memory storage enabled
+ wrapped_client = with_supermemory(
+ openai_client,
+ container_tag="test-background-tasks",
+ options=OpenAIMiddlewareOptions(
+ add_memory="always",
+ verbose=True
+ )
+ )
+
+ print(f"โœ… Background tasks tracking: {len(wrapped_client._background_tasks)} tasks")
+
+ except Exception as e:
+ print(f"โŒ Background task test error: {e}")
+
+
+async def main():
+ """Run all tests."""
+ print("๐Ÿงช Supermemory OpenAI Middleware Integration Tests")
+ print("=" * 60)
+
+ # Test async middleware
+ await test_async_middleware()
+
+ # Test sync middleware
+ test_sync_middleware()
+
+ # Test error handling
+ test_error_handling()
+
+ # Test background tasks
+ test_background_tasks()
+
+ print("\n" + "=" * 60)
+ print("๐ŸŽ‰ Integration tests completed!")
+ print("\n๐Ÿ’ก To run with real API calls, set these environment variables:")
+ print(" export OPENAI_API_KEY='your-openai-key'")
+ print(" export SUPERMEMORY_API_KEY='your-supermemory-key'")
+
+
+if __name__ == "__main__":
+ asyncio.run(main()) \ No newline at end of file