学习 FLask:卡在 OpenAI api

问题描述 投票:0回答:1
from flask import Flask, request, jsonify, send_from_directory
import openai
from openai import OpenAI
import os

app = Flask(__name__)


openai.api_key = 'sk-' # I added my key here.

@app.route('/')
def index():
    return send_from_directory('.', 'index.html')

@app.route('/analyze', methods=['POST'])
def analyze_cv():
    if 'cv' not in request.files or 'job_description' not in request.files:
        return jsonify({'error': 'CV and Job Description files are required'}), 400

    cv = request.files['cv'].read()
    job_description = request.files['job_description'].read()

    try:
        cv = cv.decode('utf-8')
    except UnicodeDecodeError:
        cv = cv.decode('latin-1')

    try:
        job_description = job_description.decode('utf-8')
    except UnicodeDecodeError:
        job_description = job_description.decode('latin-1')


    prompt = f"Given the following job description:\n{job_description}\n\nAssess the suitability of the candidate based on the CV:\n{cv}\n\nScore the candidate from 1 to 10 and provide an explanation."


    try:
        client = OpenAI(api_key = os.environ.get("OPENAI_API_KEY"),)
        openai.Completion.create
        response = client.Completions.create(
            engine="text-davinci-003",
            prompt=prompt,
            temperature=0.7,
            max_tokens=1024
        )

        score = int(response.choices[0].text.split()[0])
        explanation = response.choices[0].text.split('\n')[1]

        return jsonify({'score': score, 'explanation': explanation}), 200
    
    except Exception as e:
        print(e)  
        return jsonify({'error': 'An error occurred while analyzing the CV'}), 500

if __name__ == '__main__':
    app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CV Analyzer</title>
</head>
<body>
    <h1>CV Analyzer</h1>
    <input type="file" id="cv" accept=".pdf,.doc,.docx">
    <input type="file" id="job_description" accept=".pdf,.txt,.doc,.docx">
    <button onclick="analyze()">Analyze</button>
    <div id="result"></div>

    <script>
        function analyze() {
            var cvFile = document.getElementById('cv').files[0];
            var jobDescriptionFile = document.getElementById('job_description').files[0];

            if (!cvFile || !jobDescriptionFile) {
                alert('Please upload both CV and Job Description files.');
                return;
            }

            var formData = new FormData();
            formData.append('cv', cvFile);
            formData.append('job_description', jobDescriptionFile);

            fetch('/analyze', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('result').innerHTML = `
                    <h2>Score: ${data.score}</h2>
                    <p>${data.explanation}</p>
                `;
            })
            .catch(error => console.error('Error:', error));
        }
    </script>
</body>
</html>

所以我对上面的两个文件进行了编码。但我无法获得“分数”。 在控制台上,此错误一次又一次弹出:

The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable

127.0.0.1 - - \[04/May/2024 20:55:38\] "POST /analyze HTTP/1.1" 500 -

有人可以帮我吗?

我已经尝试过一些人给出的内容。但它就是行不通。

javascript python flask openai-api
1个回答
0
投票
from flask import Flask, request, jsonify, send_from_directory
import openai
from openai import OpenAI
import os

app = Flask(__name__)

@app.route('/')
def index():
    return send_from_directory('.', 'index.html')

@app.route('/analyze', methods=['POST'])
def analyze_cv():
    if 'cv' not in request.files or 'job_description' not in request.files:
        return jsonify({'error': 'CV and Job Description files are required'}), 400

    cv = request.files['cv'].read()
    job_description = request.files['job_description'].read()

    try:
        cv = cv.decode('utf-8')
    except UnicodeDecodeError:
        cv = cv.decode('latin-1')

    try:
        job_description = job_description.decode('utf-8')
    except UnicodeDecodeError:
        job_description = job_description.decode('latin-1')

    prompt = f"Given the following job description:\n{job_description}\n\nAssess the suitability of the candidate based on the CV:\n{cv}\n\nScore the candidate from 1 to 10 and provide an explanation."

    try:
        client = OpenAI(api_key='sk-')
        response = client.completions.create(
            model="gpt-3.5-turbo-instruct",
            prompt=prompt,
            temperature=0.7,
            max_tokens=1024
        )

        score = int(response.choices[0].text.split()[0])
        explanation = response.choices[0].text.split('\n')[1]

        return jsonify({'score': score, 'explanation': explanation}), 200
    
    except Exception as e:
        print(e)  
        return jsonify({'error': 'An error occurred while analyzing the CV'}), 500

if __name__ == '__main__':
    app.run(debug=True)

此代码现在可以运行了。但又弹出另一个错误 127.0.0.1 - - [2024 年 5 月 4 日 22:29:55]“GET / HTTP/1.1”304 - 错误代码:429 - {'error': {'message': '您超出了当前配额,请检查您的计划和账单详细信息。有关此错误的更多信息,请阅读文档:https://platform.openai.com/docs/guides/error-codes/api-errors.','type':'insufficient_quota','param':None , '代码': 'insufficient_quota'}} 127.0.0.1 - - [2024 年 5 月 4 日 22:30:17]“POST /分析 HTTP/1.1”500 -

© www.soinside.com 2019 - 2024. All rights reserved.