
TrustedSec LLM Library es una biblioteca de Python para interactuar con LLM locales que admiten el uso de herramientas. Permite ejecutar grandes flujos de trabajo tradicionalmente solo posibles con modelos de frontera, aprovechando los endpoints de LLM locales y la integración con MCP (Protocolo de Contexto de Modelo).
# Clone or copy the repository
git clone https://github.com/trustedsec/ts_llmlib.git
cd ts_llmlib
# Install with pip
pip install -e .
Copie el directorio ts_llmlib/ a su proyecto:
cp -rf ts_llmlib /path/to/your/project/
from ts_llmlib import ChatSession
# Initialize with defaults (connects to http://localhost:1234/v1/chat/completions)
chat = ChatSession()
# Run a prompt
response = chat.run_prompt("What files are in the current directory?")
print(response['content'])
from ts_llmlib import ChatSession
# Configure with custom settings
chat = ChatSession(
system_prompt="You are a helpful assistant that uses file tools.",
tool_list=[], # Empty = use default file tools
mcp_servers={
"default": "http://localhost:3000/mcp"
},
llm_endpoint_url="http://localhost:1234/v1/chat/completions",
model_name="qwen3-coder-next",
timeout=60,
max_runtime=300
)
response = chat.run_prompt("Write 'hello' to /tmp/greeting.txt")
print(response['content'])
from ts_llmlib import ChatSession
chat = ChatSession()
history = [
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "content": "The answer is 4."}
]
response = chat.run_prompt("Can you write that to a file?", history=history)
MCP (Protocolo de Contexto de Modelo) permite la integración con herramientas y servicios externos. Cuando los servidores MCP están configurados, ts_llmlib:
from ts_llmlib import ChatSession
chat = ChatSession(
mcp_servers={
"ghidraSvr": "http://localhost:8081/sse"
},
llm_endpoint_url="http://localhost:1234/v1/chat/completions",
model_name="qwen3-coder-next"
)
# The chat session will automatically fetch and integrate Ghidra tools
# such as list_methods, decompile_function, get_xrefs_to, etc.
ts_llmlib admite endpoints de estilo RPC y SSE (Eventos Enviados por el Servidor):
http://localhost:3000/mcphttp://localhost:3000/sse (se convierte automáticamente a /mcp para llamadas RPC)ChatSession(
system_prompt: str | None = None,
tool_list: list | None = None,
mcp_servers: dict[str, str] | None = None,
llm_endpoint_url: str = "http://localhost:1234/v1/chat/completions",
model_name: str = "default",
timeout: int = 60,
max_runtime: int = 300
)
Parámetros:
system_prompt (str | None): Prompt de sistema personalizado. Utiliza un prompt de asistente mínimo por defecto.tool_list (list | None): Lista de definiciones de herramientas personalizadas. Una lista vacía utiliza las herramientas integradas.mcp_servers (dict[str, str] | None): Diccionario que asigna nombres de servidores a URLs.llm_endpoint_url (str): URL del endpoint de la API del LLM.model_name (str): Identificador del modelo para el endpoint del LLM.timeout (int): Tiempo de espera de la solicitud HTTP en segundos.max_runtime (int): Tiempo máximo de ejecución para un prompt en segundos.response = chat.run_prompt(
user_prompt: str,
conversation_history: list[dict] | None = None,
disable_tools: list[str] | None = None,
max_runtime: int | None = None
) -> dict
Parámetros:
user_prompt (str): El mensaje o pregunta del usuario.conversation_history (list[dict] | None): Historial de conversación opcional como una lista de pares rol/contenido.disable_tools (list[str] | None): Lista de nombres de herramientas a deshabilitar para esta llamada.max_runtime (int | None): Sobrescribe el tiempo máximo de ejecución predeterminado para esta llamada específica.Retorna:
{
"content": str, # LLM response text
"tool_calls": list, # List of tool calls made (if any)
"usage": dict | None, # Token usage if available from the LLM
"error": str | None # Error message if failed
}
El ToolRegistry administra todas las herramientas disponibles para la sesión de chat:
tool_listPara sobrescribir las rutas predeterminadas, puede establecer las siguientes variables, que se verifican en ChatSession.
TS_LLM_MODEL=qwen3-coder-next TS_LLM_ENDPOINT=http://HOSTNAME:1234/v1/chat/completions
# Example usage
export TS_LLM_MODEL=qwen3-coder-next
export TS_LLM_ENDPOINT=http://HOSTNAME:1234/v1/chat/completions
ts_llmlib-redclippy
# OR
TS_LLM_MODEL=qwen3-coder-next TS_LLM_ENDPOINT=http://HOSTNAME:1234/v1/chat/completions ts_llmlib-redclippy
Analiza archivos de código fuente C/C++ en busca de vulnerabilidades de seguridad:
ts_llmlib-cpp-analyze <source_folder> <output_folder>
Análisis de binarios de ingeniería inversa con integración de Ghidra:
# Basic analysis
ts_llmlib-ghidra-analyze <output_folder>
# Rename-only mode (first pass)
ts_llmlib-ghidra-analyze --rename_only <output_folder>
# Process only previously unnamed functions
ts_llmlib-ghidra-analyze --process_unnamed_only <output_folder>
# Grouped analysis for call relationship grouping
ts_llmlib-ghidra-analyze --grouped <output_folder>
Una vez finalizada la ejecución, si no está usando --rename_only, puede limpiar la estructura ejecutando:
ts_llmlib-ghidra-cleanup <input_folder> <output_folder>
Genere informes de vulnerabilidades formateados a partir de archivos de revisión JSON:
ts_llmlib-ghidra-report <review_folder>
Ejecute la interfaz de chat RedClippy basada en Qt (nota: este ejemplo requiere pyside6):
ts_llmlib-redclippy
ts_llmlib se conecta a cualquier endpoint de API compatible con OpenAI. Servidores LLM locales comunes:
| Servidor | URL Predeterminada |
|---|---|
| Ollama | http://localhost:11434/v1/chat/completions |
| LM Studio | http://localhost:1234/v1/chat/completions |
| vLLM | http://localhost:8000/v1/chat/completions |
Dos configuraciones de tiempo de espera controlan la ejecución:
timeout): Tiempo máximo para una solicitud de API individualmax_runtime): Tiempo total de reloj permitido para el procesamiento del prompt (incluidas las llamadas a herramientas)Si se excede cualquiera de los límites, la respuesta contendrá un mensaje de error.
Todos los errores se devuelven en el diccionario de respuesta:
response = chat.run_prompt("Some prompt")
if response.get('error'):
print(f"Error: {response['error']}")
else:
print(response['content'])
max_runtimets_llmlib/
├── __init__.py # Package initialization, exports ChatSession
├── client.py # LLMClient for HTTP requests to LLM endpoints
├── chat.py # ChatSession class (main API)
├── mcp.py # MCPClient for Model Context Protocol integration
├── tools.py # ToolRegistry for tool management
├── HOW_TO_TS_LLMLIB.md # Original documentation
└── examples/ # Example scripts
├── c_cpp_analyze.py # C/C++ vulnerability analysis script
├── redclippy.py # Qt-based GUI chat application
├── ghidra_analyze.py # Ghidra binary analysis with MCP integration
├── ghidra_vuln_report.py # Vulnerability report generator
├── ghidra_cleanup.py # Output file reorganization utility
└── example_ts_llmlib.py # Example script demonstrating library usage
pyproject.toml # Modern Python package configuration (scripts defined here)
LICENSE.txt # BSD-3-Clause License
README.md # This file
Licencia BSD-3-Clause: consulte el archivo LICENSE.txt para obtener más detalles.
¡Las contribuciones son bienvenidas! No dude en enviar una Solicitud de Extracción (Pull Request).
git checkout -b feature/AmazingFeature)git commit -m 'Add some AmazingFeature')git push origin feature/AmazingFeature)| Herramienta | Parámetros | Descripción |
|---|
read_local_file | path: str | Lee el contenido de un archivo local |
write_local_file | path: str, content: str | Escribe contenido en un archivo local |
list_directory | path: str | Lista archivos y directorios en una ruta |