gemini-2.5-flash| input-price: 0.3 output-price: 2.5 max-context-length: 128_000 (cost: $0.007) Β· Anfrage: 2025-09-14T04:44:12.470385
Generated by rs-summarizer Version unbekannt
Abstract:
This video demonstrates how to implement real-time streaming of OpenAI responses within a Django web application. It covers the complete process, from configuring the backend to make streaming API calls to OpenAI, creating a Django StreamingHttpResponse that acts as a generator, and finally, developing the frontend JavaScript to continuously read and display chunks of the streamed response as they arrive. The tutorial highlights the necessary Python and JavaScript code, including handling POST requests, JSON parsing, and even integrating a markdown parser for enhanced display of AI-generated content.
Streaming OpenAI Responses in Django: A Step-by-Step Guide
views.py with an OpenAI client, urls.py for routing, and an index.html template with a text input and send button, but no functionality.generate_response): A Python function is created to interact with the OpenAI API. It calls client.chat.completions.create with stream=True, ensuring OpenAI sends back responses in chunks. This function acts as a generator, yielding each piece of new content (chunk.choices[0].delta.content) as it arrives.answer) is set up to return a StreamingHttpResponse (imported from django.http). This special response type is designed to remain open and continuously send data generated by the generate_response function, rather than waiting for the entire response to be compiled./answer URL shows the raw streamed text from OpenAI appearing progressively in the browser, although with an initial delay or partial word display in the creator's browser.@csrf_exempt and json.loads(request.body) to accept POST requests containing the user's question from the frontend.index.html template's JavaScript is modified to:
async click event listener to the submit button.e.preventDefault()).fetch POST request to the /answer endpoint with the user's input as JSON.reader from the response.body. It then enters a while (true) loop, continuously await reader.read() for new data. Each value (chunk) is decoded using TextDecoder().decode() and appended to the body.innerHTML element, creating the real-time streaming effect. The loop exits when done is true.marked JavaScript library is integrated. By simply passing the accumulated output to marked.parse(output), markdown syntax is converted to appropriate HTML tags before being displayed.response.text quick accessor requires the response to contain a valid Part, but none were returned. The candidate's finish_reason is 1.