Socket-Based Connection Template
The socket-based connection template provides a real-time way to connect your agent to Snowglobe for testing. This template is designed for applications that maintain persistent connections and require conversational state, such as real-time chat applications or streaming LLM services.When to Use
Use the socket-based template when:- Your application uses WebSocket or persistent connections
- You need to maintain conversation state across multiple messages
- You’re working with real-time streaming APIs (like OpenAI’s Realtime API)
- Your agent requires session persistence between requests
- You want to test conversational flows that depend on connection state
Template Code
When you runsnowglobe-connect init
and select the socket template, Snowglobe generates this code:
Code Walkthrough
1. Imports and Setup
- websockets: Python library for WebSocket connections
- json: For encoding/decoding WebSocket messages
- socket_cache: Dictionary to store persistent connections per conversation
- LOGGER: For debugging WebSocket interactions
2. Conversation-Based Socket Management
- Maintaining conversation context across multiple messages
- Session state preservation
- More efficient resource usage for ongoing conversations
3. WebSocket Connection Setup
- Your own WebSocket server
- Other real-time LLM services
- Custom streaming endpoints
4. Message Sending
5. Response Handling
Customization Examples
Generic WebSocket Client
Socket Cleanup and Error Handling
Server-Sent Events (SSE) Alternative
Socket Pool Management
Benefits of Socket-Based Connections
Advantages
- State Persistence: Maintain conversation context across messages
- Lower Latency: Persistent connections eliminate handshake overhead
- Real-time Communication: Support for streaming and bi-directional communication
- Resource Efficiency: Reuse connections for multiple messages
- Enhanced Features: Support for typing indicators, presence, etc.
Use Cases
- Conversational AI: Chatbots that need to remember context
- Real-time Collaboration: Multi-user applications
- Streaming Responses: Applications that stream LLM responses
- Gaming or Interactive Apps: Applications requiring low-latency communication
Testing Your Socket Implementation
-
Test the connection:
-
Monitor socket connections: Use logging to track connection lifecycle:
-
Start the client:
Performance Considerations
Memory Management
- Implement socket cleanup to prevent memory leaks
- Use weak references for automatic garbage collection
- Set reasonable limits on concurrent connections
Connection Limits
- Most services limit WebSocket connections per client
- Implement connection pooling for high-volume scenarios
- Monitor and log connection statistics
Error Recovery
- Handle network interruptions gracefully
- Implement exponential backoff for reconnection
- Provide fallback mechanisms for connection failures