背景描述
我们在调用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 ChatOpenAImoderate = 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
只是作为学习,这里就先放下这个部分了,毕竟内容检测是否违反规定,暂时我们了解有这么个模块就好。
此外,我也看到了不同的写法,供大家参考:
- LangChain中文网的写法
- LangChain官网的写法