Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Gradient Python SDK Examples

This directory contains examples demonstrating how to use the Gradient Python SDK with various frameworks and for different use cases.

## Available Examples

### Framework Integrations

These examples show how to integrate the Gradient Python SDK with popular web frameworks:

- **[Django Integration](django_integration.py)** - Simple Django views for chat completions, image generation, and agent listing
- **[Flask Integration](flask_integration.py)** - Flask routes demonstrating SDK usage with proper error handling
- **[FastAPI Integration](fastapi_integration.py)** - FastAPI endpoints with Pydantic models and async support

## Running Examples

Each example is a standalone Python script that can be run directly:

```bash
# Make sure you have the required environment variables set
export DIGITALOCEAN_ACCESS_TOKEN="your_token_here"
export GRADIENT_MODEL_ACCESS_KEY="your_model_key_here"
export GRADIENT_AGENT_ACCESS_KEY="your_agent_key_here"
export GRADIENT_AGENT_ENDPOINT="https://your-agent.agents.do-ai.run"

# Run an example
python examples/django_integration.py
```

## Framework-Specific Setup

### Django
The Django example shows how to create a Django view that uses the Gradient SDK for AI-powered responses.

### Flask
The Flask example demonstrates integrating Gradient SDK with Flask routes for web applications.

### FastAPI
The FastAPI example shows how to create async endpoints that leverage the Gradient SDK's async capabilities.

## Environment Variables

All examples require proper authentication setup:

- `DIGITALOCEAN_ACCESS_TOKEN` - For DigitalOcean API operations
- `GRADIENT_MODEL_ACCESS_KEY` - For serverless inference
- `GRADIENT_AGENT_ACCESS_KEY` - For agent-specific operations
- `GRADIENT_AGENT_ENDPOINT` - Your deployed agent endpoint

## Contributing

When adding new examples:

1. Follow the existing naming convention
2. Include comprehensive comments
3. Handle errors appropriately
4. Use environment variables for configuration
5. Add the example to this README
151 changes: 151 additions & 0 deletions examples/django_integration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
#!/usr/bin/env python3
"""
Django Integration Example for Gradient Python SDK

This example demonstrates how to integrate the Gradient Python SDK
with a Django application to create AI-powered endpoints.

Requirements:
- Django
- gradient (this SDK)

Setup:
1. Install dependencies: pip install django gradient
2. Set environment variables (see below)
3. Run: python manage.py runserver

Environment Variables Required:
- DIGITALOCEAN_ACCESS_TOKEN
- GRADIENT_MODEL_ACCESS_KEY
"""

import os
import json
from typing import Dict, Any

# Django imports
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

# Gradient SDK imports
from gradient import Gradient

# Initialize Gradient client
gradient_client = Gradient(
access_token=os.getenv("DIGITALOCEAN_ACCESS_TOKEN"),
model_access_key=os.getenv("GRADIENT_MODEL_ACCESS_KEY"),
)


@csrf_exempt
@require_http_methods(["POST"])
def chat_completion(request) -> JsonResponse:
"""
Django view for chat completions using Gradient SDK.

Expects JSON payload:
{
"messages": [{"role": "user", "content": "Hello!"}],
"model": "llama3.3-70b-instruct"
}
"""
try:
data: Dict[str, Any] = json.loads(request.body)
messages = data.get("messages", [])
model = data.get("model", "llama3.3-70b-instruct")

if not messages:
return JsonResponse({"error": "Messages are required"}, status=400)

response = gradient_client.chat.completions.create(
messages=messages,
model=model,
)

return JsonResponse({
"response": response.choices[0].message.content,
"model": response.model,
})

except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON payload"}, status=400)
except Exception as e:
return JsonResponse({"error": str(e)}, status=500)


@csrf_exempt
@require_http_methods(["POST"])
def image_generation(request) -> JsonResponse:
"""
Django view for image generation using Gradient SDK.

Expects JSON payload:
{
"prompt": "A beautiful sunset over mountains"
}
"""
try:
data: Dict[str, Any] = json.loads(request.body)
prompt = data.get("prompt")

if not prompt:
return JsonResponse({"error": "Prompt is required"}, status=400)

response = gradient_client.images.generate(prompt=prompt)

return JsonResponse({
"image_url": response.data[0].url,
})

except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON payload"}, status=400)
except Exception as e:
return JsonResponse({"error": str(e)}, status=500)


@require_http_methods(["GET"])
def list_agents(request) -> JsonResponse:
"""
Django view to list available agents.

Query parameters:
- limit: Maximum number of agents to return (default: 10)
"""
try:
limit = int(request.GET.get("limit", 10))

response = gradient_client.agents.list(limit=limit)

return JsonResponse({
"agents": [
{
"uuid": agent.uuid,
"name": agent.name,
}
for agent in response.agents
]
})

except Exception as e:
return JsonResponse({"error": str(e)}, status=500)


# URL patterns for Django
"""
# In your Django urls.py:

from django.urls import path
from . import views

urlpatterns = [
path('api/chat/', views.chat_completion, name='chat_completion'),
path('api/images/generate/', views.image_generation, name='image_generation'),
path('api/agents/', views.list_agents, name='list_agents'),
]

# Example usage:
# POST /api/chat/ with {"messages": [{"role": "user", "content": "Hello!"}]}
# POST /api/images/generate/ with {"prompt": "A sunset"}
# GET /api/agents/
"""
116 changes: 116 additions & 0 deletions examples/fastapi_integration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""
FastAPI Integration Example for Gradient Python SDK

This example demonstrates how to integrate the Gradient Python SDK
with a FastAPI application to create AI-powered endpoints.

Requirements:
- fastapi
- uvicorn
- gradient (this SDK)

Setup:
1. Install dependencies: pip install fastapi uvicorn gradient
2. Set environment variables (see below)
3. Run: python fastapi_integration.py

Environment Variables Required:
- DIGITALOCEAN_ACCESS_TOKEN
- GRADIENT_MODEL_ACCESS_KEY
"""

import os
from typing import List, Dict, Any
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

# Gradient SDK imports
from gradient import Gradient

app = FastAPI(title="Gradient AI API", version="1.0.0")

# Initialize Gradient client
gradient_client = Gradient(
access_token=os.getenv("DIGITALOCEAN_ACCESS_TOKEN"),
model_access_key=os.getenv("GRADIENT_MODEL_ACCESS_KEY"),
)


class ChatMessage(BaseModel):
role: str
content: str


class ChatRequest(BaseModel):
messages: List[ChatMessage]
model: str = "llama3.3-70b-instruct"


class ImageRequest(BaseModel):
prompt: str


@app.post("/api/chat")
async def chat_completion(request: ChatRequest):
"""
FastAPI endpoint for chat completions using Gradient SDK.
"""
try:
messages = [{"role": msg.role, "content": msg.content} for msg in request.messages]

response = gradient_client.chat.completions.create(
messages=messages,
model=request.model,
)

return {
"response": response.choices[0].message.content,
"model": response.model,
}

except Exception as e:
raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/images/generate")
async def image_generation(request: ImageRequest):
"""
FastAPI endpoint for image generation using Gradient SDK.
"""
try:
response = gradient_client.images.generate(prompt=request.prompt)

return {
"image_url": response.data[0].url,
}

except Exception as e:
raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/agents")
async def list_agents(limit: int = 10):
"""
FastAPI endpoint to list available agents.
"""
try:
response = gradient_client.agents.list(limit=limit)

return {
"agents": [
{
"uuid": agent.uuid,
"name": agent.name,
}
for agent in response.agents
]
}

except Exception as e:
raise HTTPException(status_code=500, detail=str(e))


if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Loading