Post-Training Preference Alignment for Healthcare Tool Calling
Describes how to fine-tune a small LLM with GRPO and RLVR on Amazon SageMaker AI to improve agentic tool-calling in a healthcare scenario.
This post was co-authored by Pranav Murthy, Sr. GenAI Data Scientist at AWS. Pranav fine-tuned the experiment setup to dramatically improve the results.
Introduction
A recent study from Anthropic reviewed the latest trends in agentic usage. While the study is limited to data available to Anthropic from usage of the Anthropic API, it does reveal some interesting findings. First, agentic usage is dominated by software engineering, but other domains like back-office automation and finance see significant use. Second, the study discusses the use of agents in higher-risk scenarios like retrieving and displaying patient health care records. In higher risk scenarios, it’s important to make sure that the agent is calling tools correctly. Incorrect tool calls can cause errors or introduce security problems.
One of the techniques we can use to make an agent better at tool-calling is reinforcement learning with verifiable rewards (RLVR) . RLVR uses deterministic reward signals as part of an RL training process. It works well in cases where tool calling has a clear correct or incorrect pattern - for example, calling complex tools with the right parameters in the right order. In this article we’ll describe using RLVR to fine-tune an LLM for an important but potentially risky business workflow.
Agentic AI Healthcare Workflow
For our example workflow, we’ll look at a clinical decision support (CDS) scenario. Clinical Decision Support (CDS) is software that helps doctors and nurses make better medical decisions by analyzing patient information and providing real-time recommendations, alerts, and guidance based on medical knowledge and best practices. If we want to build an agent to automate a CDS workflow, it may need to successfully interact with several tools. These include:
-
calculate_drug_dosage— weight, age, renal function (GFR), drug name, route, indication, allergy list
-
assess_cardiovascular_risk— Framingham-style: age, cholesterol (HDL/LDL), blood pressure, smoker, diabetic, family history
-
calculate_bmi_metabolic_risk— height, weight, waist circumference, activity level, fasting glucose
-
estimate_surgical_risk— ASA class, age, procedure type, comorbidities dict, anesthesia type, emergency flag
-
calculate_insulin_regimen— current A1C, weight, meal plan, activity level, type 1 vs 2, current meds
-
assess_kidney_function— creatinine, age, sex, race, weight, cystatin-C, contrast exposure flag
-
calculate_fluid_replacement— weight, burn percentage, hours since injury, urine output, fluid type
-
screen_drug_interactions— list of current medications, proposed new drug, liver function, kidney function
Calling these tools correctly is quite important. A wrong dosage calculation or missed drug interaction is dangerous for the patient. We could simply use the “best” frontier LLM, but in a high-volume application, we’re also sensitive to cost and latency. We’ll try to fine-tune a small LLM, Qwen 1.7B , and see if we can get measurable improvement in tool-calling. A complete list of tool definitions can be found here .
Prerequisites
To run the RLVR tool-calling example, you need an AWS account with an active SageMaker execution role that has permissions to create training jobs, read/write to S3, and (optionally) connect to an MLflow tracking server . Locally, you only need Python with sagemaker and datasets installed — the heavy dependencies (PyTorch 2.8, TRL, Accelerate, DeepSpeed, vLLM, and PEFT, all pulled from the latest Hugging Face main branches) are installed automatically inside the SageMaker managed training container. For compute, the example defaults to a single
ml.p4de.48xlarge instance (8× A100 GPUs), though smaller Qwen3-0.6B or Qwen 3 1.7B experiments can run on a ml.g6e.12xlarge (4x L40S). The base model is downloaded directly from the Hugging Face Hub during training, so no local model weights are needed. Finally, you'll need an S3 bucket (the SageMaker default bucket works) to stage the training dataset and store model artifacts. To follow along, all the code presented in this article is available in this GitHub repository , particularly in this notebook .Preference alignment through reinforcement learning can be resource intensive, so we recommend using an Amazon SageMaker AI training job to simplify the distributed training process. You can choose between
ml.p4de.24xlarge for faster distributed training or ml.g6e.12xlarge for a more cost-effective option. Before getting started, ensure that the ‘ ml.p4de.24xlarge for training job usage ’ or ‘ ml.g6e.12xlarge for training job usage ’ "Applied account-level quota value" for your chosen instance type is greater than or equal to 1.Qwen3 Family of Models
For this use case, we select the Qwen3 model family, specifically Qwen3-1.7B, and fine-tune it for healthcare domain tool calling. Rather than relying on labeled datasets, we use Group Relative Policy Optimization (GRPO) and Reinforcement Learning via Verifiable Rewards (RLVR) to train the model. We choose Qwen3 because it offers the widest range of model sizes, from 0.6B to 200B+ parameters in a Mixture of Experts architecture, making it adaptable to varying performance and resource requirements. These models are also pre-optimized for agentic workflows with native tool calling capabilities, making them a natural fit for this task.
Post Training Preference Alignment with Reinforcement Learning on Amazon SageMaker AI
The diagram below shows how we run the alignment job. The job executes in SageMaker AI, accessing models from HuggingFace. After the job completes, we host the customized model for inference in a SageMaker AI endpoint.

Why GRPO and RLVR?
GRPO combined with RLVR enables efficient fine-tuning of small language models for tool calling by generating multiple candidate responses per prompt and using automated verification of tool execution correctness as the training signal. This eliminates the need for expensive human-labeled datasets, allowing models to learn directly from programmatic feedback, such as whether an API call succeeds with the correct parameters, rather than requiring thousands of manually curated examples. This makes it practical to rapidly specialize models on organization-specific tools and APIs. The result is production-grade tool calling accuracy achieved through reinforcement learning that rewards successful tool invocations and penalizes failures, transforming compact models into reliable agents that can match frontier model performance on domain-specific workflows.
Distributed SageMaker Open-Source Training Recipe
We built a simplified distributed training recipe for running GRPO and RLVR training on Amazon SageMaker AI, built on top of the Hugging Face TRL library . A r ecipe-style workflow lets you scale your experiments across different models, hyperparameters, and datasets without modifying the core trainer ( GRPOTrainer ) implementation. It also makes it easy to version your configuration artifacts for repeatability and reproducibility. At a high level, you need to define the following components to kick off a GRPO with RLVR training job on Amazon SageMaker AI.
Training Recipe: This is the most important component of your workflow. It defines runtime elements such as the model, dataset, training hyperparameters, observability configuration, and more. An example training recipe used in this article is shown below.
model_name_or_path: Qwen/Qwen3-1.7Bmodel_revision: maindtype: bfloat16attn_implementation: kernels-community/flash-attn2...# Generation settingsnum_generations: 8max_grpo_completion_length:1024learning_rate: 1.0e-6...report_to: - "mlflow"seed: 42Messages-style Dataset: The dataset should follow a messages-style format with a mandatory
prompt key using the familiar system/user structure, and an optional answer key containing the expected output response. The dataset used in this article is available on Hugging Face hub as parquet files (synthetic-healthcare-tool-calling-grpo-rlvr-1k) .
Note 1: The system prompt can be as simple or as complex as needed. TRL automatically injects tool definitions, derived from tool docstrings, into the prompt at runtime, so you do not need to include them manually during data preparation.
Note 2: Including an optional
answer key can help speed up reward calculation. For example, if the expected output after a tool call is a multi-word string, the verifiable reward can be a simple string match, returning 1.0 for a correct match or 0.0 for a wrong or malformed response. If you choose not to include an answer key, you will need a functional method to validate the post-tool-call response programmatically.{ "prompt": [ { "role": "system", "content": "You are a financial planning assistant with tools for portfolio allocation, mortgage affordability, tax optimization, retirement readiness, debt payoff strategies, insurance needs, education funding, and currency exchange.\nAnalyze user requests and call the appropriate tool with all required parameters extracted from their query.\nReturn concise answers with key metrics. Do not ask for clarification - use reasonable defaults if needed." }, { "role": "user", "content": "Downsizing couple, $142k combined retirement income, $950 monthly debts (just car payment), $225k down from selling large family home, 780 credit, conventional loan in Florida (no state income tax!), 0.95% property tax, 55+ community $280/month HOA, $165/month insurance, no PMI with large down payment, 15-year term to pay off before 80. Maximum home price for retirement?" } ], # optional 'answer' key "answer": "Max Price: $741,635, Monthly Payment: $4,725 (P&I: $3,693, Tax: $587, Ins: $165, HOA: $280, PMI: $0), DTI: 48.0%"}SageMaker Model Trainer: This is where everything comes together. You kick off the distributed training job using the Amazon SageMaker AI
ModelTrainer class, which uses accelerate under the hood to orchestrate training across multi-node and multi-GPU environments. If needed, you can swap this out for a different orchestrator like torchrun by updating the sm_accelerate_grpo_train.sh entry-point script.source_code = SourceCode( source_dir="./sagemaker_code", command=f"bash sm_accelerate_grpo_train.sh {' '.join(args)}",)
compute_configs = Compute( instance_type="ml.p4de.24xlarge", instance_count=2, keep_alive_period_in_seconds=1800, volume_size_in_gb=450)...model_trainer = ModelTrainer( training_image=pytorch_image_uri, source_code=source_code, ... role=role, environment=training_env)Experimental Results
We trained the Qwen3-1.7B model using the following experimental setup to achieve state-of-the-art performance on domain-specific tool calling accuracy.
Model | Starting Learning Rate | Epochs | Max GRPO Completion Length | Num Generations |
|---|---|---|---|---|
Qwen/Qwen3-1.7B | 5.00E-06 | 25 | 1024 | 8 |
Once training is complete, it is important to evaluate the model on unseen samples to measure tool calling accuracy. In this section, we analyze the results of fine-tuning Qwen/Qwen3-1.7B on a synthetically generated healthcare tool calling dataset. To ensure a fair comparison, we benchmark against three larger models that are also optimized for agentic and tool calling workflows.
If you wish to reproduce these evaluation metrics, we recommend deploying these models to an Amazon SageMaker AI inference endpoints , either through SageMaker JumpStart or directly from the Hugging Face Hub using SageMaker Large Model Inference (LMI) containers .
Rather than reporting tool calling accuracy as a single aggregate metric, we decompose it into three distinct dimensions to isolate specific failure modes and measure improvements across different aspects of model behavior. This evaluation was conducted on ~80 held-out synthetic samples under test .
Metrics/Models | Qwen/Qwen3-1.7B (rl-tuned, healthcare) | Qwen/Qwen3-1.7B (base) | openai/gpt-oss-20b | openai/gpt-oss-120b | qwen/qwen3-next-80b-a3b |
|---|---|---|---|---|---|
response validity | 0.99 | 0.93 | 0.99 | 0.98 | 0.99 |
exact answer match | 0.6 | 0.36 | 0.5 | 0.51 | 0.47 |
tool call schema match | 0.916 | 0.635 | 0.882 | 0.91 | 0.883 |
Answer Exact Match (AEM) evaluates end-to-end task correctness by requiring the model's final answer to exactly match the ground truth after normalization (e.g., stripping extra whitespace), making it the strictest measure of whether the model got the right answer, not just a structurally valid one. Qwen3-1.7B pre fine-tuning ranked #5 vs post fine-tuning ranked #1.

Response Validity (RV) measures whether the model produces a usable, non-error response. It captures execution reliability rather than correctness, filtering out failures caused by generation errors, malformed outputs, or tool invocation crashes, and excludes samples with invalid ground truth to avoid unfair penalization. Qwen3-1.7B pre fine-tuning ranked #5 vs post fine-tuning ranked #1

Tool Call Schema Match (TCSM) assesses the precision of the tool invocation itself, jointly scoring whether the correct tool was selected (binary) and whether all arguments were accurately formatted against the ground-truth schema (recursive exact match with numeric tolerance) producing a fine-grained score between 0 and 1 that penalizes both wrong tool choice and parameter errors. Qwen3-1.7B pre fine-tuning ranked #5 vs post fine-tuning ranked #1

Conclusion
The results demonstrate that a small, RL-tuned model can match and in some cases exceed the tool calling performance of models many times its size, with Qwen3-1.7B achieving the highest exact answer match accuracy while maintaining near-perfect response validity and schema adherence. This validates the core premise of the article: that GRPO combined with RLVR is a practical alternative to labeled dataset fine-tuning, enabling organizations to build domain-specialized agents without the cost of large frontier models or manual data curation. Beyond accuracy, inference cost and latency are critical factors for high-volume agentic workflows, and the RL-tuned Qwen3-1.7B can be served on a
g5.xlarge or g6.xlarge instance at $1.00 and $0.80 per hour respectively, compared to $10.50 per hour for a g6e.12xlarge needed to serve a 72B model. Paired with Amazon SageMaker AI's fully managed distributed training infrastructure, this approach offers a compelling and cost-efficient path to production-grade tool calling for high-stakes domains like healthcare. We recommend experimenting with GRPO using RLVR on Amazon SageMaker AI through the sample notebook provided here . We also encourage you to explore additional fine-tuning examples and strategies available in this aws-samples GitHub repository .Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article