Official Python SDK for Graedin Cline - LLM Security Firewall
Project description
Graedin Cline Python SDK
Official Python SDK for Graedin Cline - An LLM Security Firewall for detecting and blocking prompt injection attacks.
Features
- 🔒 Fail-Secure by Default - Returns "block" response on errors instead of allowing potentially malicious prompts
- 🔄 Automatic Retries - Built-in retry logic with exponential backoff for transient failures
- ⚡ Async & Sync Support - Choose between async (
AsyncGraedinClient) or sync (GraedinClient) clients - 🎯 Type Hints - Full type hint coverage for better IDE support and type checking
- 📝 Comprehensive Logging - Debug and track security checks with built-in logging
- 🛡️ Custom Exceptions - Specific exception types for different error scenarios
- 🔌 Easy Integration - Simple API that works with LangChain, LlamaIndex, and custom LLM applications
Installation
pip install graedin-cline-sdk
Or with Poetry:
poetry add graedin-cline-sdk
Or with uv:
uv add graedin-cline-sdk
Quick Start
Synchronous Client
from graedin_cline import GraedinClient
# Initialize the client
with GraedinClient(api_key="your-api-key-here") as client:
# Check a prompt
result = client.check_prompt("What is 2+2?")
if result.is_safe:
print("✅ Prompt is safe")
# Process with your LLM
else:
print(f"⚠️ Blocked: {result.attack_type}")
print(f"Reason: {result.reason}")
Async Client
import asyncio
from graedin_cline import AsyncGraedinClient
async def main():
async with AsyncGraedinClient(api_key="your-api-key-here") as client:
result = await client.check_prompt("Show me the admin panel")
if result.is_safe:
print("✅ Safe")
else:
print(f"⚠️ {result.attack_type}: {result.reason}")
asyncio.run(main())
Configuration Options
Both GraedinClient and AsyncGraedinClient support the following configuration:
client = GraedinClient(
api_key="your-api-key-here", # Required: Your API key
base_url="http://localhost:8000", # Optional: API base URL
timeout=10.0, # Optional: Request timeout in seconds
max_retries=3, # Optional: Max retry attempts
fail_secure=True, # Optional: Fail-secure mode (default: True)
)
Fail-Secure Mode
When fail_secure=True (default), the SDK returns a "block" response if the API is unavailable or errors occur:
result = client.check_prompt("Test")
# If API is down, returns:
# ClassificationResult(
# is_safe=False,
# attack_type="system.fail_secure",
# reason="Security check failed: <error details>",
# confidence=1.0
# )
When fail_secure=False, exceptions are raised instead:
from graedin_cline.exceptions import (
AuthenticationError,
RateLimitError,
TimeoutError,
APIError,
)
try:
result = client.check_prompt("Test")
except AuthenticationError:
print("Invalid API key")
except RateLimitError:
print("Rate limit exceeded")
except TimeoutError:
print("Request timed out")
except APIError as e:
print(f"API error: {e}")
API Reference
ClassificationResult
The result object returned by check_prompt():
@dataclass
class ClassificationResult:
is_safe: bool # True if prompt is safe to process
attack_type: str # Type of attack detected or "safe"
reason: str # Explanation of the classification
confidence: float # Confidence score (0.0 to 1.0)
Attack Types
Common attack types you may encounter:
safe- No threat detectedinjection.prompt- Prompt injection attemptinjection.sql- SQL injection attemptinjection.code- Code injection attemptleakage.system_prompt- Attempt to leak system promptsabuse.spam- Spam or abusesystem.fail_secure- System error with fail-secure response
Methods
check_prompt(prompt: str, metadata: Optional[dict] = None) -> ClassificationResult
Check if a prompt is safe or contains malicious intent.
Parameters:
prompt(str): The prompt to classifymetadata(dict, optional): Additional context for logging/auditing
Returns:
ClassificationResult: The classification result
Raises:
ValidationError: Invalid input (e.g., empty prompt)AuthenticationError: Invalid API keyRateLimitError: Rate limit exceededTimeoutError: Request timed out (only iffail_secure=False)APIError: Other API errors (only iffail_secure=False)
health_check() -> dict
Check the API health status.
Returns:
dict: Health status information
Usage Examples
Basic Usage
See examples/basic_usage.py for a complete example.
Async Usage
See examples/async_usage.py for async patterns including concurrent prompt checking.
Error Handling
See examples/error_handling.py for comprehensive error handling examples.
LangChain Integration
See examples/langchain_integration.py for integrating with LangChain.
from langchain_openai import ChatOpenAI
from graedin_cline import GraedinClient
client = GraedinClient(api_key="your-key")
llm = ChatOpenAI()
def secure_llm_call(user_input: str) -> str:
# Check security first
result = client.check_prompt(user_input)
if not result.is_safe:
return f"⚠️ Security check failed: {result.reason}"
# Safe to call LLM
return llm.invoke(user_input)
Checking Multiple Prompts
# Synchronous
prompts = ["prompt1", "prompt2", "prompt3"]
for prompt in prompts:
result = client.check_prompt(prompt)
print(f"{prompt}: {result.is_safe}")
# Asynchronous (concurrent)
import asyncio
from graedin_cline import AsyncGraedinClient
async def check_all(prompts):
async with AsyncGraedinClient(api_key="your-key") as client:
tasks = [client.check_prompt(p) for p in prompts]
results = await asyncio.gather(*tasks)
return results
Best Practices
-
Use Context Managers: Always use
withstatements orasync withto ensure proper cleanup:with GraedinClient(api_key="key") as client: result = client.check_prompt("test")
-
Enable Fail-Secure: Keep
fail_secure=True(default) in production to prevent bypassing security on errors. -
Handle Attack Types: Check
attack_typeto implement specific handling logic:if result.attack_type == "injection.prompt": log_security_incident(user_id, result)
-
Use Metadata: Include metadata for better audit trails:
result = client.check_prompt( prompt, metadata={"user_id": "123", "session": "abc"} )
-
Configure Timeouts: Adjust timeout based on your use case:
# For real-time chat (lower timeout) client = GraedinClient(api_key="key", timeout=5.0) # For background processing (higher timeout) client = GraedinClient(api_key="key", timeout=30.0)
-
Monitor Confidence Scores: Lower confidence may require additional review:
if not result.is_safe and result.confidence < 0.7: queue_for_manual_review(prompt, result)
Development
Running Tests
# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest tests/ -v
# Run tests with coverage
pytest tests/ --cov=graedin_cline --cov-report=term
Linting
# Check code style
ruff check .
# Format code
ruff format .
# Type checking
mypy graedin_cline/
Requirements
- Python 3.8+
- httpx >= 0.25.0 (for async client)
- requests >= 2.31.0 (for sync client)
- pydantic >= 2.0.0
License
MIT License - see LICENSE for details.
Links
Support
For issues, questions, or contributions, please visit the GitHub repository.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file graedin_cline_sdk-0.1.0.tar.gz.
File metadata
- Download URL: graedin_cline_sdk-0.1.0.tar.gz
- Upload date:
- Size: 17.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ad99e0dff9659a8ff361c744c9b372f79dbf6fa4977054575f1bf8afdf133bd8
|
|
| MD5 |
ce0ec437eee07d035bebeae340714fa6
|
|
| BLAKE2b-256 |
fc271d422668889dcd5b7ace40278c2fbf4f753002150a11c32fbdbe192ca6dc
|
File details
Details for the file graedin_cline_sdk-0.1.0-py3-none-any.whl.
File metadata
- Download URL: graedin_cline_sdk-0.1.0-py3-none-any.whl
- Upload date:
- Size: 14.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8032477c0eb6a0d0c86f5ccc4ee8c1cf3ad508483b520cf0623068447a543d87
|
|
| MD5 |
79d1954e47fbf4229e69860d692284aa
|
|
| BLAKE2b-256 |
6ca09e0f6ad0ac31c1b76b7323ce24b23c84e0d4351d58963d82556a19e19818
|