gemini-2.5-flash| input-price: 0.3 output-price: 2.5 max-context-length: 128_000 (cost: $0.009) Β· Anfrage: 2025-09-14T04:47:43.495069
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 both the backend and frontend components necessary to achieve a word-by-word display of AI-generated content, rather than waiting for the complete response. The tutorial details the creation of a Python generator function to interface with the OpenAI API's streaming capability and leverages Django's StreamingHttpResponse to maintain an open connection. On the client side, JavaScript's fetch API, ReadableStream reader, and TextDecoder are used to process and incrementally display the incoming text. Furthermore, the video shows how to integrate marked.js to parse and render Markdown formatting in the streamed responses, enhancing the user experience. The presenter highlights that while this method is suitable for small applications, larger deployments might benefit from ASGI for non-blocking I/O.
Streaming OpenAI Responses in a Django App
views.py with an imported OpenAI client and API key, urls.py with an index path, and index.html containing a basic form for user input.generate_response):
generate_response is defined to take a question.client.chat.completions.create with model="gpt-4", a user message containing the question, and crucially, stream=True.chunks from the stream and yields chunk.choices[0].delta.content if new content is available, making it a Python generator.answer View (StreamingHttpResponse):
answer is created, importing StreamingHttpResponse from django.http.response.@csrf_exempt to allow POST requests without CSRF tokens.StreamingHttpResponse by passing the generate_response generator, a status=200, and content_type="text/plain".index.html, an async click event listener is added to the submit button.e.preventDefault() is used to prevent default form submission.fetch POST request is sent to the /answer/ endpoint with the user's input as a JSON message.answer view is updated to parse the incoming JSON request body using json.loads(request.body) to extract the user's message.reader from the response.body.while (true) loop to continuously read chunks.const {done, value} = await reader.read() fetches the next part of the stream.output += new TextDecoder().decode(value) decodes the chunk and appends it to an output string.body.innerHTML = output updates the display with the accumulated text.if (done) is true, indicating the stream has ended.marked.js library is introduced by adding its script tag.body.innerHTML update is changed to body.innerHTML = marked.parse(output) to interpret and render Markdown syntax in the streamed response.marked.js.