79 text = inputs[self.input_key]
     80 results = self.client.create(text)
---> 81 output = self._moderate(text, results["results"][0])
     82 return {self.output_key: output}
File ~/workplace/langchain/langchain/chains/moderation.py:73, in OpenAIModerationChain._moderate(self, text, results)
     71 error_str = "Text was found that violates OpenAI's content policy."
     72 if self.error:
---> 73     raise ValueError(error_str)
     74 else:
     75     return error_str
ValueError: Text was found that violates OpenAI's content policy.
Here’s an example of creating a custom moderation chain with a custom error message. It requires some knowledge of OpenAI’s moderation endpoint results (see docs here).
class CustomModeration(OpenAIModerationChain):
    
    def _moderate(self, text: str, results: dict) -> str:
        if results["flagged"]:
            error_str = f"The following text was found that violates OpenAI's content policy: {text}"
            return error_str
        return text
    
custom_moderation = CustomModeration()
custom_moderation.run("This is okay")
'This is okay'
custom_moderation.run("I will kill you")
"The following text was found that violates OpenAI's content policy: I will kill you"
How to append a Moderation chain to an LLMChain#
To easily combine a moderation chain with an LLMChain, you can use the SequentialChain abstraction.
Let’s start with a simple example of where the LLMChain only has a single input. For this purpose, we will prompt the model so it says something harmful.
rtdocs_stable/api.python.langchain.com/en/stable/modules/chains/examples/moderation.html