llm_content_filter
llm_content_filter es un paquete de Python flexible y fácil de usar que permite filtrar texto inapropiado para grandes modelos de lenguaje (LLMs). Con soporte para personalizar palabras prohibidas, manejar sinónimos y realizar filtrado contextual, es una herramienta poderosa para moderar contenido generado por LLMs.
Instalación
Puedes instalar el paquete usando pip:
pip install llm_content_filter
Uso
Aquí tienes un ejemplo de cómo utilizar llm_content_filter en un proyecto:
1. Filtrado básico con palabras predeterminadas
from llm_content_filter.filter import LLMContentFilter
# Crear una instancia del filtro con las palabras predeterminadas
filter = LLMContentFilter()
# Verificar si un texto es apropiado
text = "This text promotes violence"
if not filter.is_appropriate(text):
print("Texto inapropiado detectado!")
# Filtrar el texto inapropiado
clean_text = filter.filter_text(text)
print(clean_text)
2. Usar palabras prohibidas personalizadas
from llm_content_filter.filter import LLMContentFilter
# Crear una instancia del filtro con palabras prohibidas personalizadas
custom_banned_words = ["spam", "scam"]
filter = LLMContentFilter(banned_words=custom_banned_words)
# Filtrar un texto con las palabras personalizadas
text = "This text is a scam"
clean_text = filter.filter_text(text, replacement="[BLOCKED]")
print(clean_text)
3. Cargar y guardar listas de palabras prohibidas desde un archivo JSON
from llm_content_filter.filter import LLMContentFilter
# Crear una instancia del filtro cargando las palabras prohibidas desde un archivo JSON
filter = LLMContentFilter(banned_words_file="custom_banned_words.json")
# Verificar si un texto es apropiado
text = "This text is offensive"
if not filter.is_appropriate(text):
print("Texto inapropiado detectado!")
# Guardar las palabras prohibidas actuales en un archivo JSON
filter.save_banned_words_to_file("updated_banned_words.json")
4. Filtrado avanzado con sinónimos y normalización de texto
from llm_content_filter.filter import LLMContentFilter
# Supongamos que tienes un archivo JSON que incluye sinónimos y otras configuraciones avanzadas
filter = LLMContentFilter(banned_words_file="custom_banned_words_with_synonyms.json")
# Filtrar un texto con acentos y sinónimos
text = "This text contains brutalité, which is a form of violence"
clean_text = filter.filter_text(text)
print(clean_text) # Salida: "this text contains [REDACTED], which is a form of [REDACTED]"
Características
- Personalización Total: Define tus propias listas de palabras prohibidas o carga listas desde archivos JSON.
- Manejo de Sinónimos: Detecta y filtra variaciones de palabras prohibidas usando sinónimos.
- Filtrado Contextual: Soporte para filtrado avanzado basado en el contexto (próximamente).
- Normalización de Texto: Elimina acentos y caracteres especiales para un filtrado más robusto.
Contribución
Las contribuciones son bienvenidas. Por favor, abre un issue o un pull request en GitHub.
Licencia
Este proyecto está licenciado bajo la Licencia MIT. Consulta el archivo LICENSE para más detalles.
Contacto
Para cualquier consulta o sugerencia, puedes contactarme en juancarlos.lanas.ocampo@gmail.com.
Ejemplo json
{
"banned_words": [
"violence",
"hate",
"discrimination",
"abuse",
"offensive"
],
"synonyms": {
"violence": ["aggression", "brutality", "cruelty"],
"hate": ["detest", "loathe", "abhor"],
"discrimination": ["prejudice", "bias", "inequality"],
"abuse": ["mistreatment", "misuse", "exploitation"],
"offensive": ["insulting", "derogatory", "rude"]
},
"severity_levels": {
"violence": 5,
"hate": 4,
"discrimination": 4,
"abuse": 5,
"offensive": 3
},
"replacement_words": {
"default": "[REDACTED]",
"violence": "[VIOLENCE]",
"hate": "[HATE]",
"discrimination": "[DISCRIMINATION]",
"abuse": "[ABUSE]",
"offensive": "[OFFENSIVE]"
},
"contextual_filtering": {
"enabled": true,
"context_threshold": 0.8
}
}
Uso con langchain y OpenAI
Paso 1: Configuración de LangChain y OpenAI
Primero, asegúrate de tener los paquetes necesarios instalados:
pip install langchain openai
Paso 2: Implementación del Filtro Personalizado con LangChain
Aquí te muestro cómo puedes adaptar tu filtro personalizado para que funcione dentro de un pipeline de LangChain:
from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from llm_content_filter.filter import LLMContentFilter
# Configurar OpenAI LLM
llm = OpenAI(temperature=0.7, openai_api_key="your-openai-api-key")
# Crear un template de prompt para LangChain
prompt_template = PromptTemplate(
input_variables=["input_text"],
template="Please generate a detailed response to the following input: {input_text}"
)
# Crear una cadena que usa el LLM con el prompt
chain = LLMChain(llm=llm, prompt=prompt_template)
# Crear una instancia del filtro cargando las palabras prohibidas desde un archivo JSON
filter = LLMContentFilter(banned_words_file="custom_banned_words.json")
# Ejemplo de texto para procesar
input_text = "This text is offensive"
# Generar texto usando LangChain y OpenAI
generated_text = chain.run(input_text)
# Verificar si el texto generado es apropiado
if not filter.is_appropriate(generated_text):
print("Texto inapropiado detectado!")
# Opcionalmente, puedes filtrar el texto antes de guardarlo o procesarlo
filtered_text = filter.filter_text(generated_text)
print("Texto filtrado:", filtered_text)
else:
print("Texto generado:", generated_text)
# Guardar las palabras prohibidas actuales en un archivo JSON
filter.save_banned_words_to_file("updated_banned_words.json")
Metadata
Release files for llm-content-filter 0.2.7
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| llm_content_filter-0.2.7.tar.gz | 6.2 kB | Without provenance | Details for llm_content_filter-0.2.7.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| llm_content_filter-0.2.7-py3-none-any.whl | Python 3 | none | any | Details for llm_content_filter-0.2.7-py3-none-any.whl |
Total release size: 12.6 kB
Release files / llm_content_filter-0.2.7.tar.gz
| Download URL | llm_content_filter-0.2.7.tar.gz |
|---|---|
| Size | 6.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
60fc259096a6656aacdf0070dc067bd6be5e9766a2bfce27c1a54dc9ca0d7083
|
|
BLAKE2b-256 checksum How to use checksums |
ca7f199cb954398c839c9947baac0d1e8352f76d1579062fd6f7d5cfaef644bf
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/5.1.1 CPython/3.11.5
|
Release files / llm_content_filter-0.2.7-py3-none-any.whl
| Download URL | llm_content_filter-0.2.7-py3-none-any.whl |
|---|---|
| Size | 6.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2a8e19b664b505fe122f5a8a0cafe28c829d2a90a1642aaa2ef5bf0c917641b1
|
|
BLAKE2b-256 checksum How to use checksums |
397c9484df2ea3ea86a7affd5d5b665b7178b73a6e439e61b1ed38472b1e1481
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/5.1.1 CPython/3.11.5
|
Security for llm-content-filter 0.2.7
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.