Asynchronous Connection Template
The asynchronous connection template provides a high-performance way to connect your agent to Snowglobe for testing. This template is ideal when your application needs to handle multiple concurrent requests efficiently or uses async APIs.When to Use
Use the asynchronous template when:- Your application needs to handle high volumes of concurrent requests
- You’re using async LLM clients (like AsyncOpenAI)
- Your agent performs multiple I/O operations that can be parallelized
- You want optimal performance and resource utilization
- Your existing codebase is already async-based
Template Code
When you runsnowglobe-connect init
and select the asynchronous template, Snowglobe generates this code:
Code Walkthrough
1. Imports and Setup
- AsyncOpenAI: The asynchronous version of OpenAI’s client for non-blocking API calls
- Same Snowglobe imports: Uses the same request/response objects as the sync template
- Environment variable: Safely loads your OpenAI API key from environment
2. Main Async Function
acompletion
function is the async entry point that Snowglobe calls. Key differences from sync:
- Function name is
acompletion
(notcompletion
) - Decorated with
async
keyword - Can use
await
for non-blocking operations - Snowglobe automatically handles the async execution
3. Message Processing (Same as Sync)
CompletionRequest
object provides the same methods and data.
4. Async API Call
await
for the API call. This allows other requests to be processed concurrently while waiting for the LLM response.
5. Response Formatting (Same as Sync)
Performance Benefits
The asynchronous template provides several advantages:- Concurrent Processing: Handle multiple requests simultaneously
- Better Resource Utilization: CPU isn’t blocked during I/O operations
- Scalability: Handle higher request volumes with the same hardware
- Reduced Latency: Other requests don’t wait when one request is slow
Advanced Customization Examples
Multiple Concurrent API Calls
Async Database Operations
Async External API Integration
Error Handling with Retries
Testing Your Async Implementation
-
Test the connection:
-
Start the client:
- Monitor performance: The async template will show better performance under concurrent load
Performance Comparison
Feature | Synchronous | Asynchronous |
---|---|---|
Concurrent Requests | Limited | High |
Memory Usage | Higher per request | Lower overall |
CPU Utilization | Blocked during I/O | Efficient |
Implementation Complexity | Simple | Moderate |
Best For | Low-medium traffic | High traffic, complex workflows |
Common Pitfalls
1. Blocking Operations
2. Forgetting await
3. Mixing Sync and Async Incorrectly
Next Steps
- Learn about socket-based connections for real-time applications
- Compare with synchronous connections
- View more integration examples