[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,94 +2,186 @@
|
||||
id: wiki-2026-0508-tool-usage-optimization
|
||||
title: Tool Usage Optimization
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-TUOP-001]
|
||||
aliases: [Function Calling, Tool Use, Agent Tools]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [auto-reinforced, tool-usage, Optimization, Efficiency, workflows, Human-Computer-Interaction]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [llm, tool-use, function-calling, agentic]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: Python
|
||||
framework: Anthropic SDK / OpenAI SDK / MCP
|
||||
---
|
||||
|
||||
# [[Tool-Usage-Optimization|Tool-Usage-Optimization]]
|
||||
# Tool Usage Optimization
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "도구의 주인이 되는 기술: 단순히 도구를 쓰는 것을 넘어, 도구가 가진 잠재력을 극대화하고 워크플로우에 완벽히 통합하여 개인이 가진 능력을 수십 배로 증폭시키는 숙련의 미학."
|
||||
## 매 한 줄
|
||||
> **"매 LLM의 외부 capability 의 invoke"**. Tool use (function calling) 매 LLM 이 external API/code/DB 의 structured call 하는 패러다임. 2023 OpenAI function calling → 2024 parallel tools → 2025 MCP standard → 2026 매 every agent 의 backbone. 매 quality 매 tool 정의의 crisp / parallel call / error handling / cache strategy 에 의해 결정.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
도구 활용 최적화(Tool-Usage-Optimization)는 목표 달성을 위해 가용한 도구들의 기능을 깊이 이해하고, 이를 최소한의 노력으로 최대의 성과를 낼 수 있도록 체계화하는 과정입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **최적화의 단계**:
|
||||
* **Selection**: 문제의 성격에 맞는 최적의 도구 선별 (망치는 못에만 써라).
|
||||
* **Customization**: 도구의 기본 설정을 자신의 작업 스타일과 맥락에 맞게 재구성 (단축키, 플러그인 등).
|
||||
* **Combination (Stacking)**: 서로 다른 도구들을 연결하여 자동 파이프라인 형성 (예: API 연동).
|
||||
* **[[Mastery|Mastery]]**: 도구의 구조(Internal)를 이해하여 한계 지점을 파악하고 우회하는 능력.
|
||||
2. **AI 지능 측면에서의 도구 활용**:
|
||||
* **LLM Tool Use (Function Calling)**: 모델이 스스로 외부 도구(검색, 계산기, 코드 실행기 등)를 호출하여 자신의 지능을 확장하는 능력 최적화.
|
||||
3. **효과**:
|
||||
* 인지 부하 감소, 반복 태스크 자동화, 실수 방지(Error-proofing).
|
||||
### 매 핵심 mechanics
|
||||
- **Schema** — 매 JSON Schema 로 tool input 정의 — 매 model 이 fill.
|
||||
- **Choice** — `auto` / `tool` (forced) / `none`.
|
||||
- **Parallel** — 매 single turn 에 multiple tool calls (Claude / GPT-4o+).
|
||||
- **Iterative loop** — 매 tool result 의 feed back → continue → repeat.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 '한 가지 도구를 평생 다루는 장인정신'이 강조되었으나, 현대 기술 정책은 끊임없이 쏟아지는 새로운 도구를 빠르게 습득하고 기존 워크플로우에 녹여내는 '지속적 적응 정책'을 도구 활용의 새로운 정의로 수립함(RL Update).
|
||||
- **정책 변화(RL Update)**: 기업 보안 정책에서 생산성 도구의 무분별한 사용(Shadow IT)을 막으면서도 최적화된 도구 활용을 장려하기 위해, '승인된 도구 세트(Approved Stack)' 내에서 자유로운 자동화를 보장하는 정책이 확대됨.
|
||||
### 매 design principles
|
||||
- **Crisp descriptions** — 매 tool description 매 "use this when X, not when Y" 명시.
|
||||
- **Few well-named tools** > 매 many overlapping — 매 selection error rate 의 reduce.
|
||||
- **Idempotent / safe** — 매 retry-safe — 매 LLM 매 retry 함.
|
||||
- **Structured errors** — 매 tool error 매 LLM 이 recover 할 수 있게 actionable.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Rapid-Prototyping|Rapid-Prototyping]], [[Soft-Skills-Development|Soft-Skills-Development]], Human-Computer Interaction (HCI), [[Software-Design-Principles|Software-Design-Principles]], [[Operations-Research|Operations-Research]]
|
||||
- **Modern Tech/Tools**: Zapier/Make.com (Integration), CLI automation, [[AI Agents|AI Agents]] with tool-access.
|
||||
---
|
||||
### 매 modern (2025-2026)
|
||||
- **MCP (Model Context Protocol)** — 매 Anthropic 이 2024-11 release. 매 client/server tool sharing standard. 매 Claude Desktop, Cursor, Windsurf 모두 support.
|
||||
- **Tool result caching** — 매 expensive tool (DB query, web fetch) 매 cache + hash check.
|
||||
- **Tool budget** — 매 agent 의 max-call limit 의 prevent runaway.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. Code agents (file ops, shell, search).
|
||||
2. Customer support (ticket, KB, account API).
|
||||
3. Data analysis (SQL, plot, fetch).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Anthropic tool definition
|
||||
```python
|
||||
tools = [{
|
||||
"name": "get_weather",
|
||||
"description": "Get current weather. Use ONLY for weather; do not use for forecasts beyond 24h.",
|
||||
"input_schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"location": {"type": "string", "description": "City, country (e.g. 'Seoul, KR')"},
|
||||
"unit": {"type": "string", "enum": ["c", "f"], "default": "c"},
|
||||
},
|
||||
"required": ["location"],
|
||||
},
|
||||
}]
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=2000,
|
||||
tools=tools,
|
||||
messages=[{"role": "user", "content": "Weather in Seoul?"}],
|
||||
)
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Parallel tool execution
|
||||
```python
|
||||
import asyncio
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
async def run_tool(call):
|
||||
return await TOOLS[call.name](**call.input)
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
# 매 LLM이 매 multiple tool_use blocks 의 emit
|
||||
calls = [b for b in resp.content if b.type == "tool_use"]
|
||||
results = await asyncio.gather(*(run_tool(c) for c in calls))
|
||||
# 매 모든 result 의 single user message 로 feed back
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Tool loop (agentic)
|
||||
```python
|
||||
messages = [{"role": "user", "content": user_query}]
|
||||
for _ in range(MAX_TURNS):
|
||||
resp = client.messages.create(model="claude-opus-4-7", tools=tools, messages=messages)
|
||||
messages.append({"role": "assistant", "content": resp.content})
|
||||
if resp.stop_reason != "tool_use":
|
||||
break
|
||||
tool_results = [
|
||||
{"type": "tool_result", "tool_use_id": b.id,
|
||||
"content": str(TOOLS[b.name](**b.input))}
|
||||
for b in resp.content if b.type == "tool_use"
|
||||
]
|
||||
messages.append({"role": "user", "content": tool_results})
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Structured error
|
||||
```python
|
||||
def search_db(query: str):
|
||||
try:
|
||||
return {"ok": True, "rows": db.execute(query).fetchall()}
|
||||
except SQLError as e:
|
||||
return {"ok": False, "error": str(e),
|
||||
"hint": "Check column names; use `\\d table` to inspect."}
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Result caching
|
||||
```python
|
||||
import hashlib, json, functools
|
||||
|
||||
@functools.lru_cache(maxsize=1024)
|
||||
def _cached_fetch(url_hash: str, url: str):
|
||||
return requests.get(url, timeout=10).text
|
||||
|
||||
def web_fetch(url: str):
|
||||
return _cached_fetch(hashlib.sha256(url.encode()).hexdigest(), url)
|
||||
```
|
||||
|
||||
### Prompt cache + tools (Anthropic)
|
||||
```python
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
tools=tools, # 매 tools 의 cacheable
|
||||
system=[{"type": "text", "text": SYSTEM, "cache_control": {"type": "ephemeral"}}],
|
||||
messages=messages,
|
||||
)
|
||||
```
|
||||
|
||||
### MCP server (Python)
|
||||
```python
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
mcp = FastMCP("my-tools")
|
||||
|
||||
@mcp.tool()
|
||||
def query_orders(customer_id: str) -> list[dict]:
|
||||
"""Return recent orders for a customer."""
|
||||
return db.fetch_orders(customer_id)
|
||||
|
||||
if __name__ == "__main__":
|
||||
mcp.run()
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Few tools, in-app | Direct SDK tools |
|
||||
| Many shared tools across apps | MCP server |
|
||||
| Latency-critical | Pre-fetch / parallel tools |
|
||||
| Expensive tools | Cache by input hash |
|
||||
| Untrusted LLM output | Validate + sandbox tool exec |
|
||||
| Long agent loop | Tool budget + checkpoint |
|
||||
|
||||
**기본값**: 매 5-15 well-named tools, parallel calling enabled, structured errors, prompt caching on system + tool definitions.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[LLM-Inference]] · [[Agentic-AI]]
|
||||
- 변형: [[Function-Calling]] · [[MCP]] · [[ReAct]]
|
||||
- 응용: [[Code-Agent]] · [[Customer-Support-Agent]] · [[Data-Analysis-Agent]]
|
||||
- Adjacent: [[Prompt-Caching]] · [[RAG]] · [[Structured-Output]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 external state / capability 의 필요한 모든 LLM app — search, DB, email, code exec, API call.
|
||||
**언제 X**: 매 pure text generation (summary, translate) — 매 tool 매 unnecessary.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Vague tool names**: `"do_thing"` — 매 LLM 매 selection 의 fail.
|
||||
- **Too many tools**: 매 30+ tool 매 confuse — 매 group / route.
|
||||
- **No retry on transient error**: 매 502 / timeout 매 transient — 매 retry-safe + LLM 의 hint.
|
||||
- **Streaming tool output to user mid-call**: 매 tool result 매 internal — final assistant text 만 user 에.
|
||||
- **No max-turn limit**: 매 infinite loop 의 risk.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Anthropic tool use docs, OpenAI function calling, MCP spec 2024-11, parallel tool calling).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — modern tool use + MCP + caching patterns |
|
||||
|
||||
Reference in New Issue
Block a user