我正在使用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)
程序在返回的SON文件中不断返回:
{"error": "Failed to get response from API", "status_code": 404}.
我是一个使用这个的新手,所以我迫切需要任何帮助!