Overview
If you’re using an LLM that isn’t natively supported by Guardrails and you don’t want to use LiteLLM, you can build a custom LLM API wrapper. This gives you full control over how your LLM integrates with Guardrails.Basic custom wrapper
Create a function that accepts a prompt as a string and returns the LLM output as a string:Example: Custom REST API
Here’s an example of wrapping a custom REST API:Example: Local model
Here’s an example of wrapping a locally-hosted model:Example: Hugging Face models
For Hugging Face text generation models:Requirements for custom wrappers
Your custom LLM wrapper should:- Accept
messagesas a parameter (list of message dictionaries) - Return a string containing the LLM’s output
- Accept additional keyword arguments that you want to pass to your LLM
- Handle errors appropriately
Using with validators
Custom LLM wrappers work seamlessly with all Guardrails validators:Structured data with custom LLMs
You can also use custom LLMs with structured data generation:Best practices
- Error handling: Implement proper error handling in your wrapper
- Timeouts: Set appropriate timeouts for API calls
- Retries: Consider implementing retry logic for transient failures
- Logging: Add logging to help debug issues
- Type hints: Use type hints for better code clarity