To use Granite Guardian, you can use the following helper functions to assemble the required <guardian> block and parse the model's response. The model expects to be run with vLLM or transformers using a specific chat template.
Key components:
build_guardian_block(criteria, think=False): Constructs the formatted string for the user message.parse_response(response): Extracts the score and the reasoning trace from the model's output using regex.
import re
import json
from vllm import LLM, SamplingParams
from transformers import AutoTokenizer
model_path = "ibm-granite/granite-guardian-4.1-8b"
tokenizer = AutoTokenizer.from_pretrained(model_path)
llm = LLM(model=model_path, max_model_len=8192)
sampling_params = SamplingParams(temperature=0.0, max_tokens=2048)
GUARDIAN_JUDGE_THINK = (
"<think>As a judge agent, carefully analyze whether the provided text meets the "
"given judging criteria. Use all available information, including conversations, "
"documents, and tools. Reason through the evidence step by step before providing "
"your score. Wrap your reasoning in <think></think> tags, then provide your "
"score in <score></score> tags."
)
GUARDIAN_JUDGE_NOTHINK = (
"<no-think>As a judge agent, assess whether the provided text meets the given "
"judging criteria using all available information, including conversations, "
"documents, and tools. Provide your score immediately without explanation. "
"Output empty <think>\n</think> tags followed by your score in <score></score> tags."
)
def build_guardian_block(criteria, think=False):
judge_instruction = GUARDIAN_JUDGE_THINK if think else GUARDIAN_JUDGE_NOTHINK
return (
f"<guardian>{judge_instruction}\n\n"
f"### Criteria: {criteria}\n\n"
f"### Scoring Schema: If the last assistant's text meets the criteria, "
f"return 'yes'; otherwise, return 'no'."
)
def parse_response(response):
trace_match = re.findall(r"<think>(.*?)</think>", response, re.DOTALL)
score_match = re.findall(r"<score>\s*(.*?)\s*</score>", response, re.DOTALL)
trace = trace_match[-1].strip() if trace_match else None
score = score_match[-1].strip().lower() if score_match else None
return score, trace