OpenAI两类端点差异及指定GPT模型文本分类方法问询
一、/v1/completions 与 /v1/chat/completions 核心差异
- 模型适配:/v1/completions针对GPT-3系列基础模型(如text-davinci-003)设计,逻辑是纯文本补全;/v1/chat/completions专门适配GPT-3.5-turbo、GPT-4系列对话模型,基于多轮对话的消息结构运行。
- 输入格式:/v1/completions直接传入纯文本prompt;/v1/chat/completions需要传入包含
role(system/user/assistant)和content的消息数组,更适合管理对话上下文。 - 输出逻辑:/v1/completions返回补全的纯文本内容;/v1/chat/completions返回对话结构里的assistant回复,格式更规整,适配多轮交互场景。
- 成本效率:chat系列模型调用成本远低于同能力的completions模型,响应速度也更快。
二、用GPT-4/GPT-3.5-turbo系列模型实现文本分类
以下是适配/v1/chat/completions端点的评分分类代码,支持指定的所有chat模型:
class OpenAIChatClassifier(): def __init__(self, api_key): openai.api_key = api_key def get_rating(self, review, model="gpt-3.5-turbo"): # 设定对话消息:system角色明确任务规则,user角色传入待分类评论 messages = [ {"role": "system", "content": "你要把用户提供的评论按1-5分评分,1分最差,5分最好,只返回整数评分,不要额外说明"}, {"role": "user", "content": review} ] try: response = openai.ChatCompletion.create( model=model, messages=messages, temperature=0.1, # 低温度保证评分结果稳定 max_tokens=5 ) # 提取并转换评分结果 rating = int(response.choices[0].message["content"].strip()) # 校验评分范围有效性 return rating if 1 <= rating <=5 else None except (ValueError, KeyError): return None # 使用示例 # classifier = OpenAIChatClassifier(api_key="你的API密钥") # 可选model参数:"gpt-4"、"gpt-4-0314"、"gpt-4-32k"、"gpt-4-32k-0314"、"gpt-3.5-turbo"、"gpt-3.5-turbo-0301" # print(classifier.get_rating("这个产品质量很差,用一次就坏了", model="gpt-4"))
关键提示
- 模型切换:在
ChatCompletion.create的model参数中传入对应模型名称即可,比如gpt-4-32k或gpt-3.5-turbo-0301。 - 规则约束:通过
system角色明确任务要求,避免模型返回多余内容,确保输出格式符合预期。 - 结果校验:对返回内容做格式转换和范围校验,保证最终返回的是有效评分。
内容的提问来源于stack exchange,提问作者David Zayn
相关产品推荐
相关产品推荐

