Python Examples
Complete Python examples for all Tenzro services with both synchronous and asynchronous support. Perfect for data science, machine learning, and backend applications.
Setup & Installation
Install and configure the Tenzro Python SDK
# Install the Tenzro Python SDK
pip install tenzro
# Or with async support
pip install tenzro[async]
# Basic setup
import tenzro
from tenzro import Tenzro
# Initialize client
client = Tenzro(api_key="sk_your_key_here")
# Async client
import asyncio
from tenzro import AsyncTenzro
async_client = AsyncTenzro(api_key="sk_your_key_here")
# Environment variable setup
import os
os.environ["TENZRO_API_KEY"] = "sk_your_key_here"
# Client will automatically use environment variable
client = Tenzro()
# Example usage
def main():
try:
response = client.cortex.generate(
prompt="Hello, Tenzro!",
model="gpt-4o"
)
print(f"Generated text: {response.content}")
except Exception as error:
print(f"Error: {error}")
if __name__ == "__main__":
main()
# Async example
async def async_main():
try:
response = await async_client.cortex.generate(
prompt="Hello, async Tenzro!",
model="gpt-4o"
)
print(f"Generated text: {response.content}")
finally:
await async_client.close()
# Run async example
# asyncio.run(async_main())
Data Science Integration
Data Science Integration
AI-powered data analysis with pandas, numpy, and scikit-learn
import tenzro
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
client = Tenzro(api_key="sk_your_key_here")
# AI-powered data analysis
def analyze_dataset_with_ai(df):
"""Use AI to analyze a pandas DataFrame"""
# Get basic statistics
stats = df.describe().to_string()
missing_data = df.isnull().sum().to_string()
# Generate AI insights
prompt = f"""
Analyze this dataset and provide insights:
Dataset shape: {df.shape}
Statistics:
{stats}
Missing data:
{missing_data}
Columns: {list(df.columns)}
Please provide:
1. Key patterns and trends
2. Data quality assessment
3. Recommendations for further analysis
4. Potential modeling approaches
"""
response = client.cortex.generate(
prompt=prompt,
model="claude-3.5-sonnet",
max_tokens=2000
)
return response.content
# Generate synthetic data with AI
def generate_synthetic_data(description, num_samples=1000):
"""Generate synthetic data based on description"""
prompt = f"""
Generate Python code to create a synthetic dataset with {num_samples} samples.
Description: {description}
Return only the Python code that creates a pandas DataFrame named 'df'.
Use realistic data patterns and include some noise.
"""
response = client.cortex.generate(
prompt=prompt,
model="gpt-4o",
max_tokens=1000
)
# Execute the generated code
exec(response.content)
return locals().get('df')
# AI-assisted feature engineering
def suggest_features(df, target_column):
"""Get AI suggestions for feature engineering"""
sample_data = df.head(10).to_string()
prompt = f"""
Given this dataset sample with target column '{target_column}':
{sample_data}
Suggest 5 feature engineering techniques that could improve model performance.
Focus on:
1. Creating interaction features
2. Transformations
3. Derived metrics
4. Handling categorical variables
5. Time-based features (if applicable)
Provide specific Python code examples.
"""
response = client.cortex.generate(
prompt=prompt,
model="claude-3.5-sonnet",
max_tokens=1500
)
return response.content
# Example workflow
if __name__ == "__main__":
# Load or generate data
try:
df = pd.read_csv("your_data.csv")
except FileNotFoundError:
# Generate synthetic data if file doesn't exist
df = generate_synthetic_data(
"E-commerce customer data with purchase history, demographics, and churn labels"
)
# AI-powered analysis
insights = analyze_dataset_with_ai(df)
print("AI Dataset Analysis:")
print(insights)
# Feature engineering suggestions
if 'target' in df.columns:
feature_suggestions = suggest_features(df, 'target')
print("\nFeature Engineering Suggestions:")
print(feature_suggestions)
Python SDK Features
Async Support
Full asyncio support for high-performance applications
async/await
Data Science Ready
Works seamlessly with pandas, numpy, and jupyter notebooks
pandas integration
ML Integration
Built for PyTorch, TensorFlow, and scikit-learn workflows
ML frameworks
Type Hints
Full type annotations for better IDE support and debugging
mypy compatible
Next Steps
Installation
pip install tenzro
pip install tenzro[async]
pip install tenzro[data-science]
Need help? Check out our Quick Start guide or contact support