Skip to main content
Learn how to integrate Guardrails with any custom LLM API that isn’t natively supported.

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:
  1. Accept messages as a parameter (list of message dictionaries)
  2. Return a string containing the LLM’s output
  3. Accept additional keyword arguments that you want to pass to your LLM
  4. 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

  1. Error handling: Implement proper error handling in your wrapper
  2. Timeouts: Set appropriate timeouts for API calls
  3. Retries: Consider implementing retry logic for transient failures
  4. Logging: Add logging to help debug issues
  5. Type hints: Use type hints for better code clarity

Alternative: Use LiteLLM

If you don’t want to build a custom wrapper, consider using LiteLLM which supports 100+ LLM providers out of the box.