Here is a 2024 version:
@csrf_exempt
def generate_names_view(request):
print(request.method)
if request.method == 'POST':
# Parse the request body and extract the prompt
data = json.loads(request.body) # Use json.loads to parse request.body
prompt = data.get('prompt')
# Set up the OpenAI API client
openai = OpenAI(api_key=settings.OPENAI_API_KEY)
# Define a generator function to stream the response
def generate_response():
stream = openai.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
stream=True,
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
content = chunk.choices[0].delta.content
print(content)
yield content
# Return a streaming response to the client
return StreamingHttpResponse(generate_response(), content_type='text/event-stream')
# Return a JSON error if the request method is not POST
return JsonResponse({'error': 'Method not allowed.'}, status=405)
Here is the curl command to test it:
curl -X POST http://localhost:8000/test/ -H "Content-Type: application/json" -d '{"prompt":"Write the name of 10 dogs"}'
Here is how to use it from the browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Generate Names</title>
<button onclick="fetchData()">Fetch Data</button>
<div id="output"></div>
</head>
<body>
<script>
async function fetchData() {
const url = '/test/' // Replace with your URL
const data = {
prompt: 'Write a short story about a robot who is trying to learn how to love.'
}
const response = await fetch(url, {
method: 'POST', // Set the method to POST
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data) // Convert the JavaScript object to a JSON string
})
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
document.getElementById('output').innerHTML += decoder.decode(value).replace(/\n/g, '<br>');
}
}
{% comment %} fetchData().catch(console.error); {% endcomment %}
</script>
</body>
</html>
return StreamingHttpResponse(generate_response(), content_type='text/event-stream'))
– Cleanse