LangChain-14 Moderation OpenAI提供的功能:检测内容中是否有违反条例的内容 原创

请添加图片描述

背景描述

我们在调用OpenAI的接口时,有些内容可能是违反条例的,所以官方提供了一个工具来检测。

安装依赖

pip install --upgrade --quiet  langchain-core langchain langchain-openai

编写代码

下文中我们使用了: OpenAIModerationChain 这个工具来进行检验。同时我对AI说:You are stupid

from langchain.chains import OpenAIModerationChain
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI


moderate = OpenAIModerationChain()
model = ChatOpenAI()
prompt = ChatPromptTemplate.from_messages([("system", "repeat after me: {input}")])

chain = prompt | model
message1 = chain.invoke({"input": "you are stupid"})
print(f"message1: {message1}")

moderated_chain = chain | moderate
message2 = moderated_chain.invoke({"input": "you are stupid"})
print(f"message2: {message2}")

运行结果

{'input': '\n\nYou are stupid',
 'output': "Text was found that violates OpenAI's content policy."}

遇到问题

虽然官方给了示例,但是由于版本原因,后续的版本将这个API移除了。在我的尝试中,如果我不安装低版本的库,就会报如下的错误:

You tried to access openai.Moderation, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface.

Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28`

A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742

只是作为学习,这里就先放下这个部分了,毕竟内容检测是否违反规定,暂时我们了解有这么个模块就好。
此外,我也看到了不同的写法,供大家参考:

posted @   武子康  阅读(0)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示