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+ """
0 commit comments