Python Flask & OpenAI API: Step-by-Step Code Explanation for a Text Generation App
import openai: Imports the OpenAI module to access its functionalities.from flask import Flask, request, jsonify: Imports necessary components from the Flask framework: Flask for creating the web application, request for handling incoming requests, and jsonify for formatting output as JSON.app = Flask(__name__): Creates an instance of a Flask application.__name__refers to the current module, which is used to specify the root directory of the application.openai.api_key = '<your_openai_api_key>': Sets the API key for the OpenAI module, which is required to authenticate and access its services. Replace<your_openai_api_key>with your actual API key.@app.route('/'): Defines a route for the root URL ('/') of the application, making it the default page when the app is launched.def index():: Defines a function namedindex()that handles requests to the root URL.return app.send_static_file('index.html'): Returns the contents of theindex.htmlfile, likely a static HTML file, as the response for the root URL request.@app.route('/ask', methods=['POST']): Defines a route for the/askURL and specifies that it only handles HTTP POST requests.def ask():: Defines a function namedask()that handles requests to the/askroute.prompt = request.form['prompt']: Retrieves the value of the 'prompt' key from the request form data, which is sent by the client (e.g., a user input field in a web form).response = openai.Completion.create(: Creates a new completion request to the OpenAI API, using theCompletionclass.engine='davinci',: Specifies the 'davinci' engine to use for text generation. There are different engines available with varying capabilities.prompt=prompt,: Passes the receivedpromptstring to the OpenAI API as input for text generation.max_tokens=1024,: Sets a limit of 1024 tokens for the generated text. A token is a unit of text, usually around 4 characters.n=1,: Specifies to generate only one output for the given prompt.stop=None,: Does not define any stopping criteria for the text generation process. The API will generate text until the maximum number of tokens is reached or a natural stopping point is detected.temperature=0.5,: Sets the temperature parameter to 0.5. This parameter controls the creativity and randomness of the generated text. A higher temperature value leads to more creative and unexpected outputs.): Closes theopenai.Completion.create()function call.answer = response.choices[0].text.strip(): Retrieves the generated text from the API response. It accesses the first choice (index 0) from theresponse.choiceslist, extracts its text, and removes any leading or trailing whitespace.return jsonify({'answer': answer}): Returns the generatedansweras a JSON object to the client. This allows the client to easily process the response data.if __name__ == '__main__':: Checks if the script is being run as the main program. This ensures that the following code is only executed when the script is run directly (not imported as a module).app.run(debug=True): Starts the Flask application in debug mode. Debug mode enables additional features like automatic code reloading and more informative error messages, which are helpful during development.
原文地址: https://www.cveoy.top/t/topic/lB1a 著作权归作者所有。请勿转载和采集!