Chatgpt API 不断返回错误:404 无法从 API 获取响应

问题描述 投票:0回答:1

我正在使用 ChatGPT 的 API 进行文本分类任务,我上传数据集并要求 ChatGPT 确定我的文本是否与房地产有关。我的代码是:

基本设置

import json
import requests
from os import getenv

# Load JSON data from file
with open('/policy_cleaned.json', 'r', encoding='utf-8') as file:
    data = json.load(file)

# API settings
api_url = "https://api.openai.com/v1/completions"
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer sk-proj-...1u"
}

API函数

def classify_text(text):
    prompt = f"Classify the following text whether it is related to the Chinese real estate industry, and if it is specifically about Chinese real estate policy: {text}"
    payload = {
        "model": "gpt-4-turbo",  
        "prompt": prompt,
        "max_tokens": 64,
        "temperature": 0.1
    }
    response = requests.post(api_url, headers=headers, json=payload)
    if response.status_code == 200:
        result = response.json()
        return result
    else:
        return {"error": "Failed to get response from API", "status_code": response.status_code}

在我的数据集上运行并输出响应

results = []
for item in data:
    classification = classify_text(item['CleanedContent'])
    results.append({
        "PolicyID": item['PolicyID'],
        "Title": item['Title'],
        "Classification": classification
    })

with open('classified_data.json', 'w', encoding='utf-8') as file:
    json.dump(results, file, ensure_ascii=False)

程序在返回的JSON文件中不断返回:

{“error”:“无法从API获取响应”,“status_code”:404}

我是使用这个的新手,所以我迫切需要任何帮助!

python openai-api chatgpt-api
1个回答
0
投票

这是您的classify_text方法的修改版本,应该可以工作。这些更改基于 OpenAI 的API 参考中使用的示例。

import json
import requests

def classify_text(text):
    system = "Classify the following text whether it is related to the Chinese real estate industry, and if it is specifically about Chinese real estate policy"
    payload = json.dumps({
        "model": "gpt-4-turbo",  
        "messages": [
            {"role": "system", "content": system},
            {"role": "user", "content": text}
        ],
        "max_tokens": 64,
        "temperature": 0.1
    })
    response = requests.post(api_url, headers=headers, data=payload)

    # Consider printing the response output to debug any issues
    print(response.json())
    
    if response.status_code == 200:
        result = response.json()
        return result
    else:
        return {"error": "Failed to get response from API", "status_code": response.status_code}

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