使用OpenAI Classification端点遇Invalid URL错误,求解决方案
问题描述
- 成功上传用于分类训练的jsonl文件,代码及返回结果:
返回结果:res = openai.File.create(file=open("Classification.jsonl"), purpose = "classifications"){ "bytes": 1054, "created_at": 1672647540, "filename": "file", "id": "file-9GnLgjFKhSOXOYlSZtPwbJBf", "object": "file", "purpose": "classifications", "status": "uploaded", "status_details": null } - 调用分类接口时触发错误,代码:
openai.Classification.create( file="file-9GnLgjFKhSOXOYlSZtPwbJBf", query="movie is very good", search_model="ada", model="curie", max_examples=3 ) - 收到错误提示:
InvalidRequestError: Invalid URL (POST /v1/classifications)
- curl调用同样失败,严格遵循旧版官方文档操作仍出现无效URL问题。
解决方案
OpenAI已经移除了Classification旧API端点,/v1/classifications路径不再存在,这是报错的核心原因。目前可以通过以下两种方案实现文本分类需求:
方案1:用Chat Completions API结合few-shot示例
借助gpt-3.5-turbo或gpt-4模型,将分类示例直接写入prompt,让模型完成分类任务。示例代码:
import openai openai.api_key = "你的API密钥" response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "你是文本分类器,根据给定示例对输入文本分类。"}, # 替换为你jsonl文件中的真实分类示例 {"role": "user", "content": "movie is bad"}, {"role": "assistant", "content": "负面"}, {"role": "user", "content": "movie is fantastic"}, {"role": "assistant", "content": "正面"}, {"role": "user", "content": "movie is very good"} ] ) print(response.choices[0].message['content'])
方案2:使用Fine-tuning训练自定义分类模型
如果数据集规模较大,适合训练专属微调模型:
- 重新准备符合Fine-tuning格式的jsonl文件,单条数据示例(以情感分类为例):
{"prompt": "movie is bad ->", "completion": " 负面"} {"prompt": "movie is fantastic ->", "completion": " 正面"} - 上传文件时将
purpose改为fine-tune:res = openai.File.create(file=open("fine_tune_classification.jsonl"), purpose="fine-tune") - 创建微调任务:
openai.FineTune.create(training_file=res.id, model="curie") - 微调完成后,用生成的模型ID调用Completions API完成分类:
response = openai.Completion.create( model="curie:ft-your-org-2023-01-01-00-00-00", prompt="movie is very good ->" ) print(response.choices[0].text.strip())
内容的提问来源于stack exchange,提问作者Sugarplum_fairy
相关产品推荐
相关产品推荐

