You need to agree to share your contact information to access this dataset

This repository is publicly accessible, but you have to accept the conditions to access its files and content.

Log in or Sign Up to review the conditions and access this dataset content.

Teaching Small Models When Not to Call Functions

Research code and evaluation utilities for:

Teaching Small Models When Not to Call Functions: Structured Reasoning for Tool Refusal in Low-Resource Languages

This repository extends the Berkeley Function-Calling Leaderboard (BFCL) for multilingual tool-use and tool-refusal evaluation, with a focus on Vietnamese and Thai. It supports BFCL-style function-calling evaluation, intent-based refusal evaluation, multilingual BFCL data loading, distributed vLLM/Transformers inference, structured score reporting, and an optional translation middleware not used in the current paper experiments.

Paper

This work was accepted to the SIGIR '26 Short Paper Track, at the 49th International ACM SIGIR Conference on Research and Development in Information Retrieval, held July 20-24, 2026 in Melbourne, VIC, Australia.

Support and Environment Notes

If you encounter any issue with the benchmark data, evaluation setup, dependencies, or runtime behavior, please contact dung.vpt@qualgo.net. Some issues may come from differences between your local environment or hardware and the authors' evaluation environment, especially for GPU runtime, CUDA/PyTorch/vLLM versions, tokenizer chat-template behavior, and distributed inference settings.

Dataset Summary

Multilingual-BFCL is a public benchmark and evaluation release for multilingual function-calling, tool-refusal, and tool-call hallucination analysis. It contains BFCL-style English, Vietnamese, and Thai evaluation data together with the project evaluation code used to run intent-based refusal metrics and standard BFCL AST checks.

This artifact is designed for benchmark use, evaluation reproduction, and research comparison. It is not a training-data release: private fine-tuning mixtures, teacher-generated reasoning traces, and model checkpoints are intentionally excluded from the public artifact.

The Hugging Face Dataset Viewer is enabled through a small preview split at viewer/benchmark_preview.parquet. The preview is intended for quick browsing only; use the files under data_storage/ as the authoritative benchmark data for evaluation.

At a Glance

Field Value
Primary task Function calling, tool refusal, and tool-call hallucination evaluation
Languages English (en), Vietnamese (vi), Thai (th)
Paper benchmark scope BFCL v3 single-turn, non-multi-turn subsets
Samples 3,641 samples per language for the paper evaluation scope
Main released files data_storage/bfcl_single_turn_{en,vi,th}.jsonl and data_storage/data_{en,vi,th}/
Main metrics AST, Irrelevance, intent-based Live Hallucination (H-I), standard Live Hallucination (H-S)
Recommended evaluator eval.py with --backend vllm
Hugging Face Dataset Viewer Small representative preview split; not the authoritative evaluation source
Public artifact includes Benchmark data, evaluation code, distributed inference utilities, documentation
Public artifact excludes Training code, training data, model checkpoints, teacher-generated traces

Recommended Reading Path

Release Scope

This public artifact is intentionally scoped as a benchmark and evaluation framework. It releases the multilingual BFCL-style evaluation data and the code needed to run the reported benchmark protocol.

Released:

  • Benchmark/evaluation code for BFCL-style multilingual and intent-based evaluation.
  • BFCL-VN and BFCL-TH benchmark organization and evaluation utilities.
  • Distributed inference/evaluation scripts with the project vLLM backend.
  • Documentation for reproducing the reported evaluation protocol.

Not released:

  • Training code used to fine-tune model variants.
  • Model checkpoints for No-Reasoning, CoT Reasoning, Structured Reasoning, or Randomized Reasoning variants.
  • Training datasets used to construct the 50,863-example fine-tuning mixture.
  • Intermediate teacher-generated reasoning traces used during training.

The README therefore documents the paper hyperparameters and evaluation protocol, but the released artifact is intended for benchmark use and evaluation reproduction rather than full training reproduction.

Intended Uses and Limitations

Category Guidance
Intended use Evaluate tool-use capability, refusal behavior, and hallucinated tool-call intent across English, Vietnamese, and Thai.
Comparison use Compare models under the same BFCL subset scope, decoding setup, chat-template policy, and scoring mode.
Out-of-scope use Do not treat the release as a full training reproduction package or a complete production-agent safety benchmark.
Metric caution Intent-based scores (H-I) are stricter than standard format-compliance scores (H-S) because malformed attempted tool calls are counted as failures.
Data caution The paper focuses on single-turn non-multi-turn BFCL v3 subsets; multi-turn and long-context behavior are outside the reported paper scope.
Expand governance, reproducibility, and interpretation notes
  • Release governance: training mixtures, model variants, teacher traces, and checkpoints are not public due to company policy.
  • Benchmark reproducibility: the released code and benchmark data support evaluation reproduction, but not end-to-end training reproduction.
  • Metric interpretation: report AST capability together with refusal metrics. A model can improve tool-call syntax while becoming more likely to hallucinate unavailable tools.
  • Language interpretation: multilingual scores should be compared under the same chat template, backend, decoding setup, and BFCL subset selection.
  • Viewer behavior: the Dataset Viewer shows a small representative preview split. Use the canonical JSONL files under data_storage/ for benchmark runs.

Loading the Benchmark

The canonical single-turn benchmark files are:

Show benchmark file paths
data_storage/bfcl_single_turn_en.jsonl
data_storage/bfcl_single_turn_vi.jsonl
data_storage/bfcl_single_turn_th.jsonl

Minimal JSONL loading example:

Show minimal Python loading example
import json
from pathlib import Path

path = Path("data_storage/bfcl_single_turn_vi.jsonl")
records = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()]

print(len(records))
print(records[0].keys())

For full benchmark evaluation, use the project evaluator rather than manually scoring JSONL records.

Expand data organization details
  • Single-turn JSONL files: compact language-specific files for EN, VI, and TH.
  • data_storage/data_en/: English BFCL-style folder organization.
  • data_storage/data_vi/: Vietnamese BFCL-style folder organization.
  • data_storage/data_th/: Thai BFCL-style folder organization.
  • Refusal subsets: expected ground_truth can be empty when the correct behavior is not to call any function.
  • BFCL v4-style files: additional files are present under data_storage/data_{en,vi,th}/, while the paper numbers focus on BFCL v3 single-turn non-multi-turn subsets.

Documentation Index

Show documentation index
Document Purpose
README.md Project overview, paper contributions, distributed evaluation path, main results, and citation.
docs/eval-usage.md Detailed evaluation commands and usage examples.
docs/translation-middleware-guide.md Optional translation middleware workflow for multilingual BFCL evaluation; not used in the current paper experiments.
docs/tree-evaluation.md Score-tree evaluation and reporting details.
docs/bfcl-v2-scoring-formula.md BFCL v2 scoring formula notes.

TL;DR

Small language models often learn how to call tools but not when not to call tools. This is especially problematic in low-resource languages, where weak multilingual representations can make models hallucinate unavailable or inappropriate tools.

This project studies that problem on 1B-parameter multilingual models using newly created Vietnamese and Thai BFCL benchmarks. The main finding is that structured reasoning forms - lightweight key-value reasoning schemas inserted during training - substantially improve refusal behavior while preserving tool-calling capability.

Key paper findings:

  • New benchmarks: BFCL-VN and BFCL-TH, Vietnamese and Thai function-calling benchmarks with 3,641 non-multi-turn samples each.
  • Intent-based evaluation: malformed tool-call attempts should not be counted as correct refusals.
  • Structured reasoning forms: explicit supervision for deciding whether a tool should be called.
  • Refusal gains: irrelevance and live hallucination improve by roughly +10 to +30 percentage points.
  • Efficiency: structured reasoning uses 1.77-1.91x fewer reasoning tokens than free-form CoT.
  • Behavioral change: perplexity analysis shows hallucination propensity drops from 67-76% to 1.2-1.3% on irrelevance cases.
  • Distributed evaluation: the paper experiments use distributed inference/evaluation to make full multilingual BFCL evaluation practical.
  • vLLM acceleration: the authors extend the original BFCL-style inference path with a vLLM backend, continuous batching, and tensor parallelism for substantially faster evaluation.

Why This Repository Exists

BFCL evaluates whether models can produce correct function calls. However, production agentic systems also need a different capability: correctly refusing tool calls when:

  • no available tool can solve the user request,
  • the task is answerable without tools,
  • the request requires missing information,
  • using a tool would hallucinate unavailable capabilities.

The original BFCL format-compliance evaluation can overestimate refusal ability. If a model attempts a malformed call like:

Show malformed tool-call example
[get_weather(city='Michigan'

and parsing fails, standard evaluation may see "no parsed tool call" and incorrectly mark it as a correct refusal. This repo adds intent-based evaluation to inspect raw model outputs and detect such malformed tool-call attempts.

Paper Contributions Reflected in Code

This section maps the paper's main ideas to the released benchmark and evaluator. Expand it if you want implementation-level context.

Expand paper-to-code contribution details

1. BFCL-VN and BFCL-TH

The repository contains multilingual BFCL-style data:

data_storage/
β”œβ”€β”€ bfcl_single_turn_en.jsonl
β”œβ”€β”€ bfcl_single_turn_vi.jsonl
β”œβ”€β”€ bfcl_single_turn_th.jsonl
β”œβ”€β”€ data_en/
β”œβ”€β”€ data_vi/
└── data_th/

The paper starts from BFCL v3 and translates the 3,641 non-multi-turn samples into Vietnamese and Thai. Multi-turn and long-context evaluation are outside the paper scope.

Paper evaluation split Samples per language Notes
Simple 550 Non-live tool-calling capability
Multiple 200 Sequential function calls
Parallel 200 Parallel function calls
Parallel-Multiple 200 Mixed parallel/sequential calls
Irrelevance 240 No appropriate tool exists
Live AST 1,351 Real-world tool-calling capability
Live Hallucination 900 Tools cannot solve the task
Total 3,641 Per language: EN, VI, TH

The current repository also includes BFCL v4-style files under data_storage/data_{en,vi,th}/.

2. Intent-Based Evaluation

Intent-based evaluation is implemented through evaluators/relevance_checker.py and used by evaluators/ast_evaluator.py for relevance and irrelevance subsets.

The detector operates on raw model output and looks for tool-call intent even when parsing fails. It checks:

  • explicit tool-call tags such as <tool_call>,
  • structural keyword pairs such as "name" plus "arguments",
  • JSON-like tool-call structures,
  • bracket or array patterns with function-call indicators,
  • direct function-call syntax such as func(arg=value).

The evaluator also rejects incidental matches inside generated Python/code contexts to reduce false positives.

3. Structured Reasoning Forms

The paper trains models to generate a lightweight reasoning form before producing the final action. The form decomposes tool-use decisions into explicit stages:

task_summary: compare recent NVIDIA documents for guidance revision
task_type: multi_intent
ambiguity_level: low
relevant_tools_sorted: []
tool_needed: true
tool_sufficiency: no
blockers: [tool_unavailable, fresh_data]
decision: defer
hallucination_risk: high
why: no tool can access current filings, calls, and analyst notes

The key idea is not simply to add more refusal examples. Instead, the training target makes the decision process explicit:

  • Does the user task require external information?
  • Are any provided tools relevant?
  • Are the available tools sufficient?
  • Is the model at risk of hallucinating a call?
  • Should the model call, defer, clarify, or answer directly?

Main Results from the Paper

Values below are percentages rounded to the nearest integer for readability. AST measures tool-calling capability. Irr measures irrelevance/refusal. H-I is live hallucination under intent-based evaluation. H-S is live hallucination under standard format-compliance evaluation.

Short version: structured reasoning mainly improves refusal and hallucination behavior while keeping AST capability close to the standard fine-tuned models.

Expand full paper result table
Model Lang Baseline AST Baseline Irr Baseline H-I Baseline H-S No-Reasoning AST No-Reasoning Irr No-Reasoning H-I No-Reasoning H-S +Reasoning AST +Reasoning Irr +Reasoning H-I +Reasoning H-S
Llama-3.2-1B EN 9 19 25 53 31 33 28 36 33 52 43 53
Llama-3.2-1B VI 9 9 26 49 29 33 40 42 29 53 49 52
Llama-3.2-1B TH 8 6 22 43 29 29 36 39 28 50 46 51
Gemma-3-1B EN 13 21 37 69 36 50 35 38 35 60 61 65
Gemma-3-1B VI 8 21 45 74 33 33 33 37 30 53 57 61
Gemma-3-1B TH 9 30 45 74 32 25 24 28 31 53 56 61

Important takeaways:

  • Standard fine-tuning improves syntax but can hurt refusal: Gemma-Thai drops from 45% to 24% on live hallucination under intent evaluation.
  • Structured reasoning recovers refusal: Gemma-Thai improves from 24% to 56% live hallucination and from 25% to 53% irrelevance.
  • Tool-calling capability is preserved: AST remains within a few points of the no-reasoning fine-tuned model.

Paper Hyperparameters

This section records the exact experimental configuration used in the paper. The codebase can run other settings, but the reported paper results use the following setup.

These hyperparameters are provided for transparency. The training code, model checkpoints, training datasets, and teacher-generated reasoning traces are not included in this public release.

Models

Role Model
Evaluated model meta-llama/Llama-3.2-1B-Instruct
Evaluated model google/gemma-3-1b-it
Reasoning-form teacher Qwen3-Next-80B-A3B-Instruct
Expand training mixture, variants, chat templates, and evaluation hyperparameters

Training data

The fine-tuning set contains 50,863 unique examples from seven function-calling/tool-use sources.

Source Examples Share
IBM ToolRM 30,020 59.02%
Argilla Synth-APIGen 12,322 24.23%
NVIDIA Nemotron-FC-v1 4,344 8.54%
Glaive Function Calling v1 1,884 3.70%
NVIDIA When2Call SFT 1,249 2.46%
xLAM Irrelevance 976 1.92%
Hermes FC v1 68 0.13%

Only 4.38% of training examples explicitly include irrelevance cases; 95.62% are positive tool-use examples.

The actual training datasets and teacher-generated reasoning traces are not released due to company policy. The following synthetic conversational instance illustrates the structure of a reasoning-form training example without exposing any non-public training record:

{
  "tools": [
    {
      "name": "search_database",
      "description": "Search an internal company database.",
      "parameters": {
        "type": "object",
        "properties": {
          "query": {"type": "string"}
        },
        "required": ["query"]
      }
    },
    {
      "name": "send_email",
      "description": "Send an email to a recipient.",
      "parameters": {
        "type": "object",
        "properties": {
          "to": {"type": "string"},
          "body": {"type": "string"}
        },
        "required": ["to", "body"]
      }
    }
  ],
  "messages": [
    {
      "role": "user",
      "content": "What is the current weather in Michigan?"
    },
    {
      "role": "assistant",
      "content": "task_summary: answer current weather in Michigan\ntask_type: lookup\nambiguity_level: low\nrelevant_tools_sorted: []\ntool_needed: true\ntool_sufficiency: no\nblockers: [tool_unavailable, fresh_data]\ndecision: defer\nhallucination_risk: high\nwhy: no available tool can retrieve live weather data\n\nI do not have access to a weather tool or live external data in the provided tool set, so I cannot retrieve the current weather in Michigan."
    }
  ]
}

Fine-tuning hyperparameters

Hyperparameter Value
Method LoRA
LoRA rank r 32
LoRA alpha 64
Epochs 2
Learning rate 8e-5
Global batch size 32
Maximum sequence length 2048 tokens
Training hardware 2 NVIDIA H100 GPUs

Model variants

Variant Description
Baseline Pretrained instruct model, zero-shot.
No-Reasoning Standard function-calling fine-tuning.
CoT Reasoning Free-form chain-of-thought prefixes generated by Qwen3-Next-80B-A3B-Instruct on the same 50,863 examples.
Structured Reasoning Key-value reasoning forms generated by Qwen3-Next-80B-A3B-Instruct and prepended before the final action.
Randomized Reasoning Structured form with randomized decision fields for ablation.

For the structured and CoT variants, reasoning text is generated in English. Tools and reasoning forms remain in English across EN, VI, and TH; only user queries are translated.

Fine-tuning chat templates

For the fine-tuning experiments, we modified the original Gemma 3 and Llama 3.2 chat templates to support BFCL multiple and parallel tool calling. The modification keeps each model family's original conversational tokens, but injects Qwen-style tool sections:

  • Tool definitions are rendered inside <tools></tools>.
  • Tool calls are rendered as one or more <tool_call></tool_call> blocks.
  • Tool outputs are rendered inside <tool_response></tool_response>.

This is important because the original Gemma 3 chat template does not provide a native tool-call format, while the Llama 3.2 native tool path does not reliably support BFCL multiple/parallel calls. These templates were used for training-time formatting of the fine-tuned variants; the released repository focuses on benchmark and evaluation artifacts.

Gemma 3 fine-tuning chat template
{%- macro render_content(content) -%}
    {%- if content is none or content is undefined -%}
        {{- "" -}}
    {%- elif content is string -%}
        {{- content | trim -}}
    {%- elif content is iterable -%}
        {%- for item in content -%}
            {%- if item['type'] == 'image' -%}
                {{- '<start_of_image>' -}}
            {%- elif item['type'] == 'text' -%}
                {{- item['text'] | trim -}}
            {%- endif -%}
        {%- endfor -%}
    {%- else -%}
        {{- raise_exception("Invalid content type") -}}
    {%- endif -%}
{%- endmacro -%}
{{ bos_token }}
{%- if messages and messages[0]['role'] == 'system' -%}
    {%- set first_system = messages[0]['content'] -%}
    {%- set loop_messages = messages[1:] -%}
{%- else -%}
    {%- set first_system = "" -%}
    {%- set loop_messages = messages -%}
{%- endif -%}
{%- set has_tools = (tools is defined and tools) -%}
{%- if has_tools or first_system -%}
    {{- '<start_of_turn>system\n' -}}
    {%- if has_tools -%}
        {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n" -}}
        {{- "If no tool call is needed, respond normally without any <tool_call> tags.\n\n" -}}
        {{- "You are provided with function signatures within <tools></tools> XML tags:\n<tools>" -}}
        {%- for tool in tools -%}
            {{- "\n" -}}{{- tool | tojson -}}
        {%- endfor -%}
        {{- "\n</tools>\n\n" -}}
        {{- "For each function call, return a JSON object with function name and arguments within <tool_call></tool_call> XML tags:\n" -}}
        {{- "<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call>\n" -}}
        {{- "You may emit multiple <tool_call> blocks in a single assistant turn.\n" -}}
        {%- if first_system -%}
            {{- "\n" -}}
        {%- endif -%}
    {%- endif -%}
    {%- if first_system -%}
        {{- render_content(first_system) -}}
    {%- endif -%}
    {{- '<end_of_turn>\n' -}}
{%- endif -%}
{%- for message in loop_messages -%}
    {%- if message['role'] == 'system' -%}
        {{- '<start_of_turn>system\n' -}}
        {{- render_content(message['content']) -}}
        {{- '<end_of_turn>\n' -}}
    {%- elif message['role'] == 'tool' -%}
        {{- '<start_of_turn>tool\n' -}}
        {{- '<tool_response>\n' -}}
        {%- if message['content'] is string -%}
            {{- message['content'] | trim -}}
        {%- else -%}
            {{- message['content'] | tojson -}}
        {%- endif -%}
        {{- '\n</tool_response>' -}}
        {{- '<end_of_turn>\n' -}}
    {%- else -%}
        {%- set role = message['role'] -%}
        {%- if message['role'] == 'assistant' -%}
            {%- set role = 'model' -%}
        {%- endif -%}
        {{- '<start_of_turn>' + role + '\n' -}}
        {{- render_content(message['content']) -}}
        {%- if message['role'] == 'assistant' and message.tool_calls -%}
            {%- set content_has_text = false -%}
            {%- if message['content'] is string -%}
                {%- set content_has_text = (message['content'] | trim) != '' -%}
            {%- elif message['content'] is iterable -%}
                {%- set content_has_text = (message['content'] | length) > 0 -%}
            {%- endif -%}
            {%- for tool_call in message.tool_calls -%}
                {%- if (loop.first and content_has_text) or (not loop.first) -%}
                    {{- '\n' -}}
                {%- endif -%}
                {%- if tool_call.function -%}
                    {%- set tool_call = tool_call.function -%}
                {%- endif -%}
                {{- '<tool_call>\n{\"name\": \"' -}}
                {{- tool_call.name -}}
                {{- '\", \"arguments\": ' -}}
                {%- if tool_call.arguments is string -%}
                    {{- tool_call.arguments -}}
                {%- else -%}
                    {{- tool_call.arguments | tojson -}}
                {%- endif -%}
                {{- '}\n</tool_call>' -}}
            {%- endfor -%}
        {%- endif -%}
        {{- '<end_of_turn>\n' -}}
    {%- endif -%}
{%- endfor -%}
{%- if add_generation_prompt -%}
    {{- '<start_of_turn>model\n' -}}
{%- endif -%}
Llama 3.2 fine-tuning chat template
{{- bos_token }}
{%- if custom_tools is defined %}
    {%- set tools = custom_tools %}
{%- endif %}
{%- if not tools_in_user_message is defined %}
    {%- set tools_in_user_message = true %}
{%- endif %}
{%- if not date_string is defined %}
    {%- if strftime_now is defined %}
        {%- set date_string = strftime_now("%d %b %Y") %}
    {%- else %}
        {%- set date_string = "26 Jul 2024" %}
    {%- endif %}
{%- endif %}
{%- if not tools is defined %}
    {%- set tools = none %}
{%- endif %}
{%- if messages[0]['role'] == 'system' %}
    {%- set system_message = messages[0]['content']|trim %}
    {%- set messages = messages[1:] %}
{%- else %}
    {%- set system_message = "" %}
{%- endif %}
{{- "<|start_header_id|>system<|end_header_id|>\n\n" }}
{%- if tools is not none %}
    {{- "Environment: ipython\n" }}
{%- endif %}
{{- "Cutting Knowledge Date: December 2023\n" }}
{{- "Today Date: " + date_string + "\n\n" }}
{%- if tools is not none and not tools_in_user_message %}
    {{- "You may call one or more functions to assist with the user query.\n\n" }}
    {{- "Function signatures are provided within <tools></tools>:\n<tools>" }}
    {%- for t in tools %}
        {{- "\n" + (t | tojson(indent=4)) }}
    {%- endfor %}
    {{- "\n</tools>\n\n" }}
    {{- "For each function call, return a JSON object inside <tool_call> tags:\n" }}
    {{- "<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call>\n" }}
    {{- "You may emit multiple <tool_call> blocks in a single assistant turn.\n" }}
    {{- "Do not use variables.\n\n" }}
{%- endif %}
{{- system_message }}
{{- "<|eot_id|>" }}
{%- if tools_in_user_message and not tools is none %}
    {%- if messages | length != 0 %}
        {%- set first_user_message = messages[0]['content']|trim %}
        {%- set messages = messages[1:] %}
    {%- else %}
        {{- raise_exception("Cannot put tools in the first user message when there's no first user message!") }}
    {%- endif %}
    {{- '<|start_header_id|>user<|end_header_id|>\n\n' -}}
    {{- "Given the following functions, you may call one or more to answer the prompt.\n\n" }}
    {{- "Function signatures are provided within <tools></tools>:\n<tools>" }}
    {%- for t in tools %}
        {{- "\n" + (t | tojson(indent=4)) }}
    {%- endfor %}
    {{- "\n</tools>\n\n" }}
    {{- "For each function call, return a JSON object inside <tool_call> tags:\n" }}
    {{- "<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call>\n" }}
    {{- "You may emit multiple <tool_call> blocks in a single assistant turn.\n" }}
    {{- "Do not use variables.\n\n" }}
    {{- first_user_message + "<|eot_id|>"}}
{%- endif %}
{%- for message in messages %}
    {%- if message.role == "tool" or message.role == "ipython" %}
        {%- if loop.first or (messages[loop.index0 - 1].role != "tool" and messages[loop.index0 - 1].role != "ipython") %}
            {{- "<|start_header_id|>ipython<|end_header_id|>\n\n" }}
        {%- endif %}
        {{- "<tool_response>\n" }}
        {%- if message.content is mapping or message.content is iterable %}
            {{- message.content | tojson }}
        {%- else %}
            {{- message.content }}
        {%- endif %}
        {{- "\n</tool_response>" }}
        {%- if loop.last or (messages[loop.index0 + 1].role != "tool" and messages[loop.index0 + 1].role != "ipython") %}
            {{- "<|eot_id|>" }}
        {%- endif %}
    {%- elif 'tool_calls' in message %}
        {%- set content = message['content'] if message['content'] is string else "" -%}
        {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' -}}
        {%- if content | trim %}
            {{- content | trim }}
        {%- endif %}
        {%- if message.tool_calls %}
            {%- for tool_call in message.tool_calls %}
                {%- if (loop.first and content | trim) or (not loop.first) %}
                    {{- '\n' }}
                {%- endif %}
                {%- if tool_call.function %}
                    {%- set tool_call = tool_call.function %}
                {%- endif %}
                {{- "<tool_call>\n{\"name\": \"" }}
                {{- tool_call.name }}
                {{- "\", \"arguments\": " }}
                {%- if tool_call.arguments is string %}
                    {{- tool_call.arguments }}
                {%- else %}
                    {{- tool_call.arguments | tojson }}
                {%- endif %}
                {{- "}\n</tool_call>" }}
            {%- endfor %}
        {%- endif %}
        {{- "<|eot_id|>" }}
    {%- else %}
        {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n' + message['content'] | trim + '<|eot_id|>' }}
    {%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
    {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }}
{%- endif %}

Evaluation hyperparameters

Setting Value
Evaluation mode Distributed inference/evaluation
Recommended backend vllm
Decoding Greedy
Temperature Ο„ 0
Maximum generation length 2048 tokens
Evaluated languages EN, VI, TH
Evaluated BFCL scope Single-turn non-multi-turn BFCL v3 subsets
Capability metric Standard BFCL format/AST evaluation
Refusal metrics Intent-based Irrelevance and Live Hallucination
Live hallucination reporting Both intent-based H-I and standard H-S are reported

The paper evaluation uses distributed inference to reduce wall-clock time. In this repository, the vLLM backend adds continuous batching and tensor parallelism on top of the original BFCL-style evaluation flow.

The authors also optimized the inference/evaluation code for benchmark throughput beyond a single paper setting. The same code path can run many BFCL subsets, multiple languages, and multiple BFCL score-tree versions (v2, v3, and v4). However, the paper analysis focuses on the subsets most relevant to tool-call hallucination and refusal behavior: irrelevance, live hallucination, and the AST capability subsets needed to verify that refusal gains do not come from losing tool-calling ability.

Repository Layout

The primary user-facing entrypoints are eval.py, data_storage/, evaluators/, backends/, and docs/.

Show repository layout tree
bfcl-vn-th-intent-evaluation/
β”œβ”€β”€ README.md                       # Project overview and documentation index
β”œβ”€β”€ docs/                           # Supporting documentation moved out of root
β”‚   β”œβ”€β”€ bfcl-v2-scoring-formula.md
β”‚   β”œβ”€β”€ eval-usage.md
β”‚   β”œβ”€β”€ translation-middleware-guide.md
β”‚   └── tree-evaluation.md
β”œβ”€β”€ eval.py                         # Main custom evaluation entrypoint
β”œβ”€β”€ eval_with_bfcl_eval.py           # Wrapper around official BFCL evaluator
β”œβ”€β”€ eval_with_sglang.py              # SGLang-oriented evaluation path
β”œβ”€β”€ config.py                        # Evaluation configuration dataclass
β”œβ”€β”€ cli.py                           # Shared CLI/config utilities
β”œβ”€β”€ dataloader.py                    # BFCL multilingual dataset loader
β”œβ”€β”€ tool_call_parser.py              # Universal parser for model tool-call outputs
β”œβ”€β”€ translation_middleware.py        # Optional translation middleware; not used in current paper experiments
β”œβ”€β”€ model_loader.py                  # HF/LoRA model loading utilities
β”œβ”€β”€ gorilla_multiturn_handler.py     # BFCL/Gorilla multi-turn adapter
β”œβ”€β”€ backends/
β”‚   β”œβ”€β”€ base.py
β”‚   β”œβ”€β”€ transformers_backend.py
β”‚   └── vllm_backend.py
β”œβ”€β”€ evaluators/
β”‚   β”œβ”€β”€ ast_evaluator.py             # BFCL AST checker integration
β”‚   β”œβ”€β”€ relevance_checker.py         # Intent-based relevance/refusal evaluator
β”‚   └── result_exporter.py
β”œβ”€β”€ scoring/
β”‚   β”œβ”€β”€ metrics.py
β”‚   β”œβ”€β”€ tree_builder.py
β”‚   β”œβ”€β”€ tree_calculator.py
β”‚   └── tree_exporter.py
β”œβ”€β”€ data_storage/
β”‚   β”œβ”€β”€ bfcl_single_turn_en.jsonl
β”‚   β”œβ”€β”€ bfcl_single_turn_vi.jsonl
β”‚   β”œβ”€β”€ bfcl_single_turn_th.jsonl
β”‚   β”œβ”€β”€ data_en/
β”‚   β”œβ”€β”€ data_vi/
β”‚   └── data_th/
└── gorilla/
    └── berkeley-function-call-leaderboard/

Installation

Create an environment and install the dependencies:

Show installation command
pip install -r requirements.txt

Use PyTorch and vLLM builds compatible with your CUDA/runtime environment.

Distributed Inference and Evaluation

The README intentionally documents distributed evaluation as the primary usage path. The authors optimized this inference path to make large benchmark runs practical across many subsets, languages, and BFCL versions. The paper experiments evaluate full English, Vietnamese, and Thai benchmarks with distributed inference to reduce wall-clock time.

The recommended entrypoint is eval.py with the vLLM backend:

  • --backend vllm enables the custom high-throughput inference path.
  • --vllm-tensor-parallel-size shards large models across GPUs.
  • --vllm-max-num-seqs controls vLLM continuous batching.
  • --vllm-enable-chunked-prefill improves memory efficiency for long prompts.

Compared with the original BFCL-style inference path, this repository adds a vLLM backend with continuous batching, tensor parallelism, and project-local multilingual/intent-aware reporting.

Expand ready-to-run distributed evaluation commands

Distributed refusal evaluation with vLLM

Paper refusal metrics use irrelevance and live_irrelevance.

CUDA_VISIBLE_DEVICES=0,1 python eval.py \
    --model meta-llama/Llama-3.2-1B-Instruct \
    --subset irrelevance live_irrelevance \
    --language en vi th \
    --backend vllm \
    --vllm-tensor-parallel-size 2 \
    --vllm-gpu-memory-utilization 0.90 \
    --vllm-max-num-seqs 512 \
    --bfcl-version v3 \
    --skip-multi-turn \
    --temperature 0 \
    --max-new-tokens 2048 \
    --output-dir ./eval_results/llama_distributed_refusal_vllm

Distributed tool-calling capability evaluation with vLLM

Paper capability metrics use the non-live AST subsets plus live AST subsets.

CUDA_VISIBLE_DEVICES=0,1 python eval.py \
    --model google/gemma-3-1b-it \
    --subset simple_python simple_javascript simple_java multiple parallel parallel_multiple live_simple live_relevance live_multiple live_parallel live_parallel_multiple \
    --language en vi th \
    --backend vllm \
    --vllm-tensor-parallel-size 2 \
    --vllm-gpu-memory-utilization 0.90 \
    --vllm-max-num-seqs 512 \
    --bfcl-version v3 \
    --skip-multi-turn \
    --temperature 0 \
    --max-new-tokens 2048 \
    --output-dir ./eval_results/gemma_distributed_ast_vllm

Distributed Transformers fallback

Use the Transformers backend with torchrun only when vLLM is unavailable or for backend-specific compatibility checks.

CUDA_VISIBLE_DEVICES=0,1 torchrun --nproc_per_node=2 --master_port=29500 eval.py \
    --model meta-llama/Llama-3.2-1B-Instruct \
    --subset irrelevance live_irrelevance \
    --language en vi th \
    --backend transformers \
    --batch-size 8 \
    --bfcl-version v3 \
    --skip-multi-turn \
    --temperature 0 \
    --max-new-tokens 2048 \
    --output-dir ./eval_results/llama_distributed_refusal_transformers

Official BFCL Wrapper

eval_with_bfcl_eval.py wraps the official bfcl_eval CLI for compatibility checks, but it is not the primary path used for the paper results. Use eval.py for distributed multilingual evaluation, vLLM acceleration, and intent-based refusal metrics.

Use this wrapper when you specifically want the standard BFCL checker, i.e. the non-strict format-compliance path used for H-S reporting. This path checks the parsed BFCL output and does not apply the stricter raw-response intent detector from evaluators/relevance_checker.py.

Expand official BFCL wrapper command
python eval_with_bfcl_eval.py run \
    --model MODEL_REGISTERED_IN_BFCL \
    --subset live_irrelevance \
    --language en vi th \
    --backend vllm \
    --num-gpus 2 \
    --bfcl-version v3

For refusal subsets, this standard BFCL path can count malformed tool-call attempts as correct refusals when parsing fails. Use eval.py when you want the stricter intent-based refusal metric used for H-I.

Data Format

Single-turn JSONL entries follow BFCL-style structure:

Show BFCL-style JSONL record example
{
  "id": "irrelevance_1_th",
  "subset": "irrelevance",
  "language": "th",
  "test_category": "irrelevance",
  "question": [[{"role": "user", "content": "..."}]],
  "function": [
    {
      "name": "search_database",
      "description": "Search internal database",
      "parameters": {
        "type": "object",
        "properties": {
          "query": {"type": "string"}
        }
      }
    }
  ],
  "ground_truth": []
}

For refusal subsets, the expected output may be empty because the model should not call any function.

Output Files

Evaluation outputs are written under --output-dir, typically including:

Expand evaluation output file structure
eval_results/
β”œβ”€β”€ config.yaml
β”œβ”€β”€ console_output.txt
β”œβ”€β”€ metrics.json
β”œβ”€β”€ summary.csv
β”œβ”€β”€ score_tree_all.json
β”œβ”€β”€ score_tree_en.json
β”œβ”€β”€ score_tree_vi.json
β”œβ”€β”€ score_tree_th.json
└── per_subset/

Each result entry can include:

  • raw_input_text: prompt after chat template/tool injection,
  • raw_output: raw model generation before parsing,
  • prediction or parsed_prediction: parsed tool calls in BFCL format,
  • ground_truth: expected BFCL answer,
  • accuracy: sample-level score,
  • ast_result: detailed AST or relevance/refusal validation result,
  • error: evaluation error if any.

Important Evaluation Notes

Intent-based metrics are stricter than standard BFCL refusal metrics

For irrelevance and live hallucination, this repository checks raw responses for tool-call intent. A malformed attempted call is treated as a refusal failure, not a correct refusal.

If you need the non-strict standard BFCL checker instead, use eval_with_bfcl_eval.py. That path reports format-compliance behavior and is useful for reproducing H-S style numbers.

This is why numbers may be lower than official format-compliance scores. In the paper, standard evaluation inflated Gemma-3-1B live hallucination scores by roughly 29-32 percentage points:

Language Standard Intent-based Gap
EN 69.44 37.22 32.22pp
VI 73.78 44.56 29.22pp
TH 74.11 45.33 28.78pp

Capability and refusal are different metrics

Do not evaluate a tool-use model only on AST/tool-call accuracy. A model can improve AST by learning syntax while becoming more likely to hallucinate unavailable tools. For agentic IR systems, report both:

  • capability: simple, multiple, parallel, live AST,
  • refusal: irrelevance and live hallucination under intent-based evaluation.

Paper hyperparameters are fixed for reported numbers

The evaluation pipeline itself is model-agnostic and can evaluate any Hugging Face or local checkpoint that follows a supported chat/tool-call format. However, to reproduce the paper numbers, use the models, training variants, decoding settings, and BFCL subset scope listed in Paper Hyperparameters.

Distributed CLI Reference

This section is for users who want full CLI control after understanding the benchmark summary and basic evaluation path.

Expand full distributed CLI options and chat-template arguments

Most frequently used distributed options:

CUDA_VISIBLE_DEVICES=0,1 python eval.py \
    --model MODEL_OR_PATH \
    --subset irrelevance live_irrelevance simple_python simple_javascript simple_java multiple parallel parallel_multiple live_simple live_relevance live_multiple live_parallel live_parallel_multiple \
    --language en vi th \
    --data-dir ./data_storage \
    --backend vllm \
    --vllm-tensor-parallel-size 2 \
    --vllm-gpu-memory-utilization 0.90 \
    --vllm-max-num-seqs 512 \
    --bfcl-version v3 \
    --skip-multi-turn \
    --temperature 0 \
    --max-new-tokens 2048 \
    --output-dir ./eval_results/run_name

Useful flags:

  • --model: Hugging Face model name or local checkpoint path.
  • --base-model and --lora-path: evaluate LoRA fine-tuned models.
  • --subset: BFCL subsets to evaluate.
  • --language: one or more of en, vi, th.
  • --backend: use vllm for the paper-style distributed evaluation path; transformers is mainly a fallback.
  • --vllm-tensor-parallel-size: number of GPUs used by vLLM tensor parallelism.
  • --vllm-max-num-seqs: maximum concurrent sequences for continuous batching.
  • --vllm-gpu-memory-utilization: target GPU memory utilization for vLLM.
  • --bfcl-version: scoring tree version, one of v2, v3, v4.
  • --include-multi-turn: include multi-turn BFCL subsets.
  • --skip-multi-turn: explicitly skip multi-turn samples.

Tool chat-template arguments

Tool-calling models do not share a single chat-template convention. These flags control how tool definitions are inserted into the prompt before distributed inference.

Argument Meaning When to use
--force-native-tools Forces the tokenizer's native apply_chat_template(..., tools=...) path. Use only when the model/tokenizer natively supports tool definitions and the native template can represent the required tool-call format.
--force-injected-tools Bypasses native tool handling and injects tool definitions into the system prompt. Use for models whose tokenizer/chat template does not natively support tool calls. This is important for Gemma-style models, because the original Gemma chat template does not provide a native tool-call template.
--force-thai-llama-template Forces the project-specific Pythonic tool-call template originally added for Thai Llama 3.2 experiments. Use for Llama 3.x cases where the native template cannot reliably represent BFCL multiple or parallel tool calls. Llama 3 chat templates often support tool use through a model-specific path but do not robustly support multiple/parallel BFCL calls, so this flag can force a compatible injected/Pythonic format.
Injected system prompt for instruction-following models without full native tool-call support

This prompt is useful for strong instruction-following models whose capabilities can transfer directly to tool calling, but whose chat templates do not fully support native tool calls in the way Qwen3-family templates do. It is the conceptual prompt style used by --force-injected-tools.

# Tools

You may call one or more functions to assist with the user query.
If no tool call is needed, respond normally without any <tool_call> tags.

You are provided with function signatures within <tools></tools> XML tags:
<tools>
{tool_schema_json}
</tools>

For each function call, return a JSON object with function name and arguments within <tool_call></tool_call> XML tags:
<tool_call>
{"name": <function-name>, "arguments": <args-json-object>}
</tool_call>

You may emit multiple <tool_call> blocks in a single assistant turn.

Recommended usage:

  • Gemma / Gemma-3: use --force-injected-tools when native tool calls fail or when the model has no native tool-call chat template. This rewrites the tool specification into the system prompt instead of relying on tokenizer-native tools.
  • Llama 3 / Llama 3.2: use --force-thai-llama-template for BFCL multiple/parallel-call evaluation if the native Llama template emits only single-call or incompatible tool-call syntax.
  • Models with complete native tool support: use --force-native-tools only if you have verified that the tokenizer template supports both tool definitions and the required parallel/multiple function-call format.

Translation Middleware

The repository includes an optional translation middleware in translation_middleware.py and corresponding CLI options.

The current paper experiments do not use this middleware. The paper results are evaluated directly on the prepared English, Vietnamese, and Thai benchmark data.

Supported translation modes include direct sequence-to-sequence models and generic chat models. Detailed middleware examples are intentionally kept outside the README; see docs/translation-middleware-guide.md for optional usage details.

Key Modules

  • tool_call_parser.py: universal parser for Qwen, Phi, Nemotron, Llama, Mistral, Hermes, BFCL-native, JSON, and Python-call-like outputs.
  • evaluators/relevance_checker.py: detects raw tool-call intent and evaluates relevance/irrelevance cases.
  • evaluators/ast_evaluator.py: routes standard BFCL AST checks and refusal-specific checks.
  • dataloader.py: loads single-turn JSONL and BFCL v4-style multi-turn data.
  • backends/: inference abstraction for Transformers and vLLM.
  • scoring/: tree-based score calculation and reporting.
  • eval_with_bfcl_eval.py: bridge to the official BFCL evaluator.

License and Usage Notes

This public release is derived from BFCL-style benchmark organization and includes project-specific multilingual benchmark data and evaluation utilities. No standalone license file is included in this repository snapshot.

Before redistribution or commercial use, please review the upstream BFCL/Gorilla terms and any applicable terms of the underlying benchmark sources. For questions about permitted use, benchmark interpretation, or release scope, contact dung.vpt@qualgo.net.

Citation

If you use this code or benchmark, please cite:

Show BibTeX citation
@inproceedings{vo2026teaching,
  title = {Teaching Small Models When Not to Call Functions: Structured Reasoning for Tool Refusal in Low-Resource Languages},
  author = {Vo, Dung Pham Tuan and Tran, Thai Trung and Semwal, Tushar},
  booktitle = {Proceedings of the 49th International ACM SIGIR Conference on Research and Development in Information Retrieval (SIGIR '26)},
  year = {2026},
  location = {Melbourne, VIC, Australia},
  publisher = {ACM},
  doi = {10.1145/3805712.3809979},
  isbn = {979-8-4007-2599-9/2026/07}
}

Links

Contact

For questions about the paper, benchmarks, evaluation setup, or any issue with this release, please contact dung.vpt@qualgo.net.

Downloads last month
16