C.W.K.
Stream
Lesson 04 of 07 · published

The Tool Loop — 3 phase per turn

~22 min · tool-loop, multi-turn

Level 0Tokenizer
0 XP0/54 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Tool loop 의 한 cycle 은 3 phase — (1) context 전송, 모델이 tool_calls 또는 텍스트 반환. (2) 텍스트면 종료. tool_calls 면 각 tool 실행 + 결과 capture. (3) 결과 다시 보냄, 모델이 텍스트 또는 또 다른 tool_call. tool_call 없을 때까지 loop.

Phase per phase

  1. Phase 1: responses.create(input, tools=[...]). Output 이 tool_call 인지 텍스트인지 inspect.
  2. Phase 2: 매 tool_call 의 name + arguments 로 handler 호출. 결과 capture.
  3. Phase 3: 결과를 function_call_output (Responses) 또는 tool-role 메시지 (Chat Completions) 로 다음 호출에 input. 텍스트 받을 때까지 반복.

Loop depth 항상 cap

max_tool_iterations=10. 모델이 ping-pong 무한 가능 (bad prompt 에서). Cap 없으면 multi-day rate-limit 사고가 multi-day spend 사고로 변환. Circuit breaker 명시적 abort 와 clear error.

Production 에선 hook 이 필수

매 iteration 의 tool, arguments, 결과를 JSONL 에 log. Replay-based 테스팅 (Production 트랙) 의 base — captured loop 를 CI 에서 replay 가능하게.

Code

Full tool loop (Responses)·python
import json
from openai import OpenAI

client = OpenAI()

def get_weather(location, units="celsius"):
    return {"location": location, "temperature": 22, "condition": "sunny", "units": units}

def search_news(query):
    return [{"title": f"News about {query}", "url": "https://news.example.com"}]

TOOLS_MAP = {"get_weather": get_weather, "search_news": search_news}

tools = [
    {"type": "function", "name": "get_weather", "description": "Get current weather",
     "parameters": {"type": "object", "properties": {"location": {"type": "string"},
     "units": {"type": ["string", "null"], "enum": ["celsius", "fahrenheit"]}},
     "required": ["location"], "additionalProperties": False}, "strict": True},
    {"type": "function", "name": "search_news", "description": "Search recent news",
     "parameters": {"type": "object", "properties": {"query": {"type": "string"}},
     "required": ["query"], "additionalProperties": False}, "strict": True},
]

input_items = [{"role": "user", "content": "Weather in Tokyo and any AI news?"}]

while True:
    response = client.responses.create(model="gpt-5.4", tools=tools, input=input_items)
    input_items.extend(response.output)
    tool_calls = [i for i in response.output if i.type == "function_call"]
    if not tool_calls:
        print(response.output_text)
        break
    for tc in tool_calls:
        result = TOOLS_MAP[tc.name](**json.loads(tc.arguments))
        input_items.append({
            "type": "function_call_output",
            "call_id": tc.call_id,
            "output": json.dumps(result),
        })

External links

Exercise

3 개 fake tool (get_weather, get_news, get_calendar) 가진 tool loop build. iteration cap 5. 매 step 의 iteration 인덱스, 호출된 tool, 모델 reasoning 텍스트 log.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.