LLM Tool Calling 최적화 프레임워크: 언제 도구를 호출할 것인가
To Call or Not to Call: A Framework to Assess and Optimize LLM Tool Calling
TL;DR Highlight
LLM이 웹 검색 같은 외부 도구를 언제 써야 하는지 잘못 판단하고 있으며, 모델 내부 hidden state로 이를 교정할 수 있다.
Who Should Read
에이전트 파이프라인에서 웹 검색이나 외부 API 호출 타이밍을 고민하는 백엔드/AI 개발자. RAG 시스템에서 검색 비용 대비 효과를 최적화하려는 팀.
Core Mechanics
- tool calling 결정을 Necessity(필요성), Utility(유용성), Affordability(비용 대비 효과) 세 가지 차원으로 분해하는 평가 프레임워크를 제시한다.
- 모델이 스스로 판단하는 '도구 필요 여부(Perceived Need)'와 실제로 도구가 필요한지(True Need)가 자주 어긋난다 — Mistral은 필요 이상으로 도구를 안 부르고, Qwen3-IT와 Gemma3는 거의 항상 도구를 호출한다.
- 도구를 항상 쓰는 것(ALWAYS TOOL)이 최선이 아니다 — NO TOOL 성능이 이미 높을 때 도구를 쓰면 오히려 factuality(사실 정확도)가 34%의 케이스에서 떨어진다.
- 모델이 자율 결정(SELF-DECISION)하면 OPTIMAL(오라클) 대비 성능 차이가 크다 — GPT-OSS-120B 기준 0.73 vs 0.83, Llama3.2-3B 기준 0.74 vs 0.87.
- 모델의 마지막 토큰 hidden state(내부 표현값)로 학습한 경량 MLP 분류기(LNE/LUE)가 모델의 자체 판단보다 도구 필요 여부를 더 정확하게 예측한다.
- 예산 제약 상황에서 모든 모델이 비용 지시를 무시하고 budget을 초과하는 경향이 있으며, 특히 Gemma3와 Qwen3-IT는 1회 호출 비용이 $50 이상이어도 도구를 계속 호출한다.
Evidence
- Entity Task에서 OPTIMAL 전략은 SELF-DECISION 대비 더 적은 호출로 더 높은 성능을 낸다 — Llama3.2-3B-IT 기준 SELF-DECISION 0.74(340회) vs OPTIMAL 0.87(249회), 13포인트 차이.
- NO TOOL 성능이 High일 때 도구를 강제 사용하면 34%의 케이스(52/152)에서 성능이 하락하며, True Need 구간에서는 51%의 케이스에서 성능이 개선된다.
- LNE(Latent Need Estimator)는 entity task에서 모든 모델에 걸쳐 Perceived Need 대비 need 예측 정확도를 일관되게 향상시키며, 도구 호출 수를 줄이면서 factuality를 높인다 — GPT-OSS-120B 기준 LNE 0.78(351회) vs SELF-DECISION 0.73(152회).
- InvivoQuery task에서 SELF-DECISION이 NO TOOL보다 오히려 낮은 경우도 발생 — Qwen3-30B-IT SELF-DECISION 0.26 vs NO TOOL 0.46, Qwen3-30B-A3B SELF-DECISION 0.41 vs NO TOOL 0.58.
How to Apply
- 에이전트가 도구를 호출하기 전에 'NO TOOL로 돌렸을 때 성능이 낮은가(True Need)'를 판단하는 별도 MLP 분류기를 붙여볼 수 있다 — 모델의 마지막 레이어 hidden state를 feature로 쓰고, scikit-learn MLPClassifier로 5-fold cross-validation으로 학습하면 된다.
- API 비용 예산이 제한된 서비스라면 ALWAYS TOOL 대신 LNE 예측 확률로 쿼리를 랭킹한 뒤 top-K 케이스에만 도구를 호출하는 budget-aware 전략으로 바꾸면 같은 비용으로 더 높은 utility gain을 얻을 수 있다.
- 새로운 모델을 도입할 때 NO TOOL / ALWAYS TOOL / SELF-DECISION 세 가지 모드로 동일 데이터셋을 돌려서 '모델이 실제로 도구 호출로 이득을 보는 케이스가 몇 %인지' 먼저 측정하면, 도구 호출 정책 설계에 필요한 기준선을 잡을 수 있다.
Code Example
# LNE(Latent Need Estimator) 핵심 구현 스케치
# 1. hidden state 추출
from transformers import AutoModel, AutoTokenizer
import torch
import numpy as np
model_name = "meta-llama/Llama-3.2-3B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name, output_hidden_states=True)
def get_last_token_hidden_state(prompt: str, layer: int = -1):
inputs = tokenizer(prompt, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
# 마지막 토큰의 특정 레이어 hidden state 추출
hidden = outputs.hidden_states[layer] # (batch, seq_len, hidden_dim)
return hidden[0, -1, :].cpu().numpy() # 마지막 토큰
# 2. NO TOOL 세팅에서 각 쿼리별 hidden state 수집
prompts = [
"In a paragraph, could you tell me what you know about {entity}?",
# ... 500개 쿼리
]
X = np.array([get_last_token_hidden_state(p) for p in prompts])
# 3. True Need 레이블 생성 (NO TOOL 성능 < threshold -> 1)
# factuality_no_tool: 각 쿼리의 NO TOOL factuality score
threshold = 0.9
y_need = (factuality_no_tool < threshold).astype(int)
# 4. MLP 분류기 학습 (5-fold CV)
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import Pipeline
pipeline = Pipeline([
('scaler', StandardScaler()),
('clf', MLPClassifier(
hidden_layer_sizes=(128, 64),
learning_rate_init=1e-3,
max_iter=100,
early_stopping=True,
n_iter_no_change=5,
random_state=42
))
])
# 5. 예측 확률로 top-K 선택 (budget-aware)
probs = pipeline.predict_proba(X)[:, 1] # 도구 필요 확률
BUDGET_K = 250 # 전체 500개 중 250개만 도구 호출
top_k_indices = np.argsort(probs)[::-1][:BUDGET_K]
print(f"Top-{BUDGET_K} queries selected for tool calling")Terminology
관련 논문
adamsreview: Claude Code용 멀티 에이전트 PR 코드 리뷰 파이프라인
Claude Code에서 최대 7개의 병렬 서브 에이전트가 각각 다른 관점으로 PR을 리뷰하고, 자동 수정까지 해주는 오픈소스 플러그인이다. 기존 /review나 CodeRabbit보다 실제 버그를 더 많이 잡는다고 주장하지만 커뮤니티에서는 복잡도와 실효성에 대한 회의론도 나왔다.
Claude를 User Space IP Stack으로 써서 Ping에 응답시키면 얼마나 빠를까?
Claude Code에게 IP 패킷을 직접 파싱하고 ICMP echo reply를 구성하도록 시켜서 실제로 ping에 응답하게 만든 실험으로, 'Markdown이 곧 코드이고 LLM이 프로세서'라는 아이디어를 네트워크 스택 수준까지 밀어붙인 재미있는 사례다.
AI Agent를 위한 Git: re_gent
AI 코딩 에이전트(Claude Code 등)가 수행한 모든 툴 호출을 자동으로 추적하고, 어떤 프롬프트가 어느 코드 줄을 작성했는지 blame까지 가능한 버전 관리 도구다.
Agent-Native CLI를 위한 설계 원칙 10가지
AI 에이전트가 CLI 도구를 더 잘 사용할 수 있도록 설계하는 원칙들을 정리한 글로, 에이전트가 CLI를 도구로 활용하는 빈도가 높아지면서 이 설계 방식이 실용적으로 중요해지고 있다.
Agent-harness-kit: MCP 기반 멀티 에이전트 워크플로우 오케스트레이션 프레임워크
여러 AI 에이전트가 서로 역할을 나눠 협업할 수 있도록 조율하는 scaffolding 도구로, Vite처럼 설정 없이 빠르게 멀티 에이전트 파이프라인을 구성할 수 있다.
Tilde.run – AI Agent를 위한 트랜잭션 기반 버전 관리 파일시스템 샌드박스
AI 에이전트가 실제 프로덕션 데이터를 건드려도 롤백할 수 있는 격리된 샌드박스 환경을 제공하는 도구로, GitHub/S3/Google Drive를 하나의 버전 관리 파일시스템으로 묶어준다.
Related Resources
Original Abstract (Expand)
Agentic AI architectures augment LLMs with external tools, unlocking strong capabilities. However, tool use is not always beneficial; some calls may be redundant or even harmful. Effective tool use, therefore, hinges on a core LLM decision: whether to call or not call a tool, when performing a task. This decision is particularly challenging for web search tools, where the benefits of external information depend on the model's internal knowledge and its ability to integrate potentially noisy tool responses. We introduce a principled framework inspired by decision-making theory to evaluate web search tool-use decisions along three key factors: necessity, utility, and affordability. Our analysis combines two complementary lenses: a normative perspective that infers true need and utility from an optimal allocation of tool calls, and a descriptive perspective that infers the model's self-perceived need and utility from their observed behaviors. We find that models' perceived need and utility of tool calls are often misaligned with their true need and utility. Building on this framework, we train lightweight estimators of need and utility based on models' hidden states. Our estimators enable simple controllers that can improve decision quality and lead to stronger task performance than the self-perceived set up across three tasks and six models.