> For the complete documentation index, see [llms.txt](https://docs.scrt.network/secret-network-documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.scrt.network/secret-network-documentation/secret-ai/sdk/setting-up-your-environment/performance-and-best-practices.md).

# Performance & Best Practices

### Performance & Best Practices

#### Optimization Tips

1. **Connection Pooling**: Reuse client instances to benefit from connection pooling
2. **Concurrent Requests**: Use async clients for high-throughput applications
3. **Streaming**: Use streaming for long-form content to improve perceived performance
4. **Error Handling**: Implement proper retry logic for production environments
5. **Resource Management**: Use context managers for proper cleanup

#### Production Deployment

```python
import asyncio
from secret_ai_sdk._enhanced_client import EnhancedSecretAIAsyncClient

class ProductionSecretAIService:
    def __init__(self):
        self.client = EnhancedSecretAIAsyncClient(
            host="https://your-ai-endpoint.com",
            api_key="your_api_key",
            timeout=30.0,
            max_retries=3,
            validate_responses=True
        )
    
    async def generate_text(self, messages, **kwargs):
        """Production-ready text generation with error handling"""
        try:
            response = await self.client.chat(
                model=kwargs.get('model', 'default-model'),
                messages=messages,
                stream=kwargs.get('stream', False)
            )
            return response
        except Exception as e:
            # Log error and implement fallback logic
            print(f"Generation failed: {e}")
            raise
    
    async def __aenter__(self):
        return self
    
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        # Cleanup resources
        if hasattr(self.client, 'close'):
            await self.client.close()

# Usage
async def main():
    async with ProductionSecretAIService() as service:
        response = await service.generate_text([
            {"role": "user", "content": "Generate a summary of quantum computing"}
        ])
        print(response)

# Run
asyncio.run(main())
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.scrt.network/secret-network-documentation/secret-ai/sdk/setting-up-your-environment/performance-and-best-practices.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
