Skip to content

Commit 7bd78d9

Browse files
committed
feat: add simple framework integration examples
1 parent 76392b5 commit 7bd78d9

File tree

5 files changed

+744
-0
lines changed

5 files changed

+744
-0
lines changed

examples/README.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Gradient Python SDK Examples
2+
3+
This directory contains examples demonstrating how to use the Gradient Python SDK with various frameworks and for different use cases.
4+
5+
## Available Examples
6+
7+
### Framework Integrations
8+
9+
These examples show how to integrate the Gradient Python SDK with popular web frameworks:
10+
11+
- **[Django Integration](django_integration.py)** - Simple Django views for chat completions, image generation, and agent listing
12+
- **[Flask Integration](flask_integration.py)** - Flask routes demonstrating SDK usage with proper error handling
13+
- **[FastAPI Integration](fastapi_integration.py)** - FastAPI endpoints with Pydantic models and async support
14+
15+
## Running Examples
16+
17+
Each example is a standalone Python script that can be run directly:
18+
19+
```bash
20+
# Make sure you have the required environment variables set
21+
export DIGITALOCEAN_ACCESS_TOKEN="your_token_here"
22+
export GRADIENT_MODEL_ACCESS_KEY="your_model_key_here"
23+
export GRADIENT_AGENT_ACCESS_KEY="your_agent_key_here"
24+
export GRADIENT_AGENT_ENDPOINT="https://your-agent.agents.do-ai.run"
25+
26+
# Run an example
27+
python examples/django_integration.py
28+
```
29+
30+
## Framework-Specific Setup
31+
32+
### Django
33+
The Django example shows how to create a Django view that uses the Gradient SDK for AI-powered responses.
34+
35+
### Flask
36+
The Flask example demonstrates integrating Gradient SDK with Flask routes for web applications.
37+
38+
### FastAPI
39+
The FastAPI example shows how to create async endpoints that leverage the Gradient SDK's async capabilities.
40+
41+
## Environment Variables
42+
43+
All examples require proper authentication setup:
44+
45+
- `DIGITALOCEAN_ACCESS_TOKEN` - For DigitalOcean API operations
46+
- `GRADIENT_MODEL_ACCESS_KEY` - For serverless inference
47+
- `GRADIENT_AGENT_ACCESS_KEY` - For agent-specific operations
48+
- `GRADIENT_AGENT_ENDPOINT` - Your deployed agent endpoint
49+
50+
## Contributing
51+
52+
When adding new examples:
53+
54+
1. Follow the existing naming convention
55+
2. Include comprehensive comments
56+
3. Handle errors appropriately
57+
4. Use environment variables for configuration
58+
5. Add the example to this README

examples/django_integration.py

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Django Integration Example for Gradient Python SDK
4+
5+
This example demonstrates how to integrate the Gradient Python SDK
6+
with a Django application to create AI-powered endpoints.
7+
8+
Requirements:
9+
- Django
10+
- gradient (this SDK)
11+
12+
Setup:
13+
1. Install dependencies: pip install django gradient
14+
2. Set environment variables (see below)
15+
3. Run: python manage.py runserver
16+
17+
Environment Variables Required:
18+
- DIGITALOCEAN_ACCESS_TOKEN
19+
- GRADIENT_MODEL_ACCESS_KEY
20+
"""
21+
22+
import os
23+
import json
24+
from typing import Dict, Any
25+
26+
# Django imports
27+
from django.http import JsonResponse
28+
from django.views.decorators.csrf import csrf_exempt
29+
from django.views.decorators.http import require_http_methods
30+
31+
# Gradient SDK imports
32+
from gradient import Gradient
33+
34+
# Initialize Gradient client
35+
gradient_client = Gradient(
36+
access_token=os.getenv("DIGITALOCEAN_ACCESS_TOKEN"),
37+
model_access_key=os.getenv("GRADIENT_MODEL_ACCESS_KEY"),
38+
)
39+
40+
41+
@csrf_exempt
42+
@require_http_methods(["POST"])
43+
def chat_completion(request) -> JsonResponse:
44+
"""
45+
Django view for chat completions using Gradient SDK.
46+
47+
Expects JSON payload:
48+
{
49+
"messages": [{"role": "user", "content": "Hello!"}],
50+
"model": "llama3.3-70b-instruct"
51+
}
52+
"""
53+
try:
54+
data: Dict[str, Any] = json.loads(request.body)
55+
messages = data.get("messages", [])
56+
model = data.get("model", "llama3.3-70b-instruct")
57+
58+
if not messages:
59+
return JsonResponse({"error": "Messages are required"}, status=400)
60+
61+
response = gradient_client.chat.completions.create(
62+
messages=messages,
63+
model=model,
64+
)
65+
66+
return JsonResponse({
67+
"response": response.choices[0].message.content,
68+
"model": response.model,
69+
})
70+
71+
except json.JSONDecodeError:
72+
return JsonResponse({"error": "Invalid JSON payload"}, status=400)
73+
except Exception as e:
74+
return JsonResponse({"error": str(e)}, status=500)
75+
76+
77+
@csrf_exempt
78+
@require_http_methods(["POST"])
79+
def image_generation(request) -> JsonResponse:
80+
"""
81+
Django view for image generation using Gradient SDK.
82+
83+
Expects JSON payload:
84+
{
85+
"prompt": "A beautiful sunset over mountains"
86+
}
87+
"""
88+
try:
89+
data: Dict[str, Any] = json.loads(request.body)
90+
prompt = data.get("prompt")
91+
92+
if not prompt:
93+
return JsonResponse({"error": "Prompt is required"}, status=400)
94+
95+
response = gradient_client.images.generate(prompt=prompt)
96+
97+
return JsonResponse({
98+
"image_url": response.data[0].url,
99+
})
100+
101+
except json.JSONDecodeError:
102+
return JsonResponse({"error": "Invalid JSON payload"}, status=400)
103+
except Exception as e:
104+
return JsonResponse({"error": str(e)}, status=500)
105+
106+
107+
@require_http_methods(["GET"])
108+
def list_agents(request) -> JsonResponse:
109+
"""
110+
Django view to list available agents.
111+
112+
Query parameters:
113+
- limit: Maximum number of agents to return (default: 10)
114+
"""
115+
try:
116+
limit = int(request.GET.get("limit", 10))
117+
118+
response = gradient_client.agents.list(limit=limit)
119+
120+
return JsonResponse({
121+
"agents": [
122+
{
123+
"uuid": agent.uuid,
124+
"name": agent.name,
125+
}
126+
for agent in response.agents
127+
]
128+
})
129+
130+
except Exception as e:
131+
return JsonResponse({"error": str(e)}, status=500)
132+
133+
134+
# URL patterns for Django
135+
"""
136+
# In your Django urls.py:
137+
138+
from django.urls import path
139+
from . import views
140+
141+
urlpatterns = [
142+
path('api/chat/', views.chat_completion, name='chat_completion'),
143+
path('api/images/generate/', views.image_generation, name='image_generation'),
144+
path('api/agents/', views.list_agents, name='list_agents'),
145+
]
146+
147+
# Example usage:
148+
# POST /api/chat/ with {"messages": [{"role": "user", "content": "Hello!"}]}
149+
# POST /api/images/generate/ with {"prompt": "A sunset"}
150+
# GET /api/agents/
151+
"""

examples/fastapi_integration.py

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
#!/usr/bin/env python3
2+
"""
3+
FastAPI Integration Example for Gradient Python SDK
4+
5+
This example demonstrates how to integrate the Gradient Python SDK
6+
with a FastAPI application to create AI-powered endpoints.
7+
8+
Requirements:
9+
- fastapi
10+
- uvicorn
11+
- gradient (this SDK)
12+
13+
Setup:
14+
1. Install dependencies: pip install fastapi uvicorn gradient
15+
2. Set environment variables (see below)
16+
3. Run: python fastapi_integration.py
17+
18+
Environment Variables Required:
19+
- DIGITALOCEAN_ACCESS_TOKEN
20+
- GRADIENT_MODEL_ACCESS_KEY
21+
"""
22+
23+
import os
24+
from typing import List, Dict, Any
25+
from fastapi import FastAPI, HTTPException
26+
from pydantic import BaseModel
27+
28+
# Gradient SDK imports
29+
from gradient import Gradient
30+
31+
app = FastAPI(title="Gradient AI API", version="1.0.0")
32+
33+
# Initialize Gradient client
34+
gradient_client = Gradient(
35+
access_token=os.getenv("DIGITALOCEAN_ACCESS_TOKEN"),
36+
model_access_key=os.getenv("GRADIENT_MODEL_ACCESS_KEY"),
37+
)
38+
39+
40+
class ChatMessage(BaseModel):
41+
role: str
42+
content: str
43+
44+
45+
class ChatRequest(BaseModel):
46+
messages: List[ChatMessage]
47+
model: str = "llama3.3-70b-instruct"
48+
49+
50+
class ImageRequest(BaseModel):
51+
prompt: str
52+
53+
54+
@app.post("/api/chat")
55+
async def chat_completion(request: ChatRequest):
56+
"""
57+
FastAPI endpoint for chat completions using Gradient SDK.
58+
"""
59+
try:
60+
messages = [{"role": msg.role, "content": msg.content} for msg in request.messages]
61+
62+
response = gradient_client.chat.completions.create(
63+
messages=messages,
64+
model=request.model,
65+
)
66+
67+
return {
68+
"response": response.choices[0].message.content,
69+
"model": response.model,
70+
}
71+
72+
except Exception as e:
73+
raise HTTPException(status_code=500, detail=str(e))
74+
75+
76+
@app.post("/api/images/generate")
77+
async def image_generation(request: ImageRequest):
78+
"""
79+
FastAPI endpoint for image generation using Gradient SDK.
80+
"""
81+
try:
82+
response = gradient_client.images.generate(prompt=request.prompt)
83+
84+
return {
85+
"image_url": response.data[0].url,
86+
}
87+
88+
except Exception as e:
89+
raise HTTPException(status_code=500, detail=str(e))
90+
91+
92+
@app.get("/api/agents")
93+
async def list_agents(limit: int = 10):
94+
"""
95+
FastAPI endpoint to list available agents.
96+
"""
97+
try:
98+
response = gradient_client.agents.list(limit=limit)
99+
100+
return {
101+
"agents": [
102+
{
103+
"uuid": agent.uuid,
104+
"name": agent.name,
105+
}
106+
for agent in response.agents
107+
]
108+
}
109+
110+
except Exception as e:
111+
raise HTTPException(status_code=500, detail=str(e))
112+
113+
114+
if __name__ == "__main__":
115+
import uvicorn
116+
uvicorn.run(app, host="0.0.0.0", port=8000)

0 commit comments

Comments
 (0)