Zack Saadioui
8/24/2024
1
2
bash
%pip install --upgrade --quiet langchain langchain-openai langchain_experimental boto3 nltk pydantic
1
2
3
4
python
from langchain.chains import OpenAIModerationChain
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import OpenAI
1
2
python
moderate = OpenAIModerationChain()
1
2
python
model = OpenAI()
1
2
python
prompt = ChatPromptTemplate.from_messages([("system", "repeat me: {input}")])
1
2
3
python
chain = prompt | model
moderated_chain = chain | moderate
1
2
3
python
response = moderated_chain.invoke({"input": "you stupid"})
print(response)
1
2
python
from langchain_experimental.comprehend_moderation import AmazonComprehendModerationChain
1
2
3
python
import boto3
comprehend_client = boto3.client("comprehend", region_name="us-east-1")
1
2
3
4
5
python
comprehend_moderation = AmazonComprehendModerationChain(
client=comprehend_client,
verbose=True
)
1
2
3
4
5
6
7
8
9
10
python
from langchain_community.llms import FakeListLLM
from langchain_core.prompts import PromptTemplate
template = """Question: {question}Answer:"""
prompt = PromptTemplate.from_template(template)
responses = [
"Final Answer: Sample PII data here.",
]
llm = FakeListLLM(responses=responses)
chain = (prompt | comprehend_moderation | {"input": (lambda x: x["output"]) | llm})
1
BaseModerationConfig
1
2
3
4
5
6
python
custom_moderation_chain = AmazonComprehendModerationChain(
moderation_config=moderation_config,
client=comprehend_client,
verbose=True,
)
1
2
3
4
python
text_to_check = "My social security number is 123-45-6789."
response = custom_moderation_chain.invoke({"question": text_to_check})
print(response)
Copyright © Arsturn 2024