我正在使用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}.

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

推荐答案

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

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}

Python相关问答推荐

合并其中一个具有重叠范围的两个框架的最佳方法是什么?

将numpy数组与空数组相加

Pandas滚动分钟,来自其他列的相应值

自定义新元未更新参数

过滤绕轴旋转的螺旋桨

使文本输入中的文本与标签中的文本相同

如何在Python中使用时区夏令时获取任何给定本地时间的纪元值?

更改matplotlib彩色条的字体并勾选标签?

如何在具有重复数据的pandas中对groupby进行总和,同时保留其他列

比较两个数据帧并并排附加结果(获取性能警告)

numba jitClass,记录类型为字符串

使用miniconda创建环境的问题

如何使用html从excel中提取条件格式规则列表?

在Python Attrs包中,如何在field_Transformer函数中添加字段?

管道冻结和管道卸载

用NumPy优化a[i] = a[i-1]*b[i] + c[i]的迭代计算

PyQt5,如何使每个对象的 colored颜色 不同?'

如何创建一个缓冲区周围的一行与manim?

如何根据一列的值有条件地 Select 前N个组,然后按两列分组?

如何使regex代码只适用于空的目标单元格